Compare commits

..
Author SHA1 Message Date
JohnAFernandez 05f2db381a Create temp_coverity_scan.yaml
Temporary coverity scan workflow until the scheduled one gets a review
2023-10-30 11:10:32 -04:00
866 changed files with 8724 additions and 79960 deletions

No files matched your search

+40 -40
View File
@@ -6,7 +6,7 @@ on:
- 'nightly_*'
env:
QT_VERSION: 5.12.12
QT_VERSION: 5.12.9
jobs:
build_linux:
@@ -15,17 +15,36 @@ jobs:
configuration: [FastDebug, Release]
name: Linux
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/linux_build:sha-1ff82e8
container: ghcr.io/scp-fs2open/linux_build:sha-3d30dc5
steps:
# - name: Cache Qt
# id: cache-qt-lin
# uses: actions/cache@v1
# with:
# path: ${{ github.workspace }}/../Qt
# key: ${{ runner.os }}-QtCache-${{ env.QT_VERSION }}
# - name: Install Qt
# uses: jurplel/install-qt-action@v2
# with:
# version: ${{ env.QT_VERSION }}
# dir: ${{ github.workspace }}/..
# cached: ${{ steps.cache-qt-lin.outputs.cache-hit }}
# setup-python: 'false'
# aqtversion: ==1.1.3
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
- name: Prepare Vulkan SDK
uses: humbletim/[email protected]
with:
vulkan-query-version: 1.3.204.0
vulkan-components: Vulkan-Headers, Vulkan-Loader
vulkan-use-cache: true
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: gcc-9
ENABLE_QTFRED: OFF
COMPILER: gcc-5
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Compile
working-directory: ./build
@@ -45,7 +64,7 @@ jobs:
CONFIGURATION: ${{ matrix.configuration }}
run: $GITHUB_WORKSPACE/ci/linux/generate_appimage.sh $GITHUB_WORKSPACE/build/install
- name: Upload build result
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: linux-${{ matrix.configuration }}
path: ${{ github.workspace }}/build/install/*.AppImage
@@ -61,12 +80,12 @@ jobs:
submodules: true
fetch-depth: '0'
- name: Download Release builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v1
with:
name: linux-Release
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: linux-FastDebug
path: builds
@@ -164,7 +183,7 @@ jobs:
shell: bash
run: ./bin/$CONFIGURATION/unittests --gtest_shuffle
- name: Upload build result
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: windows-${{ matrix.configuration }}-${{ matrix.arch }}-${{ matrix.simd }}
path: ${{ github.workspace }}/build/install/*
@@ -184,12 +203,12 @@ jobs:
submodules: true
fetch-depth: '0'
- name: Download Release builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v1
with:
name: windows-Release-${{ matrix.arch }}-${{ matrix.simd }}
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: windows-FastDebug-${{ matrix.arch }}-${{ matrix.simd }}
path: builds
@@ -215,7 +234,7 @@ jobs:
matrix:
configuration: [FastDebug, Release]
compiler: [clang]
arch: [x86_64, arm64]
arch: [x86_64]
name: Mac
runs-on: macos-latest
steps:
@@ -257,7 +276,6 @@ jobs:
COMPILER: ${{ matrix.compiler }}
ARCHITECTURE: ${{ matrix.arch }}
JOB_CMAKE_OPTIONS: ${{ matrix.cmake_options }}
ENABLE_QTFRED: OFF
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Compile
working-directory: ./build
@@ -266,39 +284,23 @@ jobs:
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
ARCH: ${{ matrix.arch }}
XDG_RUNTIME_DIR: /root
run: $GITHUB_WORKSPACE/ci/linux/run_tests.sh
- name: Sign builds
working-directory: ./build/bin
run: |
# make sure OpenAL framework is signed
find . -name OpenAL -type f | while read xx; do codesign --force -s - $xx; done
find . -name OpenAL.framework -type d | while read xx; do codesign --force -s - $xx; done
# make sure dylibs are signed
find . -name \*.dylib -type f | while read xx; do codesign --force -s - $xx; done
# sign binaries
find . -perm +111 -type f | grep MacOS | while read xx; do codesign --force -s - $xx; done
# sign apps
find . -name \*.app -maxdepth 1 | while read xx; do codesign --force -s - $xx; done
- name: Package build result
working-directory: ./build/bin
# Use GNU tar here (part of runner image) to avoid weird corruption bug with bsdtar
# Ref: https://github.com/actions/runner-images/issues/2619
run: gtar -cvzf macos-build-${{ matrix.configuration }}-${{ matrix.arch }}.tgz *.app
run: gtar -cvzf macos-build-${{ matrix.configuration }}.tgz *.app
- name: Upload build result
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: mac-${{ matrix.configuration }}-${{ matrix.arch }}
path: ${{ github.workspace }}/build/bin/macos-build-${{ matrix.configuration }}-${{ matrix.arch }}.tgz
name: mac-${{ matrix.configuration }}
path: ${{ github.workspace }}/build/bin/macos-build-${{ matrix.configuration }}.tgz
mac_zip:
name: Build Mac distribution zip
needs: build_mac
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/sftp_upload:sha-748b19d
strategy:
matrix:
arch: [x86_64, arm64]
steps:
- uses: actions/checkout@v2
name: Checkout
@@ -307,24 +309,22 @@ jobs:
fetch-depth: '0'
ref: '${{ github.ref }}'
- name: Download Release builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: mac-Release-${{ matrix.arch }}
name: mac-Release
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: mac-FastDebug-${{ matrix.arch }}
name: mac-FastDebug
path: builds
- name: Unpack builds
working-directory: ./builds
run: |
tar -xvzf macos-build-Release-${{ matrix.arch }}.tgz
tar -xvzf macos-build-FastDebug-${{ matrix.arch }}.tgz
tar -xvzf macos-build-Release.tgz
tar -xvzf macos-build-FastDebug.tgz
- name: Create Distribution package
working-directory: ./builds
env:
ARCH: ${{ matrix.arch }}
run: $GITHUB_WORKSPACE/ci/linux/create_dist_pack.sh Mac
- name: Upload result package
working-directory: ./builds
+71 -44
View File
@@ -6,7 +6,7 @@ on:
- 'release_*'
env:
QT_VERSION: 5.12.12
QT_VERSION: 5.12.9
jobs:
create_release:
@@ -44,19 +44,65 @@ jobs:
name: Linux
needs: create_release # Don't run this job until create_release is done and successful
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/linux_build:sha-1ff82e8
container: ghcr.io/scp-fs2open/linux_build:sha-3d30dc5
steps:
# - name: Cache Qt
# id: cache-qt-lin
# uses: actions/cache@v1
# cache the Qt directory so we don't have to reinstall it every time
# cache.inputs:
# path - A list of files, directories, and wildcard patterns to cache and restore. See @actions/glob for supported patterns.
# key - An explicit key for restoring and saving the cache
# restore-keys - An ordered list of keys to use for restoring the cache if no cache hit occurred for key
# cache.outputs:
# cache-hit true when an exact match was found for the key, false otherwise.
# with:
# path: ${{ github.workspace }}/../Qt
# key: ${{ runner.os }}-QtCache-${{ env.QT_VERSION }}
# - name: Install Qt
# uses: jurplel/install-qt-action@v2
# installs Qt in the action workflow
# install-qt-action.inputs:
# version desired qt version to install
# host Host platform of Qt, default to platform used by runs-on
# target target platform of Qt, default to desktop
# arch target architecture of Qt, only used for windows or android builds
# dir root dir Qt will be installed to
# install-deps if true, auto-install dependencies on linux. Default true
# modules whitespace delimited list string of additional addon modules to install
# archives whitespace delimited list string of Qt archives to install
# cached if true, Don't download Qt but set ENVARs; use with cache.outputs.cache-hit
# setup-python Set to false to skip using setup-python to find/download a valid python version
# set-env if true, set ENVARs; default = false
# aqtversion version of aqtinstall to use; default = 2.0.0
# py7zrversion version of py7zr to use; default = 0.16.1
# extra additional arguments to pass to aqinstall
# ENVARS set:
# Qt5_DIR / Qt6_DIR
# Qt bin dir appended to PATH
# QT_PLUGIN_PATH, QML2_IMPORT_PATH, PKG_CONFIG_PATH, LD_LIBRARY_PATH
# with:
# version: ${{ env.QT_VERSION }}
# dir: ${{ github.workspace }}/..
# cached: ${{ steps.cache-qt-lin.outputs.cache-hit }}
# setup-python: 'false'
# aqtversion: ==1.1.3
- uses: actions/checkout@v1
# checks-out your repository under $GITHUB_WORKSPACE, so your workflow can access it.
name: Checkout
with:
submodules: true # `true` to checkout submodules, `recursive` to recursively checkout submodules
ref: '${{ github.ref }}'
- name: Prepare Vulkan SDK
uses: humbletim/[email protected]
with:
vulkan-query-version: 1.3.204.0
vulkan-components: Vulkan-Headers, Vulkan-Loader
vulkan-use-cache: true
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: gcc-9
ENABLE_QTFRED: OFF
COMPILER: gcc-5
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Compile
working-directory: ./build
@@ -76,7 +122,7 @@ jobs:
CONFIGURATION: ${{ matrix.configuration }}
run: $GITHUB_WORKSPACE/ci/linux/generate_appimage.sh $GITHUB_WORKSPACE/build/install
- name: Upload build result
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
# Upload the url file for use with other runners
# upload-artifact.inputs:
# if-no-files-found=warn What to do if path fails to find any files.
@@ -103,13 +149,13 @@ jobs:
ref: '${{ github.ref }}'
- name: Download Release builds
# Grab the release builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: linux-Release
path: builds
- name: Download FastDebug builds
# Grab the debug builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: linux-FastDebug
path: builds
@@ -120,7 +166,7 @@ jobs:
run: $GITHUB_WORKSPACE/ci/linux/create_dist_pack.sh Linux
- name: Upload result package
# Stash the result to artifact filespace
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: ${{ steps.generate_package.outputs.package_name }}
path: ${{ steps.generate_package.outputs.package_path }}
@@ -220,7 +266,7 @@ jobs:
shell: bash
run: ./bin/$CONFIGURATION/unittests --gtest_shuffle
- name: Upload build result
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: windows-${{ matrix.configuration }}-${{ matrix.arch }}-${{ matrix.simd }}
path: ${{ github.workspace }}/build/install/*
@@ -244,13 +290,13 @@ jobs:
fetch-depth: '0'
ref: '${{ github.ref }}'
- name: Download Release builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: windows-Release-${{ matrix.arch }}-${{ matrix.simd }}
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: windows-FastDebug-${{ matrix.arch }}-${{ matrix.simd }}
path: builds
@@ -265,13 +311,13 @@ jobs:
run: $GITHUB_WORKSPACE/ci/linux/create_dist_pack.sh Windows
- name: Upload result package
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: ${{ steps.generate_package.outputs.package_name }}
path: ${{ steps.generate_package.outputs.package_path }}
- name: Upload debug package
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: ${{ steps.generate_package.outputs.debug_name }}
path: ${{ steps.generate_package.outputs.debug_path }}
@@ -290,7 +336,7 @@ jobs:
matrix:
configuration: [FastDebug, Release]
compiler: [clang]
arch: [x86_64, arm64]
arch: [x86_64]
name: Mac
needs: create_release
runs-on: macos-latest
@@ -327,7 +373,6 @@ jobs:
COMPILER: ${{ matrix.compiler }}
ARCHITECTURE: ${{ matrix.arch }}
JOB_CMAKE_OPTIONS: ${{ matrix.cmake_options }}
ENABLE_QTFRED: OFF
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Compile
working-directory: ./build
@@ -336,39 +381,23 @@ jobs:
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
ARCH: ${{ matrix.arch }}
XDG_RUNTIME_DIR: /root
run: $GITHUB_WORKSPACE/ci/linux/run_tests.sh
- name: Sign builds
working-directory: ./build/bin
run: |
# make sure OpenAL framework is signed
find . -name OpenAL -type f | while read xx; do codesign --force -s - $xx; done
find . -name OpenAL.framework -type d | while read xx; do codesign --force -s - $xx; done
# make sure dylibs are signed
find . -name \*.dylib -type f | while read xx; do codesign --force -s - $xx; done
# sign binaries
find . -perm +111 -type f | grep MacOS | while read xx; do codesign --force -s - $xx; done
# sign apps
find . -name \*.app -maxdepth 1 | while read xx; do codesign --force -s - $xx; done
- name: Package build result
working-directory: ./build/bin
# Use GNU tar here (part of runner image) to avoid weird corruption bug with bsdtar
# Ref: https://github.com/actions/runner-images/issues/2619
run: gtar -cvzf macos-build-${{ matrix.configuration }}-${{ matrix.arch }}.tgz *.app
run: gtar -cvzf macos-build-${{ matrix.configuration }}.tgz *.app
- name: Upload build result
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: mac-${{ matrix.configuration }}-${{ matrix.arch }}
path: ${{ github.workspace }}/build/bin/macos-build-${{ matrix.configuration }}-${{ matrix.arch }}.tgz
name: mac-${{ matrix.configuration }}
path: ${{ github.workspace }}/build/bin/macos-build-${{ matrix.configuration }}.tgz
mac_zip:
name: Build Mac distribution zip
needs: build_mac
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/sftp_upload:sha-748b19d
strategy:
matrix:
arch: [x86_64, arm64]
steps:
- uses: actions/checkout@v2
name: Checkout
@@ -377,28 +406,26 @@ jobs:
fetch-depth: '0'
ref: '${{ github.ref }}'
- name: Download Release builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: mac-Release-${{ matrix.arch }}
name: mac-Release
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: mac-FastDebug-${{ matrix.arch }}
name: mac-FastDebug
path: builds
- name: Unpack builds
working-directory: ./builds
run: |
tar -xvzf macos-build-Release-${{ matrix.arch }}.tgz
tar -xvzf macos-build-FastDebug-${{ matrix.arch }}.tgz
tar -xvzf macos-build-Release.tgz
tar -xvzf macos-build-FastDebug.tgz
- name: Create Distribution package
id: generate_package
working-directory: ./builds
env:
ARCH: ${{ matrix.arch }}
run: $GITHUB_WORKSPACE/ci/linux/create_dist_pack.sh Mac
- name: Upload result package
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: ${{ steps.generate_package.outputs.package_name }}
path: ${{ steps.generate_package.outputs.package_path }}
+59
View File
@@ -0,0 +1,59 @@
name: Publish Standalone docker image
on:
push:
tags:
- 'nightly_*'
- 'release_*'
jobs:
build_images:
if: github.repository == 'scp-fs2open/fs2open.github.com'
strategy:
matrix:
configuration: [FastDebug, Release]
include:
- configuration: FastDebug
tag_suffix: -debug
- configuration: Release
tag_suffix: ""
fail-fast: false
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
name: Checkout
with:
submodules: true
- name: Prepare Vulkan SDK
uses: humbletim/[email protected]
with:
vulkan-query-version: 1.3.204.0
vulkan-components: Vulkan-Headers, Vulkan-Loader
vulkan-use-cache: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Docker meta
id: docker_meta
uses: crazy-max/ghaction-docker-meta@v1
with:
images: ghcr.io/scp-fs2open/standalone_server
tag-latest: false
- name: Login to GitHub Docker Registry
uses: docker/login-action@v1
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.CR_PAT }}
- name: Build and push
id: docker_build
uses: docker/build-push-action@v2
with:
context: .
file: ./docker/standalone/Dockerfile
push: true
tags: ${{ steps.docker_meta.outputs.tags }}${{ matrix.tag_suffix }}
labels: ${{ steps.docker_meta.outputs.labels }}
build-args: |
build_type=${{ matrix.configuration }}
+40 -40
View File
@@ -6,7 +6,7 @@ on:
- 'test/*'
env:
QT_VERSION: 5.12.12
QT_VERSION: 5.12.9
jobs:
build_linux:
@@ -15,8 +15,22 @@ jobs:
configuration: [FastDebug, Release]
name: Linux
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/linux_build:sha-1ff82e8
container: ghcr.io/scp-fs2open/linux_build:sha-3d30dc5
steps:
# - name: Cache Qt
# id: cache-qt-lin
# uses: actions/cache@v1
# with:
# path: ${{ github.workspace }}/../Qt
# key: ${{ runner.os }}-QtCache-${{ env.QT_VERSION }}
# - name: Install Qt
# uses: jurplel/install-qt-action@v2
# with:
# version: ${{ env.QT_VERSION }}
# dir: ${{ github.workspace }}/..
# cached: ${{ steps.cache-qt-lin.outputs.cache-hit }}
# setup-python: 'false'
# aqtversion: ==1.1.3
- uses: actions/checkout@v1
name: Checkout
with:
@@ -27,11 +41,16 @@ jobs:
[[ "${{ github.ref }}" =~ ^refs\/heads\/test\/(.*)$ ]]
# Override the revision string so that the builds are named correctly
echo "set(FSO_VERSION_REVISION_STR ${BASH_REMATCH[1]})" > "version_override.cmake"
- name: Prepare Vulkan SDK
uses: humbletim/[email protected]
with:
vulkan-query-version: 1.3.204.0
vulkan-components: Vulkan-Headers, Vulkan-Loader
vulkan-use-cache: true
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: gcc-9
ENABLE_QTFRED: OFF
COMPILER: gcc-5
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Compile
working-directory: ./build
@@ -51,7 +70,7 @@ jobs:
CONFIGURATION: ${{ matrix.configuration }}
run: $GITHUB_WORKSPACE/ci/linux/generate_appimage.sh $GITHUB_WORKSPACE/build/install
- name: Upload build result
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: linux-${{ matrix.configuration }}
path: ${{ github.workspace }}/build/install/*.AppImage
@@ -68,12 +87,12 @@ jobs:
fetch-depth: '0'
ref: '${{ github.ref }}'
- name: Download Release builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v1
with:
name: linux-Release
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: linux-FastDebug
path: builds
@@ -177,7 +196,7 @@ jobs:
shell: bash
run: ./bin/$CONFIGURATION/unittests --gtest_shuffle
- name: Upload build result
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: windows-${{ matrix.configuration }}-${{ matrix.arch }}-${{ matrix.simd }}
path: ${{ github.workspace }}/build/install/*
@@ -198,12 +217,12 @@ jobs:
fetch-depth: '0'
ref: '${{ github.ref }}'
- name: Download Release builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v1
with:
name: windows-Release-${{ matrix.arch }}-${{ matrix.simd }}
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: windows-FastDebug-${{ matrix.arch }}-${{ matrix.simd }}
path: builds
@@ -229,7 +248,7 @@ jobs:
matrix:
configuration: [FastDebug, Release]
compiler: [clang]
arch: [x86_64, arm64]
arch: [x86_64]
name: Mac
runs-on: macos-latest
steps:
@@ -270,7 +289,6 @@ jobs:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: ${{ matrix.compiler }}
ARCHITECTURE: ${{ matrix.arch }}
ENABLE_QTFRED: OFF
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Compile
working-directory: ./build
@@ -279,39 +297,23 @@ jobs:
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
ARCH: ${{ matrix.arch }}
XDG_RUNTIME_DIR: /root
run: $GITHUB_WORKSPACE/ci/linux/run_tests.sh
- name: Sign builds
working-directory: ./build/bin
run: |
# make sure OpenAL framework is signed
find . -name OpenAL -type f | while read xx; do codesign --force -s - $xx; done
find . -name OpenAL.framework -type d | while read xx; do codesign --force -s - $xx; done
# make sure dylibs are signed
find . -name \*.dylib -type f | while read xx; do codesign --force -s - $xx; done
# sign binaries
find . -perm +111 -type f | grep MacOS | while read xx; do codesign --force -s - $xx; done
# sign apps
find . -name \*.app -maxdepth 1 | while read xx; do codesign --force -s - $xx; done
- name: Package build result
working-directory: ./build/bin
# Use GNU tar here (part of runner image) to avoid weird corruption bug with bsdtar
# Ref: https://github.com/actions/runner-images/issues/2619
run: gtar -cvzf macos-build-${{ matrix.configuration }}-${{ matrix.arch }}.tgz *.app
run: gtar -cvzf macos-build-${{ matrix.configuration }}.tgz *.app
- name: Upload build result
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v2
with:
name: mac-${{ matrix.configuration }}-${{ matrix.arch }}
path: ${{ github.workspace }}/build/bin/macos-build-${{ matrix.configuration }}-${{ matrix.arch }}.tgz
name: mac-${{ matrix.configuration }}
path: ${{ github.workspace }}/build/bin/macos-build-${{ matrix.configuration }}.tgz
mac_zip:
name: Build Mac distribution zip
needs: build_mac
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/sftp_upload:sha-748b19d
strategy:
matrix:
arch: [x86_64, arm64]
steps:
- uses: actions/checkout@v2
name: Checkout
@@ -320,24 +322,22 @@ jobs:
fetch-depth: '0'
ref: '${{ github.ref }}'
- name: Download Release builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: mac-Release-${{ matrix.arch }}
name: mac-Release
path: builds
- name: Download FastDebug builds
uses: actions/download-artifact@v3
uses: actions/download-artifact@v2
with:
name: mac-FastDebug-${{ matrix.arch }}
name: mac-FastDebug
path: builds
- name: Unpack builds
working-directory: ./builds
run: |
tar -xvzf macos-build-Release-${{ matrix.arch }}.tgz
tar -xvzf macos-build-FastDebug-${{ matrix.arch }}.tgz
tar -xvzf macos-build-Release.tgz
tar -xvzf macos-build-FastDebug.tgz
- name: Create Distribution package
working-directory: ./builds
env:
ARCH: ${{ matrix.arch }}
run: $GITHUB_WORKSPACE/ci/linux/create_dist_pack.sh Mac
- name: Upload result package
working-directory: ./builds
+20 -14
View File
@@ -6,27 +6,42 @@ on:
- master
env:
QT_VERSION: 5.12.12
QT_VERSION: 5.12.9
jobs:
build_linux:
strategy:
matrix:
configuration: [Debug, Release]
compiler: [gcc-9, gcc-13, clang-16]
compiler: [gcc-5, gcc-10]
cmake_options: [""]
include:
# Also include configurations that check if the code compiles without the graphics backends
- configuration: Debug
compiler: gcc-13
compiler: gcc-10
cmake_options: -DFSO_BUILD_WITH_OPENGL=OFF -DFSO_BUILD_WITH_VULKAN=OFF
- configuration: Release
compiler: gcc-13
compiler: gcc-10
cmake_options: -DFSO_BUILD_WITH_OPENGL=OFF -DFSO_BUILD_WITH_VULKAN=OFF
name: Linux
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/linux_build:sha-1ff82e8
container: ghcr.io/scp-fs2open/linux_build:sha-3d30dc5
steps:
# - name: Cache Qt
# id: cache-qt-lin
# uses: actions/cache@v1
# with:
# path: ${{ github.workspace }}/../Qt
# key: ${{ runner.os }}-QtCache-${{ env.QT_VERSION }}
# - name: Install Qt
# uses: jurplel/install-qt-action@v2
# with:
# version: ${{ env.QT_VERSION }}
# dir: ${{ github.workspace }}/..
# cached: ${{ steps.cache-qt-lin.outputs.cache-hit }}
# setup-python: 'false'
# aqtversion: ==1.1.3
- uses: actions/checkout@v1
name: Checkout
with:
@@ -35,22 +50,13 @@ jobs:
uses: hendrikmuhs/ccache-action@v1
with:
key: ${{ runner.os }}-${{ matrix.configuration }}-${{ matrix.compiler }}
- name: Configure ccache
run: |
ccache --set-config=sloppiness=pch_defines,time_macros
ccache -p
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: ${{ matrix.compiler }}
JOB_CMAKE_OPTIONS: ${{ matrix.cmake_options }}
CCACHE_PATH: /usr/local/bin/ccache
ENABLE_QTFRED: ON
Qt5_DIR: /qt/${{ env.QT_VERSION }}/gcc_64/lib/cmake/Qt5
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Compile
working-directory: ./build
run: LD_LIBRARY_PATH=$Qt5_DIR/lib:$LD_LIBRARY_PATH ninja -k 20 all
- name: Show CCache statistics
run: ccache --show-stats
@@ -2,36 +2,42 @@ name: Weekly Coverity Scan for Freespace Open
# adapted from code by "albert-github" on the doxygen repository
# many thanks for figuring this out first so it could be less painful for us!
# keep this from running on everyone's fork
# if: github.ref == 'refs/heads/master'
#This mode is for testing
#on: [push, pull_request]
# This mode is for testing
on: [push, pull_request]
# In production, push on a specific schedule
on:
schedule:
- cron: "57 18 * * *" # Run once per a week on Friday morning (4 AM EST), to avoid Coverity's submission limits
#on:
# schedule:
# - cron: "1 0 * * 5" # Run once per a week on Friday morning (midnight UTC, 4 AM EST), to avoid Coverity's submission limits
env:
QT_VERSION: 5.12.12
QT_VERSION: 5.12.9
coverity_email: [email protected]
coverity_token: ${{ secrets.COVERITY_TOKEN }}
jobs:
build:
name: Build FSO With Coverity Wrapper
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/linux_build:sha-1ff82e8
runs-on: ${{ matrix.config.os }}
strategy:
fail-fast: false
matrix:
config:
- { name: "GCC on ubuntu", os: ubuntu-latest, build_type: "Release" }
steps:
- name: Install Dependencies
run: |
sudo apt-get install ninja-build
sudo apt install cmake libsdl2-dev g++
sudo apt-get install libopenal-dev
sudo apt-get install -y libudev-dev
sudo apt-get install doxygen
sudo apt install graphviz
- name: Checkout
uses: actions/checkout@v1
uses: actions/checkout@v4
with:
submodules: true # `true` to checkout submodules, `recursive` to recursively checkout submodules
submodules: recursive # `true` to checkout submodules, `recursive` to recursively checkout submodules
# pipe results of wget to a log file because it's very verbose and rarely fails
- name: Install Coverity
@@ -45,11 +51,17 @@ jobs:
echo "$(pwd)/cov-scan/bin" >> $GITHUB_PATH
echo "NPROC=$(getconf _NPROCESSORS_ONLN)" >> $GITHUB_ENV
- name: Prepare Vulkan SDK
uses: humbletim/[email protected]
with:
vulkan-query-version: 1.3.204.0
vulkan-components: Vulkan-Headers, Vulkan-Loader
vulkan-use-cache: true
- name: Configure CMake for FSO
env:
CONFIGURATION: FastDebug
COMPILER: gcc-9
ENABLE_QTFRED: OFF
CONFIGURATION: Release
compiler: gcc-5
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Build FSO with Coverity Wrapper
+27 -19
View File
@@ -3,27 +3,41 @@ name: Check a pull request
on: [pull_request]
env:
QT_VERSION: 5.12.12
QT_VERSION: 5.12.9
jobs:
build_linux:
strategy:
matrix:
configuration: [Debug, Release]
compiler: [gcc-9, gcc-13, clang-16]
compiler: [gcc-5, gcc-10, clang-9]
cmake_options: [""]
include:
# Also include configurations that check if the code compiles without the graphics backends
- configuration: Debug
compiler: gcc-13
compiler: gcc-10
cmake_options: -DFSO_BUILD_WITH_OPENGL=OFF -DFSO_BUILD_WITH_VULKAN=OFF
- configuration: Release
compiler: gcc-13
compiler: gcc-10
cmake_options: -DFSO_BUILD_WITH_OPENGL=OFF -DFSO_BUILD_WITH_VULKAN=OFF
name: Linux
runs-on: ubuntu-latest
container: ghcr.io/scp-fs2open/linux_build:sha-1ff82e8
container: ghcr.io/scp-fs2open/linux_build:sha-3d30dc5
steps:
# - name: Cache Qt
# id: cache-qt-lin
# uses: actions/cache@v1
# with:
# path: ${{ github.workspace }}/../Qt
# key: ${{ runner.os }}-QtCache-${{ env.QT_VERSION }}
# - name: Install Qt
# uses: jurplel/install-qt-action@v2
# with:
# version: ${{ env.QT_VERSION }}
# dir: ${{ github.workspace }}/..
# cached: ${{ steps.cache-qt-lin.outputs.cache-hit }}
# setup-python: 'false'
# aqtversion: ==1.1.3
- uses: actions/checkout@v1
name: Checkout
with:
@@ -33,18 +47,17 @@ jobs:
uses: hendrikmuhs/ccache-action@v1
with:
key: ${{ runner.os }}-${{ matrix.configuration }}-${{ matrix.compiler }}
save: false # Caches are created by a separate job and only restored for PRs
verbose: 1
- name: Configure ccache
run: ccache --set-config=sloppiness=pch_defines,time_macros
- name: Prepare Vulkan SDK
uses: humbletim/[email protected]
with:
vulkan-query-version: 1.3.204.0
vulkan-components: Vulkan-Headers, Vulkan-Loader
vulkan-use-cache: true
- name: Configure CMake
env:
CONFIGURATION: ${{ matrix.configuration }}
COMPILER: ${{ matrix.compiler }}
JOB_CMAKE_OPTIONS: ${{ matrix.cmake_options }}
CCACHE_PATH: /usr/local/bin/ccache
ENABLE_QTFRED: ON
Qt5_DIR: /qt/${{ env.QT_VERSION }}/gcc_64/lib/cmake/Qt5
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Compile
working-directory: ./build
@@ -55,8 +68,6 @@ jobs:
CONFIGURATION: ${{ matrix.configuration }}
XDG_RUNTIME_DIR: /root
run: $GITHUB_WORKSPACE/ci/linux/run_tests.sh
- name: Show CCache statistics
run: ccache --show-stats
- name: Run Clang Tidy
# Clang-tidy reuses the precompiled headers so this only makes sense for the clang compilers
if: startsWith(matrix.compiler, 'clang-')
@@ -171,7 +182,7 @@ jobs:
matrix:
configuration: [Debug, Release]
compiler: [clang]
arch: [x86_64, arm64]
arch: [x86_64]
cmake_options: [""]
name: Mac
runs-on: macos-latest
@@ -199,8 +210,7 @@ jobs:
- name: ccache
uses: hendrikmuhs/ccache-action@v1
with:
key: ${{ runner.os }}-${{ matrix.configuration }}-${{ matrix.compiler }}-${{ matrix.arch }}
save: false # Caches are created by a separate job and only restored for PRs
key: ${{ runner.os }}-${{ matrix.configuration }}-${{ matrix.compiler }}
- name: Prepare Vulkan SDK
uses: humbletim/[email protected]
with:
@@ -213,7 +223,6 @@ jobs:
COMPILER: ${{ matrix.compiler }}
ARCHITECTURE: ${{ matrix.arch }}
JOB_CMAKE_OPTIONS: ${{ matrix.cmake_options }}
ENABLE_QTFRED: OFF
run: $GITHUB_WORKSPACE/ci/linux/configure_cmake.sh
- name: Compile
working-directory: ./build
@@ -222,7 +231,6 @@ jobs:
working-directory: ./build
env:
CONFIGURATION: ${{ matrix.configuration }}
ARCH: ${{ matrix.arch }}
XDG_RUNTIME_DIR: /root
run: $GITHUB_WORKSPACE/ci/linux/run_tests.sh
- name: Run Clang Tidy
+14 -3
View File
@@ -47,6 +47,20 @@ endif()
PROJECT(FS2_Open LANGUAGES ${FSO_LANGUAGES})
find_program(CCACHE_PROGRAM ccache)
# Currently only GCC support ccache properly without generating additional warnings
# Enable ccache on Mac even for clang
if(CCACHE_PROGRAM AND ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR APPLE))
if(NOT CMAKE_C_COMPILER_LAUNCHER)
message(STATUS "Using ccache for C compilation: ${CCACHE_PROGRAM}")
SET(CMAKE_C_COMPILER_LAUNCHER ${CCACHE_PROGRAM})
endif()
if(NOT CMAKE_CXX_COMPILER_LAUNCHER)
message(STATUS "Using ccache for C++ compilation: ${CCACHE_PROGRAM}")
SET(CMAKE_CXX_COMPILER_LAUNCHER ${CCACHE_PROGRAM})
endif()
endif()
IF(CMAKE_CROSSCOMPILING)
SET(IMPORT_EXE_DIR "IMPORT_EXE_DIR-NOTFOUND" CACHE FILEPATH "Required for a cross compiling build, point to binary directory of a cmake build for the real OS")
INCLUDE(${IMPORT_EXE_DIR}/ImportExecutables.cmake)
@@ -127,8 +141,6 @@ OPTION(FSO_BUILD_WITH_OPENGL_DEBUG "Enables debug option for OpenGL" OFF)
OPTION(FSO_BUILD_WITH_VULKAN "Enable compilation of the Vulkan renderer" OFF)
OPTION(FSO_BUILD_WITH_OPENXR_DEBUG "Enables debug option for OpenXR" OFF)
MARK_AS_ADVANCED(FORCE FSO_CMAKE_DEBUG)
MARK_AS_ADVANCED(FORCE FSO_BUILD_INCLUDED_LIBS)
MARK_AS_ADVANCED(FORCE FSO_USE_OPENALSOFT)
@@ -142,7 +154,6 @@ mark_as_advanced(FORCE FSO_BUILD_WITH_FFMPEG)
mark_as_advanced(FORCE FSO_BUILD_WITH_OPENGL)
mark_as_advanced(FORCE FSO_BUILD_WITH_OPENGL_DEBUG)
mark_as_advanced(FORCE FSO_BUILD_WITH_VULKAN)
mark_as_advanced(FORCE FSO_BUILD_WITH_OPENXR_DEBUG)
# Include cotire file from https://github.com/sakra/cotire/
include(cotire)
+12 -20
View File
@@ -1,16 +1,17 @@
#!/usr/bin/env bash
if [ "$COMPILER" = "gcc-9" ]; then
export CC=gcc-9
export CXX=g++-9
if [ "$COMPILER" = "gcc-5" ]; then
export CC=gcc-5
export CXX=g++-5
fi
if [ "$COMPILER" = "gcc-13" ]; then
export CC=gcc-13
export CXX=g++-13
if [ "$COMPILER" = "gcc-10" ]; then
export CC=gcc-10
export CXX=g++-10
fi
if [ "$COMPILER" = "clang-16" ]; then
export CC=clang-16
export CXX=clang++-16
if [ "$COMPILER" = "clang-9" ]; then
# Work around bug in clang that uses the wrong installation directory: https://bugs.llvm.org/show_bug.cgi?id=47460
export CC=$(readlink -f $(which clang-9))
export CXX=$(readlink -f $(which clang++-9))
fi
LD_LIBRARY_PATH=$Qt5_DIR/lib:$LD_LIBRARY_PATH
@@ -33,11 +34,6 @@ if [[ "$COMPILER" =~ ^clang.*$ ]]; then
CXXFLAGS="$CXXFLAGS -Qunused-arguments"
fi
if [ ! "$CCACHE_PATH" = "" ]; then
echo "Using ccache at $CCACHE_PATH"
CMAKE_OPTIONS="$CMAKE_OPTIONS -DCMAKE_C_COMPILER_LAUNCHER=$CCACHE_PATH -DCMAKE_CXX_COMPILER_LAUNCHER=$CCACHE_PATH"
fi
mkdir build
cd build
@@ -48,11 +44,7 @@ export LD_LIBRARY_PATH
if [ "$RUNNER_OS" = "macOS" ]; then
brew install ninja
fi
# CMAKE_JOB_POOLS and CMAKE_JOB_POOL_LINK ensure that when using ninja, link operations are done sequentially
# we have some build rules that do not play nice with parallel invocation and that fixes these issues
cmake -G Ninja -DFSO_FATAL_WARNINGS=ON -DCMAKE_EXPORT_COMPILE_COMMANDS=ON $CMAKE_OPTIONS $PLATFORM_CMAKE_OPTIONS \
-DCMAKE_INSTALL_PREFIX="$(pwd)/install" -DCMAKE_BUILD_TYPE=$CONFIGURATION \
-DFFMPEG_USE_PRECOMPILED=ON -DFSO_BUILD_TESTS=ON -DFSO_BUILD_INCLUDED_LIBS=ON -DFSO_BUILD_QTFRED=${ENABLE_QTFRED:-OFF} \
-DSHADERS_ENABLE_COMPILATION=ON -DCMAKE_JOB_POOLS=link=1 -DCMAKE_JOB_POOL_LINK=link ..
-DFFMPEG_USE_PRECOMPILED=ON -DFSO_BUILD_TESTS=ON -DFSO_BUILD_INCLUDED_LIBS=ON -DFSO_BUILD_QTFRED=OFF \
-DSHADERS_ENABLE_COMPILATION=ON ..
+4 -4
View File
@@ -26,11 +26,11 @@ elif [ "$OS" = "Windows" ]; then
echo "debug_name=$(get_package_name)-debug-$ARCH-$SIMD.7z" >> $GITHUB_OUTPUT
echo "debug_mime=$(file -b --mime-type "$(pwd)/$(get_package_name)-debug-$ARCH-$SIMD.7z")" >> $GITHUB_OUTPUT
elif [ "$OS" = "Mac" ]; then
tar -cvzf "$(get_package_name)-builds-Mac-$ARCH.tar.gz" *.app
tar -cvzf "$(get_package_name)-builds-Mac.tar.gz" *.app
echo "package_path=$(pwd)/$(get_package_name)-builds-Mac-$ARCH.tar.gz" >> $GITHUB_OUTPUT
echo "package_name=$(get_package_name)-builds-Mac-$ARCH.tar.gz" >> $GITHUB_OUTPUT
echo "package_mime=$(file -b --mime-type "$(pwd)/$(get_package_name)-builds-Mac-$ARCH.tar.gz")" >> $GITHUB_OUTPUT
echo "package_path=$(pwd)/$(get_package_name)-builds-Mac.tar.gz" >> $GITHUB_OUTPUT
echo "package_name=$(get_package_name)-builds-Mac.tar.gz" >> $GITHUB_OUTPUT
echo "package_mime=$(file -b --mime-type "$(pwd)/$(get_package_name)-builds-Mac.tar.gz")" >> $GITHUB_OUTPUT
else
echo "Invalid OS: $OS"
fi
-7
View File
@@ -5,13 +5,6 @@ HERE=$(dirname "$SCRIPT")
export LD_LIBRARY_PATH=$(pwd)/bin/lib:$LD_LIBRARY_PATH
# if on mac and building for architecture that doesn't match host
# then unittests will fail so we just need to skip it (for now)
if [ "$RUNNER_OS" = "macOS" ] && [ "$ARCH" != "$(uname -m)" ]; then
echo "Skipping tests due to architecture mismatch!"
exit 0
fi
if [ "$CONFIGURATION" = "Debug"] && [[ "$RUNNER_OS" != "macOS" ]] ; then
valgrind --leak-check=full --error-exitcode=1 --gen-suppressions=all \
--suppressions="$HERE/valgrind.supp" ./bin/unittests --gtest_shuffle
+5 -9
View File
@@ -8,8 +8,7 @@ from file_list import ReleaseFile
from util import retry_multi, GLOBAL_TIMEOUT
LINUX_KEY = "Linux"
MACOSX_X64_KEY = "Mac-x86_64"
MACOSX_ARM64_KEY = "Mac-arm64"
MACOSX_KEY = "Mac"
WIN32_SSE2_KEY = "Win32-SSE2"
WIN64_SSE2_KEY = "Win64-SSE2"
WIN32_AVX_KEY = "Win32-AVX"
@@ -35,8 +34,7 @@ metadata = {
platforms = {
LINUX_KEY: 'linux',
MACOSX_X64_KEY: 'macosx',
MACOSX_ARM64_KEY: 'macosx',
MACOSX_KEY: 'macosx',
WIN32_SSE2_KEY: 'windows',
WIN64_SSE2_KEY: 'windows',
WIN32_AVX_KEY: 'windows',
@@ -45,8 +43,7 @@ platforms = {
envs = {
LINUX_KEY: 'linux && x86_64', # Linux only has 64bit builds
MACOSX_X64_KEY: 'macosx && x86_64',
MACOSX_ARM64_KEY: 'macosx && arm64',
MACOSX_KEY: 'macosx',
WIN32_SSE2_KEY: 'windows',
WIN64_SSE2_KEY: 'windows && x86_64',
WIN32_AVX_KEY: 'windows && avx',
@@ -138,7 +135,7 @@ def render_nebula_release(version, stability, files, config):
'label': label,
'properties': props,
})
elif group.startswith('Mac') and fn.startswith(os.path.basename(fn) + '.app/'):
elif group == MACOSX_KEY and fn.startswith(os.path.basename(fn) + '.app/'):
if 'qtfred' in fn:
if '-FASTDBG' in fn:
label = 'QtFRED Debug'
@@ -151,8 +148,7 @@ def render_nebula_release(version, stability, files, config):
label = None
props = {
"arm64": "arm64" in fn,
"x64": "x64" in fn,
"x64": True, # All Mac builds are 64-bit
"sse2": True, # There are no forced options on mac but 64-bit always implies SSE2 so we set that here
"avx": False,
"avx2": False,
+7 -8
View File
@@ -7,15 +7,15 @@ PLACEHOLDER
[b]Deprecations:[/b]
PLACEHOLDER
Deprecations are a mechanism in FSO where a certain feature or aspect of the engine has changed or is no longer supported. Since this would normally break existing mods, we have the mod table feature "[tt]$Target Version:[/tt]" with which a mod can specify what version of FSO it was developed with. Any features listed under Deprecations will be removed or changed when the target version of a mod is at least the version released in this post.
Deprecations are a mechanism in FSO where a certain feature or aspect of the engine has changed or is no longer supported. Since this would normally break existing mods we have the mod table feature "[tt]$Target Version:[/tt]" with which a mod can specify what version of FSO it was developed with. The features listed above will be removed or changed when the target version of a mod is at least the version released in this post.
[size=5pt]Previous [url=https://www.hard-light.net/forums/index.php?topic=99015.0]23.2.1 Release Thread[/url][/size]
[size=5pt]Previous [url=https://www.hard-light.net/forums/index.php?topic=98682.0]23.0.0 Release Thread[/url][/size]
Launchers, if you don't have one already:
[b]All platforms: [/b] For every day use, we recommend [url=https://knossosnet.github.io/Knossos-Release-Page/]Knossos.NET[/url], an integrated solution for downloading and launching mods.
[b]All platforms: [/b] For every day use, we recommend [url=https://www.hard-light.net/forums/index.php?topic=94068.0]Knossos[/url], an integrated solution for downloading and launching mods.
[hidden=Alternative Launchers]
Cross-platform: [url=https://www.hard-light.net/forums/index.php?topic=89162]wxLauncher 0.12.x Test Build[/url] (legacy project for a unified launcher)
Cross-platform: [url=https://www.hard-light.net/forums/index.php?topic=89162]wxLauncher 0.12.x Test Build[/url] (ongoing project for a unified launcher, you should upgrade to the latest RC/test build if you have not yet)
[b]Important:[/b] For best compatibility with FSO 3.8 and later you should use at least wxLauncher 0.12.
Windows: [url=http://scp.fsmods.net/builds/Launcher55g.zip]Launcher 5.5g[/url] ([url=https://scp.indiegames.us/builds/Launcher55g.zip]Mirror[/url]) ([url=https://www.mediafire.com/?wdvzn7hhhzh418m]Mirror[/url]) Not compatible with Windows 8+, use wxLauncher above
@@ -41,7 +41,7 @@ Linux: [url=https://www.hard-light.net/forums/index.php/topic,53206.0.html]YAL[
[b]What are those SSE, SSE2 and AVX builds I keep seeing everywhere?[/b]
[url=https://www.hard-light.net/forums/index.php?topic=65628.0]Your answer is in this topic.[/url]
Don't want to deal with that? Use [url=https://knossosnet.github.io/Knossos-Release-Page/]Knossos.NET[/url] and it will download the best build specifically for your PC!
Don't want to deal with that? Use [url=https://www.hard-light.net/forums/index.php?topic=94068.0]Knossos[/url] and it will download the best build specifically for your PC!
[/hidden]
[img]https://scp.indiegames.us/img/linux-icon.png[/img] [color=green][size=12pt]Linux 64-bit[/size][/color]
@@ -53,9 +53,8 @@ Alternatively, if there is a package in your software repository then you should
[img]https://scp.indiegames.us/img/mac-icon.png[/img] [color=green][size=12pt]macOS[/size][/color]
[size=8pt]macOS 10.9+[/size]
[b]Intel (64-bit):[/b] ${build(groups["Mac"].subFiles["x86_64"])}
[b]Apple Silicon:[/b] ${build(groups["Mac"].subFiles["arm64"])}
[size=8pt]macOS 10.9+, 64-bit (Intel)[/size]
${build(groups["Mac"].mainFile)}
These builds are not signed and so by default will fail to launch. To run them simply right-click on the app, click open, then click open again on the security confirmation dialog. You should only have to do this once for each app.
If running the game through Knossos or Knossos.NET this step should not be necessary.
-6
View File
@@ -7,9 +7,3 @@ if (CMAKE_SIZEOF_VOID_P EQUAL 8)
else()
set(IS_64BIT FALSE)
endif()
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(aarch64|arm64|ARM64)")
set(IS_ARM64 TRUE)
else()
set(IS_ARM64 FALSE)
endif()
-8
View File
@@ -22,14 +22,6 @@ SET(LIBRAY_DESTINATION "../Frameworks")
set(PLATFORM_MAC TRUE CACHE INTERNAL "" FORCE)
# Maybe override arm64 setting if we are compiling for different architecture
# If not specified, or if it's a universal build, then this should do nothing
if(CMAKE_OSX_ARCHITECTURES MATCHES "arm64")
set(IS_ARM64 TRUE)
elseif(CMAKE_OSX_ARCHITECTURES MATCHES "x86_64")
set(IS_ARM64 FALSE)
endif()
# Generate and don't strip debug symbols
# These settings don't seem to generate debug symbols for code and Freespace2
# so those settings are set manually in code and Freespace2's CMakeLists.txt files
-1
View File
@@ -9,7 +9,6 @@
#cmakedefine SCP_HAVE_STD_MAX_ALIGN_T
#cmakedefine01 IS_64BIT
#cmakedefine01 IS_ARM64
#cmakedefine01 SCP_HAVE_STRCASECMP
#cmakedefine01 SCP_HAVE_STRNCASECMP
+8 -29
View File
@@ -83,41 +83,20 @@ if(SUPPORTS_SHIFT_NEGATIVE_VALUE)
set(COMPILER_FLAGS "${COMPILER_FLAGS} -Wno-shift-negative-value")
endif()
# Check if there is a user-set optimisation flag
string(REGEX MATCH "-O[a-zA-Z|0-9]+" CXX_OPT_FLAG ${CXX_BASE_FLAGS})
string(REGEX MATCH "-O[a-zA-Z|0-9]+" C_OPT_FLAG ${C_BASE_FLAGS})
set(COMPILER_FLAGS_RELEASE "-O2 -Wno-unused-variable -Wno-unused-parameter")
# If no user-set opt flag, set -O2 and -Og
if ("${CXX_OPT_FLAG}" STREQUAL "")
set(CXX_OPT_FLAG_RELEASE "-O2")
set(CXX_OPT_FLAG_DEBUG "-Og")
else()
set(CXX_OPT_FLAG_RELEASE "${CXX_OPT_FLAG}")
set(CXX_OPT_FLAG_DEBUG "${CXX_OPT_FLAG}")
endif()
if ("${C_OPT_FLAG}" STREQUAL "")
set(C_OPT_FLAG_RELEASE "-O2")
set(C_OPT_FLAG_DEBUG "-Og")
else()
set(C_OPT_FLAG_RELEASE "${C_OPT_FLAG}")
set(C_OPT_FLAG_DEBUG "${C_OPT_FLAG}")
endif()
set(COMPILER_FLAGS_DEBUG "-Og -g -Wshadow")
set(CXX_FLAGS_RELEASE "${CXX_OPT_FLAG_RELEASE} -Wno-unused-variable -Wno-unused-parameter")
set(C_FLAGS_RELEASE "${C_OPT_FLAG_RELEASE} -Wno-unused-variable -Wno-unused-parameter")
set(CXX_FLAGS_DEBUG "${CXX_OPT_FLAG_DEBUG} -g -Wshadow")
set(C_FLAGS_DEBUG "${C_OPT_FLAG_DEBUG} -g -Wshadow")
# Always use the base flags and add our compiler flags at the back
# Always use the base flags and add our compiler flags at the bacl
set(CMAKE_CXX_FLAGS "${CXX_BASE_FLAGS} ${COMPILER_FLAGS}")
set(CMAKE_C_FLAGS "${C_BASE_FLAGS} ${COMPILER_FLAGS}")
set(CMAKE_CXX_FLAGS_RELEASE ${CXX_FLAGS_RELEASE})
set(CMAKE_C_FLAGS_RELEASE ${C_FLAGS_RELEASE})
set(CMAKE_CXX_FLAGS_RELEASE ${COMPILER_FLAGS_RELEASE})
set(CMAKE_C_FLAGS_RELEASE ${COMPILER_FLAGS_RELEASE})
set(CMAKE_CXX_FLAGS_DEBUG ${COMPILER_FLAGS_DEBUG})
set(CMAKE_C_FLAGS_DEBUG ${COMPILER_FLAGS_DEBUG})
set(CMAKE_CXX_FLAGS_DEBUG ${CXX_FLAGS_DEBUG})
set(CMAKE_C_FLAGS_DEBUG ${C_FLAGS_DEBUG})
set(CMAKE_EXE_LINKER_FLAGS "")
+6 -28
View File
@@ -113,41 +113,19 @@ if(SUPPORTS_STRINGOP_TRUNCATION)
set(COMPILER_FLAGS "${COMPILER_FLAGS} -Wno-stringop-overflow")
endif()
# Check if there is a user-set optimisation flag
string(REGEX MATCH "-O[a-zA-Z|0-9]+" CXX_OPT_FLAG ${CXX_BASE_FLAGS})
string(REGEX MATCH "-O[a-zA-Z|0-9]+" C_OPT_FLAG ${C_BASE_FLAGS})
set(COMPILER_FLAGS_RELEASE "-O2 -Wno-unused-variable -Wno-unused-but-set-variable -Wno-array-bounds -Wno-empty-body -Wno-clobbered -Wno-unused-parameter")
# If no user-set opt flag, set -O2 and -Og
if ("${CXX_OPT_FLAG}" STREQUAL "")
set(CXX_OPT_FLAG_RELEASE "-O2")
set(CXX_OPT_FLAG_DEBUG "-Og")
else()
set(CXX_OPT_FLAG_RELEASE "${CXX_OPT_FLAG}")
set(CXX_OPT_FLAG_DEBUG "${CXX_OPT_FLAG}")
endif()
if ("${C_OPT_FLAG}" STREQUAL "")
set(C_OPT_FLAG_RELEASE "-O2")
set(C_OPT_FLAG_DEBUG "-Og")
else()
set(C_OPT_FLAG_RELEASE "${C_OPT_FLAG}")
set(C_OPT_FLAG_DEBUG "${C_OPT_FLAG}")
endif()
set(CXX_FLAGS_RELEASE "${CXX_OPT_FLAG_RELEASE} -Wno-unused-variable -Wno-unused-but-set-variable -Wno-array-bounds -Wno-empty-body -Wno-clobbered -Wno-unused-parameter")
set(C_FLAGS_RELEASE "${C_OPT_FLAG_RELEASE} -Wno-unused-variable -Wno-unused-but-set-variable -Wno-array-bounds -Wno-empty-body -Wno-clobbered -Wno-unused-parameter")
set(CXX_FLAGS_DEBUG "${CXX_OPT_FLAG_DEBUG} -g -Wshadow")
set(C_FLAGS_DEBUG "${C_OPT_FLAG_DEBUG} -g -Wshadow")
set(COMPILER_FLAGS_DEBUG "-Og -g -Wshadow")
# Always use the base flags and add our compiler flags at the back
set(CMAKE_CXX_FLAGS "${CXX_BASE_FLAGS} ${COMPILER_FLAGS}")
set(CMAKE_C_FLAGS "${C_BASE_FLAGS} ${COMPILER_FLAGS}")
set(CMAKE_CXX_FLAGS_RELEASE ${CXX_FLAGS_RELEASE})
set(CMAKE_C_FLAGS_RELEASE ${C_FLAGS_RELEASE})
set(CMAKE_CXX_FLAGS_RELEASE ${COMPILER_FLAGS_RELEASE})
set(CMAKE_C_FLAGS_RELEASE ${COMPILER_FLAGS_RELEASE})
set(CMAKE_CXX_FLAGS_DEBUG ${CXX_FLAGS_DEBUG})
set(CMAKE_C_FLAGS_DEBUG ${C_FLAGS_DEBUG})
set(CMAKE_CXX_FLAGS_DEBUG ${COMPILER_FLAGS_DEBUG})
set(CMAKE_C_FLAGS_DEBUG ${COMPILER_FLAGS_DEBUG})
set(CMAKE_EXE_LINKER_FLAGS "${LINKER_FLAGS}")
+3 -5
View File
@@ -6,8 +6,8 @@ if (EXISTS "${PROJECT_SOURCE_DIR}/version_override.cmake")
include("${PROJECT_SOURCE_DIR}/version_override.cmake")
endif()
set_if_not_defined(FSO_VERSION_MAJOR 24)
set_if_not_defined(FSO_VERSION_MINOR 1)
set_if_not_defined(FSO_VERSION_MAJOR 23)
set_if_not_defined(FSO_VERSION_MINOR 3)
set_if_not_defined(FSO_VERSION_BUILD 0)
# A numeric revision e.g. the CI build number
@@ -35,9 +35,7 @@ ELSE()
SET(FSO_BINARY_SUFFIX "${FSO_VERSION_MAJOR}_${FSO_VERSION_MINOR}_${FSO_VERSION_BUILD}_${FSO_VERSION_REVISION_STR}")
ENDIF()
IF(IS_ARM64)
SET(FSO_BINARY_SUFFIX "${FSO_BINARY_SUFFIX}_arm64")
ELSEIF(IS_64BIT)
IF(IS_64BIT)
# This is a 64-bit builds
SET(FSO_BINARY_SUFFIX "${FSO_BINARY_SUFFIX}_x64")
ENDIF()
-15
View File
@@ -25,10 +25,6 @@ if (FSO_BUILD_WITH_OPENGL)
endif()
endif()
if(FSO_BUILD_WITH_OPENXR_DEBUG)
add_definitions(-DFS_OPENXR_DEBUG)
endif()
TARGET_LINK_LIBRARIES(code PUBLIC openal)
TARGET_LINK_LIBRARIES(code PUBLIC ${LUA_LIBS})
TARGET_LINK_LIBRARIES(code PUBLIC ${PNG_LIBS})
@@ -79,17 +75,6 @@ target_link_libraries(code PUBLIC hidapi::hidapi)
target_link_libraries(code PUBLIC imgui)
IF(NOT APPLE)
target_link_libraries(code PUBLIC OpenXR::openxr_loader)
target_include_directories(code PUBLIC OpenXR::Headers)
ENDIF()
IF(CMAKE_SYSTEM_NAME MATCHES "Linux")
# On Linux, we need to access X11 window data.
# On Windows, SDL already provides everything, so no need to do anything
find_package(X11)
target_link_libraries(code PUBLIC ${X11_LIBRARIES})
ENDIF()
# Headers for standalone "gui" on UNIX
IF(UNIX)
TARGET_LINK_LIBRARIES(code PUBLIC ${MONGOOSE_LIBS})
+1 -1
View File
@@ -47,7 +47,7 @@ ProgramInstance::ProgramInstance(const actions::Program* program) : _program(pro
ProgramState ProgramInstance::step()
{
if (!_locals.host.isValid()) {
if (!_locals.host.IsValid()) {
return ProgramState::Done;
}
+5 -5
View File
@@ -277,7 +277,7 @@ typedef struct ai_info {
// Probably become obsolete, to be replaced by path_start, path_cur, etc.
waypoint_list *wp_list; // waypoint list being followed
int wp_index; // waypoint index in list
size_t wp_index; // waypoint index in list
int wp_flags; // waypoint flags, see WPF_xxxx
int waypoint_speed_cap; // -1 no cap, otherwise cap - changed to int by Goober5000
@@ -533,11 +533,11 @@ extern void ai_ignore_wing(object *ignorer, int wingnum);
extern void ai_dock_with_object(object *docker, int docker_index, object *dockee, int dockee_index, int dock_type);
extern void ai_stay_still(object *still_objp, vec3d *view_pos);
extern void ai_do_default_behavior(object *obj);
extern void ai_start_waypoints(object *objp, waypoint_list *wp_list, int wp_flags, int start_index);
extern void ai_start_waypoints(object *objp, waypoint_list *wp_list, int wp_flags);
extern void ai_ship_hit(object *objp_ship, object *hit_objp, vec3d *hit_normal);
extern void ai_ship_destroy(int shipnum);
extern vec3d ai_get_acc_limit(vec3d* vel_limit, const object* objp);
extern void ai_turn_towards_vector(const vec3d *dest, object *objp, const vec3d *slide_vec, const vec3d *rel_pos, float bank_override, int flags, const vec3d *rvec = nullptr, const vec3d* turnrate_mod = nullptr);
extern void ai_turn_towards_vector(vec3d *dest, object *objp, vec3d *slide_vec, vec3d *rel_pos, float bank_override, int flags, vec3d *rvec = nullptr, vec3d* turnrate_mod = nullptr);
extern void init_ai_object(int objnum);
extern void ai_init(void); // Call this one to parse ai.tbl.
extern void ai_level_init(void); // Call before each level to reset AI
@@ -597,8 +597,8 @@ extern void set_predicted_enemy_pos(vec3d *predicted_enemy_pos, object *pobjp, v
extern int is_instructor(object *objp);
extern int find_enemy(int objnum, float range, int max_attackers, int ship_info_index = -1);
float ai_get_weapon_speed(const ship_weapon *swp);
void set_predicted_enemy_pos_turret(vec3d *predicted_enemy_pos, const vec3d *gun_pos, const object *pobjp, const vec3d *enemy_pos, const vec3d *enemy_vel, float weapon_speed, float time_enemy_in_range);
float ai_get_weapon_speed(ship_weapon *swp);
void set_predicted_enemy_pos_turret(vec3d *predicted_enemy_pos, vec3d *gun_pos, object *pobjp, vec3d *enemy_pos, vec3d *enemy_vel, float weapon_speed, float time_enemy_in_range);
// function to change rearm status for ai ships (called from sexpression code)
extern void ai_set_rearm_status( int team, int new_status );
-3
View File
@@ -47,7 +47,6 @@ namespace AI {
Depart_sound_played,// Goober5000 - replacement for AL's hack ;)
Target_own_team, // this attack goal is allowed to target friendlies
Afterburn_hard, // afterburn as hard as possible to the goal
Waypoints_in_reverse, // decrement instead of increment
NUM_VALUES
};
@@ -157,9 +156,7 @@ namespace AI {
Whackable_debris,
Whackable_asteroids,
Dynamic_goals_afterburn_hard,
Player_orders_afterburn_hard,
Hudsquadmsg_tactical_disarm_disable,
Align_to_target_when_guarding_still,
NUM_VALUES
};
+4 -8
View File
@@ -258,7 +258,7 @@ void parse_ai_profiles_tbl(const char *filename)
if (optional_string("$Glide Attack Percent:")) {
parse_float_list(profile->glide_attack_percent, NUM_SKILL_LEVELS);
//Percent is nice for modders, but here in the code we want it between 0 and 1.0
//Percent is nice for modders, but here in the code we want it betwwen 0 and 1.0
//While we're at it, verify the range
for (i = 0; i < NUM_SKILL_LEVELS; i++) {
if (profile->glide_attack_percent[i] < 0.0f || profile->glide_attack_percent[i] > 100.0f) {
@@ -271,7 +271,7 @@ void parse_ai_profiles_tbl(const char *filename)
if (optional_string("$Circle Strafe Percent:")) {
parse_float_list(profile->circle_strafe_percent, NUM_SKILL_LEVELS);
//Percent is nice for modders, but here in the code we want it between 0 and 1.0
//Percent is nice for modders, but here in the code we want it betwwen 0 and 1.0
//While we're at it, verify the range
for (i = 0; i < NUM_SKILL_LEVELS; i++) {
if (profile->circle_strafe_percent[i] < 0.0f || profile->circle_strafe_percent[i] > 100.0f) {
@@ -284,7 +284,7 @@ void parse_ai_profiles_tbl(const char *filename)
if (optional_string("$Glide Strafe Percent:")) {
parse_float_list(profile->glide_strafe_percent, NUM_SKILL_LEVELS);
//Percent is nice for modders, but here in the code we want it between 0 and 1.0
//Percent is nice for modders, but here in the code we want it betwwen 0 and 1.0
//While we're at it, verify the range
for (i = 0; i < NUM_SKILL_LEVELS; i++) {
if (profile->glide_strafe_percent[i] < 0.0f || profile->glide_strafe_percent[i] > 100.0f) {
@@ -297,7 +297,7 @@ void parse_ai_profiles_tbl(const char *filename)
if (optional_string("$Random Sidethrust Percent:")) {
parse_float_list(profile->random_sidethrust_percent, NUM_SKILL_LEVELS);
//Percent is nice for modders, but here in the code we want it between 0 and 1.0
//Percent is nice for modders, but here in the code we want it betwwen 0 and 1.0
//While we're at it, verify the range
for (i = 0; i < NUM_SKILL_LEVELS; i++) {
if (profile->random_sidethrust_percent[i] < 0.0f || profile->random_sidethrust_percent[i] > 100.0f) {
@@ -625,12 +625,8 @@ void parse_ai_profiles_tbl(const char *filename)
set_flag(profile, "$dynamic goals afterburn hard:", AI::Profile_Flags::Dynamic_goals_afterburn_hard);
set_flag(profile, "$player orders afterburn hard:", AI::Profile_Flags::Player_orders_afterburn_hard);
set_flag(profile, "$hud squad messages use tactical disarm/disable:", AI::Profile_Flags::Hudsquadmsg_tactical_disarm_disable);
set_flag(profile, "$align to target when guarding stationary ship:", AI::Profile_Flags::Align_to_target_when_guarding_still);
// if we've been through once already and are at the same place, force a move
if (saved_Mp && (saved_Mp == Mp))
{
+10 -9
View File
@@ -76,7 +76,7 @@ extern void big_ship_collide_recover_start(object *objp, object *big_objp, vec3d
// If truly_random flag set (haha), then generate a pretty random number. Otherwise, generate a static rand which
// tends to not change from frame to frame.
// Try four times and choose nearest point to increase chance of getting a good point.
void ai_bpap(const object *objp, const vec3d *attacker_objp_pos, const vec3d *attacker_objp_fvec, vec3d *attack_point, vec3d *local_attack_point, float fov, float weapon_travel_dist, vec3d *surface_normal, const ship_subsys *ss)
void ai_bpap(object *objp, vec3d *attacker_objp_pos, vec3d *attacker_objp_fvec, vec3d *attack_point, vec3d *local_attack_point, float fov, float weapon_travel_dist, vec3d *surface_normal, ship_subsys *ss)
{
float nearest_dist;
vec3d result_point, best_point;
@@ -193,7 +193,7 @@ done_1:
//
// Note: Default value for fov is 1.0f 1.0f means don't use fov parameter.
// If fov != 1.0f, try up to four times to find a point that's in the field of view.
void ai_big_pick_attack_point_turret(const object *objp, ship_subsys *ssp, const vec3d *gpos, const vec3d *gvec, vec3d *attack_point, float fov, float weapon_travel_dist)
void ai_big_pick_attack_point_turret(object *objp, ship_subsys *ssp, vec3d *gpos, vec3d *gvec, vec3d *attack_point, float fov, float weapon_travel_dist)
{
if (!timestamp_elapsed(ssp->turret_pick_big_attack_point_timestamp)) {
vec3d result_point;
@@ -213,7 +213,7 @@ void ai_big_pick_attack_point_turret(const object *objp, ship_subsys *ssp, const
// Note: Default value for fov is 1.0f 1.0f means don't use fov parameter.
// If fov != 1.0f, try up to four times to find a point that's in the field of view.
// Note, attacker_objp can be a ship or a weapon.
void ai_big_pick_attack_point(const object *objp, const object *attacker_objp, vec3d *attack_point, float fov)
void ai_big_pick_attack_point(object *objp, object *attacker_objp, vec3d *attack_point, float fov)
{
Assert(objp->instance > -1);
Assert(objp->type == OBJ_SHIP);
@@ -411,7 +411,7 @@ int ai_big_maybe_follow_subsys_path(int do_dot_check)
}
}
if ( ship_subsystem_in_sight(En_objp, aip->targeted_subsys, &geye, &gsubpos, true) ) {
if ( ship_subsystem_in_sight(En_objp, aip->targeted_subsys, &geye, &gsubpos, 1) ) {
subsys_in_sight = 1;
}
}
@@ -538,15 +538,15 @@ bool ai_new_maybe_reposition_attack_subsys() {
model_local_to_global_point(&geye, &ep->pnt, pm, 0, &Pl_objp->orient, &Pl_objp->pos);
// get world pos of subsystem
get_subsystem_pos(&gsubpos, target_objp, aip->targeted_subsys);
polymodel* tgt_pm = model_get(Ship_info[Ships[target_objp->instance].ship_info_index].model_num);
model_local_to_global_point(&gsubpos, &vmd_zero_vector, tgt_pm, aip->targeted_subsys->system_info->subobj_num, &En_objp->orient, &En_objp->pos);
// you're in sight! shoot it!
if (ship_subsystem_in_sight(En_objp, aip->targeted_subsys, &geye, &gsubpos, false))
if (ship_subsystem_in_sight(En_objp, aip->targeted_subsys, &geye, &gsubpos, 0))
return false;
// not in sight, gotta get there
vec3d* good_pos = nullptr;
vec3d world_goal_pos;
// For performance reasons we only recheck once a second, otherwise we reuse the last found target.
if (timestamp_elapsed(aip->next_dynamic_path_check_time)) {
vec3d tgt2pl = Pl_objp->pos - target_objp->pos;
@@ -568,6 +568,7 @@ bool ai_new_maybe_reposition_attack_subsys() {
vm_rot_point_around_line(&goal_pos, &tgt2pl, angle2goal, &vmd_zero_vector, &cross);
// then scale in (or out) towards our subsys
vec3d world_goal_pos;
float new_radius = ((subsys_dist - pl_dist) * (angle2goal / angle2subsys)) + pl_dist;
vm_vec_copy_scale(&world_goal_pos, &goal_pos, new_radius / pl_dist);
world_goal_pos += target_objp->pos;
@@ -1034,7 +1035,7 @@ void ai_big_chase()
ai_big_pick_attack_point(En_objp, Pl_objp, &enemy_pos, 0.8f);
weapon_info* wip = ai_get_weapon(&shipp->weapons);
bool ballistic_aiming = !IS_VEC_NULL(&The_mission.gravity) && wip && wip->gravity_const != 0.0f;
bool ballistic_aiming = !IS_VEC_NULL(&The_mission.gravity) && wip->gravity_const != 0.0f;
bool valid_ballistic_trajectory = true;
if (!ballistic_aiming) {
@@ -1841,7 +1842,7 @@ void ai_big_strafe()
/*
if ( aip->goal_objnum != aip->target_objnum ) {
UNREACHABLE("The goal objnum does not match the target objnum in ai_big_strafe(), please report to the SCP!"); // what is going on here? - Get Alan
Int3(); // what is going on here? - Get Alan
aip->mode = AIM_NONE;
return;
}
+2 -2
View File
@@ -24,8 +24,8 @@ void ai_big_subsys_path_cleanup(ai_info *aip);
void ai_big_strafe();
int ai_big_maybe_enter_strafe_mode(const object *objp, int weapon_objnum);
void ai_big_strafe_maybe_attack_turret(const object *ship_objp, const object *weapon_objp);
void ai_big_pick_attack_point(const object *objp, const object *attacker_objp, vec3d *attack_point, float fov=1.0f);
void ai_big_pick_attack_point_turret(const object *objp, ship_subsys *ssp, const vec3d *gpos, const vec3d *gvec, vec3d *attack_point, float weapon_travel_dist, float fov=1.0f);
void ai_big_pick_attack_point(object *objp, object *attacker_objp, vec3d *attack_point, float fov=1.0f);
void ai_big_pick_attack_point_turret(object *objp, ship_subsys *ssp, vec3d *gpos, vec3d *gvec, vec3d *attack_point, float weapon_travel_dist, float fov=1.0f);
// default distance for following subsystem path points --wookieejedi
// the value is 5 because that was the original value specified in ai_big_maybe_follow_subsys_path()
+135 -291
View File
@@ -287,15 +287,6 @@ float AI_frametime;
char** Ai_class_names = NULL;
//used for good-primary-time
typedef struct {
object_ship_wing_point_team subject;
object_ship_wing_point_team target;
int weapon_index;
} primary_fire_info;
static SCP_vector<primary_fire_info> Preferred_primary_info;
typedef struct {
int team;
int weapon_index;
@@ -303,7 +294,7 @@ typedef struct {
int ship_registry_index;
} huge_fire_info;
static SCP_vector<huge_fire_info> Ai_huge_fire_info;
SCP_vector<huge_fire_info> Ai_huge_fire_info;
int Ai_last_arrive_path; // index of ship_bay path used by last arrival from a fighter bay
@@ -395,10 +386,10 @@ int is_preferred_weapon(int weapon_num, object *firer_objp, object *target_objp)
continue;
auto ship_entry = &Ship_registry[hfi->ship_registry_index];
if (!ship_entry->has_objp())
if (!ship_entry->objp)
continue;
int signature = ship_entry->objp()->signature;
int signature = ship_entry->objp->signature;
// sigatures, weapon_index, and team must match
if ( (signature == target_signature) && (hfi->weapon_index == weapon_num) && (hfi->team == firer_team) )
@@ -1010,9 +1001,6 @@ void ai_level_init()
ai_init_secondary_info();
Ai_last_arrive_path=0;
// clear out the preferred primaries so that it doesn't persist between missions or between mission reloads
Preferred_primary_info.clear();
}
// BEGIN STEALTH
@@ -1021,7 +1009,7 @@ void ai_level_init()
/**
* Check if object is a stealth ship
*/
bool is_object_stealth_ship(const object *objp)
bool is_object_stealth_ship(object* objp)
{
if (objp->type == OBJ_SHIP) {
if (Ships[objp->instance].flags[Ship::Ship_Flags::Stealth]) {
@@ -1109,7 +1097,7 @@ float get_skill_stealth_dot_scaler()
return 1.0f;
}
int ai_is_stealth_visible(const object *viewer_objp, const object *stealth_objp)
int ai_is_stealth_visible(object *viewer_objp, object *stealth_objp)
{
ship *shipp;
vec3d vec_to_stealth;
@@ -1315,7 +1303,7 @@ void ai_compensate_for_retail_turning(vec3d* vel_limit, vec3d* acc_limit, float
// If rvec != NULL, use it to match bank by calling vm_angular_move_matrix.
// (rvec defaults to NULL)
// optionally specified turnrate_mod contains multipliers for each component of the turnrate (RATE, so 0.5 = slower)
void ai_turn_towards_vector(const vec3d* dest, object* objp, const vec3d* slide_vec, const vec3d* rel_pos, float bank_override, int flags, const vec3d* rvec, const vec3d* turnrate_mod)
void ai_turn_towards_vector(vec3d* dest, object* objp, vec3d* slide_vec, vec3d* rel_pos, float bank_override, int flags, vec3d* rvec, vec3d* turnrate_mod)
{
matrix curr_orient;
vec3d vel_in, vel_out, desired_fvec, src;
@@ -1328,7 +1316,7 @@ void ai_turn_towards_vector(const vec3d* dest, object* objp, const vec3d* slide_
// Don't allow a ship to turn if it has no engine strength.
// AL 3-12-98: objp may not always be a ship!
if ( (objp->type == OBJ_SHIP) && !(flags & AITTV_VIA_SEXP) ) {
if (!Ships[objp->instance].flags[Ship::Ship_Flags::Maneuver_despite_engines] && ship_subsystems_blown(&Ships[objp->instance], SUBSYSTEM_ENGINE))
if (!Ships[objp->instance].flags[Ship::Ship_Flags::Maneuver_despite_engines] && ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f)
return;
}
@@ -1905,7 +1893,7 @@ int Player_attacking_enabled = 1;
/**
* Determine whether an object is targetable within a nebula
*/
bool object_is_targetable(const object *target, const ship *viewer)
int object_is_targetable(object *target, ship *viewer)
{
// if target is ship, check if visible by team
if (target->type == OBJ_SHIP)
@@ -2413,7 +2401,7 @@ int find_nearby_threat(int objnum, int enemy_team_mask, float range, int *count)
/**
* Number of live turrets with target_objnum
*/
int num_turrets_attacking(const object *turret_parent, int target_objnum)
int num_turrets_attacking(object *turret_parent, int target_objnum)
{
ship_subsys *ss;
ship *shipp;
@@ -2579,7 +2567,7 @@ void ai_attack_object(object* attacker, object* attacked, int ship_info_index)
}
// don't abort a support call if you're disabled!
if (!ship_subsystems_blown(&Ships[attacker->instance], SUBSYSTEM_ENGINE))
if (ship_get_subsystem_strength(&Ships[attacker->instance], SUBSYSTEM_ENGINE) > 0.0f)
ai_set_goal_abort_support_call(attacker, aip);
aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME); // No dynamic targeting for 7 seconds.
@@ -2655,7 +2643,7 @@ void ai_evade_object(object *evader, object *evaded)
Assert(Ships[evader->instance].ai_index != -1);
if (evaded == evader) {
UNREACHABLE("Ship %s is trying to evade itself. Please report to the SCP!", Ships[evader->instance].ship_name); // Bogus! Who tried to get me to evade myself! Trace out and fix!
Int3(); // Bogus! Who tried to get me to evade myself! Trace out and fix!
return;
}
@@ -3416,7 +3404,7 @@ void ai_dock_with_object(object *docker, int docker_index, object *dockee, int d
aip->submode_start_time = Missiontime;
break;
default:
UNREACHABLE("Unknown dock type in ai_dock_with_object of %d. Please report to the SCP!", dock_type); // Bogus dock_type.
Int3(); // Bogus dock_type.
}
// Goober5000 - we no longer need to set dock_path_index because it's easier to grab the path from the dockpoint
@@ -3476,19 +3464,12 @@ void ai_dock_with_object(object *docker, int docker_index, object *dockee, int d
// Cause a ship to fly its waypoints.
// flags tells:
// WPF_REPEAT Set -> repeat waypoints.
// WPF_BACKTRACK Go in reverse.
void ai_start_waypoints(object *objp, waypoint_list *wp_list, int wp_flags, int start_index)
// WPF_REPEAT Set -> repeat waypoints.
void ai_start_waypoints(object *objp, waypoint_list *wp_list, int wp_flags)
{
ai_info *aip;
Assert(wp_list != NULL);
if (start_index < 0 || start_index >= (int)wp_list->get_waypoints().size())
{
Warning(LOCATION, "Starting index for %s on '%s' is out of range!", Ships[objp->instance].ship_name, wp_list->get_name());
start_index = (wp_flags & WPF_BACKTRACK) ? (int)wp_list->get_waypoints().size() - 1 : 0;
}
aip = &Ai_info[Ships[objp->instance].ai_index];
if ( (aip->mode == AIM_WAYPOINTS) && (aip->wp_list == wp_list) )
@@ -3496,7 +3477,7 @@ void ai_start_waypoints(object *objp, waypoint_list *wp_list, int wp_flags, int
if (aip->wp_index == INVALID_WAYPOINT_POSITION)
{
Warning(LOCATION, "aip->wp_index should have been assigned already!");
aip->wp_index = start_index;
aip->wp_index = 0;
}
return;
}
@@ -3512,10 +3493,9 @@ void ai_start_waypoints(object *objp, waypoint_list *wp_list, int wp_flags, int
aip->ai_flags.remove(AI::AI_Flags::Formation_object);
aip->wp_list = wp_list;
aip->wp_index = start_index;
aip->wp_index = 0;
aip->wp_flags = wp_flags;
aip->mode = AIM_WAYPOINTS;
aip->submode_parm0 = start_index; // keep track of the start index because we need it for Fix_ai_path_order_bug
Assert(aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC);
}
@@ -3637,7 +3617,7 @@ int Debug_k = 0;
*
* Return this value. Return value of 0.0f means no collision is possible.
*/
float compute_collision_time(const vec3d *targpos, const vec3d *targvel, const vec3d *attackpos, float weapon_speed)
float compute_collision_time(vec3d *targpos, vec3d *targvel, vec3d *attackpos, float weapon_speed)
{
vec3d vec_to_target;
float pos_dot_vel;
@@ -3756,7 +3736,7 @@ void ai_update_aim(ai_info *aip)
bool ai_willing_to_afterburn_hard(ai_info* aip) {
return aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC ?
The_mission.ai_profile->flags[AI::Profile_Flags::Dynamic_goals_afterburn_hard] :
(aip->active_goal > -1 && aip->goals[aip->active_goal].flags[AI::Goal_Flags::Afterburn_hard]);
aip->goals[aip->active_goal].flags[AI::Goal_Flags::Afterburn_hard];
}
// pedal to the metal!!1!
@@ -4505,6 +4485,9 @@ void ai_safety()
aip->submode = AISS_2;
aip->submode_start_time = Missiontime;
break;
case AISS_1a: // Pick a safe point because we just got whacked!
Int3();
break;
case AISS_2:
if (ai_safety_goto_spot(Pl_objp) < 25.0f) {
aip->submode = AISS_3;
@@ -4514,9 +4497,8 @@ void ai_safety()
case AISS_3:
ai_safety_circle_spot(Pl_objp);
break;
case AISS_1a: // Pick a safe point because we just got whacked!
default:
UNREACHABLE("Bad AI submode for ai_safety mode of %d. Please report to the SCP!", aip->submode); // Illegal submode for ai_safety();
Int3(); // Illegal submode for ai_safety();
break;
}
}
@@ -4528,7 +4510,7 @@ void ai_safety()
// optionally returns true if Pl_objp's (pl_treat_as_ship_p) fly to order was issued to him directly,
// or if the order was issued to his wing (returns false) (can be NULL, and result is only
// valid if Pl_done_p was not NULL and was set true by function.
void ai_fly_to_target_position(const vec3d* target_pos, bool* pl_done_p=NULL, bool* pl_treat_as_ship_p=NULL)
void ai_fly_to_target_position(vec3d* target_pos, bool* pl_done_p=NULL, bool* pl_treat_as_ship_p=NULL)
{
float dot, dist_to_goal;
ship *shipp = &Ships[Pl_objp->instance];
@@ -4860,11 +4842,11 @@ void ai_waypoints()
// sanity checking for stuff that should never happen
if (aip->wp_index == INVALID_WAYPOINT_POSITION) {
if (aip->wp_list == NULL) {
UNREACHABLE("Waypoints should have been assigned already!");
ai_start_waypoints(Pl_objp, &Waypoint_lists.front(), WPF_REPEAT, 0);
Warning(LOCATION, "Waypoints should have been assigned already!");
ai_start_waypoints(Pl_objp, &Waypoint_lists.front(), WPF_REPEAT);
} else {
UNREACHABLE("Waypoints should have been started already!");
ai_start_waypoints(Pl_objp, aip->wp_list, WPF_REPEAT, 0);
Warning(LOCATION, "Waypoints should have been started already!");
ai_start_waypoints(Pl_objp, aip->wp_list, WPF_REPEAT);
}
}
@@ -4874,32 +4856,17 @@ void ai_waypoints()
ai_fly_to_target_position(aip->wp_list->get_waypoints()[aip->wp_index].get_pos(), &done, &treat_as_ship);
if ( done ) {
bool reached_end;
// go on to next waypoint in path
if (aip->wp_flags & WPF_BACKTRACK) {
--aip->wp_index;
reached_end = (aip->wp_index == -1);
} else {
++aip->wp_index;
reached_end = (aip->wp_index == (int)aip->wp_list->get_waypoints().size());
}
++aip->wp_index;
if (reached_end) {
if ( aip->wp_index == aip->wp_list->get_waypoints().size() ) {
// have reached the last waypoint. Do I repeat?
if ( aip->wp_flags & WPF_REPEAT ) {
// go back to the start.
if (aip->wp_flags & WPF_BACKTRACK) {
aip->wp_index = (int)aip->wp_list->get_waypoints().size() - 1;
} else {
aip->wp_index = 0;
}
aip->wp_index = 0;
} else {
// stay on the last waypoint.
if (aip->wp_flags & WPF_BACKTRACK) {
++aip->wp_index;
} else {
--aip->wp_index;
}
--aip->wp_index;
// Log a message that the wing or ship reached his waypoint and
// remove the goal from the AI goals of the ship pr wing, respectively.
@@ -5492,61 +5459,6 @@ float G_collision_time;
vec3d G_predicted_pos, G_fire_pos;
/*
* plieblang
* Used by the good-primary-time sexp to store the info supplied from there
* weapon_idx indexes into Weapon_info if the primary preference is being set
*/
void ai_set_or_clear_preferred_primary_weapon(bool set_it, const object_ship_wing_point_team *subject, const object_ship_wing_point_team *target, int weapon_idx)
{
// force the ai to reselect a primary instead of possibly waiting the normal elapsed time
for (auto so : list_range(&Ship_obj_list))
{
auto subject_objp = &Objects[so->objnum];
if (subject_objp->flags[Object::Object_Flags::Should_be_dead])
continue;
auto subject_shipp = &Ships[subject_objp->instance];
if (!subject->matches(subject_shipp))
continue;
auto subject_aip = &Ai_info[subject_shipp->ai_index];
if (subject_aip->target_objnum < 0)
continue;
auto target_objp = &Objects[subject_aip->target_objnum];
if (target_objp->type != OBJ_SHIP || !target->matches(&Ships[target_objp->instance]))
continue;
// for AIs that match this subject-target pair, select a new primary immediately
subject_aip->primary_select_timestamp = timestamp(1);
}
if (set_it)
{
for (auto& ppi : Preferred_primary_info)
{
if (ppi.subject == *subject && ppi.target == *target)
{
ppi.weapon_index = weapon_idx;
return;
}
}
// not found, so add a new entry
Preferred_primary_info.push_back({ *subject, *target, weapon_idx });
}
else
{
Preferred_primary_info.erase(
std::remove_if(Preferred_primary_info.begin(), Preferred_primary_info.end(), [&](const primary_fire_info& ppi) {
return ppi.subject == *subject && ppi.target == *target;
}), Preferred_primary_info.end()
);
}
}
//old version of this fuction, this will be useful for playing old missions and not having the new primary
//selection code throw off the balance of the mission.
// If:
@@ -5632,7 +5544,6 @@ int ai_select_primary_weapon(object *objp, object *other_objp, Weapon::Info_Flag
{
// Pointer Set Up
ship *shipp = &Ships[objp->instance];
ship *other_shipp = nullptr;
ship_weapon *swp = &shipp->weapons;
// Debugging
@@ -5644,46 +5555,6 @@ int ai_select_primary_weapon(object *objp, object *other_objp, Weapon::Info_Flag
return -1;
}
bool other_is_ship = (other_objp->type == OBJ_SHIP);
if (other_is_ship)
{
other_shipp = &Ships[other_objp->instance];
//if the good-primary-time sexp has been used, return that weapon immediately
//if smart primary weapon selection isn't set, turning this override behavior off might not do anything
//however this seems acceptable
for (const auto &ppi : Preferred_primary_info)
{
if (ppi.subject.matches(shipp) && ppi.target.matches(other_shipp))
{
int weapon_idx = ppi.weapon_index;
//figure out what bank the weapon belongs to
int bank_num = -1;
for (int i = 0; i < MAX_SHIP_PRIMARY_BANKS; i++) {
if (weapon_idx == swp->primary_bank_weapons[i]) {
bank_num = i;
break;
}
}
//if it's a valid bank, set it and return
if (bank_num != -1) {
//forcing a ship to use a certain primary should prevent it from linking weapons
shipp->flags.set(Ship::Ship_Flags::Force_primary_unlinking);
swp->current_primary_bank = bank_num;
return bank_num;
}
}
}
}
// we're not prioritizing a specific primary weapon
shipp->flags.remove(Ship::Ship_Flags::Force_primary_unlinking);
//not using the new AI, use the old version of this function instead.
if (!(Ai_info[shipp->ai_index].ai_profile_flags[AI::Profile_Flags::Smart_primary_weapon_selection]))
{
@@ -5719,11 +5590,12 @@ int ai_select_primary_weapon(object *objp, object *other_objp, Weapon::Info_Flag
}
}
bool other_is_ship = (other_objp->type == OBJ_SHIP);
float enemy_remaining_shield = get_shield_pct(other_objp);
if ( other_is_ship )
{
ship_info* other_sip = &Ship_info[other_shipp->ship_info_index];
ship_info* other_sip = &Ship_info[Ships[other_objp->instance].ship_info_index];
if (other_sip->class_type >= 0 && Ship_types[other_sip->class_type].flags[Ship::Type_Info_Flags::Targeted_by_huge_Ignored_by_small_only]) {
//Check if we have a capital+ weapon on board
@@ -5739,7 +5611,7 @@ int ai_select_primary_weapon(object *objp, object *other_objp, Weapon::Info_Flag
if (enemy_remaining_shield <= 0.05f || (wip->shield_factor * 1.33f > wip->armor_factor))
{
swp->current_primary_bank = i;
nprintf(("AI", "%i: Ship %s selecting weapon %s (capital+) vs target %s\n", Framecount, shipp->ship_name, wip->name, other_shipp->ship_name));
nprintf(("AI", "%i: Ship %s selecting weapon %s (capital+) vs target %s\n", Framecount, Ships[objp->instance].ship_name, wip->name, Ships[other_objp->instance].ship_name));
return i;
}
}
@@ -5777,7 +5649,7 @@ int ai_select_primary_weapon(object *objp, object *other_objp, Weapon::Info_Flag
i_hullfactor_prev_bank = 0; // Just switch to the first one
}
swp->current_primary_bank = i_hullfactor_prev_bank; // Select the best weapon
nprintf(("AI", "%i: Ship %s selecting weapon %s (no shields) vs target %s\n", Framecount, shipp->ship_name, Weapon_info[swp->primary_bank_weapons[i_hullfactor_prev_bank]].name, (other_is_ship ? other_shipp->ship_name : "non-ship") ));
nprintf(("AI", "%i: Ship %s selecting weapon %s (no shields) vs target %s\n", Framecount, shipp->ship_name, Weapon_info[swp->primary_bank_weapons[i_hullfactor_prev_bank]].name, (other_is_ship ? Ships[other_objp->instance].ship_name : "non-ship") ));
return i_hullfactor_prev_bank; // Return
}
@@ -5899,11 +5771,6 @@ void set_primary_weapon_linkage(object *objp)
shipp->flags.remove(Ship::Ship_Flags::Primary_linked);
//bail if it's been included in a good-primary-time
if (shipp->flags[Ship::Ship_Flags::Force_primary_unlinking]) {
return;
}
// AL: ensure target is a ship!
if ( (aip->target_objnum != -1) && (Objects[aip->target_objnum].type == OBJ_SHIP) ) {
// If trying to destroy a big ship (i.e., not disable/disarm), always unleash all weapons
@@ -6183,7 +6050,6 @@ int ai_fire_primary_weapon(object *objp)
enemy_sip = NULL;
}
//plieblang - added check for size of Preferred_primaries to force reevaluation if good-primary-time has been used in the meantime
if ( (swp->current_primary_bank < 0) || (swp->current_primary_bank >= swp->num_primary_banks) || timestamp_elapsed(aip->primary_select_timestamp)) {
Weapon::Info_Flags flags = Weapon::Info_Flags::NUM_VALUES;
if ( aip->targeted_subsys != NULL ) {
@@ -6191,7 +6057,7 @@ int ai_fire_primary_weapon(object *objp)
}
ai_select_primary_weapon(objp, enemy_objp, flags);
ship_primary_changed(shipp); // AL: maybe send multiplayer information when AI ship changes primaries
aip->primary_select_timestamp = timestamp(5 * MILLISECONDS_PER_SECOND); // Maybe change primary weapon five seconds from now.
aip->primary_select_timestamp = timestamp(5 * 1000); // Maybe change primary weapon five seconds from now.
}
//We can only check LoS if we have a target defined
@@ -6266,7 +6132,7 @@ int ai_fire_primary_weapon(object *objp)
int type;
type = aip->targeted_subsys->system_info->type;
if (ship_subsystems_blown(&Ships[tobjp->instance], type)) {
if (ship_get_subsystem_strength(&Ships[tobjp->instance], type) == 0.0f) {
aip->target_objnum = -1;
return 0;
}
@@ -6306,7 +6172,7 @@ int ai_fire_primary_weapon(object *objp)
// threshold => max distance from pos to be considered "near"
//
// exit: number of ships within threshold units of pos
int num_nearby_fighters(int enemy_team_mask, const vec3d *pos, float threshold)
int num_nearby_fighters(int enemy_team_mask, vec3d *pos, float threshold)
{
ship_obj *so;
object *ship_objp;
@@ -6477,7 +6343,7 @@ bool ai_select_secondary_weapon(object *objp, ship_weapon *swp, flagset<Weapon::
/**
* @return number of objects homing on object *target_objp
*/
int compute_num_homing_objects(const object *target_objp)
int compute_num_homing_objects(object *target_objp)
{
int count = 0;
@@ -6559,7 +6425,7 @@ float compute_incoming_payload(object *target_objp)
// OR: secondary los flag is set but no line of sight is availabe
// Note: If player is attacking a ship, that ship is allowed to fire at player. Otherwise, we get in a situation in which
// player is attacking a large ship, but that large ship is not defending itself with missiles.
bool check_ok_to_fire(int objnum, int target_objnum, const weapon_info *wip, int secondary_bank, const vec3d *firing_pos_global)
int check_ok_to_fire(int objnum, int target_objnum, weapon_info *wip, int secondary_bank, ship_subsys* turret)
{
int num_homers = 0;
@@ -6575,8 +6441,8 @@ bool check_ok_to_fire(int objnum, int target_objnum, const weapon_info *wip, int
if (The_mission.ai_profile->flags[AI::Profile_Flags::Require_exact_los] || wip->wi_flags[Weapon::Info_Flags::Require_exact_los]) {
//Check if th AI has Line of Sight and is allowed to fire
if (!check_los(objnum, target_objnum, 10.0f, -1, secondary_bank, firing_pos_global)) {
return false;
if (!check_los(objnum, target_objnum, 10.0f, -1, secondary_bank, turret)) {
return 0;
}
}
@@ -6590,14 +6456,14 @@ bool check_ok_to_fire(int objnum, int target_objnum, const weapon_info *wip, int
// At Easy, 2/7...at Expert, 5/7
int t = ((Missiontime /(65536*10)) ^ target_objnum ^ 0x01) % (NUM_SKILL_LEVELS+2);
if (t > Ai_info[Ships[tobjp->instance].ai_index].ai_chance_to_use_missiles_on_plr) {
return false;
return 0;
}
}
int swarmers = 0;
if (wip->wi_flags[Weapon::Info_Flags::Swarm])
swarmers = 2; // Note, always want to be able to fire swarmers if no currently incident homers.
if (The_mission.ai_profile->max_allowed_player_homers[Game_skill_level] < num_homers + swarmers) {
return false;
return 0;
}
} else if (num_homers > 3) {
float incoming_payload;
@@ -6605,22 +6471,22 @@ bool check_ok_to_fire(int objnum, int target_objnum, const weapon_info *wip, int
incoming_payload = compute_incoming_payload(&Objects[target_objnum]);
if (incoming_payload > tobjp->hull_strength) {
return false;
return 0;
}
}
}
}
return true;
return 1;
}
// --------------------------------------------------------------------------
// Returns true if *aip has a line of sight to its current target.
// threshold defines the minimum radius for an object to be considered relevant for LoS
bool check_los(int objnum, int target_objnum, float threshold, int primary_bank, int secondary_bank, const vec3d *firing_pos_global) {
bool check_los(int objnum, int target_objnum, float threshold, int primary_bank, int secondary_bank, ship_subsys* turret) {
//Do both checks over an XOR-Check for more detailed messages
int sources = (primary_bank != -1 ? 1 : 0) + (secondary_bank != -1 ? 1 : 0) + (firing_pos_global != nullptr ? 1 : 0);
int sources = (primary_bank != -1 ? 1 : 0) + (secondary_bank != -1 ? 1 : 0) + (turret != nullptr ? 1 : 0);
Assertion(sources >= 1, "Cannot check line of sight from a model with neither a primar bank, nor secondary bank nor a turret set as a source.");
Assertion(sources <= 1, "Cannot check line of sight from a model with more than one source set.");
@@ -6628,8 +6494,10 @@ bool check_los(int objnum, int target_objnum, float threshold, int primary_bank,
object* firing_ship = &Objects[objnum];
if (firing_pos_global != nullptr) {
start = *firing_pos_global;
if (turret != nullptr) {
vec3d turret_fvec;
//It doesn't like not having an fvec output vector, so give it a dummy vector
ship_get_global_turret_gun_info(firing_ship, turret, &start, &turret_fvec, 1, nullptr);
} else {
bool is_primary = secondary_bank == -1;
ship *shipp = &Ships[firing_ship->instance];
@@ -6941,7 +6809,7 @@ float ai_get_weapon_dist(ship_weapon *swp)
return MIN((Weapon_info[weapon_num].max_speed * Weapon_info[weapon_num].lifetime), Weapon_info[weapon_num].weapon_range);
}
float ai_get_weapon_speed(const ship_weapon *swp)
float ai_get_weapon_speed(ship_weapon *swp)
{
int bank_num, weapon_num;
@@ -6985,7 +6853,7 @@ weapon_info* ai_get_weapon(ship_weapon *swp)
// Also, stuff globals G_predicted_pos, G_collision_time and G_fire_pos.
// *pobjp object firing the weapon
// *eobjp object being fired upon
void set_predicted_enemy_pos_turret(vec3d *predicted_enemy_pos, const vec3d *gun_pos, const object *pobjp, const vec3d *enemy_pos, const vec3d *enemy_vel, float weapon_speed, float time_enemy_in_range)
void set_predicted_enemy_pos_turret(vec3d *predicted_enemy_pos, vec3d *gun_pos, object *pobjp, vec3d *enemy_pos, vec3d *enemy_vel, float weapon_speed, float time_enemy_in_range)
{
ship *shipp = &Ships[pobjp->instance];
float range_time;
@@ -7853,8 +7721,8 @@ void ai_stealth_sweep()
break;
default:
UNREACHABLE("Bad submode in ai_steath_sweep of %d. Please report to the SCP!", aip->submode_parm0);
break;
Int3();
}
// when close to goal_pt, update next goal pt
@@ -8629,13 +8497,13 @@ void ai_cruiser_chase()
ship *shipp = &Ships[Pl_objp->instance];
ai_info *aip = &Ai_info[shipp->ai_index];
Assertion(En_objp->type == OBJ_SHIP, "En_objp is of type %d which is illegal in ai_cruiser_chase. Please report to the SCP!", En_objp->type);
if (En_objp->type != OBJ_SHIP) {
Int3();
return;
}
Assertion(En_objp->instance > -1, "En_objp has a bad instance of %d which is illegal in ai_cruiser_chase. Please report to the SCP!", En_objp->instance);
if (En_objp->instance < 0) {
Int3();
return;
}
@@ -8804,7 +8672,9 @@ void ai_chase()
flagset<Ship::Ship_Flags> enemy_shipp_flags;
int has_fired = -1;
Assertion(aip->mode == AIM_CHASE, "ai_chase was called but the ship was not in the chase ai mode. It is in %d instead. This is a fundamental problem and needs to be reported to the SCP, right away!", aip->mode);
if (aip->mode != AIM_CHASE) {
Int3();
}
// by default we try to chase anything
bool go_after_it = true;
@@ -8936,40 +8806,38 @@ void ai_chase()
// Set predicted_enemy_pos.
// See if attacking a subsystem.
weapon_info* wip = ai_get_weapon(&shipp->weapons);
if (wip) {
bool ballistic = !IS_VEC_NULL(&The_mission.gravity) && wip->gravity_const != 0.0f;
if (aip->targeted_subsys != NULL && get_shield_pct(En_objp) < HULL_DAMAGE_THRESHOLD_PERCENT) {
Assert(En_objp->type == OBJ_SHIP);
vec3d target_pos;
get_subsystem_pos(&target_pos, En_objp, aip->targeted_subsys);
bool ballistic = !IS_VEC_NULL(&The_mission.gravity) && wip->gravity_const != 0.0f;
if (aip->targeted_subsys != NULL && get_shield_pct(En_objp) < HULL_DAMAGE_THRESHOLD_PERCENT) {
Assert(En_objp->type == OBJ_SHIP);
vec3d target_pos;
get_subsystem_pos(&target_pos, En_objp, aip->targeted_subsys);
if (!ballistic)
if (!ballistic)
predicted_enemy_pos = target_pos;
else {
vec3d gravity_vec = The_mission.gravity * wip->gravity_const;
has_valid_ballistic_trajectory =
physics_lead_ballistic_trajectory(&Pl_objp->pos, &target_pos, &aip->last_aim_enemy_vel, wip->max_speed, &gravity_vec, &predicted_enemy_pos);
if (has_valid_ballistic_trajectory)
predicted_enemy_pos = Pl_objp->pos + predicted_enemy_pos * vm_vec_dist(&Pl_objp->pos, &target_pos);
else
predicted_enemy_pos = target_pos;
else {
vec3d gravity_vec = The_mission.gravity * wip->gravity_const;
has_valid_ballistic_trajectory =
physics_lead_ballistic_trajectory(&Pl_objp->pos, &target_pos, &aip->last_aim_enemy_vel, wip->max_speed, &gravity_vec, &predicted_enemy_pos);
}
if (has_valid_ballistic_trajectory)
predicted_enemy_pos = Pl_objp->pos + predicted_enemy_pos * vm_vec_dist(&Pl_objp->pos, &target_pos);
else
predicted_enemy_pos = target_pos;
}
predicted_vec_to_enemy = real_vec_to_enemy;
} else {
if (!ballistic)
set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, &aip->last_aim_enemy_pos, &aip->last_aim_enemy_vel, aip);
else {
vec3d gravity_vec = The_mission.gravity * wip->gravity_const;
has_valid_ballistic_trajectory =
physics_lead_ballistic_trajectory(&Pl_objp->pos, &aip->last_aim_enemy_pos, &aip->last_aim_enemy_vel, wip->max_speed, &gravity_vec, &predicted_enemy_pos);
predicted_vec_to_enemy = real_vec_to_enemy;
} else {
if (!ballistic)
set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, &aip->last_aim_enemy_pos, &aip->last_aim_enemy_vel, aip);
else {
vec3d gravity_vec = The_mission.gravity * wip->gravity_const;
has_valid_ballistic_trajectory =
physics_lead_ballistic_trajectory(&Pl_objp->pos, &aip->last_aim_enemy_pos, &aip->last_aim_enemy_vel, wip->max_speed, &gravity_vec, &predicted_enemy_pos);
if (has_valid_ballistic_trajectory)
predicted_enemy_pos = Pl_objp->pos + predicted_enemy_pos * vm_vec_dist(&Pl_objp->pos, &aip->last_aim_enemy_pos);
else
set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, &aip->last_aim_enemy_pos, &aip->last_aim_enemy_vel, aip);
}
if (has_valid_ballistic_trajectory)
predicted_enemy_pos = Pl_objp->pos + predicted_enemy_pos * vm_vec_dist(&Pl_objp->pos, &aip->last_aim_enemy_pos);
else
set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, &aip->last_aim_enemy_pos, &aip->last_aim_enemy_vel, aip);
}
}
}
@@ -9296,7 +9164,7 @@ void ai_chase()
}
break;
default:
UNREACHABLE("Somehow we changed a call to get a random number in ai_chase so it's not 0-4, please report to the SCP!"); // Impossible!
Int3(); // Impossible!
}
}
@@ -9822,7 +9690,7 @@ float dock_orient_and_approach(object *docker_objp, int docker_index, object *do
// Goober5000 - moved out here to save calculations
if (dock_mode != DOA_DOCK_STAY)
if (!Ships[docker_objp->instance].flags[Ship::Ship_Flags::Maneuver_despite_engines] && ship_subsystems_blown(&Ships[docker_objp->instance], SUBSYSTEM_ENGINE))
if (!Ships[docker_objp->instance].flags[Ship::Ship_Flags::Maneuver_despite_engines] && ship_get_subsystem_strength(&Ships[docker_objp->instance], SUBSYSTEM_ENGINE) <= 0.0f)
return 9999.9f;
// If dockee has moved much, then path will be recreated.
@@ -10242,7 +10110,7 @@ void guard_object_was_hit(object *guard_objp, object *hitter_objp)
}
// don't attack if you can't see him
if ( awacs_get_level(hitter_objp, &Ships[aip->shipnum], true) < 1.0f ) {
if ( awacs_get_level(hitter_objp, &Ships[aip->shipnum], 1) < 1 ) {
// if he's a stealth and visible, but not targetable, ok to attack.
if ( is_object_stealth_ship(hitter_objp) ) {
if ( ai_is_stealth_visible(guard_objp, hitter_objp) != STEALTH_IN_FRUSTUM ) {
@@ -10742,7 +10610,7 @@ void ai_big_guard()
break;
default:
UNREACHABLE("Illegal submode of %d for guard mode in ai_big_guard. Please report to the SCP!", aip->submode);
Int3(); // Illegal submode for Guard mode.
// AL 06/03/97 comment out Int3() to allow milestone to get out the door
aip->submode = AIS_GUARD_PATROL;
aip->submode_start_time = Missiontime;
@@ -10771,7 +10639,7 @@ void ai_guard()
guard_objp = &Objects[aip->guard_objnum];
if (guard_objp == Pl_objp) {
UNREACHABLE("The ship %s has been found to be guarding itself in ai_guard. Please report to the SCP!", shipp->ship_name); // This seems illegal. Why is a ship guarding itself?
Int3(); // This seems illegal. Why is a ship guarding itself?
aip->guard_objnum = -1;
return;
}
@@ -10892,14 +10760,14 @@ void ai_guard()
// Goal point is in front.
// If close to goal point, don't change direction, just change speed.
if (dist_to_goal_point > Pl_objp->radius + 10.0f) {
turn_towards_point(Pl_objp, &goal_point, nullptr, 0.0f);
turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
}
set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed + (dist_to_goal_point-40.0f)/20.0f);
}
} else {
if (dot_to_goal_point > 0.8f) {
turn_towards_point(Pl_objp, &goal_point, nullptr, 0.0f);
turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed + dist_to_goal_point*0.1f);
} else {
set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed - dist_to_goal_point*0.1f - 1.0f);
@@ -10908,14 +10776,10 @@ void ai_guard()
// consider guard object STILL
} else if (guard_objp->radius < 50.0f) {
if (dist_to_goal_point > 15.0f) {
turn_towards_point(Pl_objp, &goal_point, nullptr, 0.0f);
turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
set_accel_for_target_speed(Pl_objp, (dist_to_goal_point-10.0f)/2.0f);
} else if (Pl_objp->phys_info.speed < 1.0f) {
if (aip->ai_profile_flags[AI::Profile_Flags::Align_to_target_when_guarding_still]) {
turn_towards_point(Pl_objp, &guard_objp->pos, nullptr, 0.0f, &guard_objp->orient);
} else {
turn_away_from_point(Pl_objp, &guard_objp->pos, 0.0f);
}
turn_away_from_point(Pl_objp, &guard_objp->pos, 0.0f);
}
// It's a big ship
} else if (dist_to_guardobj > MAX_GUARD_DIST + Pl_objp->radius + guard_objp->radius) {
@@ -10954,7 +10818,7 @@ void ai_guard()
break;
default:
UNREACHABLE("Illegal ai submode of %d for guard mode in ai_guard for ship %s. Pleae report to the SCP!", aip->submode, shipp->ship_name);
Int3(); // Illegal submode for Guard mode.
// AL 06/03/97 comment out Int3() to allow milestone to get out the door
aip->submode = AIS_GUARD_PATROL;
aip->submode_start_time = Missiontime;
@@ -11098,7 +10962,7 @@ void ai_do_objects_repairing_stuff( object *repaired_objp, object *repair_objp,
break;
default:
UNREACHABLE("Illegal repair info type of %d in ai_do_objects_repairing_stuff. Pleae report to the SCP!", how);
Int3(); // bogus type of repair info
}
// repair_objp might be NULL if we are cleaning up this mode because of the support ship
@@ -11135,7 +10999,7 @@ void ai_do_objects_repairing_stuff( object *repaired_objp, object *repair_objp,
break;
default:
UNREACHABLE("Illegal repair info type of %d in ai_do_objects_repairing_stuff. Pleae report to the SCP!", how);
Int3(); // bogus type of repair info
}
}
@@ -11959,7 +11823,7 @@ void ai_dock()
default:
{
UNREACHABLE("Illegal dock submode of %d in ai_dock. Pleae report to the SCP!", aip->submode);
Int3(); // Error, bogus submode
}
} // end of switch statement
@@ -12149,7 +12013,7 @@ void ai_process_subobjects(int objnum)
}
// Deal with a ship with blown out engines.
if (ship_subsystems_blown(shipp, SUBSYSTEM_ENGINE)) {
if (ship_get_subsystem_strength(shipp, SUBSYSTEM_ENGINE) == 0.0f) {
// Karajorma - if Player_use_ai is ever fixed to work on multiplayer it should be checked that any player ships
// aren't under AI control here
if ((!(objp->flags[Object::Object_Flags::Player_ship])) && (sip->is_fighter_bomber()) && !(shipp->flags[Ship::Ship_Flags::Dying])) {
@@ -12213,7 +12077,7 @@ object *get_wing_leader(int wingnum)
// If this ship is disabled, try another ship in the wing.
int n = 0;
while (!Ships[ship_num].flags[Ship::Ship_Flags::Maneuver_despite_engines] && ship_subsystems_blown(&Ships[ship_num], SUBSYSTEM_ENGINE)) {
while (!Ships[ship_num].flags[Ship::Ship_Flags::Maneuver_despite_engines] && ship_get_subsystem_strength(&Ships[ship_num], SUBSYSTEM_ENGINE) == 0.0f) {
n++;
if (n >= wingp->current_count) {
@@ -12613,14 +12477,10 @@ int ai_formation()
}
if (aip->mode == AIM_WAYPOINTS) {
if (The_mission.ai_profile->flags[AI::Profile_Flags::Fix_ai_path_order_bug]){
// skip if wing leader has no waypoint order or a different waypoint list
// ...or if it's a different start index or direction
if ( (laip->mode != AIM_WAYPOINTS)
|| (laip->wp_list != aip->wp_list)
|| (laip->submode_parm0 != aip->submode_parm0)
|| ((laip->wp_flags & WPF_BACKTRACK) != (aip->wp_flags & WPF_BACKTRACK))
) {
if ((laip->mode != AIM_WAYPOINTS) || !(aip->wp_list == laip->wp_list)){
return 1;
}
}
@@ -12629,15 +12489,8 @@ int ai_formation()
aip->wp_index = laip->wp_index;
aip->wp_flags = laip->wp_flags;
if (aip->wp_list != nullptr) {
if (aip->wp_flags & WPF_BACKTRACK) {
if (aip->wp_index == -1)
++aip->wp_index;
} else {
if (aip->wp_index == (int)aip->wp_list->get_waypoints().size())
--aip->wp_index;
}
}
if ((aip->wp_list != NULL) && (aip->wp_index == aip->wp_list->get_waypoints().size()))
--aip->wp_index;
}
#ifndef NDEBUG
@@ -12927,23 +12780,14 @@ void ai_do_repair_frame(object *objp, ai_info *aip, float frametime)
repaired = ship_do_rearm_frame( objp, frametime ); // hook to do missile rearming
// See if fully repaired. If so, cause process to stop.
if ( repaired ) {
// We can repair ships without being docked, so only do this if we are docked
if (repair_aip->submode == AIS_DOCK_4) {
repair_aip->submode = AIS_UNDOCK_0;
repair_aip->submode_start_time = Missiontime;
// if repairing player object -- tell him done with repair
if (!MULTIPLAYER_CLIENT) {
ai_do_objects_repairing_stuff(objp, &Objects[support_objnum], REPAIR_INFO_COMPLETE);
}
}
//If Repairing self
else if (&Objects[support_objnum] == objp) { // Undocking ends the repair,
// but since we don'tneed to do that in this case, end it here
ai_do_objects_repairing_stuff(objp, &Objects[support_objnum], REPAIR_INFO_END);
if (!MULTIPLAYER_CLIENT) {
hud_support_view_stop();
}
if ( repaired && (repair_aip->submode == AIS_DOCK_4)) {
repair_aip->submode = AIS_UNDOCK_0;
repair_aip->submode_start_time = Missiontime;
// if repairing player object -- tell him done with repair
if ( !MULTIPLAYER_CLIENT ) {
ai_do_objects_repairing_stuff( objp, &Objects[support_objnum], REPAIR_INFO_COMPLETE );
}
}
}
@@ -13554,8 +13398,8 @@ int ai_acquire_emerge_path(object *pl_objp, int parent_objnum, int allowed_path_
Assertion(shipp->ai_index >= 0, "Arriving ship does not have a valid ai index. Has %d instead. Please report!", shipp->ai_index);
ai_info *aip = &Ai_info[shipp->ai_index];
Assertion(parent_objnum > -1, "parent_objnum in ai_acquire_emerge_path was found to be %d, which is an invalid value. Please report to the SCP!", parent_objnum);
if ( parent_objnum == -1 ) {
Int3();
return -1;
}
@@ -13908,7 +13752,10 @@ int ai_acquire_depart_path(object *pl_objp, int parent_objnum, int allowed_path_
*/
void ai_bay_depart()
{
auto aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
ai_info *aip;
int anchor_shipnum;
aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
// if no path to follow, leave this mode
if ( aip->path_start < 0 ) {
@@ -13917,8 +13764,8 @@ void ai_bay_depart()
}
// check if parent ship valid; if not, abort depart
auto anchor_ship_entry = ship_registry_get(Parse_names[Ships[Pl_objp->instance].departure_anchor]);
if (!anchor_ship_entry || !ship_useful_for_departure(anchor_ship_entry->shipnum, Ships[Pl_objp->instance].departure_path_mask))
anchor_shipnum = ship_name_lookup(Parse_names[Ships[Pl_objp->instance].departure_anchor]);
if (anchor_shipnum < 0 || !ship_useful_for_departure(anchor_shipnum, Ships[Pl_objp->instance].departure_path_mask))
{
mprintf(("Aborting bay departure!\n"));
aip->mode = AIM_NONE;
@@ -13929,7 +13776,7 @@ void ai_bay_depart()
ai_manage_bay_doors(Pl_objp, aip, false);
if ( anchor_ship_entry->shipp()->bay_doors_status != MA_POS_READY )
if ( Ships[anchor_shipnum].bay_doors_status != MA_POS_READY )
return;
// follow the path to the final point
@@ -14306,7 +14153,7 @@ void ai_maybe_depart(object *objp)
if (!shipp->is_departing()) {
if (sip->is_fighter_bomber()) {
if (aip->warp_out_timestamp == 0) {
//if (ship_subsystems_blown(shipp, SUBSYSTEM_WEAPONS)) {
//if (ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS) == 0.0f) {
// aip->warp_out_timestamp = timestamp(Random::next(10, 19) * 1000);
//}
} else if (timestamp_elapsed(aip->warp_out_timestamp)) {
@@ -14411,7 +14258,7 @@ void ai_warp_out(object *objp)
case AIS_WARP_5:
break;
default:
UNREACHABLE("Illegal ai submode of %d in ai_warp_out. Pleae report to the SCP!", aip->submode);
Int3(); // Illegal submode for warping out.
}
}
@@ -14657,7 +14504,7 @@ int aas_1(object *objp, ai_info *aip, vec3d *safe_pos)
return 1;
} else {
UNREACHABLE("aas_1 has been passed an invalid object type of %d, please report to the SCP!", objp->type);
Int3(); // Illegal -- supposedly avoiding a shockwave, but neither ship nor weapon. What is it!?
}
return 0;
@@ -14786,8 +14633,8 @@ void ai_maybe_self_destruct(object *objp, ai_info *aip)
// mission would be broken.
// Also, don't blow up the ship if it has a ship flag preventing this - Goober5000
if ((Ship_info[shipp->ship_info_index].is_small_ship()) && (shipp->wingnum >= 0) && !(shipp->flags[Ship::Ship_Flags::No_disabled_self_destruct])) {
if ((ship_subsystems_blown(shipp, SUBSYSTEM_ENGINE)) ||
(ship_subsystems_blown(shipp, SUBSYSTEM_WEAPONS))) {
if ((ship_get_subsystem_strength(shipp, SUBSYSTEM_ENGINE) <= 0.0f) ||
(ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS) <= 0.0f)) {
if (aip->self_destruct_timestamp < 0)
aip->self_destruct_timestamp = timestamp(90 * 1000); // seconds until self-destruct
} else {
@@ -14921,7 +14768,7 @@ void validate_mode_submode(ai_info *aip)
case SM_ATTACK_FOREVER:
break;
default:
UNREACHABLE("validate_mode_submode found an illegal submode for AIM_CHASE of %d. Please report to the SCP!", aip->submode);
Int3();
}
break;
@@ -14935,7 +14782,7 @@ void validate_mode_submode(ai_info *aip)
case AIS_STRAFE_POSITION:
break;
default:
UNREACHABLE("validate_mode_submode found an illegal submode for AIM_STRAFE of %d. Please report to the SCP!", aip->submode);
Int3();
}
break;
}
@@ -14964,9 +14811,6 @@ void ai_frame(int objnum)
//Default to glide OFF
Pl_objp->phys_info.flags &= ~PF_GLIDING;
// turn off trigger down
shipp->weapons.flags.remove(Ship::Weapon_Flags::Primary_trigger_down);
// warping out?
if ((aip->mode == AIM_WARP_OUT) || (aip->ai_flags[AI::AI_Flags::Trying_unsuccessfully_to_warp]))
@@ -15817,7 +15661,7 @@ void maybe_set_dynamic_chase(ai_info *aip, int hitter_objnum)
}
// only set as target if can be targeted.
if (awacs_get_level(&Objects[hitter_objnum], &Ships[aip->shipnum], true) < 1.0f) {
if (awacs_get_level(&Objects[hitter_objnum], &Ships[aip->shipnum], 1) < 1) {
return;
}
@@ -16070,7 +15914,7 @@ void ai_ship_hit(object *objp_ship, object *hit_objp, vec3d *hit_normal)
objp_hitter = hit_objp;
hitter_objnum = OBJ_INDEX(hit_objp);
} else {
UNREACHABLE("ai_ship_hit has been passed an invalid object type of %d, please report to the SCP!", hit_objp->type);
Int3(); // Hmm, what kind of object hit this if not weapon or ship? Get MikeK.
return;
}
@@ -16549,8 +16393,8 @@ void ai_rearm_repair( object *objp, int docker_index, object *goal_objp, int doc
// of a path_num associated with than dockbay (this is an index into polymodel->paths[])
int ai_return_path_num_from_dockbay(object *dockee_objp, int dockbay_index)
{
Assertion(dockbay_index > -1 && dockee_objp != nullptr, "ai_return_path_num_from_dockbay has been passed invalid docking info: %s dockbay index of %d, please report to the SCP!", dockee_objp == nullptr ? "null pointer dockee object and " : "", dockbay_index);
if ( dockbay_index < 0 || dockee_objp == nullptr ) {
if ( dockbay_index < 0 || dockee_objp == NULL ) {
Int3(); // should never happen
return -1;
}
+59 -66
View File
@@ -214,7 +214,7 @@ void ai_maybe_add_form_goal(wing* wingp)
int wingnum;
if (Netgame.type_flags & NG_TYPE_TEAM) {
const ship_registry_entry* ship_regp = ship_registry_get(Ships[wingp->ship_index[j]].ship_name);
wingnum = TVT_wings[ship_regp->p_objp()->team];
wingnum = TVT_wings[ship_regp->p_objp->team];
ai_add_ship_goal_player(AIG_TYPE_PLAYER_SHIP, AI_GOAL_FORM_ON_WING, -1, Ships[Wings[wingnum].ship_index[Wings[wingnum].special_ship]].ship_name, aip);
} else {
wingnum = Starting_wings[0];
@@ -487,12 +487,10 @@ void ai_goal_purge_invalid_goals( ai_goal *aigp, ai_goal *goal_list, ai_info *ai
// these goals cannot be associated to wings, but can to a ship in a wing. So, we should find out
// if the ship is in a wing so we can purge goals which might operate on that wing
ship_index = ship_name_lookup(name);
Assertion(ship_index > -1, "Found a bad ship_index of %d in ai_goal_purge_invalid_goals, please report to the SCP!", ship_index); // get allender -- this is sort of odd
if ( ship_index < 0 ) {
return;
if ( ship_index == -1 ) {
Int3(); // get allender -- this is sort of odd
return;
}
wingnum = Ships[ship_index].wingnum;
purge_goal = goal_list;
@@ -728,7 +726,7 @@ void ai_goal_fixup_dockpoints(ai_info *aip, ai_goal *aigp)
// from the mission goals (i.e. those goals which come from events) in that we don't
// use sexpressions for goals from the player...so we enumerate all the parameters
void ai_add_goal_sub_player(int type, int mode, int submode, const char *target_name, ai_goal *aigp, const ai_lua_parameters& lua_target )
void ai_add_goal_sub_player(int type, int mode, int submode, char *target_name, ai_goal *aigp, const ai_lua_parameters& lua_target )
{
Assert ( (type == AIG_TYPE_PLAYER_WING) || (type == AIG_TYPE_PLAYER_SHIP) );
@@ -751,9 +749,6 @@ void ai_add_goal_sub_player(int type, int mode, int submode, const char *target_
if ( target_name != NULL )
aigp->target_name = ai_get_goal_target_name( target_name, &aigp->target_name_index );
if (The_mission.ai_profile->flags[AI::Profile_Flags::Player_orders_afterburn_hard])
aigp->flags.set(AI::Goal_Flags::Afterburn_hard);
// special case certain orders from player so that ships continue to do the right thing
@@ -818,7 +813,7 @@ int ai_goal_num(ai_goal *goals)
}
void ai_add_goal_sub_scripting(int type, int mode, int submode, int priority, const char *target_name, ai_goal *aigp )
void ai_add_goal_sub_scripting(int type, int mode, int submode, int priority, char *target_name, ai_goal *aigp )
{
Assert ( (type == AIG_TYPE_PLAYER_WING) || (type == AIG_TYPE_PLAYER_SHIP) );
@@ -835,7 +830,7 @@ void ai_add_goal_sub_scripting(int type, int mode, int submode, int priority, co
aigp->priority = priority;
}
void ai_add_ship_goal_scripting(int mode, int submode, int priority, const char *shipname, ai_info *aip)
void ai_add_ship_goal_scripting(int mode, int submode, int priority, char *shipname, ai_info *aip)
{
int empty_index;
ai_goal *aigp;
@@ -859,7 +854,7 @@ void ai_add_ship_goal_scripting(int mode, int submode, int priority, const char
// is issued to ship or wing (from player), mode is AI_GOAL_*. submode is the submode the
// ship should go into. shipname is the object of the action. aip is the ai_info pointer
// of the ship receiving the order
void ai_add_ship_goal_player( int type, int mode, int submode, const char *shipname, ai_info *aip, const ai_lua_parameters& lua_target)
void ai_add_ship_goal_player( int type, int mode, int submode, char *shipname, ai_info *aip, const ai_lua_parameters& lua_target)
{
int empty_index;
ai_goal *aigp;
@@ -880,7 +875,7 @@ void ai_add_ship_goal_player( int type, int mode, int submode, const char *shipn
// adds a goal from the player to the given wing (which in turn will add it to the proper
// ships in the wing
void ai_add_wing_goal_player( int type, int mode, int submode, const char *shipname, int wingnum, const ai_lua_parameters& lua_target)
void ai_add_wing_goal_player( int type, int mode, int submode, char *shipname, int wingnum, const ai_lua_parameters& lua_target)
{
int i, empty_index;
wing *wingp = &Wings[wingnum];
@@ -904,7 +899,7 @@ void ai_add_wing_goal_player( int type, int mode, int submode, const char *shipn
// common routine to add a sexpression mission goal to the appropriate goal structure.
void ai_add_goal_sub_sexp( int sexp, int type, ai_info *aip, ai_goal *aigp, const char *actor_name )
void ai_add_goal_sub_sexp( int sexp, int type, ai_info *aip, ai_goal *aigp, char *actor_name )
{
int node, dummy, op;
@@ -918,30 +913,22 @@ void ai_add_goal_sub_sexp( int sexp, int type, ai_info *aip, ai_goal *aigp, cons
switch (op) {
case OP_AI_WAYPOINTS_ONCE:
case OP_AI_WAYPOINTS:
{
case OP_AI_WAYPOINTS: {
int ref_type;
bool is_nan, is_nan_forever;
ref_type = Sexp_nodes[CDR(node)].subtype;
Assertion(ref_type == SEXP_ATOM_STRING || ref_type == SEXP_ATOM_CONTAINER_DATA, "Found a bad ref_type in ai_add_goal_sub_sexp of %d. Please report to the SCP!", ref_type);
// referenced by name
// save the waypoint path name -- the list will get resolved when the goal is checked
// for achievability.
aigp->target_name = ai_get_goal_target_name(CTEXT(CDR(node)), &aigp->target_name_index); // waypoint path name;
if (ref_type == SEXP_ATOM_STRING || ref_type == SEXP_ATOM_CONTAINER_DATA) { // referenced by name
// save the waypoint path name -- the list will get resolved when the goal is checked
// for achievability.
aigp->target_name = ai_get_goal_target_name(CTEXT(CDR(node)), &aigp->target_name_index); // waypoint path name;
} else
Int3();
aigp->priority = atoi( CTEXT(CDR(CDR(node))) );
aigp->ai_mode = AI_GOAL_WAYPOINTS;
if ( op == OP_AI_WAYPOINTS_ONCE )
aigp->ai_mode = AI_GOAL_WAYPOINTS_ONCE;
if (CDDDDR(node) < 0)
aigp->int_data = 0; // handle optional node separately because we don't subtract 1 here
else
aigp->int_data = eval_num(CDDDDR(node), is_nan, is_nan_forever) - 1;
if (is_sexp_true(CDDDDDR(node)))
aigp->flags.set(AI::Goal_Flags::Waypoints_in_reverse);
break;
}
@@ -1003,9 +990,9 @@ void ai_add_goal_sub_sexp( int sexp, int type, ai_info *aip, ai_goal *aigp, cons
// this goal needs some extra setup
// if this doesn't work, the goal will be immediately removed
auto ship_entry = ship_registry_get(aigp->target_name);
if (ship_entry && ship_entry->has_shipp())
if (ship_entry && ship_entry->shipp)
{
auto target_aip = &Ai_info[ship_entry->shipp()->ai_index];
auto target_aip = &Ai_info[ship_entry->shipp->ai_index];
target_aip->ai_flags.set(AI::AI_Flags::Awaiting_repair);
Assertion(aip != nullptr, "Must provide aip if assigning a rearm goal!");
ai_goal_fixup_dockpoints( aip, aigp );
@@ -1465,8 +1452,15 @@ void ai_add_goal_ship_internal( ai_info *aip, int goal_type, char *name, int /*
int gindex;
ai_goal *aigp;
#ifndef NDEBUG
// Goober5000 - none of the goals act on the actor, as in ai_add_goal_sub_sexp
Assertion(strcmp(name, Ships[aip->shipnum].ship_name) != 0, "The goals apply to the actor in ai_add_goal_ship_internal for ship %s, please report to the SCP!", name);
if (!strcmp(name, Ships[aip->shipnum].ship_name))
{
// not good
Int3();
return;
}
#endif
// find an empty slot to put this goal in.
gindex = ai_goal_find_empty_slot( aip->goals, aip->active_goal );
@@ -1517,7 +1511,7 @@ void ai_add_goal_ship_internal( ai_info *aip, int goal_type, char *name, int /*
break;
default:
UNREACHABLE("unsupported internal goal of %d found in ai_add_goal_ship_internal. Please report to the SCP", goal_type); // see Mike K or Mark A.
Int3(); // unsupported internal goal -- see Mike K or Mark A.
return;
}
@@ -1595,7 +1589,7 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
// if the wing target is valid then be sure to set the override bit so that it always
// gets executed next
if ( aigp->ai_mode == AI_GOAL_FORM_ON_WING ) {
if (!target_ship_entry || !target_ship_entry->has_shipp())
if (!target_ship_entry || !target_ship_entry->shipp)
return ai_achievability::NOT_ACHIEVABLE;
aigp->flags.set(AI::Goal_Flags::Goal_override);
@@ -1655,7 +1649,7 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
// can't determine the status of this goal if ship not valid
// or we haven't found a valid subsystem index yet
if ( !target_ship_entry || !target_ship_entry->has_shipp() || (aigp->flags[AI::Goal_Flags::Subsys_needs_fixup]) ) {
if ( !target_ship_entry || !target_ship_entry->shipp || (aigp->flags[AI::Goal_Flags::Subsys_needs_fixup]) ) {
status = 0;
break;
}
@@ -1664,13 +1658,13 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
// as 0 so we can continue. (The subsystem name must be turned into an index into the ship's subsystems
// for this goal to be valid).
Assert ( aigp->ai_submode >= 0 );
ssp = ship_get_indexed_subsys( target_ship_entry->shipp(), aigp->ai_submode );
ssp = ship_get_indexed_subsys( target_ship_entry->shipp, aigp->ai_submode );
if (ssp != NULL) {
// see MWA 3/20/97 comment above - instead of checking the mission log, check the current hits
status = (ssp->current_hits <= 0.0f) ? 1 : 0;
} else {
// not supposed to ever happen, but could if there is a mismatch between the table and model subsystems
nprintf(("AI", "Couldn't find subsystem %d for ship %s\n", aigp->ai_submode, target_ship_entry->shipp()->ship_name));
nprintf(("AI", "Couldn't find subsystem %d for ship %s\n", aigp->ai_submode, target_ship_entry->shipp->ship_name));
status = 0;
}
break;
@@ -1683,11 +1677,11 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
// destroyed when shipnum is valid
// can't determine the status of this goal if ship not valid
if (!target_ship_entry || !target_ship_entry->has_shipp()) {
if (!target_ship_entry || !target_ship_entry->shipp) {
status = 0;
} else {
// see MWA 3/20/97 comment above - instead of checking the mission log, check the current hits
status = (target_ship_entry->shipp()->subsys_info[SUBSYSTEM_ENGINE].aggregate_current_hits <= 0.0f) ? 1 : 0;
status = (target_ship_entry->shipp->subsys_info[SUBSYSTEM_ENGINE].aggregate_current_hits <= 0.0f) ? 1 : 0;
}
break;
}
@@ -1699,11 +1693,11 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
// destroyed when shipnum is valid
// can't determine the status of this goal if ship not valid
if (!target_ship_entry || !target_ship_entry->has_shipp()) {
if (!target_ship_entry || !target_ship_entry->shipp) {
status = 0;
} else {
// see MWA 3/20/97 comment above - instead of checking the mission log, check the current hits
status = (target_ship_entry->shipp()->subsys_info[SUBSYSTEM_TURRET].aggregate_current_hits <= 0.0f) ? 1 : 0;
status = (target_ship_entry->shipp->subsys_info[SUBSYSTEM_TURRET].aggregate_current_hits <= 0.0f) ? 1 : 0;
}
break;
}
@@ -1731,8 +1725,8 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
}
// fly-to-ship can potentially be determined
if (aigp->ai_mode == AI_GOAL_FLY_TO_SHIP && target_ship_entry && target_ship_entry->has_objp()) {
auto dist = vm_vec_dist(&target_ship_entry->objp()->pos, &objp->pos);
if (aigp->ai_mode == AI_GOAL_FLY_TO_SHIP && target_ship_entry && target_ship_entry->objp) {
auto dist = vm_vec_dist(&target_ship_entry->objp->pos, &objp->pos);
if (dist < aigp->float_data) {
return_val = ai_achievability::SATISFIED;
status = 1;
@@ -1846,9 +1840,9 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
// Goober5000 - before doing anything else, check if this is a disarm goal for an arrived ship...
if ((status == SHIP_STATUS_ARRIVED) && (aigp->ai_mode == AI_GOAL_DISARM_SHIP || aigp->ai_mode == AI_GOAL_DISARM_SHIP_TACTICAL))
{
if (target_ship_entry && target_ship_entry->has_shipp()) {
if (target_ship_entry && target_ship_entry->shipp) {
// if the ship has no turrets, we can't disarm it!
if (target_ship_entry->shipp()->subsys_info[SUBSYSTEM_TURRET].type_count == 0)
if (target_ship_entry->shipp->subsys_info[SUBSYSTEM_TURRET].type_count == 0)
return ai_achievability::NOT_ACHIEVABLE;
} else {
UNREACHABLE("Target name %s is not an arrived ship!", aigp->target_name);
@@ -1882,8 +1876,8 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
}
if (!(aigp->flags[AI::Goal_Flags::Dockee_index_valid])) {
if (target_ship_entry && target_ship_entry->has_shipp()) {
int modelnum = Ship_info[target_ship_entry->shipp()->ship_info_index].model_num;
if (target_ship_entry && target_ship_entry->shipp) {
int modelnum = Ship_info[target_ship_entry->shipp->ship_info_index].model_num;
aigp->dockee.index = model_find_dock_name_index(modelnum, aigp->dockee.name);
aigp->flags.set(AI::Goal_Flags::Dockee_index_valid);
} else
@@ -1900,11 +1894,11 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
return ai_achievability::NOT_KNOWN;
// we must also determine if we're prevented from docking for any reason
if (!target_ship_entry || !target_ship_entry->has_shipp()) {
if (!target_ship_entry || !target_ship_entry->shipp) {
UNREACHABLE("Target name %s is not an arrived ship!", aigp->target_name);
return ai_achievability::NOT_ACHIEVABLE; // force this goal to be invalid
}
auto goal_objp = target_ship_entry->objp();
auto goal_objp = target_ship_entry->objp;
// if the ship that I am supposed to dock with is docked with something else, then I need to put my goal on hold
// [MK, 4/23/98: With Mark, we believe this fixes the problem of Comet refusing to warp out after docking with Omega.
@@ -1953,9 +1947,9 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
// might happen too, so err on the safe side. (Yay for emergent paragraph justification!)
if ((aip->mode == AIM_DOCK) && (aip->submode >= AIS_UNDOCK_0))
{
if ( target_ship_entry && target_ship_entry->has_objp() ) {
if ( target_ship_entry && target_ship_entry->shipp ) {
// only put it on hold if it's someone other than the guy we're undocking from right now!!
if (aip->goal_objnum != target_ship_entry->objnum)
if (aip->goal_objnum != target_ship_entry->shipp->objnum)
return ai_achievability::NOT_KNOWN;
} else {
UNREACHABLE("Target name %s is not an arrived ship!", aigp->target_name);
@@ -1968,8 +1962,8 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
// have fixed up the subsystem name (of the subsystem to destroy) into an index into
// the ship's subsystem list
if ( aigp->flags[AI::Goal_Flags::Subsys_needs_fixup] ) {
if ( target_ship_entry && target_ship_entry->has_shipp() ) {
aigp->ai_submode = ship_find_subsys( target_ship_entry->shipp(), aigp->docker.name );
if ( target_ship_entry && target_ship_entry->shipp ) {
aigp->ai_submode = ship_find_subsys( target_ship_entry->shipp, aigp->docker.name );
aigp->flags.remove(AI::Goal_Flags::Subsys_needs_fixup);
} else {
UNREACHABLE("Target name %s is not an arrived ship!", aigp->target_name);
@@ -1978,11 +1972,11 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
}
} else if ( ((aigp->ai_mode == AI_GOAL_IGNORE) || (aigp->ai_mode == AI_GOAL_IGNORE_NEW)) && (status == SHIP_STATUS_ARRIVED) ) {
// for ignoring a ship, call the ai_ignore object function, then declare the goal satisfied
if (!target_ship_entry || !target_ship_entry->has_objp()) {
if (!target_ship_entry || !target_ship_entry->shipp) {
UNREACHABLE("Target name %s is not an arrived ship!", aigp->target_name);
return ai_achievability::NOT_ACHIEVABLE; // force this goal to be invalid
}
auto ignored = target_ship_entry->objp();
auto ignored = target_ship_entry->objp;
ai_ignore_object(objp, ignored, (aigp->ai_mode == AI_GOAL_IGNORE_NEW));
@@ -2036,22 +2030,22 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
if ( status == SHIP_STATUS_GONE )
return ai_achievability::NOT_ACHIEVABLE;
if ( !target_ship_entry || !target_ship_entry->has_shipp() ) {
if ( !target_ship_entry || !target_ship_entry->shipp ) {
UNREACHABLE("Target name %s is not an arrived ship!", aigp->target_name);
return ai_achievability::NOT_ACHIEVABLE;
}
// if destination currently being repaired, then goal is still active
if ( Ai_info[target_ship_entry->shipp()->ai_index].ai_flags[AI::AI_Flags::Being_repaired] )
if ( Ai_info[target_ship_entry->shipp->ai_index].ai_flags[AI::AI_Flags::Being_repaired] )
return ai_achievability::ACHIEVABLE;
// if the destination ship is dying or departing (but not completed yet), the mark goal as
// not achievable.
if ( target_ship_entry->shipp()->is_dying_or_departing())
if ( target_ship_entry->shipp->is_dying_or_departing())
return ai_achievability::NOT_ACHIEVABLE;
// if the destination object is no longer awaiting repair, then remove the item
if ( !(Ai_info[target_ship_entry->shipp()->ai_index].ai_flags[AI::AI_Flags::Awaiting_repair]) )
if ( !(Ai_info[target_ship_entry->shipp->ai_index].ai_flags[AI::AI_Flags::Awaiting_repair]) )
return ai_achievability::NOT_ACHIEVABLE;
// not repairing anything means that he can do this goal!!!
@@ -2066,7 +2060,7 @@ ai_achievability ai_mission_goal_achievable( int objnum, ai_goal *aigp )
// if he is repairing something, he can satisfy his repair goal (his goal_objnum)
// return GOAL_NOT_KNOWN which is kind of a hack which puts the goal on hold until it can be
// satisfied.
if ( aip->goal_objnum != target_ship_entry->objnum )
if ( aip->goal_objnum != target_ship_entry->shipp->objnum )
return ai_achievability::NOT_KNOWN;
return ai_achievability::ACHIEVABLE;
@@ -2340,11 +2334,10 @@ void ai_process_mission_orders( int objnum, ai_info *aip )
case AI_GOAL_WAYPOINTS: // do nothing for waypoints
case AI_GOAL_WAYPOINTS_ONCE: {
int flags = 0;
if (current_goal->ai_mode == AI_GOAL_WAYPOINTS)
if ( current_goal->ai_mode == AI_GOAL_WAYPOINTS)
flags |= WPF_REPEAT;
if (current_goal->flags[AI::Goal_Flags::Waypoints_in_reverse])
flags |= WPF_BACKTRACK;
ai_start_waypoints(objp, current_goal->wp_list, flags, current_goal->int_data);
ai_start_waypoints(objp, current_goal->wp_list, flags);
break;
}
@@ -2551,7 +2544,7 @@ void ai_process_mission_orders( int objnum, ai_info *aip )
break;
default:
UNREACHABLE("unsupported goal of %d found in ai_process_mission_orders. Please report to the SCP", current_goal->ai_mode);
Int3();
break;
}
+4 -4
View File
@@ -168,17 +168,17 @@ extern void ai_process_mission_orders( int objnum, ai_info *aip );
extern int ai_goal_num(ai_goal *goals);
// adds goals to ships/wing through sexpressions
extern void ai_add_ship_goal_scripting(int mode, int submode, int priority, const char *shipname, ai_info *aip);
extern void ai_add_ship_goal_scripting(int mode, int submode, int priority, char *shipname, ai_info *aip);
extern void ai_add_ship_goal_sexp( int sexp, int type, ai_info *aip );
extern void ai_add_wing_goal_sexp( int sexp, int type, wing *wingp );
extern void ai_add_goal_sub_sexp( int sexp, int type, ai_info *aip, ai_goal *aigp, const char *actor_name);
extern void ai_add_goal_sub_sexp( int sexp, int type, ai_info *aip, ai_goal *aigp, char *actor_name);
extern int ai_remove_goal_sexp_sub( int sexp, ai_goal* aigp );
extern void ai_remove_wing_goal_sexp( int sexp, wing *wingp );
// adds goals to ships/sings through player orders
extern void ai_add_ship_goal_player(int type, int mode, int submode, const char* shipname, ai_info* aip, const ai_lua_parameters& lua_target = { object_ship_wing_point_team(), luacpp::LuaValueList{} });
extern void ai_add_wing_goal_player(int type, int mode, int submode, const char* shipname, int wingnum, const ai_lua_parameters& lua_target = { object_ship_wing_point_team(), luacpp::LuaValueList{} });
extern void ai_add_ship_goal_player(int type, int mode, int submode, char* shipname, ai_info* aip, const ai_lua_parameters& lua_target = { object_ship_wing_point_team(), luacpp::LuaValueList{} });
extern void ai_add_wing_goal_player(int type, int mode, int submode, char* shipname, int wingnum, const ai_lua_parameters& lua_target = { object_ship_wing_point_team(), luacpp::LuaValueList{} });
extern void ai_remove_ship_goal( ai_info *aip, int index );
extern void ai_clear_ship_goals( ai_info *aip );
+7 -7
View File
@@ -14,24 +14,24 @@
#include "weapon/weapon.h"
//Returns true if the specified object is a stealth ship, false if not
bool is_object_stealth_ship(const object* objp);
bool is_object_stealth_ship(object* objp);
//Number of live turrets on the object attacking
int num_turrets_attacking(const object *turret_parent, int target_objnum);
int num_turrets_attacking(object *turret_parent, int target_objnum);
//Determine whether an object is targetable within a nebula (checks for stealth)
bool object_is_targetable(const object *target, const ship *viewer);
int object_is_targetable(object *target, ship *viewer);
//Returns the number of enemy fighters within threshold of pos.
int num_nearby_fighters(int enemy_team_mask, const vec3d *pos, float threshold);
int num_nearby_fighters(int enemy_team_mask, vec3d *pos, float threshold);
//Returns true if OK for *aip to fire its current weapon at its current target.
bool check_ok_to_fire(int objnum, int target_objnum, const weapon_info *wip, int secondary_bank, const vec3d *firing_pos_global);
int check_ok_to_fire(int objnum, int target_objnum, weapon_info *wip, int secondary_bank, ship_subsys* turret);
//Returns true if *aip has a line of sight to its current target.
bool check_los(int objnum, int target_objnum, float threshold, int primary_bank, int secondary_bank, const vec3d *firing_pos_global);
bool check_los(int objnum, int target_objnum, float threshold, int primary_bank, int secondary_bank, ship_subsys* turret);
//Does all the stuff needed to aim and fire a turret.
void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss);
void ai_turret_execute_behavior(ship *shipp, ship_subsys *ss);
#endif
+17 -23
View File
@@ -97,35 +97,29 @@ SCP_vector<SCP_string> ai_lua_get_general_order_categories(bool enabled_only)
return list;
}
// Provides a list of general orders for mission saving. You can only get one kind
// of list at a time. If onlyEnabled and onlyValid are both true, for example, you will get
// a list of onlyEnabled orders. If you need a list of enabled orders that are also valid, you'll
// need to get both lists separately and compare.
SCP_vector<SCP_string> ai_lua_get_general_orders(bool onlyEnabled, bool onlyValid, const SCP_string& category)
{
SCP_vector<SCP_string> list;
for (const auto& order : Lua_player_orders) {
for (auto order : Lua_player_orders) {
if (order.second.generalOrder) {
bool add = false;
// All general orders
if (!onlyEnabled && !onlyValid && category.empty()) {
// Only enabled orders
if (onlyEnabled && order.second.cur_enabled) {
add = true;
// Only valid orders
} else if (onlyValid && order.second.cur_valid) {
add = true;
// Only orders that match the category requested
} else if ((!category.empty()) && (order.second.category == category)) {
add = true;
// All general orders
} else {
// Only enabled orders
if (onlyEnabled && order.second.cur_enabled) {
add = true;
// Only valid orders
} else if (onlyValid && order.second.cur_valid) {
add = true;
// Only orders that match the category requested
} else if ((!category.empty()) && (order.second.category == category)) {
add = true;
}
add = true;
}
if (add) {
@@ -167,7 +161,7 @@ void ai_lua_validate_general_order(int sexp_op, bool validity)
}
void ai_lua_reset_general_orders() {
for (const auto& order : Lua_player_orders) {
for (auto order : Lua_player_orders) {
ai_lua_enable_general_order(order.first, false);
ai_lua_validate_general_order(order.first, false);
}
@@ -254,7 +248,7 @@ void ai_lua_start_general(int lua_sexp_id, int target_objnum)
ai_info aip;
aip.shipnum = -1;
if (target_objnum >= 0 && Objects[target_objnum].type == OBJ_SHIP) {
if (target_objnum >= 0) {
aip.lua_ai_target = {object_ship_wing_point_team(&Ships[Objects[target_objnum].instance]), {}};
}
@@ -389,7 +383,7 @@ ai_achievability ai_lua_is_achievable(const ai_goal* aigp, int objnum){
if (!retVals.empty() && retVals[0].getValueType() == luacpp::ValueType::USERDATA) {
scripting::api::enum_h enumData;
retVals[0].getValue(scripting::api::l_Enum.Get(&enumData));
if (!enumData.isValid()) {
if (!enumData.IsValid()) {
Error(LOCATION, "LuaAI SEXP achievability hook returned an invalid avilability enum.");
return ai_achievability::ACHIEVABLE;
}
+243 -178
View File
@@ -72,29 +72,29 @@ const char* Turret_valid_types[NUM_TURRET_TYPES] = {
};
typedef struct eval_enemy_obj_struct {
int turret_parent_objnum = -1; // parent of turret
float weapon_travel_dist = 0.0f; // max targeting range of turret weapon
int enemy_team_mask = 0;
bool weapon_system_ok = false; // is the weapon subsystem of turret ship ok
int eeo_flags = 0;
int turret_parent_objnum; // parent of turret
float weapon_travel_dist; // max targeting range of turret weapon
int enemy_team_mask;
int weapon_system_ok; // is the weapon subsystem of turret ship ok
int eeo_flags;
const vec3d *tpos = nullptr;
const vec3d *tvec = nullptr;
const ship_subsys *turret_subsys = nullptr;
int current_enemy = -1;
vec3d *tpos;
vec3d *tvec;
ship_subsys *turret_subsys;
int current_enemy;
float nearest_attacker_dist = 99999.0f; // nearest ship
int nearest_attacker_objnum = -1;
float nearest_attacker_dist; // nearest ship
int nearest_attacker_objnum;
float nearest_homing_bomb_dist = 99999.0f; // nearest homing bomb
int nearest_homing_bomb_objnum = -1;
float nearest_homing_bomb_dist; // nearest homing bomb
int nearest_homing_bomb_objnum;
float nearest_bomb_dist = 99999.0f; // nearest non-homing bomb
int nearest_bomb_objnum = -1;
float nearest_bomb_dist; // nearest non-homing bomb
int nearest_bomb_objnum;
float nearest_dist = 99999.0f; // nearest ship attacking this turret
int nearest_objnum = -1;
float nearest_dist; // nearest ship attacking this turret
int nearest_objnum;
} eval_enemy_obj_struct;
// the current world orientation of the turret matrix, corresponding to its fvec and uvec defined in the model
@@ -118,9 +118,9 @@ void turret_instance_find_world_orient(matrix* out_mat, int model_instance_num,
* @param tpos Turret initial position
* @param dist Distance from turret to center point of object
*
* @return true if objp is in fov of the specified turret. Otherwise return false.
* @return 1 if objp is in fov of the specified turret. Otherwise return 0.
*/
bool object_in_turret_fov(const object *objp, const ship_subsys *ss, const vec3d *tvec, const vec3d *tpos, float dist)
bool object_in_turret_fov(object *objp, ship_subsys *ss, vec3d *tvec, vec3d *tpos, float dist)
{
vec3d v2e;
float size_mod;
@@ -175,9 +175,9 @@ bool object_in_turret_fov(const object *objp, const ship_subsys *ss, const vec3d
* @param bomb_objp Bomb specified
* @param ship_objp Ship specified
*
* @return true if bomb_objp is headed towards ship_objp
* @return 1 if bomb_objp is headed towards ship_objp
*/
bool bomb_headed_towards_ship(const object *bomb_objp, const object *ship_objp)
int bomb_headed_towards_ship(object *bomb_objp, object *ship_objp)
{
float dot;
vec3d bomb_to_ship_vector;
@@ -185,7 +185,11 @@ bool bomb_headed_towards_ship(const object *bomb_objp, const object *ship_objp)
vm_vec_normalized_dir(&bomb_to_ship_vector, &ship_objp->pos, &bomb_objp->pos);
dot = vm_vec_dot(&bomb_objp->orient.vec.fvec, &bomb_to_ship_vector);
return ( dot > 0 );
if ( dot > 0 ) {
return 1;
}
return 0;
}
// Set active weapon for turret
@@ -197,7 +201,7 @@ bool bomb_headed_towards_ship(const object *bomb_objp, const object *ship_objp)
* @note All non-negative return values are expressed in what I like to call "widx"s.
* @return -1 if unable to find a weapon for the target at all.
*/
int turret_select_best_weapon(const ship_subsys *turret, const object * /*target*/)
int turret_select_best_weapon(ship_subsys *turret, object * /*target*/)
{
//TODO: Fill this out with extraodinary gun-picking algorithms
if(turret->weapons.num_primary_banks > 0)
@@ -211,7 +215,7 @@ int turret_select_best_weapon(const ship_subsys *turret, const object * /*target
/**
* Returns true if all weapons in swp have the specified flag
*/
bool all_turret_weapons_have_flags(const ship_weapon *swp, flagset<Weapon::Info_Flags> flags)
bool all_turret_weapons_have_flags(ship_weapon *swp, flagset<Weapon::Info_Flags> flags)
{
int i;
for(i = 0; i < swp->num_primary_banks; i++)
@@ -228,7 +232,7 @@ bool all_turret_weapons_have_flags(const ship_weapon *swp, flagset<Weapon::Info_
return true;
}
bool all_turret_weapons_have_flags(const ship_weapon *swp, Weapon::Info_Flags flags)
bool all_turret_weapons_have_flags(ship_weapon *swp, Weapon::Info_Flags flags)
{
int i;
for (i = 0; i < swp->num_primary_banks; i++)
@@ -249,7 +253,7 @@ bool all_turret_weapons_have_flags(const ship_weapon *swp, Weapon::Info_Flags fl
* Returns true if any of the weapons in swp have flags
*
*/
bool turret_weapon_has_flags(const ship_weapon *swp, Weapon::Info_Flags flags)
bool turret_weapon_has_flags(ship_weapon *swp, Weapon::Info_Flags flags)
{
Assert(swp != NULL);
@@ -275,7 +279,7 @@ bool turret_weapon_has_flags(const ship_weapon *swp, Weapon::Info_Flags flags)
/**
* Just gloms all the flags from all the weapons into one variable. More efficient if all you need to do is test for the existence of a flag.
*/
flagset<Weapon::Info_Flags> turret_weapon_aggregate_flags(const ship_weapon *swp)
flagset<Weapon::Info_Flags> turret_weapon_aggregate_flags(ship_weapon *swp)
{
Assert(swp != NULL);
@@ -303,7 +307,7 @@ flagset<Weapon::Info_Flags> turret_weapon_aggregate_flags(const ship_weapon *swp
* @note It might be a little faster to optimize based on WP_LASER should only appear in primaries
* and WP_MISSILE in secondaries. but in the interest of future coding I leave it like this.
*/
bool turret_weapon_has_subtype(const ship_weapon *swp, int subtype)
bool turret_weapon_has_subtype(ship_weapon *swp, int subtype)
{
Assert(swp != NULL);
@@ -331,7 +335,7 @@ bool turret_weapon_has_subtype(const ship_weapon *swp, int subtype)
*
* @return a pointer to the Weapon_info for weapon_num
*/
const weapon_info *get_turret_weapon_wip(const ship_weapon *swp, int weapon_num)
weapon_info *get_turret_weapon_wip(ship_weapon *swp, int weapon_num)
{
Assert(weapon_num < MAX_SHIP_WEAPONS);
Assert(weapon_num >= 0);
@@ -348,7 +352,7 @@ const weapon_info *get_turret_weapon_wip(const ship_weapon *swp, int weapon_num)
return &Weapon_info[wi_index];
}
int get_turret_weapon_next_fire_stamp(const ship_weapon *swp, int weapon_num)
int get_turret_weapon_next_fire_stamp(ship_weapon *swp, int weapon_num)
{
Assert(weapon_num < MAX_SHIP_WEAPONS);
Assert(weapon_num >= 0);
@@ -375,7 +379,7 @@ void set_turret_weapon_next_fire_stamp(ship_weapon *swp, int weapon_num, int del
*
* @todo This function is kinda slow
*/
float longest_turret_weapon_range(const ship_weapon *swp)
float longest_turret_weapon_range(ship_weapon *swp)
{
float longest_range_so_far = 0.0f;
float weapon_range;
@@ -488,7 +492,7 @@ void evaluate_obj_as_target(object *objp, eval_enemy_obj_struct *eeo)
{
object *turret_parent_obj = &Objects[eeo->turret_parent_objnum];
ship *shipp;
auto ss = eeo->turret_subsys;
ship_subsys *ss = eeo->turret_subsys;
float dist, dist_comp;
bool turret_has_no_target = false;
@@ -766,10 +770,12 @@ void evaluate_obj_as_target(object *objp, eval_enemy_obj_struct *eeo)
* @param laser_flag
* @param missile_flag
*/
int get_nearest_turret_objnum(int turret_parent_objnum, const ship_subsys *turret_subsys, int enemy_team_mask, const vec3d *tpos, const vec3d *tvec, int current_enemy, bool big_only_flag, bool small_only_flag, bool tagged_only_flag, bool beam_flag, bool flak_flag, bool laser_flag, bool missile_flag)
int get_nearest_turret_objnum(int turret_parent_objnum, ship_subsys *turret_subsys, int enemy_team_mask, vec3d *tpos, vec3d *tvec, int current_enemy, bool big_only_flag, bool small_only_flag, bool tagged_only_flag, bool beam_flag, bool flak_flag, bool laser_flag, bool missile_flag)
{
//float weapon_travel_dist;
int weapon_system_ok;
eval_enemy_obj_struct eeo;
auto swp = &turret_subsys->weapons;
ship_weapon *swp = &turret_subsys->weapons;
// list of stuff to go thru
ship_obj *so;
@@ -782,7 +788,10 @@ int get_nearest_turret_objnum(int turret_parent_objnum, const ship_subsys *turre
// weapon_travel_dist=wip->lssm_lock_range;
// Set flag based on strength of weapons subsystem. If weapons subsystem is destroyed, don't let turrets fire at bombs
bool weapon_system_ok = !ship_subsystems_blown(&Ships[Objects[turret_parent_objnum].instance], SUBSYSTEM_WEAPONS);
weapon_system_ok = 0;
if ( ship_get_subsystem_strength( &Ships[Objects[turret_parent_objnum].instance], SUBSYSTEM_WEAPONS ) > 0 ) {
weapon_system_ok = 1;
}
// Initialize eeo struct.
eeo.turret_parent_objnum = turret_parent_objnum;
@@ -814,6 +823,18 @@ int get_nearest_turret_objnum(int turret_parent_objnum, const ship_subsys *turre
eeo.tvec = tvec;
eeo.turret_subsys = turret_subsys;
eeo.nearest_attacker_dist = 99999.0f;
eeo.nearest_attacker_objnum = -1;
eeo.nearest_homing_bomb_dist = 99999.0f;
eeo.nearest_homing_bomb_objnum = -1;
eeo.nearest_bomb_dist = 99999.0f;
eeo.nearest_bomb_objnum = -1;
eeo.nearest_dist = 99999.0f;
eeo.nearest_objnum = -1;
// here goes the new targeting priority setting
int n_tgt_priorities;
int priority_weapon_idx = -1;
@@ -1043,7 +1064,7 @@ int get_nearest_turret_objnum(int turret_parent_objnum, const ship_subsys *turre
break;
default:
UNREACHABLE("Invalid target type of %d sent to get_nearest_turret_objnum. Please report to the SCP!", turret_subsys->turret_targeting_order[i]);
Int3(); //Means invalid number passed.
}
}
}
@@ -1063,7 +1084,7 @@ DCF_BOOL(use_parent_target, Use_parent_target)
* @param tvec Forward vector of turret (world coords)
* @param current_enemy Objnum of current turret target
*/
int find_turret_enemy(const ship_subsys *turret_subsys, int objnum, const vec3d *tpos, const vec3d *tvec, int current_enemy)
int find_turret_enemy(ship_subsys *turret_subsys, int objnum, vec3d *tpos, vec3d *tvec, int current_enemy)
{
int enemy_team_mask, enemy_objnum;
ship_info *sip;
@@ -1150,9 +1171,9 @@ int find_turret_enemy(const ship_subsys *turret_subsys, int objnum, const vec3d
Assert( !((Objects[enemy_objnum].flags[Object::Object_Flags::Flak_protected]) && flak_flag) );
Assert( !((Objects[enemy_objnum].flags[Object::Object_Flags::Laser_protected]) && laser_flag) );
Assert( !((Objects[enemy_objnum].flags[Object::Object_Flags::Missile_protected]) && missile_flag) );
Assertion(!Objects[enemy_objnum].flags[Object::Object_Flags::Protected], "find_turret_enemy selected an object of type %d %s that is protected, please report to the SCP!", Objects[enemy_objnum].type, Objects[enemy_objnum].type == OBJ_SHIP ? Ships[Objects[enemy_objnum].instance].ship_name : "");
if ( Objects[enemy_objnum].flags[Object::Object_Flags::Protected] ) {
Int3();
enemy_objnum = aip->target_objnum;
}
}
@@ -1184,6 +1205,8 @@ void ship_get_global_turret_info(const object *objp, const model_subsystem *tp,
model_instance_local_to_global_dir(gvec, &tp->turret_norm, model_instance_num, tp->subobj_num, &objp->orient, true);
}
void turret_ai_update_aim(ai_info *aip, object *En_Objp, ship_subsys *ss);
/**
* Given an object and a turret on that object, return the actual firing point of the gun and its normal.
*
@@ -1194,44 +1217,86 @@ void ship_get_global_turret_info(const object *objp, const model_subsystem *tp,
* @param objp Pointer to object
* @param ssp Pointer to turret subsystem
* @param gpos Absolute position of gun firing point
* @param avg_origin Use virtual gun pos corresponding to the average of the firing points
* @param gvec Vector from *gpos to *targetp
* @param use_angles Use current angles
* @param targetp Absolute position of target object
* @param targetp Pointer to target object
*/
void ship_get_global_turret_gun_info(const object *objp, const ship_subsys *ssp, vec3d *gpos, bool avg_origin, vec3d *gvec, bool use_angles, const vec3d *targetp)
void ship_get_global_turret_gun_info(object *objp, ship_subsys *ssp, vec3d *gpos, vec3d *gvec, int use_angles, vec3d *targetp)
{
vec3d *gun_pos;
vec3d * gun_pos;
model_subsystem *tp = ssp->system_info;
polymodel_instance *pmi = model_get_instance(Ships[objp->instance].model_instance_num);
polymodel *pm = model_get(pmi->model_num);
vec3d avg_gun_pos;
if (avg_origin) {
vm_vec_avg_n(&avg_gun_pos, tp->turret_num_firing_points, tp->turret_firing_point);
gun_pos = &avg_gun_pos;
} else {
gun_pos = &tp->turret_firing_point[ssp->turret_next_fire_pos % tp->turret_num_firing_points];
}
gun_pos = &tp->turret_firing_point[ssp->turret_next_fire_pos % tp->turret_num_firing_points];
model_instance_local_to_global_point(gpos, gun_pos, pm, pmi, tp->turret_gun_sobj, &objp->orient, &objp->pos);
// we might not need to calculate this
if (!gvec)
return;
if (use_angles) {
model_instance_local_to_global_dir(gvec, &tp->turret_norm, pm, pmi, tp->turret_gun_sobj, &objp->orient);
} else if (tp->flags[Model::Subsystem_Flags::Share_fire_direction]) {
vec3d avg, tmp_pos, tmp_target, enemy_point, turret_norm;
vm_vec_avg_n(&avg, tp->turret_num_firing_points, tp->turret_firing_point);
model_instance_local_to_global_point(&tmp_pos, &avg, pm, pmi, tp->turret_gun_sobj, &objp->orient, &objp->pos);
if (targetp == nullptr) {
ship* shipp = &Ships[Objects[ssp->parent_objnum].instance];
Assertion(ssp->turret_enemy_objnum >= 0, "The turret enemy object number %d for %s on ship name %s is invalid.", ssp->turret_enemy_objnum, ssp->sub_name, shipp->ship_name);
object *lep = &Objects[ssp->turret_enemy_objnum];
int best_weapon_tidx = turret_select_best_weapon(ssp, lep);
//This turret doesn't have any good weapons
if (best_weapon_tidx < 0)
return;
weapon_info *wip = get_turret_weapon_wip(&ssp->weapons, best_weapon_tidx);
float weapon_system_strength = ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS);
turret_ai_update_aim(&Ai_info[shipp->ai_index], &Objects[ssp->turret_enemy_objnum], ssp);
if ((ssp->targeted_subsys != nullptr) && !(ssp->flags[Ship::Subsystem_Flags::No_SS_targeting])) {
vm_vec_unrotate(&enemy_point, &ssp->targeted_subsys->system_info->pnt, &Objects[ssp->turret_enemy_objnum].orient);
vm_vec_add2(&enemy_point, &ssp->last_aim_enemy_pos);
} else {
if ((lep->type == OBJ_SHIP) && (Ship_info[Ships[lep->instance].ship_info_index].is_big_or_huge())) {
// the turret norm here is from the perspective of the base submodel, not the gun submodel
model_instance_local_to_global_dir(&turret_norm, &tp->turret_norm, pm, pmi, pm->submodel[tp->subobj_num].parent, &objp->orient);
ai_big_pick_attack_point_turret(lep, ssp, &tmp_pos, &turret_norm, &enemy_point, MIN(wip->max_speed * wip->lifetime, wip->weapon_range), tp->turret_fov);
}
else {
enemy_point = ssp->last_aim_enemy_pos;
}
}
vec3d target_moving_direction = ssp->last_aim_enemy_vel;
//Try to guess where the enemy will be, and store that spot in predicted_enemy_pos
if (The_mission.ai_profile->flags[AI::Profile_Flags::Use_additive_weapon_velocity]) {
vm_vec_scale_sub2(&target_moving_direction, &objp->phys_info.vel, wip->vel_inherit_amount);
}
set_predicted_enemy_pos_turret(&tmp_target, &tmp_pos, objp, &enemy_point, &target_moving_direction, wip->max_speed, ssp->turret_time_enemy_in_range * (weapon_system_strength + 1.0f) / 2.0f);
} else {
tmp_target = *targetp;
}
vm_vec_normalized_dir(gvec, &tmp_target, &tmp_pos);
} else {
Assertion(targetp != nullptr, "The targetp parameter must not be null here!");
//vector gun_pos2;
//vm_vec_add(&gun_pos2, gpos, gun_pos);
vm_vec_normalized_dir(gvec, targetp, gpos);
}
// per firingpoint based changes go here for turrets
}
/**
* Update turret aiming data based on max turret aim update delay
*/
void turret_ai_update_aim(const ai_info *aip, const object *En_Objp, ship_subsys *ss)
void turret_ai_update_aim(ai_info *aip, object *En_Objp, ship_subsys *ss)
{
if (Missiontime >= ss->next_aim_pos_time)
{
@@ -1246,15 +1311,26 @@ void turret_ai_update_aim(const ai_info *aip, const object *En_Objp, ship_subsys
}
}
/**
* Sets predicted enemy position. Previously done at the beginning of aifft_rotate_turret.
* Rotate a turret towards an enemy.
*
* Some obscure model thing only John Slagel knows about.
* Sets predicted enemy position.
* If the turret (*ss) has a subsystem targeted, the subsystem is used as the predicted point.
*
* @return TRUE if caller should use angles in subsequent rotations.
*/
void aifft_update_predicted_enemy_pos(const object *objp, const ship *shipp, ship_subsys *ss, const vec3d *global_gun_pos, const vec3d *global_gun_vec, const object *lep, vec3d *predicted_enemy_pos)
int aifft_rotate_turret(object *objp, ship *shipp, ship_subsys *ss, object *lep, vec3d *predicted_enemy_pos, vec3d *gvec)
{
int ret_val __UNUSED = 0; // to be used in future, see comment @ end of function
auto pmi = model_get_instance(shipp->model_instance_num);
auto pm = model_get(pmi->model_num);
if (ss->turret_enemy_objnum != -1) {
model_subsystem *tp = ss->system_info;
vec3d target_vel;
vec3d gun_pos, gun_vec, target_vel;
//float weapon_speed;
float weapon_system_strength;
//HACK HACK HACK -WMC
//This should use the best weapon variable
@@ -1263,13 +1339,15 @@ void aifft_update_predicted_enemy_pos(const object *objp, const ship *shipp, shi
//This turret doesn't have any good weapons
if (best_weapon_tidx < 0)
return;
return 0;
auto wip = get_turret_weapon_wip(&ss->weapons, best_weapon_tidx);
weapon_info *wip = get_turret_weapon_wip(&ss->weapons, best_weapon_tidx);
// weapon_system_strength scales time enemy in range in 0..1. So, the lower this is, the worse the aiming will be.
weapon_system_strength = ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS);
ship_get_global_turret_info(objp, tp, &gun_pos, &gun_vec);
//Update "known" position and velocity of target. Only matters if max_aim_update_delay is set.
turret_ai_update_aim(&Ai_info[shipp->ai_index], &Objects[ss->turret_enemy_objnum], ss);
@@ -1283,7 +1361,7 @@ void aifft_update_predicted_enemy_pos(const object *objp, const ship *shipp, shi
}
} else {
if ((lep->type == OBJ_SHIP) && (Ship_info[Ships[lep->instance].ship_info_index].is_big_or_huge())) {
ai_big_pick_attack_point_turret(lep, ss, global_gun_pos, global_gun_vec, &enemy_point, tp->turret_fov, MIN(wip->max_speed * wip->lifetime, wip->weapon_range));
ai_big_pick_attack_point_turret(lep, ss, &gun_pos, &gun_vec, &enemy_point, tp->turret_fov, MIN(wip->max_speed * wip->lifetime, wip->weapon_range));
} else {
enemy_point = ss->last_aim_enemy_pos;
}
@@ -1296,13 +1374,24 @@ void aifft_update_predicted_enemy_pos(const object *objp, const ship *shipp, shi
vm_vec_scale_sub2(&target_vel, &objp->phys_info.vel, wip->vel_inherit_amount);
}
if (tp->flags[Model::Subsystem_Flags::Turret_distant_firepoint] || Always_use_distant_firepoints) {
//The firing point of this turret is so far away from the its center that we should consider this for firing calculations
//This will do the enemy position prediction based on their relative position and speed to the firing point, not the turret center.
vec3d temp;
ship_get_global_turret_gun_info(objp, ss, &gun_pos, &temp, 1, nullptr);
}
if (IS_VEC_NULL(&The_mission.gravity) || wip->gravity_const == 0.0f)
set_predicted_enemy_pos_turret(predicted_enemy_pos, global_gun_pos, objp, &enemy_point, &target_vel, wip->max_speed, ss->turret_time_enemy_in_range * (weapon_system_strength + 1.0f)/2.0f);
set_predicted_enemy_pos_turret(predicted_enemy_pos, &gun_pos, objp, &enemy_point, &target_vel, wip->max_speed, ss->turret_time_enemy_in_range * (weapon_system_strength + 1.0f)/2.0f);
else {
vec3d shoot_vec;
vec3d gravity_vec = The_mission.gravity * wip->gravity_const;
if (physics_lead_ballistic_trajectory(global_gun_pos, &enemy_point, &target_vel, wip->max_speed, &gravity_vec, &shoot_vec)) {
*predicted_enemy_pos = *global_gun_pos + shoot_vec * 1000.0f;
if (physics_lead_ballistic_trajectory(&gun_pos, &enemy_point, &target_vel, wip->max_speed, &The_mission.gravity, &shoot_vec)) {
*predicted_enemy_pos = gun_pos + shoot_vec * 1000.0f;
} else {
if ((ss->system_info->flags[Model::Subsystem_Flags::Turret_reset_idle]) && (timestamp_elapsed(ss->rotation_timestamp))) {
ret_val = model_rotate_gun(objp, pm, pmi, ss, predicted_enemy_pos, true);
}
return ret_val;
}
}
@@ -1314,54 +1403,36 @@ void aifft_update_predicted_enemy_pos(const object *objp, const ship *shipp, shi
// Add to predicted_enemy_pos value in .45 to 1.5x radius of enemy ship, so will often miss, but not by a huge amount.
vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, (1.0f - weapon_system_strength)*1.5f * lep->radius);
}
}
}
/**
* Rotate a turret towards an enemy.
*
* Some obscure model thing only John Slagel knows about.
*
* @return TRUE if caller should use angles in subsequent rotations.
*/
bool aifft_rotate_turret(const object *objp, const ship *shipp, ship_subsys *ss, const vec3d *global_gun_pos, const vec3d *global_gun_vec, const vec3d *predicted_enemy_pos)
{
bool ret_val __UNUSED = false; // to be used in future, see comment @ end of function
auto pmi = model_get_instance(shipp->model_instance_num);
auto pm = model_get(pmi->model_num);
if (ss->turret_enemy_objnum != -1) {
model_subsystem *tp = ss->system_info;
//Get the normalized dir between the turret and the predicted enemy position.
//If the dot product is smaller than or equal to the turret's FOV, try and point the gun at it.
vec3d v2e;
vm_vec_normalized_dir(&v2e, predicted_enemy_pos, global_gun_pos);
vm_vec_normalized_dir(&v2e, predicted_enemy_pos, &gun_pos);
bool in_fov;
in_fov = turret_fov_test(ss, global_gun_vec, &v2e);
in_fov = turret_fov_test(ss, gvec, &v2e);
if (in_fov) {
ret_val = model_rotate_gun(objp, pm, pmi, ss, predicted_enemy_pos);
} else if ((tp->flags[Model::Subsystem_Flags::Turret_reset_idle]) &&(timestamp_elapsed(ss->rotation_timestamp))) {
ret_val = model_rotate_gun(objp, pm, pmi, ss, nullptr);
ret_val = model_rotate_gun(objp, pm, pmi, ss, predicted_enemy_pos, true);
}
} else if ((ss->system_info->flags[Model::Subsystem_Flags::Turret_reset_idle]) && (timestamp_elapsed(ss->rotation_timestamp))) {
ret_val = model_rotate_gun(objp, pm, pmi, ss, nullptr);
ret_val = model_rotate_gun(objp, pm, pmi, ss, predicted_enemy_pos, true);
}
// by default "ret_val" should be set to true for multi-part turrets, and false for single-part turrets
// but we need to keep retail behavior by default, which means always returning false unless a special
// by default "ret_val" should be set to 1 for multi-part turrets, and 0 for single-part turrets
// but we need to keep retail behavior by default, which means always returning 0 unless a special
// flag is used. the "ret_val" stuff is here is needed/wanted at a later date however.
//return ret_val;
// return false by default (to preserve retail behavior) but allow for a per-subsystem option
// return 0 by default (to preserve retail behavior) but allow for a per-subsystem option
// for using the turret normals for firing
if (ss->system_info->flags[Model::Subsystem_Flags::Fire_on_normal])
return true;
return 1;
return false;
return 0;
}
/**
@@ -1369,7 +1440,7 @@ bool aifft_rotate_turret(const object *objp, const ship *shipp, ship_subsys *ss,
*
* @return Dot product of vector from point abs_gunposp to *enemy_subsysp, if hittable
*/
float aifft_compute_turret_dot(const object *objp, const object *enemy_objp, const vec3d *abs_gunposp, const ship_subsys *turret_subsysp, const ship_subsys *enemy_subsysp)
float aifft_compute_turret_dot(object *objp, object *enemy_objp, vec3d *abs_gunposp, ship_subsys *turret_subsysp, ship_subsys *enemy_subsysp)
{
float dot_out;
vec3d subobj_pos, vector_out;
@@ -1377,7 +1448,7 @@ float aifft_compute_turret_dot(const object *objp, const object *enemy_objp, con
vm_vec_unrotate(&subobj_pos, &enemy_subsysp->system_info->pnt, &enemy_objp->orient);
vm_vec_add2(&subobj_pos, &enemy_objp->pos);
if (ship_subsystem_in_sight(enemy_objp, enemy_subsysp, abs_gunposp, &subobj_pos, true, &dot_out, &vector_out)) {
if (ship_subsystem_in_sight(enemy_objp, enemy_subsysp, abs_gunposp, &subobj_pos, 1, &dot_out, &vector_out)) {
vec3d turret_norm;
model_instance_local_to_global_dir(&turret_norm, &turret_subsysp->system_info->turret_norm, Ships[objp->instance].model_instance_num, turret_subsysp->system_info->subobj_num, &objp->orient, true);
@@ -1431,7 +1502,7 @@ DCF(mf, "Adjusts the maximum number of tries an AI may do when trying to pick a
*
* @return Dot product from turret to subsystem in *dot_out
*/
ship_subsys *aifft_find_turret_subsys(const object *objp, const ship_subsys *ssp, const vec3d *global_gun_pos, const object *enemy_objp, float *dot_out)
ship_subsys *aifft_find_turret_subsys(object *objp, ship_subsys *ssp, object *enemy_objp, float *dot_out)
{
ship *eshipp, *shipp;
ship_info *esip;
@@ -1448,6 +1519,10 @@ ship_subsys *aifft_find_turret_subsys(const object *objp, const ship_subsys *ssp
float best_dot = 0.0f;
*dot_out = best_dot;
// Compute absolute gun position.
vec3d abs_gun_pos;
ship_get_global_turret_info(objp, ssp->system_info, &abs_gun_pos, nullptr);
// Only pick a turret to attack on large ships.
if (!esip->is_big_or_huge())
return best_subsysp;
@@ -1503,7 +1578,7 @@ ship_subsys *aifft_find_turret_subsys(const object *objp, const ship_subsys *ssp
if(stride <= 0){
stride = 1;
}
int offset = Random::next((aifft_list_size % stride) + 1); // returns an offset in [0, size % stride] inclusive
int offset = (int)frand_range(0.0f, (float)(aifft_list_size % stride));
int idx;
float dot_fov_modifier = 0.0f;
@@ -1513,7 +1588,7 @@ ship_subsys *aifft_find_turret_subsys(const object *objp, const ship_subsys *ssp
}
for(idx=offset; idx<aifft_list_size; idx+=stride){
dot = aifft_compute_turret_dot(objp, enemy_objp, global_gun_pos, ssp, aifft_list[idx]);
dot = aifft_compute_turret_dot(objp, enemy_objp, &abs_gun_pos, ssp, aifft_list[idx]);
if ((dot - dot_fov_modifier)* aifft_rank[idx] > best_dot) {
best_dot = (dot - dot_fov_modifier)*aifft_rank[idx];
@@ -1528,17 +1603,34 @@ ship_subsys *aifft_find_turret_subsys(const object *objp, const ship_subsys *ssp
}
/**
* @return true if the specified target should scan for a new target, otherwise return false
* @return !0 if the specified target should scan for a new target, otherwise return 0
*/
bool turret_should_pick_new_target(ship_subsys *turret)
int turret_should_pick_new_target(ship_subsys *turret)
{
return timestamp_elapsed(turret->turret_next_enemy_check_stamp);
// int target_type;
if ( timestamp_elapsed(turret->turret_next_enemy_check_stamp) ) {
return 1;
}
/*
if ( turret->turret_enemy_objnum == -1 ) {
return 1;
}
target_type = Objects[turret->turret_enemy_objnum].type;
if ( (target_type != OBJ_SHIP) && (target_type != OBJ_ASTEROID) ) {
return 1;
}
*/
return 0;
}
/**
* Set the next fire timestamp for a turret, based on weapon type and ai class
*/
void turret_set_next_fire_timestamp(int weapon_num, const weapon_info *wip, ship_subsys *turret, const ai_info *aip)
void turret_set_next_fire_timestamp(int weapon_num, weapon_info *wip, ship_subsys *turret, ai_info *aip)
{
Assert(weapon_num < MAX_SHIP_WEAPONS);
float wait = 1000.0f;
@@ -1651,13 +1743,13 @@ void turret_set_next_fire_timestamp(int weapon_num, const weapon_info *wip, ship
/**
* Decide if a turret should launch an aspect seeking missile
*/
bool turret_should_fire_aspect(const ship_subsys *turret, const weapon_info *wip, bool in_sight)
int turret_should_fire_aspect(ship_subsys *turret, weapon_info *wip, bool in_sight)
{
if ( in_sight && (turret->turret_time_enemy_in_range >= MIN(wip->min_lock_time,AICODE_TURRET_MAX_TIME_IN_RANGE)) ) {
return true;
return 1;
}
return false;
return 0;
}
/**
@@ -1679,9 +1771,9 @@ void turret_update_enemy_in_range(ship_subsys *turret, float seconds)
/**
* Fire a weapon from a turret
*/
bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum, const vec3d *orig_firing_pos, const vec3d *orig_firing_vec, const vec3d *predicted_pos = nullptr, float flak_range_override = 100.0f, bool play_sound = true)
bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum, vec3d *turret_pos, vec3d *firing_vec, vec3d *predicted_pos = nullptr, float flak_range_override = 100.0f, bool play_sound = true)
{
matrix firing_orient;
matrix turret_orient;
int weapon_objnum;
ai_info *parent_aip;
ship *parent_ship;
@@ -1743,21 +1835,16 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
}
#endif
if (check_ok_to_fire(parent_objnum, turret->turret_enemy_objnum, wip, -1, orig_firing_pos)) {
if (check_ok_to_fire(parent_objnum, turret->turret_enemy_objnum, wip, -1, turret)) {
auto turret_enemy_objp = (turret->turret_enemy_objnum >= 0) ? &Objects[turret->turret_enemy_objnum] : nullptr;
ship_weapon* swp = &turret->weapons;
turret->turret_last_fire_direction = *orig_firing_vec;
turret->turret_last_fire_direction = *firing_vec;
const vec3d *firing_vec = orig_firing_vec;
vec3d firing_vec_buf;
if (turret->turret_inaccuracy > 0.0f)
vm_vec_random_cone(firing_vec, firing_vec, turret->turret_inaccuracy);
if (turret->turret_inaccuracy > 0.0f) {
vm_vec_random_cone(&firing_vec_buf, firing_vec, turret->turret_inaccuracy);
firing_vec = &firing_vec_buf;
}
vm_vector_2_matrix(&firing_orient, firing_vec, nullptr, nullptr);
vm_vector_2_matrix(&turret_orient, firing_vec, nullptr, nullptr);
// grab and set some burst data before turret_set_next_fire_timestamp wipes it
int old_burst_seed = swp->burst_seed[weapon_num];
@@ -1936,15 +2023,11 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
}
}
}
vec3d firing_pos_buf;
const vec3d *firing_pos = &firing_pos_buf;
// zookeeper - Firepoints should cycle normally between shots,
// so we need to get the position info separately for each shot
ship_get_global_turret_gun_info(&Objects[parent_objnum], turret, &firing_pos_buf, false, nullptr, true, nullptr);
ship_get_global_turret_gun_info(&Objects[parent_objnum], turret, turret_pos, firing_vec, 1, nullptr);
weapon_objnum = weapon_create(firing_pos, &firing_orient, turret_weapon_class, parent_objnum, -1, 1, 0, 0.0f, turret);
weapon_objnum = weapon_create( turret_pos, &turret_orient, turret_weapon_class, parent_objnum, -1, 1, 0,0.0f, turret);
weapon_set_tracking_info(weapon_objnum, parent_objnum, turret->turret_enemy_objnum, 1, turret->targeted_subsys);
//nprintf(("AI", "Turret_time_enemy_in_range = %7.3f\n", ss->turret_time_enemy_in_range));
@@ -1976,7 +2059,7 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
if(predicted_pos != NULL)
{
// pick a firing range so that it detonates properly
flak_pick_range(objp, firing_pos, predicted_pos, ship_get_subsystem_strength(parent_ship, SUBSYSTEM_WEAPONS));
flak_pick_range(objp, turret_pos, predicted_pos, ship_get_subsystem_strength(parent_ship, SUBSYSTEM_WEAPONS));
// determine what that range was
flak_range = flak_get_range(objp);
@@ -1989,7 +2072,7 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
// do mflash if the weapon has it
if (wip->muzzle_flash >= 0) {
mflash_create(firing_pos, firing_vec, &Objects[parent_ship->objnum].phys_info, wip->muzzle_flash);
mflash_create(turret_pos, firing_vec, &Objects[parent_ship->objnum].phys_info, wip->muzzle_flash);
}
// in multiplayer (and the master), then send a turret fired packet.
@@ -2008,7 +2091,7 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
if ( play_sound && wip->launch_snd.isValid() ) {
// Don't play turret firing sound if turret sits on player ship... it gets annoying.
if ( parent_objnum != OBJ_INDEX(Player_obj) || (turret->flags[Ship::Subsystem_Flags::Play_sound_for_player]) ) {
snd_play_3d( gamesnd_get_game_sound(wip->launch_snd), firing_pos, &View_position );
snd_play_3d( gamesnd_get_game_sound(wip->launch_snd), turret_pos, &View_position );
}
}
}
@@ -2040,7 +2123,7 @@ bool turret_fire_weapon(int weapon_num, ship_subsys *turret, int parent_objnum,
void turret_swarm_fire_from_turret(turret_swarm_info *tsi)
{
int weapon_objnum;
matrix firing_orient;
matrix turret_orient;
vec3d turret_pos, turret_fvec;
// parent not alive, quick out.
@@ -2053,7 +2136,7 @@ void turret_swarm_fire_from_turret(turret_swarm_info *tsi)
tsi->turret->turret_next_fire_pos = tsi->weapon_num;
// change firing point
ship_get_global_turret_gun_info(&Objects[tsi->parent_objnum], tsi->turret, &turret_pos, false, &turret_fvec, true, nullptr);
ship_get_global_turret_gun_info(&Objects[tsi->parent_objnum], tsi->turret, &turret_pos, &turret_fvec, 1, NULL);
tsi->turret->turret_next_fire_pos++;
//check if this really is a swarm. If not, how the hell did it get here?
@@ -2068,11 +2151,11 @@ void turret_swarm_fire_from_turret(turret_swarm_info *tsi)
turret_fvec = tsi->turret->turret_last_fire_direction;
}
// make firing_orient from turret_fvec -- turret->turret_last_fire_direction
vm_vector_2_matrix(&firing_orient, &turret_fvec, NULL, NULL);
// make turret_orient from turret_fvec -- turret->turret_last_fire_direction
vm_vector_2_matrix(&turret_orient, &turret_fvec, NULL, NULL);
// create weapon and homing info
weapon_objnum = weapon_create(&turret_pos, &firing_orient, tsi->weapon_class, tsi->parent_objnum, -1, 1, 0, 0.0f, tsi->turret);
weapon_objnum = weapon_create(&turret_pos, &turret_orient, tsi->weapon_class, tsi->parent_objnum, -1, 1, 0, 0.0f, tsi->turret);
weapon_set_tracking_info(weapon_objnum, tsi->parent_objnum, tsi->target_objnum, 1, tsi->target_subsys);
// do other cool stuff if weapon is created.
@@ -2131,7 +2214,7 @@ int Num_turrets_fired = 0;
* all turret movement and resetting when idle
*/
extern int Nebula_sec_range;
void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
void ai_turret_execute_behavior(ship *shipp, ship_subsys *ss)
{
float weapon_firing_range;
float weapon_min_range; // *Weapon minimum firing range -Et1
@@ -2215,21 +2298,12 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
objp = &Objects[shipp->objnum];
Assert(objp->type == OBJ_SHIP);
vec3d global_gun_pos, global_gun_vec;
if (tp->flags[Model::Subsystem_Flags::Turret_distant_firepoint] || Always_use_distant_firepoints) {
//The firing point of this turret is so far away from the its center that we should consider this for firing calculations
//This will do the enemy position prediction based on their relative position and speed to the firing point, not the turret center.
ship_get_global_turret_gun_info(objp, ss, &global_gun_pos, false, &global_gun_vec, true, nullptr);
} else {
// Use the turret info for all guns, not one gun in particular.
ship_get_global_turret_info(objp, tp, &global_gun_pos, &global_gun_vec);
}
// Update predicted enemy position. This used to be done in aifft_rotate_turret
aifft_update_predicted_enemy_pos(objp, shipp, ss, &global_gun_pos, &global_gun_vec, lep, &predicted_enemy_pos);
// Use the turret info for all guns, not one gun in particular.
vec3d gvec, gpos;
ship_get_global_turret_info(objp, tp, &gpos, &gvec);
// Rotate the turret even if time hasn't elapsed, since it needs to turn to face its target.
bool use_angles = aifft_rotate_turret(objp, shipp, ss, &global_gun_pos, &global_gun_vec, &predicted_enemy_pos);
int use_angles = aifft_rotate_turret(objp, shipp, ss, lep, &predicted_enemy_pos, &gvec);
// Multiplayer clients are now able to try to track their targets and also reset to their idle positions.
// But everything after this point is turret firing, so we need to bail here.
@@ -2253,20 +2327,18 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
float dist_to_enemy = 0.0f;
if (lep) {
if (The_mission.ai_profile->flags[AI::Profile_Flags::Turrets_ignore_target_radius])
dist_to_enemy = MAX(0, vm_vec_normalized_dir(&v2e, &predicted_enemy_pos, &global_gun_pos));
dist_to_enemy = MAX(0, vm_vec_normalized_dir(&v2e, &predicted_enemy_pos, &gpos));
else
dist_to_enemy = MAX(0, vm_vec_normalized_dir(&v2e, &predicted_enemy_pos, &global_gun_pos) - lep->radius);
dist_to_enemy = MAX(0, vm_vec_normalized_dir(&v2e, &predicted_enemy_pos, &gpos) - lep->radius);
}
// count the number of enemies, in case we have a spawning weapon
int num_ships_nearby = num_nearby_fighters(iff_get_attackee_mask(obj_team(objp)), &global_gun_pos, 1500.0f);
int num_ships_nearby = num_nearby_fighters(iff_get_attackee_mask(obj_team(objp)), &gpos, 1500.0f);
// some flags considering there may be different weapon types on this turret
bool we_did_non_spawning_logic = false;
bool tentative_return = false;
float turret_barrel_length = -1.0f;
//WMC - go through all valid weapons. Fire spawns if there are any.
int valid_weapons[MAX_SHIP_WEAPONS];
int num_valid = 0;
@@ -2298,7 +2370,7 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
if ( (wip->wi_flags[Weapon::Info_Flags::Spawn]) && !(wip->wi_flags[Weapon::Info_Flags::Smart_spawn]) )
{
if (( num_ships_nearby >= 3 ) || ((num_ships_nearby >= 2) && (frand() < 0.1f))) {
turret_fire_weapon(i, ss, parent_objnum, &global_gun_pos, &ss->turret_last_fire_direction);
turret_fire_weapon(i, ss, parent_objnum, &gpos, &ss->turret_last_fire_direction);
} else {
// Regardless of firing rate, don't check whether should fire for awhile.
if (tp->flags[Model::Subsystem_Flags::Use_multiple_guns])
@@ -2346,16 +2418,10 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
// If the barrel of this turret is long, we shouldn't try to fire if the enemy is under the gun.
// Note that this isn't the same thing as min_range, which is unrelated to barrel length.
if (tp->flags[Model::Subsystem_Flags::Turret_distant_firepoint] || Always_use_distant_firepoints) {
if (turret_barrel_length < 0.0f) {
if (tp->turret_gun_sobj >= 0) {
auto pm = model_get(tp->model_num);
auto submodel = &pm->submodel[tp->turret_gun_sobj];
turret_barrel_length = 2 * submodel->rad;
} else {
turret_barrel_length = 0.0f;
}
}
if (dist_to_enemy < turret_barrel_length) continue;
vec3d fpoint, fvec;
ship_get_global_turret_gun_info(objp, ss, &fpoint, &fvec, use_angles, &predicted_enemy_pos);
auto barrel_length = vm_vec_dist(&fpoint, &gpos);
if (dist_to_enemy < barrel_length) continue;
}
// Don't try to fire beyond weapon_limit_range (or within min range)
@@ -2473,7 +2539,7 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
// Maybe pick a new enemy, unless targeting has been taken over by scripting
if ( turret_should_pick_new_target(ss) && !ss->scripting_target_override && !(ss->flags[Ship::Subsystem_Flags::Forced_target])) {
Num_find_turret_enemy++;
int objnum = find_turret_enemy(ss, parent_objnum, &global_gun_pos, &global_gun_vec, ss->turret_enemy_objnum);
int objnum = find_turret_enemy(ss, parent_objnum, &gpos, &gvec, ss->turret_enemy_objnum);
if (objnum >= 0) {
if (ss->turret_enemy_objnum == -1) {
@@ -2495,7 +2561,7 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
float dot = 1.0f;
lep = &Objects[ss->turret_enemy_objnum];
if (( lep->type == OBJ_SHIP ) && !(ss->flags[Ship::Subsystem_Flags::No_SS_targeting])) {
ss->targeted_subsys = aifft_find_turret_subsys(objp, ss, &global_gun_pos, lep, &dot);
ss->targeted_subsys = aifft_find_turret_subsys(objp, ss, lep, &dot);
}
// recheck in 2-3 seconds
ss->turret_next_enemy_check_stamp = timestamp((int)((MAX(dot, 0.5f) * The_mission.ai_profile->turret_target_recheck_time) + (The_mission.ai_profile->turret_target_recheck_time / 2.0f)));
@@ -2536,15 +2602,14 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
return;
}
//This can't happen. See above code
//if ( lep == nullptr ){
// return;
//}
if ( lep == nullptr ){
return;
}
//This can't happen. See above code
//Assert(ss->turret_enemy_objnum != -1);
bool in_fov = turret_fov_test(ss, &global_gun_vec, &v2e);
bool in_fov = turret_fov_test(ss, &gvec, &v2e);
bool something_was_ok_to_fire = false;
// the only reason predicted_enemy_pos might be zero, while everything else is valid is if
@@ -2599,13 +2664,13 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
// We're ready to fire... now get down to specifics, like where is the
// actual gun point and normal, not just the one for whole turret.
ship_get_global_turret_gun_info(objp, ss, &global_gun_pos, false, &global_gun_vec, use_angles, &predicted_enemy_pos);
ship_get_global_turret_gun_info(objp, ss, &gpos, &gvec, use_angles, &predicted_enemy_pos);
// Fire in the direction the turret is facing, not right at the target regardless of turret dir.
// [Yet this retail comment precedes the calculation of vector-to-enemy...]
vm_vec_sub(&v2e, &predicted_enemy_pos, &global_gun_pos);
vm_vec_sub(&v2e, &predicted_enemy_pos, &gpos);
dist_to_enemy = vm_vec_normalize(&v2e);
float dot = vm_vec_dot(&v2e, &global_gun_vec);
float dot = vm_vec_dot(&v2e, &gvec);
// (flak jitter moved to after we obtain shoot_vector below)
@@ -2670,7 +2735,7 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
// Check if turret should fire and enemy's engines are
// in line of sight
if (turret_should_fire_aspect(ss, wip, in_sight) &&
ship_get_closest_subsys_in_sight(&Ships[lep->signature], SUBSYSTEM_ENGINE, &global_gun_pos))
ship_get_closest_subsys_in_sight(&Ships[lep->signature], SUBSYSTEM_ENGINE, &gpos))
{
ok_to_fire = true;
}
@@ -2680,14 +2745,14 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
if ( ok_to_fire && (tp->flags[Model::Subsystem_Flags::Turret_hull_check]) ) {
int model_num = Ship_info[shipp->ship_info_index].model_num;
vec3d end;
vm_vec_scale_add(&end, &global_gun_pos, &global_gun_vec, model_get_radius(model_num));
vm_vec_scale_add(&end, &gpos, &gvec, model_get_radius(model_num));
mc_info hull_check;
hull_check.model_instance_num = shipp->model_instance_num;
hull_check.model_num = model_num;
hull_check.orient = &objp->orient;
hull_check.pos = &objp->pos;
hull_check.p0 = &global_gun_pos;
hull_check.p0 = &gpos;
hull_check.p1 = &end;
hull_check.flags = MC_CHECK_MODEL | MC_CHECK_RAY;
@@ -2727,7 +2792,7 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
// (Despite the retail comment above, retail actually fired toward the enemy; v2e = vector-to-enemy)
vec3d shoot_vector = v2e;
if (tp->flags[Model::Subsystem_Flags::Fire_on_normal])
shoot_vector = global_gun_vec;
shoot_vector = gvec;
// if the weapon is a flak gun, add some jitter to its aim so it fires in a "cone"
// to make a cool visual effect and make them less lethal
@@ -2735,7 +2800,7 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
flak_jitter_aim(&shoot_vector, dist_to_enemy, ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS), wip);
}
turret_fire_weapon(valid_weapons[valid_index], ss, parent_objnum, &global_gun_pos, &shoot_vector, &predicted_enemy_pos, 100.0f, play_sound);
turret_fire_weapon(valid_weapons[valid_index], ss, parent_objnum, &gpos, &shoot_vector, &predicted_enemy_pos, 100.0f, play_sound);
}
else
{
@@ -2804,7 +2869,7 @@ void ai_turret_execute_behavior(const ship *shipp, ship_subsys *ss)
}
}
bool turret_std_fov_test(const ship_subsys *ss, const vec3d *gvec, const vec3d *v2e, float size_mod)
bool turret_std_fov_test(ship_subsys *ss, vec3d *gvec, vec3d *v2e, float size_mod)
{
model_subsystem *tp = ss->system_info;
float dot = vm_vec_dot(v2e, gvec);
@@ -2814,7 +2879,7 @@ bool turret_std_fov_test(const ship_subsys *ss, const vec3d *gvec, const vec3d *
return false;
}
bool turret_adv_fov_test(const ship_subsys *ss, const vec3d *gvec, const vec3d *v2e, float size_mod)
bool turret_adv_fov_test(ship_subsys *ss, vec3d *gvec, vec3d *v2e, float size_mod)
{
model_subsystem *tp = ss->system_info;
float dot = vm_vec_dot(v2e, gvec);
@@ -2840,7 +2905,7 @@ bool turret_adv_fov_test(const ship_subsys *ss, const vec3d *gvec, const vec3d *
return false;
}
bool turret_fov_test(const ship_subsys *ss, const vec3d *gvec, const vec3d *v2e, float size_mod)
bool turret_fov_test(ship_subsys *ss, vec3d *gvec, vec3d *v2e, float size_mod)
{
bool in_fov = false;
if (ss->system_info->turret_base_fov > -1.0f)
+3 -3
View File
@@ -22,19 +22,19 @@ anim_instance *init_anim_instance(anim *ptr, int bpp)
{
anim_instance *inst;
Assertion(ptr, "Bad pointer in init_anim_instance(), please report to the SCP!");
if (!ptr) {
Int3();
return NULL;
}
if ( ptr->flags & ANF_STREAMED ) {
Assertion(ptr->file_offset > -1, "Bad file offset of %d in init_anim_instance(), please report to the SCP!", ptr->file_offset);
if ( ptr->file_offset < 0 ) {
Int3();
return NULL;
}
} else {
Assertion(ptr->data, "Bad data in init_anim_instance(), please report to the SCP!");
if ( !ptr->data ) {
Int3();
return NULL;
}
}
+10 -19
View File
@@ -401,12 +401,12 @@ object *asteroid_create(asteroid_field *asfieldp, int asteroid_type, int asteroi
vec3d rotvel;
if ( Game_mode & GM_NORMAL ) {
vm_vec_rand_vec_quick(&rotvel);
vm_vec_scale(&rotvel, asip->rotational_vel_multiplier * (frand()/4.0f + 0.1f));
vm_vec_scale(&rotvel, frand()/4.0f + 0.1f);
objp->phys_info.rotvel = rotvel;
vm_vec_rand_vec_quick(&objp->phys_info.vel);
} else {
static_randvec( rand_base++, &rotvel );
vm_vec_scale(&rotvel, asip->rotational_vel_multiplier * (static_randf(rand_base++)/4.0f + 0.1f));
vm_vec_scale(&rotvel, static_randf(rand_base++)/4.0f + 0.1f);
objp->phys_info.rotvel = rotvel;
static_randvec( rand_base++, &objp->phys_info.vel );
}
@@ -1049,7 +1049,6 @@ bool asteroid_is_within_view(vec3d *pos, float range, bool range_override)
*/
static void maybe_throw_asteroid()
{
Assertion(Asteroid_field.num_used_field_debris_types > 0, "maybe_throw_asteroid() called while num_used_field_debris_types was 0; this should never happen, get a coder!");
for (asteroid_target& target : Asteroid_targets) {
if (!timestamp_elapsed(target.throw_stamp))
@@ -1333,9 +1332,10 @@ int asteroid_check_collision(object *pasteroid, object *other_obj, vec3d *hitpos
mc.flags = (MC_CHECK_MODEL | MC_CHECK_SPHERELINE);
// copy important data
int orig_flags = mc.flags; // make a copy of start end positions of sphere in big ship RF
vec3d orig_p0 = *mc.p0;
vec3d orig_p1 = *mc.p1;
int copy_flags = mc.flags; // make a copy of start end positions of sphere in big ship RF
vec3d copy_p0, copy_p1;
copy_p0 = *mc.p0;
copy_p1 = *mc.p1;
// first test against the sphere - if this fails then don't do any submodel tests
mc.flags = MC_ONLY_SPHERE | MC_CHECK_SPHERELINE;
@@ -1361,7 +1361,7 @@ int asteroid_check_collision(object *pasteroid, object *other_obj, vec3d *hitpos
}
// Only check single submodel now, since children of moving submodels are handled as moving as well
mc.flags = orig_flags | MC_SUBMODEL;
mc.flags = copy_flags | MC_SUBMODEL;
// check each submodel in turn
for (auto submodel: submodel_vector) {
@@ -1406,9 +1406,9 @@ int asteroid_check_collision(object *pasteroid, object *other_obj, vec3d *hitpos
}
// Now complete base model collision checks that do not take into account rotating submodels.
mc.flags = orig_flags;
mc.p0 = &orig_p0;
mc.p1 = &orig_p1;
mc.flags = copy_flags;
*mc.p0 = copy_p0;
*mc.p1 = copy_p1;
mc.orient = &heavy_obj->orient;
// usual ship_ship collision test
@@ -2239,10 +2239,6 @@ static void asteroid_parse_section()
stuff_float(&asteroid_p->max_speed);
}
if (optional_string("$Rotational Velocity Multiplier:")) {
stuff_float(&asteroid_p->rotational_vel_multiplier);
}
if(optional_string("$Damage Type:")) {
char buf[NAME_LENGTH];
stuff_string(buf, F_NAME, NAME_LENGTH);
@@ -2585,11 +2581,6 @@ void asteroid_frame()
return;
}
// If no asteroid types are defined for the field, abort.
if (Asteroid_field.num_used_field_debris_types <= 0) {
return;
}
// If there are no explicit targets, fall back to default retail targeting behavior
if (Asteroid_field.target_names.empty()) {
int objnum = set_asteroid_throw_objnum();
+1 -3
View File
@@ -63,7 +63,6 @@ public:
int num_detail_levels; // number of detail levels for this ship
int detail_distance[MAX_ASTEROID_DETAIL_LEVELS]; // distance to change detail levels at
float max_speed; // cap on speed for asteroid
float rotational_vel_multiplier; // rotational velocity multiplier for asteroid --wookieejedi
int damage_type_idx; //Damage type of the asteroid
int damage_type_idx_sav; // stored value from table used to reset damage_type_idx
float inner_rad; // radius within which maximum area effect damage is applied
@@ -81,8 +80,7 @@ public:
float gravity_const; // multiplier for mission gravity
asteroid_info( )
: type(ASTEROID_TYPE_DEBRIS), num_detail_levels(0), max_speed(0),
rotational_vel_multiplier(1), damage_type_idx(0),
: type(ASTEROID_TYPE_DEBRIS), num_detail_levels(0), max_speed(0), damage_type_idx(0),
damage_type_idx_sav( -1 ), inner_rad( 0 ), outer_rad( 0 ),
damage( 0 ), blast( 0 ), initial_asteroid_strength( 0 ),
fireball_radius_multiplier( -1 ), spawn_weight( 1 ), gravity_const( 0 )
+1 -1
View File
@@ -869,7 +869,7 @@ void EndAutoPilot()
Assert( CurrentNav >= 0 );
int goal = 0;
const char *goal_name = NULL;
char *goal_name = NULL;
if (Navs[CurrentNav].flags & NP_WAYPOINT)
{
-1
View File
@@ -425,7 +425,6 @@ DCF(bm_used, "Shows BmpMan Slot Usage") {
SCP_stringstream text;
text << "BmpMan Used Slots\n";
text << " " << std::dec << std::setw(4) << std::setfill('0') << none << ", NONE\n";
text << " " << std::dec << std::setw(4) << std::setfill('0') << pcx << ", PCX\n";
text << " " << std::dec << std::setw(4) << std::setfill('0') << user << ", User\n";
text << " " << std::dec << std::setw(4) << std::setfill('0') << tga << ", TGA\n";
+17 -57
View File
@@ -14,8 +14,8 @@
#include "ship/ship.h" //compute_slew_matrix
//*************************IMPORTANT GLOBALS*************************
fov_t VIEWER_ZOOM_DEFAULT = DEFAULT_FOV;
fov_t COCKPIT_ZOOM_DEFAULT = DEFAULT_FOV;
fov_t VIEWER_ZOOM_DEFAULT = 0.75f; // Default viewer zoom, 0.625 as per multi-lateral agreement on 3/24/97
fov_t COCKPIT_ZOOM_DEFAULT = 0.75f;
float Sexp_fov = 0.0f;
warp_camera Warp_camera;
@@ -54,9 +54,6 @@ APPLY_TO_FOV_T(*, mul)
APPLY_TO_FOV_T(+, add)
APPLY_TO_FOV_T(-, sub)
// Used to set the default value for in-game options
static constexpr float fov_default = DEFAULT_FOV;
static SCP_string fov_display(float val)
{
auto degrees = fl_degrees(val);
@@ -67,55 +64,18 @@ static SCP_string fov_display(float val)
auto FovOption = options::OptionBuilder<float>("Graphics.FOV",
std::pair<const char*, int>{"Field Of View", 1703},
std::pair<const char*, int>{"The vertical field of view", 1704})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.range(0.436332f, 1.5708f)
.change_listener([](const float& val, bool) {
VIEWER_ZOOM_DEFAULT = val;
return true;
})
.display(fov_display)
.default_val(fov_default)
.default_val(0.75f)
.level(options::ExpertLevel::Advanced)
.importance(60)
.finish();
bool Use_cockpit_fov = false;
auto CockpitFOVToggleOption = options::OptionBuilder<bool>("Graphics.CockpitFOVToggle",
std::pair<const char*, int>{"Cockpit FOV Toggle", 1838},
std::pair<const char*, int>{"Whether or not to use a different FOV for cockpit rendering from normal rendering", 1839})
.category(std::make_pair("Graphics", 1825))
.default_val(false)
.change_listener([](bool val, bool) {
if (!val) {
COCKPIT_ZOOM_DEFAULT = VIEWER_ZOOM_DEFAULT;
}
return true; // This option will always persist so we never return false
})
.level(options::ExpertLevel::Advanced)
.bind_to(&Use_cockpit_fov)
.importance(61)
.finish();
auto CockpitFovOption = options::OptionBuilder<float>("Graphics.CockpitFOV",
std::pair<const char*, int>{"Cockpit Field Of View", 1840},
std::pair<const char*, int>{"The vertical field of view for cockpit rendering. Only works if cockpits are active and cockpit FOV toggle is turned on.", 1841})
.category(std::make_pair("Graphics", 1825))
.range(0.436332f, 1.5708f)
.change_listener([](const float& val, bool) {
if (Use_cockpit_fov){
COCKPIT_ZOOM_DEFAULT = val;
} else {
COCKPIT_ZOOM_DEFAULT = VIEWER_ZOOM_DEFAULT;
}
return true;
})
.display(fov_display)
.default_val(fov_default)
.level(options::ExpertLevel::Advanced)
.importance(62)
.finish();
//*************************CLASS: camera*************************
//This is where the camera class begins! :D
camera::camera(const char *in_name, int in_signature)
@@ -341,7 +301,7 @@ void camera::set_rotation_facing(vec3d *in_target, float in_rotation_time, float
// if we have a host, we need the difference between the camera's current orient and the orient we want
// if not, we will later set the absolute orientation, rather than the orientation relative to the host
if (object_host.isValid())
if (object_host.IsValid())
{
vm_transpose(orient);
temp_matrix = temp_matrix * *orient;
@@ -364,7 +324,7 @@ void camera::do_frame(float /*in_frametime*/)
object *camera::get_object_host()
{
if(object_host.isValid())
if(object_host.IsValid())
return object_host.objp;
else
return NULL;
@@ -377,7 +337,7 @@ int camera::get_object_host_submodel()
object *camera::get_object_target()
{
if(object_target.isValid())
if(object_target.IsValid())
return object_target.objp;
else
return NULL;
@@ -413,7 +373,7 @@ void camera::get_info(vec3d *position, matrix *orientation, bool apply_camera_or
bool use_host_orient = false;
//POSITION
if(!(flags & CAM_STATIONARY_POS) || object_host.isValid())
if(!(flags & CAM_STATIONARY_POS) || object_host.IsValid())
{
c_pos = vmd_zero_vector;
@@ -422,7 +382,7 @@ void camera::get_info(vec3d *position, matrix *orientation, bool apply_camera_or
pos_y.get(&pt.xyz.y, NULL);
pos_z.get(&pt.xyz.z, NULL);
if(object_host.isValid())
if(object_host.IsValid())
{
object *objp = object_host.objp;
int model_num = object_get_model(objp);
@@ -484,9 +444,9 @@ void camera::get_info(vec3d *position, matrix *orientation, bool apply_camera_or
if(orientation != NULL)
{
bool target_set = false;
if(!(flags & CAM_STATIONARY_ORI) || object_target.isValid() || object_host.isValid())
if(!(flags & CAM_STATIONARY_ORI) || object_target.IsValid() || object_host.IsValid())
{
if(object_target.isValid())
if(object_target.IsValid())
{
object *target_objp = object_target.objp;
int model_num = object_get_model(target_objp);
@@ -521,7 +481,7 @@ void camera::get_info(vec3d *position, matrix *orientation, bool apply_camera_or
vm_vector_2_matrix(&c_ori, &targetvec, NULL, NULL);
target_set = true;
}
else if(object_host.isValid())
else if(object_host.IsValid())
{
if(eyep)
{
@@ -794,7 +754,7 @@ subtitle::subtitle(int in_x_pos, int in_y_pos, const char* in_text, const char*
//Get text size
for(int i = 0; i < num_text_lines; i++)
{
gr_get_string_size(&w, &h, text_line_ptrs[i], static_cast<size_t>(text_line_lens[i]));
gr_get_string_size(&w, &h, text_line_ptrs[i], text_line_lens[i]);
if(w > tw)
tw = w;
@@ -1051,7 +1011,7 @@ int camid::getSignature()
return sig;
}
bool camid::isValid() const
bool camid::isValid()
{
if(idx >= Cameras.size())
return false;
@@ -1243,7 +1203,7 @@ vec3d normal_cache;
void get_turret_cam_pos(camera *cam, vec3d *pos)
{
object_h obj(cam->get_object_host());
if(!obj.isValid())
if(!obj.IsValid())
return;
ship* shipp = &Ships[cam->get_object_host()->instance];
ship_subsys* ssp = GET_FIRST(&shipp->subsys_list);
@@ -1251,7 +1211,7 @@ void get_turret_cam_pos(camera *cam, vec3d *pos)
{
if(ssp->system_info->subobj_num == cam->get_object_host_submodel())
{
ship_get_global_turret_gun_info(cam->get_object_host(), ssp, pos, true, &normal_cache, true, nullptr);
ship_get_global_turret_gun_info(cam->get_object_host(), ssp, pos, &normal_cache, 1, NULL);
vec3d offset = vmd_zero_vector;
offset.xyz.x = 0.0001f;
vm_vec_add2(pos, &offset); // prevent beam turrets from crashing with a nullvec
@@ -1264,7 +1224,7 @@ void get_turret_cam_pos(camera *cam, vec3d *pos)
void get_turret_cam_orient(camera *cam, matrix *ori)
{
object_h obj(cam->get_object_host());
if(!obj.isValid())
if(!obj.IsValid())
return;
vm_vector_2_matrix(ori, &normal_cache, vm_vec_same(&normal_cache, &cam->get_object_host()->orient.vec.uvec)?NULL:&cam->get_object_host()->orient.vec.uvec, NULL);
}
-2
View File
@@ -20,8 +20,6 @@
#define EXTERN_CAM_BBOX_CONSTANT_PADDING 5.0f
#define EXTERN_CAM_BBOX_MULTIPLIER_PADDING 1.5f
#define DEFAULT_FOV 0.75f;
struct asymmetric_fov {
float left, right, up, down;
friend asymmetric_fov operator* (const asymmetric_fov&, const float&);
+16 -18
View File
@@ -91,10 +91,12 @@ cf_pathtype Pathtypes[CF_MAX_PATH_TYPES] = {
};
// clang-format on
#define CFILE_STACK_MAX 8
int cfile_inited = 0;
static int Cfile_stack_pos = 0;
static SCP_vector<SCP_string> Cfile_stack;
static char Cfile_stack[CFILE_STACK_MAX][CFILE_ROOT_DIRECTORY_LEN];
std::array<CFILE, MAX_CFILE_BLOCKS> Cfile_block_list;
@@ -328,16 +330,17 @@ int cfile_push_chdir(int type)
_getcwd(OriginalDirectory, CFILE_ROOT_DIRECTORY_LEN - 1);
cf_create_default_path_string(dir, type, NULL);
Assert(Cfile_stack_pos < CFILE_STACK_MAX);
int rc = _cfile_chdir(dir.c_str(), OriginalDirectory);
// if success then push the original directory on to the stack
if (rc == 0) {
Cfile_stack.push_back(OriginalDirectory);
if (Cfile_stack_pos >= CFILE_STACK_MAX) {
return -1;
}
return rc;
strcpy_s(Cfile_stack[Cfile_stack_pos++], OriginalDirectory);
cf_create_default_path_string(dir, type, NULL);
return _cfile_chdir(dir.c_str(), OriginalDirectory);
}
/**
@@ -360,16 +363,13 @@ int cfile_chdir(const char *dir)
int cfile_pop_dir()
{
if (Cfile_stack.empty())
Assert(Cfile_stack_pos);
if ( !Cfile_stack_pos )
return -1;
int rc = cfile_chdir(Cfile_stack.back().c_str());
Assertion(rc == 0, "Failed to chdir() to previous directory (%s)!", Cfile_stack.back().c_str());
Cfile_stack.pop_back();
return rc;
Cfile_stack_pos--;
return cfile_chdir(Cfile_stack[Cfile_stack_pos]);
}
// flush (delete all files in) the passed directory (by type), return the # of files deleted
@@ -681,8 +681,6 @@ CFILE* _cfopen(const char* source, int line, const char* file_path, const char*
} else {
// Path type given?
Assert( dir_type != CF_TYPE_ANY );
if (dir_type == CF_TYPE_ANY)
return NULL;
// Create the directory if necessary
cf_create_directory(dir_type, location_flags);
+1 -1
View File
@@ -1172,7 +1172,7 @@ void cf_build_file_list()
}
Warning(LOCATION, "Some critical files might be shadowed! Please check the debug log for details.\n\n"
SIZE_T_ARG " file(s) detected, including:\n%s", count, shadowed.c_str());
"%lu file(s) detected, including:\n%s", count, shadowed.c_str());
}
critical_shadowed.clear();
+1 -1
View File
@@ -82,7 +82,7 @@ void SpawnShipCheat::runCheat() {
if (ptr->system_info->type == SUBSYSTEM_TURRET)
{
ptr->weapons.flags.set(Ship::Weapon_Flags::Beam_Free);
ptr->turret_next_fire_stamp = timestamp(Random::next(50, 4000));
ptr->turret_next_fire_stamp = timestamp((int)frand_range(50.0f, 4000.0f));
}
}
+71 -151
View File
@@ -15,7 +15,6 @@
#include "globalincs/pstypes.h"
#include "globalincs/systemvars.h"
#include "globalincs/version.h"
#include "graphics/openxr.h"
#include "graphics/shadows.h"
#include "hud/hudconfig.h"
#include "io/joy.h"
@@ -40,7 +39,6 @@
#ifdef SCP_UNIX
#include "osapi/osapi.h"
#include <dirent.h>
#include <sys/stat.h>
#endif
#include <cstring>
@@ -198,8 +196,6 @@ Flag exe_params[] =
{ "-warp_flash", "Enable flash upon warp", true, 0, EASY_DEFAULT, "Gameplay", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-warp_flash", },
{ "-no_ap_interrupt", "Disable interrupting autopilot", true, 0, EASY_DEFAULT, "Gameplay", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-no_ap_interrupt", },
{ "-no_screenshake", "Disable screen shaking", true, 0, EASY_DEFAULT, "Gameplay", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-no_screenshake", },
{ "-vr", "Enable Virtual Reality Mode", true, 0, EASY_DEFAULT, "Gameplay", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-vr", },
{ "-no_unfocused_pause","Don't pause if the window isn't focused", true, 0, EASY_DEFAULT, "Gameplay", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-no_unfocused_pause", },
//flag launcher text FSO on_flags off_flags category reference URL
{ "-nosound", "Disable all sound", false, 0, EASY_DEFAULT, "Audio", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-nosound", },
@@ -223,7 +219,6 @@ Flag exe_params[] =
//flag launcher text FSO on_flags off_flags category reference URL
{ "-no_set_gamma", "Disable setting of gamma", true, 0, EASY_DEFAULT, "Troubleshoot", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-no_set_gamma", },
{ "-no_ingame_options", "Disable using ingame options", true, 0, EASY_DEFAULT, "Troubleshoot", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-no_ingame_options", },
{ "-nomovies", "Disable video playback", true, 0, EASY_DEFAULT, "Troubleshoot", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-nomovies", },
{ "-noparseerrors", "Disable parsing errors", true, 0, EASY_DEFAULT, "Troubleshoot", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-noparseerrors", },
{ "-loadallweps", "Load all weapons, even those not used", true, 0, EASY_DEFAULT, "Troubleshoot", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-loadallweps", },
@@ -269,6 +264,7 @@ Flag exe_params[] =
{ "-verify_vps", "Spew VP CRCs to vp_crcs.txt", true, 0, EASY_DEFAULT, "Dev Tool", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-verify_vps", },
{ "-reparse_mainhall", "Reparse mainhall.tbl when loading halls", false, 0, EASY_DEFAULT, "Dev Tool", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-reparse_mainhall", },
{ "-noninteractive", "Disables interactive dialogs", true, 0, EASY_DEFAULT, "Dev Tool", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-noninteractive", },
{ "-no_unfocused_pause","Don't pause if the window isn't focused", true, 0, EASY_DEFAULT, "Dev Tool", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-no_unfocused_pause", },
{ "-benchmark_mode", "Puts the game into benchmark mode", true, 0, EASY_DEFAULT, "Dev Tool", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-benchmark_mode", },
{ "-profile_frame_time","Profile frame time", true, 0, EASY_DEFAULT, "Dev Tool", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-profile_frame_time", },
{ "-profile_write_file", "Write profiling information to file", true, 0, EASY_DEFAULT, "Dev Tool", "http://www.hard-light.net/wiki/index.php/Command-Line_Reference#-profile_write_file", },
@@ -413,7 +409,6 @@ cmdline_parm allow_autpilot_interrupt("-no_ap_interrupt", nullptr, AT_NONE);
cmdline_parm stretch_menu("-stretch_menu", nullptr, AT_NONE); // Cmdline_stretch_menu
cmdline_parm capture_mouse("-capture_mouse", nullptr, AT_NONE); // Cmdline_capture_mouse
cmdline_parm no_screenshake("-no_screenshake", nullptr, AT_NONE); // Cmdline_no_screenshake
cmdline_parm vr("-vr", nullptr, AT_NONE);
cmdline_parm deadzone("-deadzone",
"Sets the joystick deadzone. Integer value from 0 to 100 as a percentage of the joystick's range (100% would make the stick do nothing). Disables deadzone slider in the in-game Options menu.", AT_INT); //Cmdline_deadzone
@@ -424,7 +419,6 @@ int Cmdline_stretch_menu = 0;
bool Cmdline_capture_mouse = false;
int Cmdline_no_screenshake = 0;
int Cmdline_deadzone = -1;
bool Cmdline_enable_vr = false;
// Audio related
cmdline_parm voice_recognition_arg("-voicer", NULL, AT_NONE); // Cmdline_voice_recognition
@@ -462,7 +456,6 @@ SCP_string Cmdline_lang;
cmdline_parm loadallweapons_arg("-loadallweps", NULL, AT_NONE); // Cmdline_load_all_weapons
cmdline_parm nomovies_arg("-nomovies", NULL, AT_NONE); // Cmdline_nomovies -- Allows video streaming
cmdline_parm no_set_gamma_arg("-no_set_gamma", NULL, AT_NONE); // Cmdline_no_set_gamma
cmdline_parm no_ingame_options_arg("-no_ingame_options", NULL, AT_NONE); // Cmdline_no_ingame_options
cmdline_parm no_fbo_arg("-disable_fbo", NULL, AT_NONE); // Cmdline_no_fbo
cmdline_parm no_pbo_arg("-disable_pbo", NULL, AT_NONE); // Cmdline_no_pbo
cmdline_parm mipmap_arg("-mipmap", NULL, AT_NONE); // Cmdline_mipmap
@@ -486,7 +479,6 @@ cmdline_parm fix_registry("-fix_registry", NULL, AT_NONE);
int Cmdline_load_all_weapons = 0;
int Cmdline_nomovies = 0;
int Cmdline_no_set_gamma = 0;
bool Cmdline_no_ingame_options = false;
int Cmdline_no_fbo = 0;
int Cmdline_no_pbo = 0;
int Cmdline_ati_color_swap = 0;
@@ -521,9 +513,7 @@ cmdline_parm stats_arg("-stats", NULL, AT_NONE); // Cmdline_show_stats
cmdline_parm save_render_targets_arg("-save_render_target", NULL, AT_NONE); // Cmdline_save_render_targets
cmdline_parm window_arg("-window", NULL, AT_NONE); // Cmdline_window
cmdline_parm fullscreen_window_arg("-fullscreen_window", "Fullscreen/borderless window (Windows only)", AT_NONE);
cmdline_parm deprecated_res_arg("-res", "Deprecated, resolution, formatted like 1600x900", AT_STRING);
cmdline_parm render_res_arg("-render_res", "Resolution, formatted like 1600x900", AT_STRING);
cmdline_parm window_res_arg("-window_res", "Window resolution, formatted like 1600x900.", AT_STRING);
cmdline_parm res_arg("-res", "Resolution, formatted like 1600x900", AT_STRING);
cmdline_parm center_res_arg("-center_res", "Resolution of center monitor, formatted like 1600x900", AT_STRING);
cmdline_parm verify_vps_arg("-verify_vps", NULL, AT_NONE); // Cmdline_verify_vps -- spew VP crcs to vp_crcs.txt
cmdline_parm parse_cmdline_only(PARSE_COMMAND_LINE_STRING, "Ignore any cmdline_fso.cfg files", AT_NONE);
@@ -561,7 +551,6 @@ int Cmdline_show_stats = 0;
int Cmdline_save_render_targets = 0;
int Cmdline_window = 0;
int Cmdline_fullscreen_window = 0;
tl::optional<std::pair<uint16_t, uint16_t>>Cmdline_window_res = tl::nullopt;
char *Cmdline_res = 0;
char *Cmdline_center_res = 0;
int Cmdline_verify_vps = 0;
@@ -1209,133 +1198,93 @@ bool cmdline_parm::has_param() {
}
#ifdef SCP_UNIX
extern void normalize_directory_separators(SCP_string &str);
static SCP_string get_real_mod_path(const char *mod)
// Return a vector with all filesystem names of "parent/dir" relative to parent.
// dir must not contain a slash.
static SCP_vector<SCP_string> unix_get_single_dir_names(const SCP_string& parent, const SCP_string& dir)
{
DIR *dirp;
SCP_string fullpath;
SCP_string mod_path = mod;
SCP_vector<SCP_string> ret;
normalize_directory_separators(mod_path);
fullpath = SCP_string(".") + DIR_SEPARATOR_STR;
fullpath += mod_path;
// check if path already exists
dirp = opendir(fullpath.c_str());
if (dirp) {
// found it, return unchanged
closedir(dirp);
return mod_path;
DIR *dp;
if ((dp = opendir(parent.c_str())) == NULL) {
Warning(LOCATION, "Can't open directory '%s' when searching mod paths. Ignoring. errno=%d", parent.c_str(), errno);
return ret;
}
// not found, check for a difference in case
SCP_string new_mod_path;
SCP_string part;
struct dirent *dir;
SCP_string::size_type separator;
SCP_string::size_type offset = 0;
fullpath = SCP_string(".") + DIR_SEPARATOR_STR;
do {
separator = mod_path.find(DIR_SEPARATOR_CHAR, offset);
if (separator != SCP_string::npos) {
part = mod_path.substr(offset, separator-offset);
offset += separator-offset + 1;
} else {
part = mod_path.substr(offset);
offset += part.length();
dirent *dirp;
while ((dirp = readdir(dp)) != NULL) {
if (!stricmp(dirp->d_name, dir.c_str())) {
ret.push_back(dirp->d_name);
}
}
(void)closedir(dp);
dirp = opendir(fullpath.c_str());
return ret;
}
if ( !dirp ) {
break;
}
// Return a vector with all filesystem names of "parent/dir" relative to parent.
// Recurses to deal with slashes in dir.
static SCP_vector<SCP_string> unix_get_dir_names(const SCP_string& parent, const SCP_string& dir)
{
size_t slash = dir.find_first_of("/\\");
while ((dir = readdir(dirp)) != nullptr) {
if (stricmp(dir->d_name, part.c_str())) {
continue;
}
SCP_string fn = fullpath + dir->d_name;
// make sure it accessible and a directory
struct stat buf;
if (stat(fn.c_str(), &buf) == -1) {
continue;
}
if ( !S_ISDIR(buf.st_mode) ) {
continue;
}
if ( !new_mod_path.empty() ) {
new_mod_path += DIR_SEPARATOR_STR;
}
new_mod_path += dir->d_name;
fullpath += dir->d_name;
fullpath += DIR_SEPARATOR_STR;
break;
}
if (dirp) {
closedir(dirp);
}
} while (offset < mod_path.length());
// Append anything left from mod_path onto the new path. This will catch trailing separators
// as well as mod folders which don't exist so that the mod string remains unchanged except
// for the directory name case.
if (new_mod_path.length() != mod_path.length()) {
new_mod_path += mod_path.substr(new_mod_path.length());
// no subdirectories, no need to recurse
if (slash == std::string::npos) {
return unix_get_single_dir_names(parent, dir);
}
return new_mod_path;
// get the names of the first component of dir
SCP_vector<SCP_string> this_dir_names = unix_get_single_dir_names(parent, dir.substr(0, slash));
SCP_string rest = dir.substr(slash + 1);
SCP_vector<SCP_string> ret;
// search for the rest of dir in each of these
SCP_vector<SCP_string>::iterator ii, end = this_dir_names.end();
for (ii = this_dir_names.begin(); ii != end; ++ii) {
SCP_string this_dir_path = parent + "/" + *ii;
SCP_vector<SCP_string> mod_path = unix_get_dir_names(this_dir_path, rest);
// add all found paths relative to parent
SCP_vector<SCP_string>::iterator ii2, end2 = mod_path.end();
for (ii2 = mod_path.begin(); ii2 != end2; ++ii2) {
ret.push_back(*ii + "/" + *ii2);
}
}
return ret;
}
// For case sensitive filesystems (e.g. Linux/BSD) perform case-insensitive dir matches.
//
// NOTE: Aside from change in case no alterations should be made to the modlist. Missing
// mod folders should be left in place and no errors or warnings should be generated.
// There should be no difference between Windows and non-Windows modlist handling.
static void handle_unix_modlist(char **modlist, size_t *len)
{
// search filesystem for given paths
SCP_vector<SCP_string> mod_paths;
for (char *cur_mod = strtok(*modlist, ","); cur_mod != NULL; cur_mod = strtok(NULL, ",")) {
SCP_string path = get_real_mod_path(cur_mod);
mod_paths.push_back(path);
for (char *cur_mod = strtok(*modlist, ","); cur_mod != NULL; cur_mod = strtok(NULL, ","))
{
SCP_vector<SCP_string> this_mod_paths = unix_get_dir_names(".", cur_mod);
// Ignore non-existing mods for unit tests
if (!running_unittests && this_mod_paths.empty()) {
ReleaseWarning(LOCATION, "Can't find mod '%s'. Ignoring.", cur_mod);
}
mod_paths.insert(mod_paths.end(), this_mod_paths.begin(), this_mod_paths.end());
}
// create new char[] to replace modlist
size_t total_len = 0;
for (auto &path : mod_paths) {
total_len += path.length() + 1;
SCP_vector<SCP_string>::iterator ii, end = mod_paths.end();
for (ii = mod_paths.begin(); ii != end; ++ii) {
total_len += ii->length() + 1;
}
char *new_modlist = new char[total_len + 1];
memset(new_modlist, 0, total_len + 1);
for (auto &path : mod_paths) {
strcat_s(new_modlist, total_len + 1, path.c_str());
strcat_s(new_modlist, total_len + 1, ",");
end = mod_paths.end();
for (ii = mod_paths.begin(); ii != end; ++ii) {
strcat_s(new_modlist, total_len + 1, ii->c_str());
strcat_s(new_modlist, total_len + 1, ","); // replace later with NUL
}
// remove trailing comma
new_modlist[total_len-1] = '\0';
// make the rest of the modlist manipulation unaware that anything happened here
delete [] *modlist;
*modlist = new_modlist;
@@ -1764,48 +1713,31 @@ bool SetCmdlineParams()
// d3d windowed
if(window_arg.found()) {
// We need to set both values since we don't know if we are going to use the new config system
//options::OptionsManager::instance()->setOverride("Graphics.WindowMode", "0");
options::OptionsManager::instance()->setOverride("Graphics.WindowMode", "0");
Cmdline_window = 1;
}
if ( fullscreen_window_arg.found( ) )
{
//options::OptionsManager::instance()->setOverride("Graphics.WindowMode", "1");
options::OptionsManager::instance()->setOverride("Graphics.WindowMode", "1");
Cmdline_fullscreen_window = 1;
Cmdline_window = 0; /* Make sure no-one sets both */
}
if(render_res_arg.found() || deprecated_res_arg.found()){
if (render_res_arg.found()) {
Cmdline_res = render_res_arg.str();
}
else {
Cmdline_res = deprecated_res_arg.str();
mprintf(("Deprecated -res argument. Use -render_res instead...\n"));
}
if(res_arg.found()){
Cmdline_res = res_arg.str();
/*int width = 0;
int width = 0;
int height = 0;
if (sscanf(Cmdline_res, "%dx%d", &width, &height) == 2) {
if ( sscanf(Cmdline_res, "%dx%d", &width, &height) == 2 ) {
SCP_string override;
sprintf(override, "{\"width\":%d,\"height\":%d}", width, height);
options::OptionsManager::instance()->setOverride("Graphics.Resolution", override);
} else {
Warning(LOCATION, "Failed to parse -res parameter \"%s\". Must be in format \"<width>x<height>\".\n", Cmdline_res);
}*/
}
if(window_res_arg.found()){
int width = 0;
int height = 0;
if ( sscanf(window_res_arg.str(), "%dx%d", &width, &height) == 2 ) {
Cmdline_window_res.emplace(static_cast<uint16_t>(width), static_cast<uint16_t>(height));
} else {
Warning(LOCATION, "Failed to parse -window_res parameter \"%s\". Must be in format \"<width>x<height>\".\n", window_res_arg.str());
mprintf(("Failed to parse -res parameter \"%s\". Must be in format \"<width>x<height>\".\n", Cmdline_res));
}
}
if(center_res_arg.found()){
Cmdline_center_res = center_res_arg.str();
}
@@ -1840,7 +1772,7 @@ bool SetCmdlineParams()
if(mod_arg.found() ) {
Cmdline_mod = mod_arg.str();
// strip off blank space if it's there
// strip off blank space it it's there
if ( Cmdline_mod[strlen(Cmdline_mod)-1] == ' ' ) {
Cmdline_mod[strlen(Cmdline_mod)-1] = '\0';
}
@@ -1900,7 +1832,7 @@ bool SetCmdlineParams()
if (val > 0.1) {
VIEWER_ZOOM_DEFAULT = val;
} else {
VIEWER_ZOOM_DEFAULT = DEFAULT_FOV;
VIEWER_ZOOM_DEFAULT = 0.75f;
}
}
@@ -1914,14 +1846,6 @@ bool SetCmdlineParams()
}
}
if (vr.found()) {
Cmdline_enable_vr = true;
if (fov_arg.found() || fov_cockpit_arg.found()) {
Warning(LOCATION, "FoV Command line settings found. VR-Mode will override these with the HMD's native FoV...");
}
openxr_prepare();
}
if (orb_radar.found())
{
Cmdline_orb_radar = 1;
@@ -1977,10 +1901,6 @@ bool SetCmdlineParams()
Cmdline_no_set_gamma = 1;
}
if (no_ingame_options_arg.found()) {
Cmdline_no_ingame_options = true;
}
if(no_vsync_arg.found() )
{
Gr_enable_vsync = false;
+1 -5
View File
@@ -6,13 +6,12 @@
* source.
*
*/
*/
#ifndef FS_CMDLINE_HEADER_FILE
#define FS_CMDLINE_HEADER_FILE
#include <tl/optional.hpp>
int parse_cmdline(int argc, char *argv[]);
@@ -47,7 +46,6 @@ extern int Cmdline_use_last_pilot;
extern int Cmdline_window;
extern int Cmdline_fullscreen_window;
extern char *Cmdline_res;
extern tl::optional<std::pair<uint16_t, uint16_t>>Cmdline_window_res;
extern char *Cmdline_center_res;
@@ -91,7 +89,6 @@ extern int Cmdline_stretch_menu;
extern bool Cmdline_capture_mouse;
extern int Cmdline_no_screenshake;
extern int Cmdline_deadzone;
extern bool Cmdline_enable_vr;
// Audio related
extern int Cmdline_voice_recognition;
@@ -114,7 +111,6 @@ extern SCP_string Cmdline_lang;
extern int Cmdline_load_all_weapons;
extern int Cmdline_nomovies; // WMC Toggles movie playing support
extern int Cmdline_no_set_gamma;
extern bool Cmdline_no_ingame_options;
extern int Cmdline_no_fbo;
extern int Cmdline_no_pbo;
extern int Cmdline_mipmap;
+2 -2
View File
@@ -923,8 +923,8 @@ bool control_config_do_reset(bool cycle, bool API_Access)
// first, determine how many bindings need to be changed
for (size_t e = 0; e < Control_config.size(); ++e) {
const auto& item = Control_config[e];
const auto& default_item = default_bindings[e];
auto item = Control_config[e];
auto default_item = default_bindings[e];
if (item.disabled) {
// skip
+1 -1
View File
@@ -947,7 +947,7 @@ int check_control(int id, int key = -1);
void control_get_axes_readings(int *axis_v, float frame_time);
/**
* @brief Marks the given control (by IoActionId) as used
* @brief Markes the given control (by IoActionId) as used
*
* @details Updates the ::used timestamp, triggers a script hook, and marks ::continous_ongoing as true
*/
+9 -11
View File
@@ -48,13 +48,12 @@ int Joy_dead_zone_size = 10;
auto DeadZoneOption = options::OptionBuilder<int>("Input.JoystickDeadZone",
std::pair<const char*, int>{"Deadzone", 1377},
std::pair<const char*, int>{"The deadzone used for all joysticks", 1744})
.category(std::make_pair("Input", 1827))
.category("Input")
.range(0, 45)
.level(options::ExpertLevel::Beginner)
.default_val(10)
.bind_to(&Joy_dead_zone_size)
.importance(1)
.flags({options::OptionFlags::RetailBuiltinOption})
.finish();
int Joy_sensitivity = 9;
@@ -62,13 +61,12 @@ int Joy_sensitivity = 9;
auto SensitivityOption = options::OptionBuilder<int>("Input.JoystickSensitivity",
std::pair<const char*, int>{"Sensitivity", 1745},
std::pair<const char*, int>{"The sensitivity used for all joysticks", 1746})
.category(std::make_pair("Input", 1827))
.category("Input")
.range(0, 9)
.level(options::ExpertLevel::Beginner)
.default_val(9)
.bind_to(&Joy_sensitivity)
.importance(2)
.flags({options::OptionFlags::RetailBuiltinOption})
.finish();
//! arrays which hold the key mappings. The array index represents a key-independent action.
@@ -266,11 +264,11 @@ void control_config_common_init_bindings() {
(HUD_TARGETBOX_TOGGLE_WIREFRAME, KEY_ALTED | KEY_SHIFTED | KEY_Q, -1, COMPUTER_TAB, 1, "Toggle HUD Wireframe Target View", CC_TYPE_TRIGGER)
// Custom Controls
(CUSTOM_CONTROL_1, KEY_ALTED | KEY_SHIFTED | KEY_1, -1, COMPUTER_TAB, 1784, "Custom Control 1", CC_TYPE_TRIGGER, true)
(CUSTOM_CONTROL_2, KEY_ALTED | KEY_SHIFTED | KEY_2, -1, COMPUTER_TAB, 1785, "Custom Control 2", CC_TYPE_TRIGGER, true)
(CUSTOM_CONTROL_3, KEY_ALTED | KEY_SHIFTED | KEY_3, -1, COMPUTER_TAB, 1786, "Custom Control 3", CC_TYPE_TRIGGER, true)
(CUSTOM_CONTROL_4, KEY_ALTED | KEY_SHIFTED | KEY_4, -1, COMPUTER_TAB, 1787, "Custom Control 4", CC_TYPE_TRIGGER, true)
(CUSTOM_CONTROL_5, KEY_ALTED | KEY_SHIFTED | KEY_5, -1, COMPUTER_TAB, 1788, "Custom Control 5", CC_TYPE_TRIGGER, true)
(CUSTOM_CONTROL_1, KEY_ALTED | KEY_SHIFTED | KEY_1, -1, COMPUTER_TAB, 0, "Custom Control 1", CC_TYPE_TRIGGER, true)
(CUSTOM_CONTROL_2, KEY_ALTED | KEY_SHIFTED | KEY_2, -1, COMPUTER_TAB, 0, "Custom Control 2", CC_TYPE_TRIGGER, true)
(CUSTOM_CONTROL_3, KEY_ALTED | KEY_SHIFTED | KEY_3, -1, COMPUTER_TAB, 0, "Custom Control 3", CC_TYPE_TRIGGER, true)
(CUSTOM_CONTROL_4, KEY_ALTED | KEY_SHIFTED | KEY_4, -1, COMPUTER_TAB, 0, "Custom Control 4", CC_TYPE_TRIGGER, true)
(CUSTOM_CONTROL_5, KEY_ALTED | KEY_SHIFTED | KEY_5, -1, COMPUTER_TAB, 0, "Custom Control 5", CC_TYPE_TRIGGER, true)
.end(); // Builder
// init default preset
@@ -453,7 +451,7 @@ const char* Joy_button_text_french_u[] = {
"Bouton 13", "Bouton 14", "Bouton 15", "Bouton 16", "Bouton 17", "Bouton 18",
"Bouton 19", "Bouton 20", "Bouton 21", "Bouton 22", "Bouton 23", "Bouton 24",
"Bouton 25", "Bouton 26", "Bouton 27", "Bouton 28", "Bouton 29", "Bouton 30",
"Bouton 31", "Bouton 32", ("Chapeau Arri\xc3\xa8""re"), "Chapeau Avant", "Chapeau Gauche", "Chapeau Droite"
"Bouton 31", "Bouton 32", "Chapeau Arri\xc3\xa8""re", "Chapeau Avant", "Chapeau Gauche", "Chapeau Droite"
};
const char* Joy_button_text_polish_u[] = {
@@ -462,7 +460,7 @@ const char* Joy_button_text_polish_u[] = {
"Przyc.13", "Przyc.14", "Przyc.15", "Przyc.16", "Przyc.17", "Przyc.18",
"Przyc.19", "Przyc.20", "Przyc.21", "Przyc.22", "Przyc.23", "Przyc.24",
"Przyc.25", "Przyc.26", "Przyc.27", "Przyc.28", "Przyc.29", "Przyc.30",
"Przyc.31", "Przyc.32", "Hat Ty\xc5\x82", ("Hat Prz\xc3\xb3""d"), "Hat Lewo", "Hat Prawo"
"Przyc.31", "Przyc.32", "Hat Ty\xc5\x82", "Hat Prz\xc3\xb3""d", "Hat Lewo", "Hat Prawo"
};
const char* Joy_button_text_english_u[] = {
-1
View File
@@ -52,7 +52,6 @@ struct MovieProperties {
FrameSize size;
float fps = -1.0f;
float duration = 0.0f;
FramePixelFormat pixelFormat = FramePixelFormat::Invalid;
};
+2 -14
View File
@@ -25,8 +25,6 @@
extern int Cmdline_nomovies;
bool Movie_active = false;
const char* Cutscene_bitmap_name[GR_NUM_RESOLUTIONS] = {
"ViewFootage",
@@ -62,18 +60,6 @@ static cutscene_info *get_cutscene_pointer(char *cutscene_filename)
return NULL;
}
int get_cutscene_index_by_name(const char* name)
{
for (int i = 0; i < static_cast<int>(Cutscenes.size()); i++) {
if (!stricmp(name, Cutscenes[i].name)) {
return i;
}
}
// Didn't find anything.
return -1;
}
static void cutscene_info_init(cutscene_info *csni)
{
csni->filename[0] = '\0';
@@ -236,6 +222,7 @@ void cutscene_mark_viewable(const char* filename)
// change to lower case
strlwr(file);
int i = 0;
for (SCP_vector<cutscene_info>::iterator cut = Cutscenes.begin(); cut != Cutscenes.end(); ++cut)
{
// change the cutscene file name to lower case
@@ -248,6 +235,7 @@ void cutscene_mark_viewable(const char* filename)
cut->flags.set(Cutscene::Cutscene_Flags::Viewable);
return;
}
i++;
}
Warning(LOCATION, "Could not find cutscene '%s' in listing; cannot mark it viewable...", filename);
-4
View File
@@ -37,8 +37,6 @@ typedef struct cutscene_info
extern SCP_vector<cutscene_info> Cutscenes;
extern bool Movie_active;
// initializa table data
void cutscene_init();
@@ -50,6 +48,4 @@ void cutscenes_screen_do_frame();
void cutscene_mark_viewable(const char* filename);
int get_cutscene_index_by_name(const char* name);
#endif
-1
View File
@@ -503,7 +503,6 @@ MovieProperties FFMPEGDecoder::getProperties() const
props.size.height = static_cast<size_t>(m_status->videoCodecPars.height);
props.fps = static_cast<float>(getFrameRate(m_status->videoStream, m_status->videoCodecCtx));
props.duration = static_cast<float>(m_status->videoStream->duration * av_q2d(m_status->videoStream->time_base));
props.pixelFormat = getPixelFormat(getConversionFormat(m_status->videoCodecPars.pixel_format));
-3
View File
@@ -278,7 +278,6 @@ bool play(const char* name) {
// clear the screen and hide the mouse cursor
io::mouse::CursorManager::get()->pushStatus();
io::mouse::CursorManager::get()->showCursor(false);
Movie_active = true;
gr_reset_clip();
gr_set_color(255, 255, 255);
gr_set_clear_color(0, 0, 0);
@@ -305,8 +304,6 @@ bool play(const char* name) {
mprintf(("MOVIE ERROR: Found invalid movie! (%s)\n", name));
}
Movie_active = false;
// show the mouse cursor again
io::mouse::CursorManager::get()->popStatus();
+11 -10
View File
@@ -501,11 +501,11 @@ object *debris_create_only(int parent_objnum, int parent_ship_class, int alt_typ
}
else if (vaporize) {
db->model_num = Debris_vaporize_model;
db->submodel_num = (Debris_num_submodels <= 0 ? 0 : Random::next(Debris_num_submodels));
db->submodel_num = Random::next(Debris_num_submodels);
}
else {
db->model_num = Debris_model;
db->submodel_num = (Debris_num_submodels <= 0 ? 0 : Random::next(Debris_num_submodels));
db->submodel_num = Random::next(Debris_num_submodels);
}
}
else {
@@ -644,7 +644,7 @@ object *debris_create_only(int parent_objnum, int parent_ship_class, int alt_typ
if (spark_timeout >= 0) {
db->fire_timeout = _timestamp(spark_timeout);
} else if (parent_objnum >= 0) {
float t = 1000*Objects[parent_objnum].radius/3 + (fl2i(1000*3*Objects[parent_objnum].radius) == 0 ? 0 : Random::next(fl2i(1000*3*Objects[parent_objnum].radius)));
float t = 1000*Objects[parent_objnum].radius/3 + Random::next(fl2i(1000*3*Objects[parent_objnum].radius));
db->fire_timeout = _timestamp(fl2i(t)); // fireballs last from 5 - 30 seconds
} else {
db->fire_timeout = TIMESTAMP::immediate();
@@ -926,9 +926,10 @@ int debris_check_collision(object *pdebris, object *other_obj, vec3d *hitpos, co
mc.flags = (MC_CHECK_MODEL | MC_CHECK_SPHERELINE);
// copy important data
int orig_flags = mc.flags; // make a copy of start end positions of sphere in big ship RF
vec3d orig_p0 = *mc.p0;
vec3d orig_p1 = *mc.p1;
int copy_flags = mc.flags; // make a copy of start end positions of sphere in big ship RF
vec3d copy_p0, copy_p1;
copy_p0 = *mc.p0;
copy_p1 = *mc.p1;
// first test against the sphere - if this fails then don't do any submodel tests
mc.flags = MC_ONLY_SPHERE | MC_CHECK_SPHERELINE;
@@ -954,7 +955,7 @@ int debris_check_collision(object *pdebris, object *other_obj, vec3d *hitpos, co
}
// Only check single submodel now, since children of moving submodels are handled as moving as well
mc.flags = orig_flags | MC_SUBMODEL;
mc.flags = copy_flags | MC_SUBMODEL;
if (Ship_info[Ships[pship_obj->instance].ship_info_index].collision_lod > -1) {
mc.lod = Ship_info[Ships[pship_obj->instance].ship_info_index].collision_lod;
@@ -1004,9 +1005,9 @@ int debris_check_collision(object *pdebris, object *other_obj, vec3d *hitpos, co
}
// Now complete base model collision checks that do not take into account rotating submodels.
mc.flags = orig_flags;
mc.p0 = &orig_p0;
mc.p1 = &orig_p1;
mc.flags = copy_flags;
*mc.p0 = copy_p0;
*mc.p1 = copy_p1;
mc.orient = &heavy_obj->orient;
// usual ship_ship collision test
+2 -2
View File
@@ -220,8 +220,8 @@ struct Decal {
vm_vec_make(&scale, 1.f, 1.f, 1.f);
}
bool isValid() const {
if (!object.isValid()) {
bool isValid() {
if (!object.IsValid()) {
return false;
}
if (object.objp->flags[Object::Object_Flags::Should_be_dead]) {
-8
View File
@@ -1,17 +1,9 @@
in vec4 fragTexCoord;
out vec4 fragOut0;
#ifdef COPY_ARRAY
uniform sampler2DArray tex;
#else
uniform sampler2D tex;
#endif
void main()
{
#ifdef COPY_ARRAY
fragOut0 = texture(tex, vec3(fragTexCoord.xy, 0));
#else
fragOut0 = texture(tex, fragTexCoord.xy);
#endif
}
+4 -15
View File
@@ -118,13 +118,10 @@ uniform sampler2DArray sMiscmap;
uniform sampler2DArray shadow_map;
out vec4 fragOut0;
#ifndef FLAG_SHADOW_MAP
out vec4 fragOut1;
out vec4 fragOut2;
out vec4 fragOut3;
out vec4 fragOut4;
#endif
vec3 FresnelLazarovEnv(vec3 specColor, vec3 view, vec3 normal, float gloss)
{
@@ -188,9 +185,10 @@ void main()
#ifdef FLAG_SHADOW_MAP
// need depth and depth squared for variance shadow maps
fragOut0 = vec4(vertIn.position.z, vertIn.position.z * vertIn.position.z * VARIANCE_SHADOW_SCALE_INV, 0.0, 1.0);
return;
#else
if (true) {
return;
}
#endif
vec3 eyeDir = vec3(normalize(-vertIn.position).xyz);
vec2 texCoord = vertIn.texCoord.xy;
@@ -265,9 +263,6 @@ void main()
if (FLAG_ACTIVE(MODEL_SDR_FLAG_SPEC)) {
specColor = texture(sSpecmap, vec3(texCoord, float(sSpecmapIndex)));
if (FLAG_ACTIVE(MODEL_SDR_FLAG_ALPHA_MULT)) {
specColor *= alphaMult;
}
if(alphaGloss) glossData = specColor.a;
if(gammaSpec) {
specColor.rgb = max(specColor.rgb, vec3(0.03f)); // hardcoded minimum specular value. read John Hable's blog post titled 'Everything Is Shiny'.
@@ -402,11 +397,6 @@ void main()
emissiveColor.rgb += glowColor * GLOW_MAP_INTENSITY;
}
if (FLAG_ACTIVE(MODEL_SDR_FLAG_ALPHA_MULT)) {
//Since this is emissive, we need to premultiply it for intensity, and apply alpha to not replace existing emissive
emissiveColor *= alphaMult;
}
if (FLAG_ACTIVE(MODEL_SDR_FLAG_FOG)) {
vec3 finalFogColor = fogColor.rgb;
if (FLAG_ACTIVE(MODEL_SDR_FLAG_HDR)) {
@@ -463,5 +453,4 @@ void main()
fragOut3 = vec4(specColor.rgb, fresnelFactor);
fragOut4 = emissiveColor;
}
#endif
}
+1
View File
@@ -5,6 +5,7 @@ out vec4 fragOut2;
out vec4 fragOut3;
out vec4 fragOut4;
out vec4 fragOut5;
out float gl_FragDepth;
uniform sampler2DMS texColor;
uniform sampler2DMS texPos;
@@ -37,6 +37,7 @@ vec3 Uncharted2ToneMapping(vec3 hdr_color) // John Hable's filmic
hdr_color = ((hdr_color * (A * hdr_color + C * B) + D * E) / (hdr_color * (A * hdr_color + B) + D * F)) - E / F;
float white = ((W * (A * W + C * B) + D * E) / (W * (A * W + B) + D * F)) - E / F;
hdr_color /= white;
hdr_color = linear_to_srgb(hdr_color); // return from linear color space to SRGB color space
return hdr_color;
}
@@ -64,6 +65,7 @@ vec3 aces(vec3 hdr_color)
hdr_color = aces_input * hdr_color;
hdr_color = rtt_and_odt_fit(hdr_color);
hdr_color = aces_output * hdr_color;
hdr_color = linear_to_srgb(hdr_color);
return hdr_color;
}
@@ -77,6 +79,7 @@ vec3 aces_approx(vec3 hdr_color) // also filmic, higher contrast then Uncharted2
hdr_color *= 0.6f;
hdr_color = clamp((hdr_color*(a*hdr_color+b))/(hdr_color*(c*hdr_color+d)+e), 0.0f, 1.0f);
hdr_color = linear_to_srgb(hdr_color); // return from linear color space to SRGB color space
return hdr_color;
}
@@ -93,6 +96,7 @@ vec3 rhj_lumaToneMapping(vec3 hdr_color) // reinhard_jodie
float luma = dot(hdr_color, vec3(0.2126, 0.7152, 0.0722)); //dot products are a bit more expensive
float toneMappedLuma = luma / (1.0 + luma);
hdr_color *= toneMappedLuma / luma;
hdr_color = linear_to_srgb(hdr_color); // return from linear color space to SRGB color space
return hdr_color;
}
@@ -101,12 +105,14 @@ vec3 reinhard_extended(vec3 hdr_color)
float max_white = 1.0;
vec3 numerator = hdr_color * (1.0f + (hdr_color / vec3(max_white * max_white)));
hdr_color = numerator / (1.0f + hdr_color);
hdr_color = linear_to_srgb(hdr_color); // return from linear color space to SRGB color space
return hdr_color;
}
vec3 linearToneMapping(vec3 hdr_color)
{
hdr_color = clamp(hdr_color, 0., 1.);
hdr_color = linear_to_srgb(hdr_color); // return from linear color space to SRGB color space
return hdr_color;
}
@@ -149,7 +155,7 @@ vec3 PPC_RGB( vec3 color ) {
funswitch(color.g),
funswitch(color.b));
return color;
return linear_to_srgb(color);
}
@@ -168,7 +174,7 @@ vec3 PPC( vec3 color ) {
else {
luma_tone = sh_offsetY;
}
return color * luma_tone / luma;
return linear_to_srgb(color * luma_tone / luma);
}
@@ -207,9 +213,5 @@ void main()
break;
}
#ifdef LINEAR_OUT
fragOut0 = vec4(color.rgb, 1.0);
#else
fragOut0 = vec4(linear_to_srgb(color.rgb), 1.0);
#endif
}
+19 -19
View File
@@ -11,7 +11,7 @@ $AI:
+Actively Pursues: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
+Turrets attack this: YES
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Sentry Gun
$Counts for Alone: YES
@@ -32,7 +32,7 @@ $AI:
+Guards attack this: YES
+Turrets attack this: YES
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Escape Pod
$Praise Destruction: YES
@@ -51,7 +51,7 @@ $AI:
+Actively Pursues: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
+Turrets attack this: YES
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Cargo
$Scannable: YES
@@ -65,7 +65,7 @@ $Fog:
+Compl dist: 500.0
$AI:
+Passive docks: ( "cargo" )
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Support
$Counts for Alone: YES
@@ -92,7 +92,7 @@ $AI:
+Turrets attack this: YES
+Active docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
;;WMC - Stealth ships always have another type, so this isn't used
$Name: Stealth
@@ -118,7 +118,7 @@ $AI:
+Turrets attack this: YES
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Fighter
$Counts for Alone: YES
@@ -146,7 +146,7 @@ $AI:
+Can Form Wing: YES
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Bomber
$Counts for Alone: YES
@@ -174,7 +174,7 @@ $AI:
+Can Form Wing: YES
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
;;WMC - This fighter/bomber type doesn't seem to be used anywhere, because no ship is set as both fighter and bomber
$Name: Fighter/bomber
@@ -202,7 +202,7 @@ $AI:
+Can Form Wing: YES
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Transport
$Counts for Alone: YES
@@ -232,7 +232,7 @@ $AI:
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
+Targeted by 'Huge' weapons and Ignored by 'small only' weapons: YES
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Freighter
$Counts for Alone: YES
@@ -264,7 +264,7 @@ $AI:
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
+Targeted by 'Huge' weapons and Ignored by 'small only' weapons: YES
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: AWACS
$Counts for Alone: YES
@@ -294,7 +294,7 @@ $AI:
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
+Targeted by 'Huge' weapons and Ignored by 'small only' weapons: YES
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Gas Miner
$Counts for Alone: YES
@@ -324,7 +324,7 @@ $AI:
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
+Targeted by 'Huge' weapons and Ignored by 'small only' weapons: YES
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Cruiser
$Counts for Alone: YES
@@ -354,7 +354,7 @@ $AI:
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
+Targeted by 'Huge' weapons and Ignored by 'small only' weapons: YES
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Corvette
$Counts for Alone: YES
@@ -384,7 +384,7 @@ $AI:
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
+Targeted by 'Huge' weapons and Ignored by 'small only' weapons: YES
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Capital
$Counts for Alone: YES
@@ -414,7 +414,7 @@ $AI:
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
+Targeted by 'Huge' weapons and Ignored by 'small only' weapons: YES
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Super Cap
$Counts for Alone: YES
@@ -442,7 +442,7 @@ $AI:
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
+Targeted by 'Huge' weapons and Ignored by 'small only' weapons: YES
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Drydock
$Counts for Alone: YES
@@ -468,7 +468,7 @@ $AI:
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
+Targeted by 'Huge' weapons and Ignored by 'small only' weapons: YES
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
$Name: Knossos Device
$Counts for Alone: YES
@@ -492,6 +492,6 @@ $AI:
+Passive docks: ( "support" )
+Ignored on cripple by: ( "navbuoy" "sentry gun" "escape pod" "cargo" "support" "stealth" "fighter" "bomber" "fighter/bomber" "transport" "freighter" "awacs" "gas miner" "cruiser" "corvette" "capital" "super cap" "drydock" "knossos device" )
+Targeted by 'Huge' weapons and Ignored by 'small only' weapons: YES
$Skip Death Roll Percent Chance: 0.0
$Vaporize Percent Chance: 0.0
#End
+2 -2
View File
@@ -51,7 +51,7 @@ bool Fireball_use_3d_warp = false;
static auto WarpOption __UNUSED = options::OptionBuilder<bool>("Graphics.3dWarp",
std::pair<const char*, int>{"3D Warp", 1770},
std::pair<const char*, int>{"Use a 3D model for warp effects", 1771})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.default_val(true)
.level(options::ExpertLevel::Advanced)
.bind_to(&Fireball_use_3d_warp)
@@ -1052,7 +1052,7 @@ float fireball_wormhole_intensity(fireball *fb)
rad = (float)pow((fb->total_time - t) / fb->warp_close_duration, 0.4f);
}
return rad;
}
}
extern void warpin_queue_render(model_draw_list *scene, object *obj, matrix *orient, vec3d *pos, int texture_bitmap_num, float radius, float life_percent, float max_radius, bool warp_3d, int warp_glow_bitmap, int warp_ball_bitmap, int warp_model_id);
+1 -1
View File
@@ -27,7 +27,7 @@ bool Fireball_warp_flash = false;
static auto WarpFlashOption __UNUSED = options::OptionBuilder<bool>("Graphics.WarpFlash",
std::pair<const char*, int>{"Warp Flash", 1768},
std::pair<const char*, int>{"Show flash upon warp open or close", 1769})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.default_val(true)
.level(options::ExpertLevel::Advanced)
.bind_to_once(&Fireball_warp_flash)
+1 -1
View File
@@ -499,7 +499,7 @@ void help_overlay_blit(int overlay_id, int resolution_index)
font::set_font(help_overlaylist[overlay_id].fontlist.at(resolution_index));
for (idx = 0; idx < textcount; idx++) {
gr_set_color_fast(&Color_black);
gr_get_string_size(&width, &height, help_overlaylist[overlay_id].textlist.at(0).at(idx).string, strlen(help_overlaylist[overlay_id].textlist.at(0).at(idx).string));
gr_get_string_size(&width, &height, help_overlaylist[overlay_id].textlist.at(0).at(idx).string, (int)strlen(help_overlaylist[overlay_id].textlist.at(0).at(idx).string));
gr_rect(help_overlaylist[overlay_id].textlist.at(resolution_index).at(idx).x_coord-2*HELP_PADDING, help_overlaylist[overlay_id].textlist.at(resolution_index).at(idx).y_coord-3*HELP_PADDING, width+4*HELP_PADDING, height+4*HELP_PADDING, GR_RESIZE_MENU);
gr_set_color_fast(&Color_bright_white);
gr_printf_menu(help_overlaylist[overlay_id].textlist.at(resolution_index).at(idx).x_coord, help_overlaylist[overlay_id].textlist.at(resolution_index).at(idx).y_coord,
+2 -6
View File
@@ -113,9 +113,7 @@ const char *GS_event_text[] =
"GS_EVENT_LAB",
"GS_EVENT_PXO_HELP",
"GS_EVENT_FICTION_VIEWER", // 65
"GS_EVENT_SCRIPTING",
"GS_EVENT_SCRIPTING_MISSION",
"GS_EVENT_INGAME_OPTIONS"
"GS_EVENT_SCRIPTING"
};
//XSTR:ON
@@ -178,9 +176,7 @@ const char *GS_state_text[] =
"GS_STATE_PXO_HELP", // 50
"GS_STATE_START_GAME",
"GS_STATE_FICTION_VIEWER",
"GS_STATE_SCRIPTING",
"GS_STATE_SCRIPTING_MISSION",
"GS_STATE_INGAME_OPTIONS"
"GS_STATE_SCRIPTING"
};
//XSTR:ON
-4
View File
@@ -89,8 +89,6 @@ enum GS_EVENT {
GS_EVENT_PXO_HELP,
GS_EVENT_FICTION_VIEWER,
GS_EVENT_SCRIPTING,
GS_EVENT_SCRIPTING_MISSION,
GS_EVENT_INGAME_OPTIONS,
GS_NUM_EVENTS // Last one++
};
@@ -161,8 +159,6 @@ enum GS_STATE {
GS_STATE_START_GAME,
GS_STATE_FICTION_VIEWER,
GS_STATE_SCRIPTING,
GS_STATE_SCRIPTING_MISSION,
GS_STATE_INGAME_OPTIONS,
GS_NUM_STATES // Last one++
};
+6 -9
View File
@@ -48,12 +48,11 @@ static bool music_volume_change_listener(float new_val, bool /*initial*/)
static auto MusicVolumeOption __UNUSED = options::OptionBuilder<float>("Audio.Music",
std::pair<const char*, int>{"Music", 1371},
std::pair<const char*, int>{"Volume used for playing music", 1760})
.category(std::make_pair("Audio", 1826))
.category("Audio")
.default_val(Default_music_volume)
.range(0.0f, 1.0f)
.change_listener(music_volume_change_listener)
.importance(1)
.flags({options::OptionFlags::RetailBuiltinOption})
.finish();
typedef struct tagSNDPATTERN {
@@ -341,7 +340,7 @@ void event_music_init()
Warning(LOCATION, "Soundtrack file %s was not found with its specified extension, but another file %s exists in the modpack. Please update the extension and adjust audio specifications if necessary.", filename, res.name_ext.c_str());
#endif
Warning(LOCATION, "Soundtrack file %s was not found. The soundtrack '%s' will not be used.", filename, soundtrack.name);
Warning(LOCATION, "One or more files in '%s' could not be loaded. The soundtrack will not be used.", soundtrack.name);
all_patterns_valid = false;
break;
}
@@ -971,13 +970,11 @@ int event_music_friendly_arrival()
// overlay
if (Soundtracks[Current_soundtrack_num].flags & EMF_ALLIED_ARRIVAL_OVERLAY)
{
// Goober5000 - This is how retail did it. For some reason, FS2 only has one
// Goober5000 - I didn't touch this part... for some reason, FS2 only has one
// arrival music pattern, and this is it
if (Patterns[SONG_AARV_1].handle >= 0)
{
audiostream_play(Patterns[SONG_AARV_1].handle, (Master_event_music_volume * aav_music_volume), 0); // no looping
audiostream_set_sample_cutoff(Patterns[SONG_AARV_1].handle, fl2i(Patterns[SONG_AARV_1].num_measures * Patterns[SONG_AARV_1].samples_per_measure));
}
Assert(Patterns[SONG_AARV_1].handle >= 0 );
audiostream_play(Patterns[SONG_AARV_1].handle, (Master_event_music_volume * aav_music_volume), 0); // no looping
audiostream_set_sample_cutoff(Patterns[SONG_AARV_1].handle, fl2i(Patterns[SONG_AARV_1].num_measures * Patterns[SONG_AARV_1].samples_per_measure) );
}
// don't overlay
else
+1 -1
View File
@@ -319,7 +319,7 @@ enum class InterfaceSounds {
MIN_INTERFACE_SOUNDS =70 //!< MIN_INTERFACE_SOUNDS
};
// These two id types are defined as subclasses so that type safe implicit conversions are possible from the predefined
// These two id types are defined as sublcasses so that type safe implicit conversions are possible from the predefined
// sound enum values
struct gamesnd_id_tag{};
+2 -2
View File
@@ -191,8 +191,8 @@ class flagset {
return *this;
}
bool any_set() const { return values.any(); }
bool none_set() const { return values.none(); }
bool any_set() { return values.any(); }
bool none_set() { return values.none(); }
void from_u64(std::uint64_t num) { values = (unsigned long) num; }
-1
View File
@@ -72,7 +72,6 @@
#define MAX_POLYGON_MODELS 300
// object.h
//If this value exceeds 2^16-1, this will break collision pair caching as is. Proceed with caution.
#define MAX_OBJECTS 5000 //Increased from 3500 to 5000 in 2022
// from weapon.h (and beam.h)
+3 -3
View File
@@ -288,7 +288,7 @@ constexpr bool LoggingEnabled = false;
// Disabling this functionality is dangerous, crazy values can run rampant unchecked, and the longer it's disabled
// the more likely you are to have problems getting it working again.
#if defined(NDEBUG)
# define Assert(expr) do { ASSUME(expr); (void)sizeof(expr); } while (false)
# define Assert(expr) do { ASSUME(expr); } while (false)
#else
# define Assert(expr) do {\
if (!(expr)) {\
@@ -442,7 +442,7 @@ public:
class camera *getCamera();
size_t getIndex();
int getSignature();
bool isValid() const;
bool isValid();
};
#include "globalincs/vmallocator.h"
@@ -453,7 +453,7 @@ public:
// - is not "none"
// - is not "<none>"
inline bool VALID_FNAME(const char* x) {
return (x[0] != '\0') && stricmp(x, "none") != 0 && stricmp(x, "<none>") != 0;
return strlen((x)) && stricmp((x), "none") != 0 && stricmp((x), "<none>") != 0;
}
/**
* @brief Checks if the specified string may be a valid file name
+13 -12
View File
@@ -12,6 +12,7 @@
#include "debugconsole/console.h"
#include "globalincs/pstypes.h"
#include "graphics/2d.h"
#include "io/timer.h"
#include "nebula/neb.h"
#include "options/Option.h"
@@ -33,6 +34,12 @@ float Cutscene_delta_time = 1.0f;
//How far along a change is (0 to 1)
float Cutscene_bars_progress = 1.0f;
//FADEIN STUFF
shader Viewer_shader;
FadeType Fade_type = FI_NONE;
int Fade_start_timestamp = 0;
int Fade_end_timestamp = 0;
// The detail level. Anything below zero draws simple models earlier than it
// should. Anything above zero draws higher detail models longer than it should.
// -2=lowest
@@ -248,48 +255,45 @@ const auto ModelDetailOption __UNUSED = options::OptionBuilder<int>("Graphics.De
std::pair<const char*, int>{"Model Detail", 1739},
std::pair<const char*, int>{"Detail level of models", 1740})
.importance(8)
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.values(DetailLevelValues)
.default_val(MAX_DETAIL_LEVEL)
.change_listener([](int val, bool) {
Detail.detail_distance = val;
return true;
})
.flags({options::OptionFlags::RetailBuiltinOption})
.finish();
const auto TexturesOption __UNUSED = options::OptionBuilder<int>("Graphics.Texture",
std::pair<const char*, int>{"3D Hardware Textures", 1362},
std::pair<const char*, int>{"Level of detail of textures", 1720})
.importance(6)
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.values(DetailLevelValues)
.default_val(MAX_DETAIL_LEVEL)
.change_listener([](int val, bool) {
Detail.hardware_textures = val;
return true;
})
.flags({options::OptionFlags::RetailBuiltinOption})
.finish();
const auto ParticlesOption __UNUSED = options::OptionBuilder<int>("Graphics.Particles",
std::pair<const char*, int>{"Particles", 1363},
std::pair<const char*, int>{"Level of detail for particles", 1717})
.importance(5)
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.values(DetailLevelValues)
.default_val(MAX_DETAIL_LEVEL)
.change_listener([](int val, bool) {
Detail.num_particles = val;
return true;
})
.flags({options::OptionFlags::RetailBuiltinOption})
.finish();
const auto SmallDebrisOption __UNUSED = options::OptionBuilder<int>("Graphics.SmallDebris",
std::pair<const char*, int>{"Impact Effects", 1364},
std::pair<const char*, int>{"Level of detail of impact effects", 1743})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.values(DetailLevelValues)
.default_val(MAX_DETAIL_LEVEL)
.importance(4)
@@ -297,35 +301,32 @@ const auto SmallDebrisOption __UNUSED = options::OptionBuilder<int>("Graphics.Sm
Detail.num_small_debris = val;
return true;
})
.flags({options::OptionFlags::RetailBuiltinOption})
.finish();
const auto ShieldEffectsOption __UNUSED = options::OptionBuilder<int>("Graphics.ShieldEffects",
std::pair<const char*, int>{"Shield Hit Effects", 1718},
std::pair<const char*, int>{"Level of detail of shield impacts", 1719})
.importance(3)
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.values(DetailLevelValues)
.default_val(MAX_DETAIL_LEVEL)
.change_listener([](int val, bool) {
Detail.shield_effects = val;
return true;
})
.flags({options::OptionFlags::RetailBuiltinOption})
.finish();
const auto StarsOption __UNUSED = options::OptionBuilder<int>("Graphics.Stars",
std::pair<const char*, int>{"Stars", 1366},
std::pair<const char*, int>{"Number of stars in the mission", 1698})
.importance(2)
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.values(DetailLevelValues)
.default_val(MAX_DETAIL_LEVEL)
.change_listener([](int val, bool) {
Detail.num_stars = val;
return true;
})
.flags({options::OptionFlags::RetailBuiltinOption})
.finish();
// Call this with:
+13
View File
@@ -59,6 +59,19 @@
extern float Cutscene_bars_progress, Cutscene_delta_time;
extern int Cutscene_bar_flags;
//-----Fadein stuff
struct shader;
extern shader Viewer_shader;
enum FadeType {
FI_NONE,
FI_FADEIN,
FI_FADEOUT
};
extern FadeType Fade_type;
extern int Fade_start_timestamp;
extern int Fade_end_timestamp;
typedef struct vei {
angles_t angles; // Angles defining viewer location.
+1 -1
View File
@@ -34,7 +34,7 @@
#define ASSUME(x)
#if defined(NDEBUG)
# define Assertion(expr, msg, ...) do { (void)sizeof(expr); } while (false)
# define Assertion(expr, msg, ...) do { } while (false)
#else
/*
* NOTE: Assertion() can only use its proper functionality in compilers
+1 -1
View File
@@ -34,7 +34,7 @@
#define ASSUME(x)
#if defined(NDEBUG)
# define Assertion(expr, msg, ...) do { (void)sizeof(expr); } while (false)
# define Assertion(expr, msg, ...) do {} while (false)
#else
/*
* NOTE: Assertion() can only use its proper functionality in compilers
+1 -1
View File
@@ -36,7 +36,7 @@
#define ASSUME(x)
#if defined(NDEBUG)
# define Assertion(expr, msg, ...) do { (void)sizeof(expr); } while (false)
# define Assertion(expr, msg, ...) do {} while (false)
#else
/*
* NOTE: Assertion() can only use its proper functionality in compilers
+1 -1
View File
@@ -39,7 +39,7 @@
#define ASSUME(x)
#if defined(NDEBUG)
# define Assertion(expr, msg, ...) do { ASSUME(expr); (void)sizeof(expr); } while (false)
# define Assertion(expr, msg, ...) do { ASSUME(expr); } while (false)
#else
# define Assertion(expr, msg, ...) \
do { \
+1 -11
View File
@@ -21,20 +21,10 @@ template <typename T>
using SCP_vector = std::vector<T, std::allocator<T>>;
template <typename T>
bool SCP_vector_contains(const SCP_vector<T>& vector, const T& item) {
bool SCP_vector_contains(SCP_vector<T>& vector, T item) {
return std::find(vector.begin(), vector.end(), item) != vector.end();
}
template <typename T>
inline bool SCP_vector_inbounds(const SCP_vector<T>& vector, int idx) {
return ((idx >= 0) && (idx < static_cast<int>(vector.size())));
}
template <typename T>
inline bool SCP_vector_inbounds(const SCP_vector<T>& vector, size_t idx) {
return idx < vector.size();
}
template <typename T>
using SCP_list = std::list<T, std::allocator<T>>;
+33 -96
View File
@@ -25,7 +25,6 @@
#include "cmdline/cmdline.h"
#include "debugconsole/console.h"
#include "executor/global_executors.h"
#include "graphics/openxr.h"
#include "graphics/paths/PathRenderer.h"
#include "graphics/post_processing.h"
#include "graphics/util/GPUMemoryHeap.h"
@@ -116,12 +115,11 @@ static bool gamma_change_listener(float new_val, bool initial)
static auto GammaOption __UNUSED = options::OptionBuilder<float>("Graphics.Gamma",
std::pair<const char*, int>{"Brightness", 1375},
std::pair<const char*, int>{"The brightness value used for the game window", 1738})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.default_val(1.0f)
.enumerator(gamma_value_enumerator)
.display(gamma_display)
.change_listener(gamma_change_listener)
.flags({options::OptionFlags::RetailBuiltinOption})
.finish();
@@ -135,7 +133,7 @@ const auto LightingOption __UNUSED = options::OptionBuilder<int>("Graphics.Light
std::pair<const char*, int>{"Lighting", 1367},
std::pair<const char*, int>{"Level of detail of the lighting", 1715})
.importance(1)
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.values(DetailLevelValues)
.default_val(MAX_DETAIL_LEVEL)
.change_listener([](int val, bool initial) {
@@ -145,7 +143,6 @@ const auto LightingOption __UNUSED = options::OptionBuilder<int>("Graphics.Light
}
return true;
})
.flags({options::OptionFlags::RetailBuiltinOption})
.finish();
os::ViewportState Gr_configured_window_state = os::ViewportState::Windowed;
@@ -171,7 +168,7 @@ static bool mode_change_func(os::ViewportState state, bool initial)
static auto WindowModeOption __UNUSED = options::OptionBuilder<os::ViewportState>("Graphics.WindowMode",
std::pair<const char*, int>{"Window Mode", 1772},
std::pair<const char*, int>{"Controls how the game window is created", 1773})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.level(options::ExpertLevel::Beginner)
.values({{os::ViewportState::Fullscreen, {"Fullscreen", 1679}},
{os::ViewportState::Borderless, {"Borderless", 1675}},
@@ -262,13 +259,12 @@ static bool videodisplay_change(int display, bool initial)
static auto VideoDisplayOption = options::OptionBuilder<int>("Graphics.Display",
std::pair<const char*, int>{"Primary display", 1741},
std::pair<const char*, int>{"The display used for rendering", 1742})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.level(options::ExpertLevel::Beginner)
.deserializer(videodisplay_deserializer)
.serializer(videodisplay_serializer)
.enumerator(videodisplay_enumerator)
.display(videodisplay_display)
.flags({options::OptionFlags::ForceMultiValueSelection})
.default_val(0)
.change_listener(videodisplay_change)
.importance(99)
@@ -372,7 +368,7 @@ static bool resolution_change(const ResolutionInfo& /*info*/, bool initial)
static auto ResolutionOption = options::OptionBuilder<ResolutionInfo>("Graphics.Resolution",
std::pair<const char*, int>{"Resolution", 1748},
std::pair<const char*, int>{"The rendering resolution", 1749})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.level(options::ExpertLevel::Beginner)
.deserializer(resolution_deserializer)
.serializer(resolution_serializer)
@@ -388,7 +384,7 @@ bool Gr_enable_soft_particles = false;
static auto SoftParticlesOption __UNUSED = options::OptionBuilder<bool>("Graphics.SoftParticles",
std::pair<const char*, int>{"Soft Particles", 1761},
std::pair<const char*, int>{"Enable or disable soft particle rendering", 1762})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.level(options::ExpertLevel::Advanced)
.default_val(true)
.bind_to_once(&Gr_enable_soft_particles)
@@ -400,13 +396,13 @@ flagset<FramebufferEffects> Gr_framebuffer_effects;
static auto FramebufferEffectsOption __UNUSED = options::OptionBuilder<flagset<FramebufferEffects>>("Graphics.FramebufferEffects",
std::pair<const char*, int>{"Framebuffer effects", 1732},
std::pair<const char*, int>{"Controls which framebuffer effects will be applied to the scene", 1733})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.level(options::ExpertLevel::Advanced)
.values({{{}, {"None", 211}},
{{FramebufferEffects::Shockwaves}, {"Shockwaves", 1688}},
{{FramebufferEffects::Thrusters}, {"Thrusters", 1689}},
{{FramebufferEffects::Shockwaves, FramebufferEffects::Thrusters}, {"All", 1690}}})
.default_val({})
.default_val({FramebufferEffects::Shockwaves, FramebufferEffects::Thrusters})
.bind_to_once(&Gr_framebuffer_effects)
.importance(77)
.finish();
@@ -417,7 +413,7 @@ AntiAliasMode Gr_aa_mode_last_frame = AntiAliasMode::None;
static auto AAOption __UNUSED = options::OptionBuilder<AntiAliasMode>("Graphics.AAMode",
std::pair<const char*, int>{"Anti Aliasing", 1752},
std::pair<const char*, int>{"Controls the anti aliasing mode of the engine.", 1753})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.level(options::ExpertLevel::Advanced)
.values({{AntiAliasMode::None, {"None", 211}},
{AntiAliasMode::FXAA_Low, {"FXAA Low", 1681}},
@@ -436,7 +432,7 @@ extern int Cmdline_msaa_enabled;
static auto MSAAOption __UNUSED = options::OptionBuilder<int>("Graphics.MSAASamples",
std::pair<const char*, int>{"Multisample Anti Aliasing", 1758},
std::pair<const char*, int>{"Controls whether multisample anti asliasing is enabled, and with how many samples", 1759})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.level(options::ExpertLevel::Advanced)
.values({{0, {"Off", 1693}},
{4, {"4 Samples", 1694}},
@@ -460,9 +456,9 @@ bool Gr_post_processing_enabled = true;
static auto PostProcessOption __UNUSED = options::OptionBuilder<bool>("Graphics.PostProcessing",
std::pair<const char*, int>{"Post processing", 1726},
std::pair<const char*, int>{"Controls whether post processing is enabled in the engine.", 1727})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.level(options::ExpertLevel::Advanced)
.default_val(true)
.default_val(false)
.bind_to_once(&Gr_post_processing_enabled)
.importance(69)
.finish();
@@ -472,7 +468,7 @@ bool Gr_enable_vsync = true;
static auto VSyncOption __UNUSED = options::OptionBuilder<bool>("Graphics.VSync",
std::pair<const char*, int>{"Vertical Sync", 1766},
std::pair<const char*, int>{"Controls how the engine does vertical synchronization", 1767})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.level(options::ExpertLevel::Advanced)
.default_val(true)
.bind_to_once(&Gr_enable_vsync)
@@ -708,7 +704,7 @@ bool gr_resize_screen_pos(int *x, int *y, int *w, int *h, int resize_mode)
*/
bool gr_unsize_screen_pos(int *x, int *y, int *w, int *h, int resize_mode)
{
if ( resize_mode == GR_RESIZE_NONE || resize_mode == GR_RESIZE_REPLACE || (!gr_screen.custom_size && (gr_screen.rendering_to_texture == -1)) ) {
if ( resize_mode == GR_RESIZE_NONE || (!gr_screen.custom_size && (gr_screen.rendering_to_texture == -1)) ) {
return false;
}
@@ -1029,9 +1025,6 @@ void gr_close()
return;
}
if(Cmdline_enable_vr)
openxr_close();
if (Gr_original_gamma_ramp != nullptr && os::getSDLMainWindow() != nullptr) {
SDL_SetWindowGammaRamp(os::getSDLMainWindow(), Gr_original_gamma_ramp, (Gr_original_gamma_ramp + 256),
(Gr_original_gamma_ramp + 512));
@@ -1263,38 +1256,14 @@ static void init_colors()
Gr_ta_alpha.scale = 17;
}
static void gr_init_function_pointers(int mode) {
gr_screen = {};
switch (mode) {
case GR_OPENGL:
#ifdef WITH_OPENGL
gr_opengl_init_function_pointers();
#else
Error(LOCATION, "OpenGL renderer was requested but that was not compiled into this build.");
#endif
break;
case GR_VULKAN:
#ifdef WITH_VULKAN
graphics::vulkan::initialize_function_pointers();
#else
Error(LOCATION, "Vulkan renderer was requested but that was not compiled into this build.");
#endif
break;
case GR_STUB:
gr_stub_init_function_pointers();
break;
default:
UNREACHABLE("Invalid graphics mode requested"); // Invalid graphics mode
}
}
static bool gr_init_sub(std::unique_ptr<os::GraphicsOperations>&& graphicsOps, int mode, int width, int height,
int depth, float center_aspect_ratio)
{
int res = GR_1024;
bool rc = false;
gr_screen = {};
float aspect_ratio = (float)width / (float)height;
if ( (((width == 640) && (height == 480)) || ((width == 1024) && (height == 768))) && (aspect_ratio == center_aspect_ratio) ) {
@@ -1593,6 +1562,9 @@ bool gr_init(std::unique_ptr<os::GraphicsOperations>&& graphicsOps, int d_mode,
depth = d_depth;
}
if (Cmdline_vulkan)
mode = GR_VULKAN;
// if we are in standalone mode then just use special defaults
if (Is_standalone) {
mode = GR_STUB;
@@ -1602,8 +1574,6 @@ bool gr_init(std::unique_ptr<os::GraphicsOperations>&& graphicsOps, int d_mode,
center_aspect_ratio = -1.0f;
}
gr_init_function_pointers(mode);
if (gr_get_resolution_class(width, height) != GR_640) {
// check for hi-res interface files so that we can verify our width/height is correct
// if we don't have it then fall back to 640x480 mode instead
@@ -1621,17 +1591,6 @@ bool gr_init(std::unique_ptr<os::GraphicsOperations>&& graphicsOps, int d_mode,
}
}
if (Cmdline_enable_vr) {
float user_ar = i2fl(width) / i2fl(height);
float xr_ar = openxr_preinit(user_ar);
if (MAX(user_ar, xr_ar) / MIN(user_ar, xr_ar) > 1.05f) {
int newWidth = fl2i(i2fl(height) * xr_ar);
mprintf(("User specified resolution does not match OpenXR HMD aspect ratio. Adjusting width from %dpx to %dpx.", width, newWidth));
width = newWidth;
}
}
// These compiler macros will force windowed mode at the specified resolution if
// built in debug mode. This helps if you run with the debugger active as the
// game won't be switching from fullscreen to minimized every time you hit a breakpoint or
@@ -1750,12 +1709,20 @@ bool gr_init(std::unique_ptr<os::GraphicsOperations>&& graphicsOps, int d_mode,
Shadow_quality = ShadowQuality::Disabled;
}
if(Cmdline_enable_vr)
openxr_init();
return true;
}
void gr_force_windowed()
{
if ( !Gr_inited ) {
return;
}
if ( Os_debugger_running ) {
os_sleep(1000);
}
}
int gr_activated = 0;
void gr_activate(int active)
{
@@ -1770,7 +1737,7 @@ void gr_activate(int active)
}
if (active) {
if (gr_is_viewport_window()) {
if (Cmdline_fullscreen_window || Cmdline_window) {
os::getMainViewport()->restore();
} else {
os::getMainViewport()->setState(os::ViewportState::Fullscreen);
@@ -1780,7 +1747,7 @@ void gr_activate(int active)
}
if (active) {
if (!gr_is_viewport_window()) {
if (!Cmdline_fullscreen_window && !Cmdline_window) {
gr_set_gamma(Gr_gamma);
}
}
@@ -2630,12 +2597,7 @@ void gr_flip(bool execute_scripting)
uniform_buffer_managers_retire_buffers();
TRACE_SCOPE(tracing::PageFlip);
//Prevent a real page flip if OpenXR is on and claims that that wasn't the full image yet
if (!gr_openxr_flip()) {
gr_screen.gf_flip();
gr_setup_frame();
}
gr_screen.gf_flip();
}
void gr_print_timestamp(int x, int y, fix timestamp, int resize_mode)
@@ -2959,28 +2921,3 @@ void gr_get_post_process_effect_names(SCP_vector<SCP_string>& names)
names.push_back(eff.name);
}
}
bool gr_is_viewport_window()
{
if (Fred_running) {
return true;
}
if (Using_in_game_options) {
switch (Gr_configured_window_state)
{
case os::ViewportState::Windowed:
case os::ViewportState::Borderless:
return true;
break;
default:
break;
}
} else {
if (Cmdline_window || Cmdline_fullscreen_window) {
return true;
}
}
return false;
}
+1 -31
View File
@@ -203,7 +203,6 @@ enum shader_type {
SDR_TYPE_VOLUMETRIC_FOG,
SDR_TYPE_ROCKET_UI,
SDR_TYPE_COPY,
SDR_TYPE_COPY_WORLD,
SDR_TYPE_MSAA_RESOLVE,
SDR_TYPE_POST_PROCESS_SMAA_EDGE,
@@ -238,10 +237,6 @@ enum shader_type {
#define SDR_FLAG_VOLUMETRICS_DO_EDGE_SMOOTHING (1<<0)
#define SDR_FLAG_VOLUMETRICS_NOISE (1<<1)
#define SDR_FLAG_COPY_FROM_ARRAY (1 << 0)
#define SDR_FLAG_TONEMAPPING_LINEAR_OUT (1 << 0)
enum class uniform_block_type {
Lights = 0,
@@ -702,8 +697,6 @@ typedef struct screen {
// switch onscreen, offscreen
std::function<void()> gf_flip;
std::function<void()> gf_setup_frame;
// sets the clipping region
std::function<void(int x, int y, int w, int h, int resize_mode)> gf_set_clip;
@@ -919,14 +912,6 @@ typedef struct screen {
std::function<void(int x, int y, int width, int height)> gf_set_viewport;
std::function<void(bool set_override)> gf_override_fog;
//OpenXR functions
std::function<SCP_vector<const char*>()> gf_openxr_get_extensions;
std::function<bool()> gf_openxr_test_capabilities;
std::function<bool()> gf_openxr_create_session;
std::function<int64_t(const SCP_vector<int64_t>&)> gf_openxr_get_swapchain_format;
std::function<bool()> gf_openxr_acquire_swapchain_buffers;
std::function<bool()> gf_openxr_flip;
} screen;
// handy macro
@@ -981,7 +966,6 @@ extern screen gr_screen;
#define GR_RESIZE_MENU 3
#define GR_RESIZE_MENU_ZOOMED 4
#define GR_RESIZE_MENU_NO_OFFSET 5
#define GR_RESIZE_REPLACE 6
void gr_set_screen_scale(int x, int y, int zoom_x = -1, int zoom_y = -1, int max_x = gr_screen.max_w, int max_y = gr_screen.max_h, int center_x = gr_screen.center_w, int center_y = gr_screen.center_h, bool force_stretch = false);
void gr_reset_screen_scale();
@@ -1002,7 +986,7 @@ extern void gr_printf_menu_zoomed( int x, int y, const char * format, SCP_FORMAT
extern void gr_printf_no_resize( int x, int y, const char * format, SCP_FORMAT_STRING ... ) SCP_FORMAT_STRING_ARGS(3, 4);
// Returns the size of the string in pixels in w and h
extern void gr_get_string_size( int *w, int *h, const char * text, size_t len = std::string::npos );
extern void gr_get_string_size( int *w, int *h, const char * text, int len = 9999 );
// Returns the height of the current font
extern int gr_get_font_height();
@@ -1027,10 +1011,6 @@ extern void gr_activate(int active);
//#define gr_flip GR_CALL(gr_screen.gf_flip)
void gr_flip(bool execute_scripting = true);
inline void gr_setup_frame() {
gr_screen.gf_setup_frame();
}
//#define gr_set_clip GR_CALL(gr_screen.gf_set_clip)
inline void gr_set_clip(int x, int y, int w, int h, int resize_mode=GR_RESIZE_FULL)
{
@@ -1292,14 +1272,6 @@ inline void gr_sync_delete(gr_sync sync)
gr_screen.gf_sync_delete(sync);
}
//OpenXR
#define gr_openxr_get_extensions GR_CALL(gr_screen.gf_openxr_get_extensions)
#define gr_openxr_test_capabilities GR_CALL(gr_screen.gf_openxr_test_capabilities)
#define gr_openxr_create_session GR_CALL(gr_screen.gf_openxr_create_session)
#define gr_openxr_get_swapchain_format GR_CALL(gr_screen.gf_openxr_get_swapchain_format)
#define gr_openxr_acquire_swapchain_buffers GR_CALL(gr_screen.gf_openxr_acquire_swapchain_buffers)
#define gr_openxr_flip GR_CALL(gr_screen.gf_openxr_flip)
// color functions
void gr_init_color(color *c, int r, int g, int b);
void gr_init_alphacolor( color *clr, int r, int g, int b, int alpha, int type = AC_TYPE_HUD );
@@ -1428,8 +1400,6 @@ void gr_set_gamma(float gamma);
void gr_get_post_process_effect_names(SCP_vector<SCP_string> &names);
bool gr_is_viewport_window();
// Include this last to make the 2D rendering function available everywhere
#include "graphics/render.h"
+17 -2
View File
@@ -734,7 +734,7 @@ void generic_anim_render(generic_anim *ga, float frametime, int x, int y, bool m
}
}
void generic_anim_bitmap_set(generic_anim* ga, float frametime, const generic_extras* ge)
void generic_anim_render_ex(generic_anim* ga, float frametime, int x, int y, int w, int h, bool menu, const generic_extras* ge)
{
if ((ge != nullptr) && (ga->use_hud_color == true)) {
Warning(LOCATION, "Monochrome generic anims can't use extra info (yet)");
@@ -752,8 +752,23 @@ void generic_anim_bitmap_set(generic_anim* ga, float frametime, const generic_ex
generic_anim_render_fixed_frame_delay(ga, frametime, a);
}
if (ga->num_frames > 0)
if (ga->num_frames > 0) {
ga->previous_frame = ga->current_frame;
if (ga->use_hud_color) {
gr_aabitmap_ex(x, y, w, h, 0, 0, (menu ? GR_RESIZE_MENU : GR_RESIZE_FULL));
}
else {
if (ge == nullptr) {
gr_bitmap_ex(x, y, w, h, 0, 0, (menu ? GR_RESIZE_MENU : GR_RESIZE_FULL));
}
else if (ge->draw == true) {
// currently only for lua streaminganim objects
// and don't draw them unless requested...
gr_bitmap_uv(x, y, w, h, ge->u0, ge->v0, ge->u1, ge->v1, ge->resize_mode);
}
}
}
}
/*
+1 -1
View File
@@ -91,6 +91,6 @@ int generic_anim_stream(generic_anim *ga, const bool cache = true);
int generic_bitmap_load(generic_bitmap *gb);
void generic_anim_unload(generic_anim *ga);
void generic_anim_render(generic_anim *ga, float frametime, int x, int y, bool menu = false, const generic_extras *ge = nullptr);
void generic_anim_bitmap_set(generic_anim* ga, float frametime, const generic_extras* ge = nullptr);
void generic_anim_render_ex(generic_anim* ga, float frametime, int x, int y, int w, int h, bool menu = false, const generic_extras* ge = nullptr);
void generic_anim_reset(generic_anim *ga);
#endif
+2 -47
View File
@@ -18,11 +18,6 @@
#include "bmpman/bm_internal.h"
void gr_stub_setup_frame()
{
}
uint gr_stub_lock()
{
return 1;
@@ -426,37 +421,7 @@ void gr_stub_delete_query_object(int /*obj*/)
{
}
SCP_vector<const char*> gr_stub_openxr_get_extensions()
{
return {};
}
bool gr_stub_openxr_test_capabilities()
{
return false;
}
bool gr_stub_openxr_create_session()
{
return false;
}
int64_t gr_stub_openxr_get_swapchain_format(const SCP_vector<int64_t>& /*allowed*/)
{
return 0;
}
bool gr_stub_openxr_acquire_swapchain_buffers()
{
return false;
}
bool gr_stub_openxr_flip()
{
return false;
}
bool gr_stub_init()
bool gr_stub_init()
{
if (gr_screen.res != GR_640) {
gr_screen.res = GR_640;
@@ -482,13 +447,8 @@ bool gr_stub_init()
Gr_blue.mask = 0xff;
Gr_t_blue = Gr_blue;
return true;
}
void gr_stub_init_function_pointers() {
// function pointers...
gr_screen.gf_flip = gr_stub_flip;
gr_screen.gf_setup_frame = gr_stub_setup_frame;
gr_screen.gf_set_clip = gr_stub_set_clip;
gr_screen.gf_reset_clip = gr_stub_reset_clip;
@@ -612,10 +572,5 @@ void gr_stub_init_function_pointers() {
gr_screen.gf_override_fog = [](bool /*b*/) {};
gr_screen.gf_openxr_get_extensions = gr_stub_openxr_get_extensions;
gr_screen.gf_openxr_test_capabilities = gr_stub_openxr_test_capabilities;
gr_screen.gf_openxr_create_session = gr_stub_openxr_create_session;
gr_screen.gf_openxr_get_swapchain_format = gr_stub_openxr_get_swapchain_format;
gr_screen.gf_openxr_acquire_swapchain_buffers = gr_stub_openxr_acquire_swapchain_buffers;
gr_screen.gf_openxr_flip = gr_stub_openxr_flip;
return true;
}
+1 -1
View File
@@ -1,3 +1,3 @@
void gr_stub_init_function_pointers();
bool gr_stub_init();
+2 -9
View File
@@ -15,7 +15,6 @@
#include "cmdline/cmdline.h"
#include "graphics/2d.h"
#include "io/timer.h"
#include "lighting/lighting.h"
#include "lighting/lighting_profiles.h"
#include "math/bitarray.h"
@@ -44,12 +43,6 @@ struct gr_light
int type;
};
//FADEIN STUFF
shader Viewer_shader;
FadeType Fade_type = FadeType::FI_NONE;
TIMESTAMP Fade_start_timestamp = TIMESTAMP::invalid();
TIMESTAMP Fade_end_timestamp = TIMESTAMP::invalid();
// Variables
SCP_vector<gr_light> gr_lights;
graphics::model_light gr_light_uniforms[graphics::MAX_UNIFORM_LIGHTS];
@@ -339,8 +332,8 @@ void gr_set_ambient_light(int red, int green, int blue) {
gr_light_ambient[3] = 1.0f;
}
void gr_get_ambient_light(vec3d* light_vector) {
const auto& abv = ltp::current()->ambient_light_brightness;
const auto& over = ltp::current()->overall_brightness;
auto abv = ltp::current()->ambient_light_brightness;
auto over = ltp::current()->overall_brightness;
light_vector->xyz.x = over.handle(abv.handle(gr_light_ambient[0]));
light_vector->xyz.y = over.handle(abv.handle(gr_light_ambient[1]));
light_vector->xyz.z = over.handle(abv.handle(gr_light_ambient[2]));
-15
View File
@@ -5,20 +5,6 @@
#include "lighting/lighting.h"
#include "cmdline/cmdline.h"
//-----Fadein stuff
struct shader;
extern shader Viewer_shader;
enum class FadeType {
FI_NONE = 0,
FI_FADEIN,
FI_FADEOUT
};
extern FadeType Fade_type;
extern TIMESTAMP Fade_start_timestamp;
extern TIMESTAMP Fade_end_timestamp;
//Variables
extern int Num_active_gr_lights;
@@ -27,7 +13,6 @@ extern const float gr_light_zero[4];
extern const float gr_light_emission[4];
extern float gr_light_ambient[4];
//Functions
void gr_set_light(light *fs_light);
void gr_reset_lighting();
+5 -5
View File
@@ -85,7 +85,7 @@ void gr_start_instance_matrix(const vec3d *offset, const matrix *rotation)
gr_model_matrix_stack.push(offset, rotation);
const auto& model_matrix = gr_model_matrix_stack.get_transform();
auto model_matrix = gr_model_matrix_stack.get_transform();
vm_matrix4_x_matrix4(&gr_model_view_matrix, &gr_view_matrix, &model_matrix);
modelview_matrix_depth++;
@@ -109,7 +109,7 @@ void gr_end_instance_matrix()
gr_model_matrix_stack.pop();
const auto& model_matrix = gr_model_matrix_stack.get_transform();
auto model_matrix = gr_model_matrix_stack.get_transform();
vm_matrix4_x_matrix4(&gr_model_view_matrix, &gr_view_matrix, &model_matrix);
modelview_matrix_depth--;
@@ -280,7 +280,7 @@ void gr_end_2d_matrix()
gr_view_matrix = gr_last_view_matrix;
const auto& model_matrix = gr_model_matrix_stack.get_transform();
auto model_matrix = gr_model_matrix_stack.get_transform();
vm_matrix4_x_matrix4(&gr_model_view_matrix, &gr_view_matrix, &model_matrix);
htl_2d_matrix_set = false;
@@ -302,7 +302,7 @@ void gr_push_scale_matrix(const vec3d *scale_factor)
gr_model_matrix_stack.push(NULL, NULL, scale_factor);
const auto& model_matrix = gr_model_matrix_stack.get_transform();
auto model_matrix = gr_model_matrix_stack.get_transform();
vm_matrix4_x_matrix4(&gr_model_view_matrix, &gr_view_matrix, &model_matrix);
matrix_uniform_up_to_date = false;
@@ -315,7 +315,7 @@ void gr_pop_scale_matrix()
gr_model_matrix_stack.pop();
const auto& model_matrix = gr_model_matrix_stack.get_transform();
auto model_matrix = gr_model_matrix_stack.get_transform();
vm_matrix4_x_matrix4(&gr_model_view_matrix, &gr_view_matrix, &model_matrix);
modelview_matrix_depth--;
+24 -70
View File
@@ -6,19 +6,11 @@
#include <direct.h>
#endif
#if !defined __APPLE_CC__ && defined SCP_UNIX
#include<glad/glad_glx.h>
//Required because X defines none and always, which is used later
#undef None
#undef Always
#endif
#include "gropengl.h"
#include "ShaderProgram.h"
#include "gropenglbmpman.h"
#include "gropengldeferred.h"
#include "gropengldraw.h"
#include "gropenglopenxr.h"
#include "gropenglpostprocessing.h"
#include "gropenglquery.h"
#include "gropenglshader.h"
@@ -115,18 +107,6 @@ void gr_opengl_flip()
if (!GL_initted)
return;
if (Cmdline_window_res) {
GL_state.BindFrameBuffer(0, GL_DRAW_FRAMEBUFFER);
GL_state.BindFrameBuffer(Back_framebuffer, GL_READ_FRAMEBUFFER);
glReadBuffer(GL_COLOR_ATTACHMENT0);
glDrawBuffer(GL_BACK);
glBlitFramebuffer(0, 0, gr_screen.max_w, gr_screen.max_h, 0, 0, Cmdline_window_res->first, Cmdline_window_res->second, GL_COLOR_BUFFER_BIT, GL_LINEAR);
glDrawBuffer(GL_NONE);
GL_state.PopFramebufferState();
}
if (Cmdline_gl_finish)
glFinish();
@@ -143,17 +123,6 @@ void gr_opengl_flip()
#endif
}
void gr_opengl_setup_frame() {
if (!GL_initted)
return;
if (Cmdline_window_res) {
GL_state.PushFramebufferState();
GL_state.BindFrameBuffer(Back_framebuffer);
glViewport(0, 0, gr_screen.max_w, gr_screen.max_h);
}
}
void gr_opengl_set_clip(int x, int y, int w, int h, int resize_mode)
{
// check for sanity of parameters
@@ -165,7 +134,7 @@ void gr_opengl_set_clip(int x, int y, int w, int h, int resize_mode)
y = 0;
}
int to_resize = (resize_mode != GR_RESIZE_NONE && resize_mode != GR_RESIZE_REPLACE && (gr_screen.custom_size || (gr_screen.rendering_to_texture != -1)));
int to_resize = (resize_mode != GR_RESIZE_NONE && (gr_screen.custom_size || (gr_screen.rendering_to_texture != -1)));
int max_w = ((to_resize) ? gr_screen.max_w_unscaled : gr_screen.max_w);
int max_h = ((to_resize) ? gr_screen.max_h_unscaled : gr_screen.max_h);
@@ -174,30 +143,28 @@ void gr_opengl_set_clip(int x, int y, int w, int h, int resize_mode)
gr_unsize_screen_pos(&max_w, &max_h);
}
if (resize_mode != GR_RESIZE_REPLACE) {
if (x >= max_w) {
x = max_w - 1;
}
if (x >= max_w) {
x = max_w - 1;
}
if (y >= max_h) {
y = max_h - 1;
}
if (y >= max_h) {
y = max_h - 1;
}
if (x + w > max_w) {
w = max_w - x;
}
if (x + w > max_w) {
w = max_w - x;
}
if (y + h > max_h) {
h = max_h - y;
}
if (y + h > max_h) {
h = max_h - y;
}
if (w > max_w) {
w = max_w;
}
if (w > max_w) {
w = max_w;
}
if (h > max_h) {
h = max_h;
}
if (h > max_h) {
h = max_h;
}
gr_screen.offset_x_unscaled = x;
@@ -934,10 +901,9 @@ int opengl_init_display_device()
return 0;
}
void gr_opengl_init_function_pointers()
void opengl_setup_function_pointers()
{
gr_screen.gf_flip = gr_opengl_flip;
gr_screen.gf_setup_frame = gr_opengl_setup_frame;
gr_screen.gf_set_clip = gr_opengl_set_clip;
gr_screen.gf_reset_clip = gr_opengl_reset_clip;
@@ -1066,13 +1032,6 @@ void gr_opengl_init_function_pointers()
gr_screen.gf_override_fog = gr_opengl_override_fog;
gr_screen.gf_openxr_get_extensions = gr_opengl_openxr_get_extensions;
gr_screen.gf_openxr_test_capabilities = gr_opengl_openxr_test_capabilities;
gr_screen.gf_openxr_create_session = gr_opengl_openxr_create_session;
gr_screen.gf_openxr_get_swapchain_format = gr_opengl_openxr_get_swapchain_format;
gr_screen.gf_openxr_acquire_swapchain_buffers = gr_opengl_openxr_acquire_swapchain_buffers;
gr_screen.gf_openxr_flip = gr_opengl_openxr_flip;
// NOTE: All function pointers here should have a Cmdline_nohtl check at the top
// if they shouldn't be run in non-HTL mode, Don't keep separate entries.
// *****************************************************************************
@@ -1271,12 +1230,6 @@ bool gr_opengl_init(std::unique_ptr<os::GraphicsOperations>&& graphicsOps)
Error(LOCATION, "Failed to load OpenGL!");
}
#if !defined __APPLE_CC__ && defined SCP_UNIX
if (!gladLoadGLXLoader(GL_context->getLoaderFunction(), nullptr, 0)) {
Error(LOCATION, "Failed to load GLX!");
}
#endif
// version check
GL_version = (GLVersion.major * 10) + GLVersion.minor;
@@ -1309,6 +1262,11 @@ bool gr_opengl_init(std::unique_ptr<os::GraphicsOperations>&& graphicsOps)
}
#endif
// this MUST be done before any other gr_opengl_* or
// opengl_* function calls!!
opengl_setup_function_pointers();
mprintf(( " OpenGL Vendor : %s\n", glGetString(GL_VENDOR) ));
mprintf(( " OpenGL Renderer : %s\n", glGetString(GL_RENDERER) ));
mprintf(( " OpenGL Version : %s\n", glGetString(GL_VERSION) ));
@@ -1388,15 +1346,11 @@ bool gr_opengl_init(std::unique_ptr<os::GraphicsOperations>&& graphicsOps)
Gr_current_green = &Gr_green;
Gr_current_alpha = &Gr_alpha;
gr_setup_frame();
gr_opengl_reset_clip();
gr_opengl_clear();
gr_opengl_flip();
gr_setup_frame();
gr_opengl_clear();
gr_opengl_flip();
gr_setup_frame();
gr_opengl_clear();
glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &GL_max_elements_vertices);
-1
View File
@@ -16,7 +16,6 @@
#include "globalincs/pstypes.h"
#include "graphics/grinternal.h"
void gr_opengl_init_function_pointers();
bool gr_opengl_init(std::unique_ptr<os::GraphicsOperations>&& graphicsOps);
void gr_opengl_cleanup(bool closing, int minimize=1);
int opengl_check_for_errors(const char *err_at = NULL);
+122 -213
View File
@@ -1,7 +1,6 @@
#include "gropengldeferred.h"
#include "globalincs/vmallocator.h"
#include "ShaderProgram.h"
#include "gropengldraw.h"
@@ -171,42 +170,11 @@ void gr_opengl_deferred_lighting_end()
GL_state.ColorMask(true, true, true, false);
}
static GLuint deferred_light_cylinder_vbo = 0;
static GLuint deferred_light_cylinder_ibo = 0;
static GLushort deferred_light_cylinder_vcount = 0;
static GLuint deferred_light_cylinder_icount = 0;
static GLuint deferred_light_sphere_vbo = 0;
static GLuint deferred_light_sphere_ibo = 0;
static GLushort deferred_light_sphere_vcount = 0;
static GLuint deferred_light_sphere_icount = 0;
extern SCP_vector<light> Lights;
extern int Num_lights;
namespace ltp = lighting_profiles;
using namespace ltp;
static bool override_fog = false;
graphics::deferred_light_data*
// common conversion operations to translate a game light data structure into a render-ready light uniform.
prepare_light_uniforms(light& l, graphics::util::UniformAligner& uniformAligner)
{
graphics::deferred_light_data* light_data = uniformAligner.addTypedElement<graphics::deferred_light_data>();
light_data->lightType = static_cast<int>(l.type);
vec3d diffuse;
diffuse.xyz.x = l.r * l.intensity;
diffuse.xyz.y = l.g * l.intensity;
diffuse.xyz.z = l.b * l.intensity;
light_data->diffuseLightColor = diffuse;
// Set a default value for all lights. Only the first directional light will change this.
light_data->enable_shadows = false;
light_data->sourceRadius = l.source_radius;
return light_data;
}
void gr_opengl_deferred_lighting_finish()
{
@@ -220,8 +188,8 @@ void gr_opengl_deferred_lighting_finish()
GL_state.SetAlphaBlendMode(ALPHA_BLEND_ADDITIVE);
gr_zbuffer_set(GR_ZBUFF_NONE);
// GL_state.DepthFunc(GL_GREATER);
// GL_state.DepthMask(GL_FALSE);
//GL_state.DepthFunc(GL_GREATER);
//GL_state.DepthMask(GL_FALSE);
opengl_shader_set_current(gr_opengl_maybe_create_shader(SDR_TYPE_DEFERRED_LIGHTING, 0));
@@ -246,7 +214,7 @@ void gr_opengl_deferred_lighting_finish()
if (Shadow_quality != ShadowQuality::Disabled) {
GL_state.Texture.Enable(4, GL_TEXTURE_2D_ARRAY, Shadow_map_texture);
}
// We need to use stable sorting here to make sure that the relative ordering of the same light types is the same as
// the rest of the code. Otherwise the shadow mapping would be applied while rendering the wrong light which would
// lead to flickering lights in some circumstances
@@ -257,43 +225,19 @@ void gr_opengl_deferred_lighting_finish()
size_t num_data_elements = Lights.size();
// Get a uniform buffer for our data
auto light_buffer = gr_get_uniform_buffer(uniform_block_type::Lights, num_data_elements);
auto& light_uniform_aligner = light_buffer.aligner();
auto matrix_buffer = gr_get_uniform_buffer(uniform_block_type::Matrices, num_data_elements);
auto& matrix_uniform_aligner = matrix_buffer.aligner();
auto buffer = gr_get_uniform_buffer(uniform_block_type::Lights, num_data_elements);
auto& uniformAligner = buffer.aligner();
// This is the light which is responsible for shadows and volumetric nebula lighting
const light* global_light = nullptr;
vec3d global_light_diffuse;
// To allow reduced bind calls, we sort lights into subsets based on rendering methods.
// It might seem optimal to create these subsets as lights are added, or some other method,
// but this keeps the graphics implementation methods better contained and profiling currently
// (dec 2023) shows negligable cost of doing it this way.
SCP_vector<light> full_frame_lights = SCP_vector<light>();
SCP_vector<light> sphere_lights = SCP_vector<light>();
SCP_vector<light> cylinder_lights = SCP_vector<light>();
for (auto& l : Lights) {
switch (l.type) {
case Light_Type::Directional:
full_frame_lights.push_back(l);
break;
case Light_Type::Cone:
FALLTHROUGH;
case Light_Type::Point:
sphere_lights.push_back(l);
break;
case Light_Type::Tube:
cylinder_lights.push_back(l);
break;
}
}
{
GR_DEBUG_SCOPE("Build buffer data");
auto lp = ltp::current();
auto header = light_uniform_aligner.getHeader<deferred_global_data>();
auto header = uniformAligner.getHeader<deferred_global_data>();
if (Shadow_quality != ShadowQuality::Disabled) {
// Avoid this overhead when we are not going to use these values
header->shadow_mv_matrix = Shadow_view_matrix_light;
@@ -314,178 +258,133 @@ void gr_opengl_deferred_lighting_finish()
// Only the first directional light uses shaders so we need to know when we already saw that light
bool first_directional = true;
for (auto& l : Lights) {
auto light_data = uniformAligner.addTypedElement<deferred_light_data>();
for (auto& l : full_frame_lights) {
auto light_data = prepare_light_uniforms(l, light_uniform_aligner);
if (Shadow_quality != ShadowQuality::Disabled) {
light_data->enable_shadows = first_directional ? 1 : 0;
}
light_data->lightType = static_cast<int>(l.type);
// Global light direction should match shadow light direction
if (first_directional) {
global_light = &l;
global_light_diffuse = light_data->diffuseLightColor;
}
vec3d diffuse;
diffuse.xyz.x = l.r * l.intensity;
diffuse.xyz.y = l.g * l.intensity;
diffuse.xyz.z = l.b * l.intensity;
vec4 light_dir;
light_dir.xyzw.x = -l.vec.xyz.x;
light_dir.xyzw.y = -l.vec.xyz.y;
light_dir.xyzw.z = -l.vec.xyz.z;
light_dir.xyzw.w = 0.0f;
vec4 view_dir;
light_data->diffuseLightColor = diffuse;
vm_vec_transform(&view_dir, &light_dir, &gr_view_matrix);
// Set a default value for all lights. Only the first directional light will change this.
light_data->enable_shadows = false;
light_data->sourceRadius = l.source_radius;
light_data->lightDir.xyz.x = view_dir.xyzw.x;
light_data->lightDir.xyz.y = view_dir.xyzw.y;
light_data->lightDir.xyz.z = view_dir.xyzw.z;
switch (l.type) {
case Light_Type::Directional:
if (Shadow_quality != ShadowQuality::Disabled) {
light_data->enable_shadows = first_directional ? 1 : 0;
}
first_directional = false;
}
for (auto& l : sphere_lights) {
auto light_data = prepare_light_uniforms(l, light_uniform_aligner);
// Global light direction should match shadow light direction
if (first_directional) {
global_light = &l;
global_light_diffuse = diffuse;
}
vec4 light_dir;
light_dir.xyzw.x = -l.vec.xyz.x;
light_dir.xyzw.y = -l.vec.xyz.y;
light_dir.xyzw.z = -l.vec.xyz.z;
light_dir.xyzw.w = 0.0f;
vec4 view_dir;
if (l.type == Light_Type::Cone) {
light_data->dualCone = (l.flags & LF_DUAL_CONE) ? 1.0f : 0.0f;
vm_vec_transform(&view_dir, &light_dir, &gr_view_matrix);
light_data->lightDir.xyz.x = view_dir.xyzw.x;
light_data->lightDir.xyz.y = view_dir.xyzw.y;
light_data->lightDir.xyz.z = view_dir.xyzw.z;
first_directional = false;
break;
case Light_Type::Cone:
light_data->dualCone = l.dual_cone ? 1.0f : 0.0f;
light_data->coneAngle = l.cone_angle;
light_data->coneInnerAngle = l.cone_inner_angle;
light_data->coneDir = l.vec2;
FALLTHROUGH;
case Light_Type::Point: {
float rad = (Lighting_mode == lighting_mode::COCKPIT) ? lp->cockpit_light_radius_modifier.handle(MAX(l.rada, l.radb)) : MAX(l.rada, l.radb);
light_data->lightRadius = rad;
//A small padding factor is added to guard against potentially clipping the edges of the light with facets of the volume mesh.
light_data->scale.xyz.x = rad * 1.05f;
light_data->scale.xyz.y = rad * 1.05f;
light_data->scale.xyz.z = rad * 1.05f;
break;
}
case Light_Type::Tube: {
float rad = (Lighting_mode == lighting_mode::COCKPIT) ? lp->cockpit_light_radius_modifier.handle(l.radb) : l.radb;
light_data->lightRadius = rad;
light_data->lightType = LT_TUBE;
vec3d a;
vm_vec_sub(&a, &l.vec, &l.vec2);
auto length = vm_vec_mag(&a);
//Tube light volumes must be extended past the length of their requested light vector
//to allow smooth fall-off from all angles. Since the light volume starts at the mesh
//origin we must extend it here. Later the position will be adjusted as well.
length += light_data->lightRadius * 2.0f;
//A small padding factor is added to guard against potentially clipping the edges of the light with facets of the volume mesh.
light_data->scale.xyz.x = rad * 1.05f;
light_data->scale.xyz.y = rad * 1.05f;
light_data->scale.xyz.z = length;
break;
}
}
float rad = (Lighting_mode == lighting_mode::COCKPIT)
? lp->cockpit_light_radius_modifier.handle(MAX(l.rada, l.radb))
: MAX(l.rada, l.radb);
light_data->lightRadius = rad;
// A small padding factor is added to guard against potentially clipping the edges of the light with facets
// of the volume mesh.
light_data->scale.xyz.x = rad * 1.05f;
light_data->scale.xyz.y = rad * 1.05f;
light_data->scale.xyz.z = rad * 1.05f;
}
for (auto& l : cylinder_lights) {
auto light_data = prepare_light_uniforms(l, light_uniform_aligner);
float rad =
(Lighting_mode == lighting_mode::COCKPIT) ? lp->cockpit_light_radius_modifier.handle(l.radb) : l.radb;
light_data->lightRadius = rad;
light_data->lightType = LT_TUBE;
vec3d a;
vm_vec_sub(&a, &l.vec, &l.vec2);
auto length = vm_vec_mag(&a);
// Tube light volumes must be extended past the length of their requested light vector
// to allow smooth fall-off from all angles. Since the light volume starts at the mesh
// origin we must extend it here. Later the position will be adjusted as well.
length += light_data->lightRadius * 2.0f;
// A small padding factor is added to guard against potentially clipping the edges of the light with facets
// of the volume mesh.
light_data->scale.xyz.x = rad * 1.05f;
light_data->scale.xyz.y = rad * 1.05f;
light_data->scale.xyz.z = length;
}
// Uniform data has been assembled, upload it to the GPU and issue the draw calls
light_buffer.submitData();
}
{
for (size_t i = 0; i<full_frame_lights.size(); i++) {
// just keeping things aligned really.
matrix_uniform_aligner.addTypedElement<graphics::matrix_uniforms>();
}
for (auto& l : sphere_lights) {
auto matrix_data = matrix_uniform_aligner.addTypedElement<graphics::matrix_uniforms>();
g3_start_instance_matrix(&l.vec, &vmd_identity_matrix, true);
matrix_data->modelViewMatrix = gr_model_view_matrix;
matrix_data->projMatrix = gr_projection_matrix;
g3_done_instance(true);
}
for (auto& l : cylinder_lights ) {
auto matrix_data = matrix_uniform_aligner.addTypedElement<graphics::matrix_uniforms>();
vec3d dir, newPos;
matrix orient;
vm_vec_sub(&dir, &l.vec, &l.vec2);
vm_vector_2_matrix(&orient, &dir, nullptr, nullptr);
// Tube light volumes must be extended past the length of their requested light vector
// to allow smooth fall-off from all angles. Since the light volume starts at the mesh
// origin we must extend it, which has been done above, and then move it backwards one radius.
vm_vec_normalize(&dir);
vm_vec_scale_sub(&newPos, &l.vec2, &dir, l.radb);
g3_start_instance_matrix(&newPos, &orient, true);
matrix_data->modelViewMatrix = gr_model_view_matrix;
matrix_data->projMatrix = gr_projection_matrix;
g3_done_instance(true);
}
matrix_buffer.submitData();
buffer.submitData();
}
{
GR_DEBUG_SCOPE("Render light geometry");
gr_bind_uniform_buffer(uniform_block_type::DeferredGlobals,
light_buffer.getBufferOffset(0),
sizeof(graphics::deferred_global_data),
light_buffer.bufferHandle());
gr_bind_uniform_buffer(uniform_block_type::Matrices,
matrix_buffer.getBufferOffset(0),
sizeof(graphics::matrix_uniforms),
matrix_buffer.bufferHandle());
gr_bind_uniform_buffer(uniform_block_type::DeferredGlobals, buffer.getBufferOffset(0),
sizeof(graphics::deferred_global_data), buffer.bufferHandle());
size_t element_index = 0;
vertex_layout vertex_declare;
vertex_declare.add_vertex_component(vertex_format_data::POSITION3, sizeof(float) * 3, 0);
for (auto& l : Lights) {
GR_DEBUG_SCOPE("Deferred apply single light");
for (size_t i = 0; i<full_frame_lights.size(); i++) {
GR_DEBUG_SCOPE("Deferred apply single dir light");
switch (l.type) {
case Light_Type::Directional:
gr_bind_uniform_buffer(uniform_block_type::Lights, buffer.getAlignerElementOffset(element_index),
sizeof(graphics::deferred_light_data), buffer.bufferHandle());
opengl_draw_full_screen_textured(0.0f, 0.0f, 1.0f, 1.0f);
++element_index;
break;
case Light_Type::Cone:
case Light_Type::Point:
gr_bind_uniform_buffer(uniform_block_type::Lights, buffer.getAlignerElementOffset(element_index),
sizeof(graphics::deferred_light_data), buffer.bufferHandle());
gr_opengl_draw_deferred_light_sphere(&l.vec);
++element_index;
break;
case Light_Type::Tube:
gr_bind_uniform_buffer(uniform_block_type::Lights, buffer.getAlignerElementOffset(element_index),
sizeof(graphics::deferred_light_data), buffer.bufferHandle());
gr_bind_uniform_buffer(uniform_block_type::Lights,
light_buffer.getAlignerElementOffset(element_index),
sizeof(graphics::deferred_light_data),
light_buffer.bufferHandle());
opengl_draw_full_screen_textured(0.0f, 0.0f, 1.0f, 1.0f);
++element_index;
}
if (!sphere_lights.empty()) {
opengl_bind_vertex_layout(vertex_declare, deferred_light_sphere_vbo, deferred_light_sphere_ibo);
}
for (size_t i = 0; i<sphere_lights.size(); i++) {
gr_bind_uniform_buffer(uniform_block_type::Lights,
light_buffer.getAlignerElementOffset(element_index),
sizeof(graphics::deferred_light_data),
light_buffer.bufferHandle());
gr_bind_uniform_buffer(uniform_block_type::Matrices,
matrix_buffer.getAlignerElementOffset(element_index),
sizeof(graphics::matrix_uniforms),
matrix_buffer.bufferHandle());
glDrawRangeElements(GL_TRIANGLES,
0,
deferred_light_sphere_vcount,
deferred_light_sphere_icount,
GL_UNSIGNED_SHORT,
0);
opengl_draw_sphere();
++element_index;
}
if (!cylinder_lights.empty()) {
opengl_bind_vertex_layout(vertex_declare, deferred_light_cylinder_vbo, deferred_light_cylinder_ibo);
}
for (size_t i = 0; i<cylinder_lights.size(); i++) {
gr_bind_uniform_buffer(uniform_block_type::Lights,
light_buffer.getAlignerElementOffset(element_index),
sizeof(graphics::deferred_light_data),
light_buffer.bufferHandle());
gr_bind_uniform_buffer(uniform_block_type::Matrices,
matrix_buffer.getAlignerElementOffset(element_index),
sizeof(graphics::matrix_uniforms),
matrix_buffer.bufferHandle());
glDrawRangeElements(GL_TRIANGLES,
0,
deferred_light_cylinder_vcount,
deferred_light_cylinder_icount,
GL_UNSIGNED_SHORT,
0);
++element_index;
vec3d dir, newPos;
matrix orient;
vm_vec_sub(&dir, &l.vec, &l.vec2);
vm_vector_2_matrix(&orient, &dir, nullptr, nullptr);
//Tube light volumes must be extended past the length of their requested light vector
//to allow smooth fall-off from all angles. Since the light volume starts at the mesh
//origin we must extend it, which has been done above, and then move it backwards one radius.
vm_vec_normalize(&dir);
vm_vec_scale_sub(&newPos, &l.vec2, &dir, l.radb);
gr_opengl_draw_deferred_light_cylinder(&newPos, &orient);
++element_index;
break;
default:
continue;
}
}
}
@@ -636,6 +535,11 @@ void gr_opengl_draw_deferred_light_sphere(const vec3d *position)
}
static GLuint deferred_light_cylinder_vbo = 0;
static GLuint deferred_light_cylinder_ibo = 0;
static GLushort deferred_light_cylinder_vcount = 0;
static GLuint deferred_light_cylinder_icount = 0;
void gr_opengl_deferred_light_cylinder_init(int segments) // Generate a VBO of a cylinder of radius and height 1.0f, based on code at http://www.ogre3d.org/tikiwiki/ManualSphereMeshes
{
unsigned int nVertex = (segments + 1) * 2 * 3 + 6; // Can someone verify this?
@@ -752,6 +656,11 @@ void gr_opengl_deferred_light_cylinder_init(int segments) // Generate a VBO of a
Vertices = nullptr;
}
static GLuint deferred_light_sphere_vbo = 0;
static GLuint deferred_light_sphere_ibo = 0;
static GLushort deferred_light_sphere_vcount = 0;
static GLuint deferred_light_sphere_icount = 0;
void gr_opengl_deferred_light_sphere_init(int rings, int segments) // Generate a VBO of a sphere of radius 1.0f, based on code at http://www.ogre3d.org/tikiwiki/ManualSphereMeshes
{
unsigned int nVertex = (rings + 1) * (segments+1) * 3;
-4
View File
@@ -1,9 +1,6 @@
#pragma once
#include "globalincs/pstypes.h"
#include "graphics/util/UniformAligner.h"
#include "graphics/util/uniform_structs.h"
#include "lighting/lighting.h"
void gr_opengl_deferred_init();
@@ -12,7 +9,6 @@ void gr_opengl_deferred_lighting_begin(bool clearNonColorBufs = false);
void gr_opengl_deferred_lighting_msaa();
void gr_opengl_deferred_lighting_end();
void gr_opengl_deferred_lighting_finish();
graphics::deferred_light_data* prepare_light_uniforms(light& l, graphics::util::UniformAligner& uniformAligner);
void gr_opengl_deferred_light_sphere_init(int rings, int segments);
void gr_opengl_deferred_light_cylinder_init(int segments);
-51
View File
@@ -50,10 +50,6 @@ GLuint Scene_depth_texture_ms;
GLuint Cockpit_depth_texture;
GLuint Scene_stencil_buffer;
GLuint Back_framebuffer;
GLuint Back_texture;
GLuint Back_depth_texture;
GLuint Distortion_framebuffer = 0;
GLuint Distortion_texture[2];
int Distortion_switch = 0;
@@ -529,53 +525,6 @@ void opengl_setup_scene_textures()
GL_state.Texture.SetTarget(GL_TEXTURE_2D);
}
if (Cmdline_window_res) {
//Gen Framebuffer
glGenFramebuffers(1, &Back_framebuffer);
GL_state.BindFrameBuffer(Back_framebuffer);
opengl_set_object_label(GL_FRAMEBUFFER, Back_framebuffer, "Backbuffer");
// setup main render texture
// setup high dynamic range color texture
glGenTextures(1, &Back_texture);
GL_state.Texture.SetActiveUnit(0);
GL_state.Texture.SetTarget(GL_TEXTURE_2D);
GL_state.Texture.Enable(Back_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
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_WRAP_R, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, gr_screen.max_w, gr_screen.max_h, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, Back_texture, 0);
opengl_set_object_label(GL_TEXTURE, Back_texture, "Backbuffer texture");
glGenTextures(1, &Back_depth_texture);
GL_state.Texture.SetActiveUnit(0);
GL_state.Texture.SetTarget(GL_TEXTURE_2D);
GL_state.Texture.Enable(Back_depth_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
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_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, gr_screen.max_w, gr_screen.max_h, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
opengl_set_object_label(GL_TEXTURE, Back_depth_texture, "Backbuffer depth texture");
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, Back_depth_texture, 0);
gr_zbuffer_set(GR_ZBUFF_FULL);
glClear(GL_DEPTH_BUFFER_BIT);
}
//Setup thruster distortion framebuffer
if (Gr_framebuffer_effects.any_set())
{
-3
View File
@@ -38,9 +38,6 @@ extern GLuint Scene_depth_texture_ms;
extern GLuint Cockpit_depth_texture;
extern GLuint Scene_stencil_buffer;
extern GLuint Back_framebuffer;
extern GLuint Back_texture;
void gr_opengl_update_distortion();
void gr_opengl_sphere(material *material_def, float rad);
-471
View File
@@ -1,471 +0,0 @@
#include "gropenglopenxr.h"
#include "io/cursor.h"
#include "io/mouse.h"
#include "graphics/matrix.h"
#include "graphics/opengl/gropengl.h"
#include "graphics/opengl/gropengldraw.h"
#include "graphics/opengl/gropenglshader.h"
#include "graphics/opengl/gropenglstate.h"
#include "graphics/opengl/ShaderProgram.h"
#include "osapi/osapi.h"
#ifdef WIN32
#define XR_USE_PLATFORM_WIN32
#include <unknwn.h>
#elif defined __APPLE_CC__
//Not supported
#elif defined SCP_UNIX
#define XR_USE_PLATFORM_XLIB
#include<X11/Xlib.h>
#include<glad/glad_glx.h>
#endif
#define XR_USE_GRAPHICS_API_OPENGL
#include "graphics/openxr_internal.h"
#include <SDL_syswm.h>
#ifndef __APPLE_CC__
//SETUP FUNCTIONS OGL
SCP_vector<const char*> gr_opengl_openxr_get_extensions() {
return { XR_KHR_OPENGL_ENABLE_EXTENSION_NAME };
}
bool gr_opengl_openxr_test_capabilities() {
XrGraphicsRequirementsOpenGLKHR requirements{
XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR,
nullptr,
0,
0
};
if (openxr_callExtensionFunction<PFN_xrGetOpenGLGraphicsRequirementsKHR>("xrGetOpenGLGraphicsRequirementsKHR", xr_instance, xr_system, &requirements) != XR_SUCCESS) {
mprintf(("Failed to query OpenXR graphics requirements!\n"));
return false;
}
if (requirements.minApiVersionSupported > XR_MAKE_VERSION(GLVersion.major, GLVersion.minor, 0)) {
mprintf(("System doesn't meet OpenXR graphics requirements (min %" PRIu64 ", available %" PRIu64 ")!\n", requirements.minApiVersionSupported, static_cast<XrVersion>(XR_MAKE_VERSION(GLVersion.major, GLVersion.minor, 0))));
return false;
}
return true;
}
#ifdef WIN32
bool gr_opengl_openxr_create_session() {
SDL_SysWMinfo wmInfo;
SDL_VERSION(&wmInfo.version);
SDL_GetWindowWMInfo(os::getSDLMainWindow(), &wmInfo);
XrGraphicsBindingOpenGLWin32KHR graphicsBinding{
XR_TYPE_GRAPHICS_BINDING_OPENGL_WIN32_KHR,
nullptr,
wmInfo.info.win.hdc,
(HGLRC) SDL_GL_GetCurrentContext() //uuuuuugly, and not technically allowed by the standard, but this "opaque" SDL_GLContext type is just the hGLRC on Win32
};
XrSessionCreateInfo sessionCreateInfo{
XR_TYPE_SESSION_CREATE_INFO,
&graphicsBinding,
0,
xr_system
};
XrResult sessionInit = xrCreateSession(xr_instance, &sessionCreateInfo, &xr_session);
if (sessionInit != XR_SUCCESS) {
mprintf(("Failed to create OpenXR session with code %d\n", static_cast<int>(sessionInit)));
return false;
}
return true;
}
#elif defined SCP_UNIX
bool gr_opengl_openxr_create_session() {
SDL_SysWMinfo wmInfo;
SDL_VERSION(&wmInfo.version);
SDL_GetWindowWMInfo(os::getSDLMainWindow(), &wmInfo);
XWindowAttributes wa;
XGetWindowAttributes(wmInfo.info.x11.display, wmInfo.info.x11.window, &wa);
GLXContext glxcontext = (GLXContext) SDL_GL_GetCurrentContext(); //uuuuuugly, and not technically allowed by the standard, but this "opaque" SDL_GLContext type is just the GLXContext on X11
int glxfbconfigid, glxscreenid, nfbconfigs;
glXQueryContext(wmInfo.info.x11.display, glxcontext, GLX_FBCONFIG_ID, &glxfbconfigid);
glXQueryContext(wmInfo.info.x11.display, glxcontext, GLX_SCREEN, &glxscreenid);
const int fbconfigattrs[] = {GLX_FBCONFIG_ID, glxfbconfigid, None};
GLXFBConfig* fbconfigs = glXChooseFBConfig(wmInfo.info.x11.display, glxscreenid, fbconfigattrs, &nfbconfigs);
if (nfbconfigs < 1) {
mprintf(("Unable to find Linux FBConfig for OpenXR!\n"));
return false;
}
XrGraphicsBindingOpenGLXlibKHR graphicsBinding {
XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR,
nullptr,
wmInfo.info.x11.display,
static_cast<uint32_t>(XVisualIDFromVisual(wa.visual)),
fbconfigs[0],
glXGetCurrentDrawable(),
glxcontext
};
XrSessionCreateInfo sessionCreateInfo {
XR_TYPE_SESSION_CREATE_INFO,
&graphicsBinding,
0,
xr_system
};
XrResult sessionInit = xrCreateSession(xr_instance, &sessionCreateInfo, &xr_session);
if (sessionInit != XR_SUCCESS) {
mprintf(("Failed to create OpenXR session with code %d\n", static_cast<int>(sessionInit)));
return false;
}
return true;
}
#endif
int64_t gr_opengl_openxr_get_swapchain_format(const SCP_vector<int64_t>& allowed) {
//We prefer whatever our backbuffer is
if (std::find(allowed.cbegin(), allowed.cend(), GL_RGBA16F) != allowed.cend())
return GL_RGBA16F;
//Otherwise, Fallback
return allowed.front();
}
//PIPELINE FUNCTIONS OGL
std::array<SCP_vector<XrSwapchainImageOpenGLKHR>, 2> swapchainImages;
GLuint xr_fbo;
GLuint xr_swap_tex;
bool gr_opengl_openxr_acquire_swapchain_buffers() {
// create framebuffer
glGenFramebuffers(1, &xr_fbo);
GL_state.BindFrameBuffer(xr_fbo);
opengl_set_object_label(GL_FRAMEBUFFER, xr_fbo, "XR Swapchain");
//While blitting from the backbuffer is fine for the 3d-scenes, when we render a flat scene, we need to bind the backbuffer as a texture.
//Since that doesn't work, we need an intermediary. Not pretty, but it doesn't need to be for the flat scenes
glGenTextures(1, &xr_swap_tex);
GL_state.Texture.SetActiveUnit(0);
GL_state.Texture.SetTarget(GL_TEXTURE_2D);
GL_state.Texture.Enable(xr_swap_tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
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_WRAP_R, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, gr_screen.max_w, gr_screen.max_h, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, xr_swap_tex, 0);
opengl_set_object_label(GL_TEXTURE, xr_swap_tex, "XR Swap Texture");
for (uint32_t i = 0; i < 2; i++) {
uint32_t imageCount = 0;
XrResult swapchainAcq = xrEnumerateSwapchainImages(xr_swapchains[i]->swapchain, 0, &imageCount, nullptr);
if (swapchainAcq != XR_SUCCESS) {
mprintf(("Failed to acquire OpenXR swapchain %d with code %d\n", i, static_cast<int>(swapchainAcq)));
return false;
}
swapchainImages[i] = SCP_vector<XrSwapchainImageOpenGLKHR>(imageCount, { XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR, nullptr, 0 });
swapchainAcq = xrEnumerateSwapchainImages(xr_swapchains[i]->swapchain, imageCount, &imageCount, (XrSwapchainImageBaseHeader*)swapchainImages[i].data());
if (swapchainAcq != XR_SUCCESS) {
mprintf(("Failed to acquire OpenXR swapchain %d with code %d\n", i, static_cast<int>(swapchainAcq)));
return false;
}
}
return true;
}
bool gr_opengl_openxr_flip() {
if (!openxr_enabled())
return false;
static bool was_multiframe = false;
//If a stereoscopic frame has started, we're good. Otherwise, this is a normal frame that still needs to be OpenXR-Initialized
//In addition, since we don't actually blit one backbuffer per eye in monoframe mode, we need to make a copy of it to a readable texture now.
if (xr_stage == OpenXRFBStage::NONE) {
openxr_start_frame();
GR_DEBUG_SCOPE("XR Blit");
GL_state.PushFramebufferState();
GL_state.BindFrameBuffer(Cmdline_window_res ? Back_framebuffer : 0, GL_READ_FRAMEBUFFER);
GL_state.BindFrameBuffer(xr_fbo, GL_DRAW_FRAMEBUFFER);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, xr_swap_tex, 0);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
glReadBuffer(Cmdline_window_res ? GL_COLOR_ATTACHMENT0 : GL_BACK);
glBlitFramebuffer(0, 0, gr_screen.max_w, gr_screen.max_h, 0, 0, gr_screen.max_w, gr_screen.max_h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
glDrawBuffer(GL_NONE);
GL_state.PopFramebufferState();
if (was_multiframe) {
openxr_reset_offset();
was_multiframe = false;
}
}
else
was_multiframe = true;
uint32_t startFrame = xr_stage == OpenXRFBStage::SECOND ? 1 : 0;
uint32_t endFrame = xr_stage == OpenXRFBStage::FIRST ? 1 : 2;
for (uint32_t i = startFrame; i < endFrame; i++) {
XrSwapchain swapchain = xr_swapchains[i]->swapchain;
XrSwapchainImageAcquireInfo acquireImageInfo {
XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO,
nullptr
};
uint32_t activeIndex;
xrAcquireSwapchainImage(swapchain, &acquireImageInfo, &activeIndex);
XrSwapchainImageWaitInfo waitImageInfo{
XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO,
nullptr,
std::numeric_limits<int64_t>::max()
};
xrWaitSwapchainImage(swapchain, &waitImageInfo);
const XrSwapchainImageOpenGLKHR& image = swapchainImages[i][activeIndex];
//Monoframe mode: We only have one image that FSO just tried to flip. We have it in a readable texture which we'll now render as a flat plane in a fake 3D scene directly to the swapchain
if (xr_stage == OpenXRFBStage::NONE) {
GR_DEBUG_SCOPE("XR Plane");
GL_state.PushFramebufferState();
GL_state.BindFrameBuffer(xr_fbo);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, image.image, 0);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
GL_state.Texture.Enable(0, GL_TEXTURE_2D, xr_swap_tex);
opengl_shader_set_current(gr_opengl_maybe_create_shader(SDR_TYPE_COPY_WORLD, 0));
Current_shader->program->Uniforms.setTextureUniform("tex", 0);
const auto& pos = xr_views[i].pose.position;
const auto& ori = xr_views[i].pose.orientation;
vec3d position{{ { pos.x, pos.y, -pos.z } }};
position -= xr_offset;
matrix orientation;
vm_quaternion_to_matrix(&orientation, ori.x, ori.y, -ori.z, -ori.w);
gr_set_clip(0, 0, xr_swapchains[i]->width, xr_swapchains[i]->height, GR_RESIZE_REPLACE);
gr_set_proj_matrix(asymmetric_fov {
xr_views[i].fov.angleLeft,
xr_views[i].fov.angleRight,
xr_views[i].fov.angleUp,
xr_views[i].fov.angleDown
}, i2fl(xr_swapchains[i]->width) / i2fl(xr_swapchains[i]->height), 0.01f, 1000);
gr_set_view_matrix(&position, &orientation);
glViewport(0, 0, xr_swapchains[i]->width, xr_swapchains[i]->height);
GL_state.ScissorTest(GL_FALSE);
GL_state.SetZbufferType(gr_zbuffer_type::ZBUFFER_TYPE_NONE);
GLfloat v[4][5] = {
{
-2.0f * gr_screen.clip_aspect, -2.0f, 4, 0, 0
},
{
2.0f * gr_screen.clip_aspect, -2.0f, 4, 1, 0
},
{
2.0f * gr_screen.clip_aspect, 2.0f, 4, 1, 1
},
{
-2.0f * gr_screen.clip_aspect, 2.0f, 4, 0, 1
}
};
vertex_layout vert_def;
vert_def.add_vertex_component(vertex_format_data::POSITION3, sizeof(GLfloat) * 5, 0);
vert_def.add_vertex_component(vertex_format_data::TEX_COORD2, sizeof(GLfloat) * 5, sizeof(GLfloat) * 3);
gr_matrix_set_uniforms();
gr_set_clear_color(20, 20, 20);
gr_clear();
gr_set_clear_color(0, 0, 0);
opengl_render_primitives_immediate(PRIM_TYPE_TRIFAN, &vert_def, 4, v, sizeof(v));
//And if we have a curser, it also needs to be put onscreen manually
if (io::mouse::CursorManager::get()->isCursorShown()) {
opengl_shader_set_current(gr_opengl_maybe_create_shader(SDR_TYPE_COPY_WORLD, SDR_FLAG_COPY_FROM_ARRAY));
Current_shader->program->Uniforms.setTextureUniform("tex", 0);
float u_scale, v_scale;
uint32_t array_index;
int mouse_bm = io::mouse::CursorManager::get()->getCurrentCursor()->getBitmapHandle();
int mousex, mousey, mousew, mouseh;
bm_get_info(mouse_bm, &mousew, &mouseh);
gr_opengl_tcache_set(mouse_bm, TCACHE_TYPE_INTERFACE, &u_scale, &v_scale, &array_index);
mouse_get_pos(&mousex, &mousey);
float mouse_unscaled_x = i2fl(mousex) / i2fl(gr_screen.max_w) * 2.0f - 1.0f;
float mouse_unscaled_y = i2fl(mousey) / i2fl(gr_screen.max_h) * -2.0f + 1.0f;
float mouse_unscaled_w = i2fl(mousew) / i2fl(gr_screen.max_w);
float mouse_unscaled_h = i2fl(mouseh) / i2fl(gr_screen.max_h);
float left = 2.0f * gr_screen.clip_aspect * mouse_unscaled_x;
float right = left + 4.0f * gr_screen.clip_aspect * mouse_unscaled_w;
float top = 2.0f * mouse_unscaled_y;
float bottom = top - 4.0f * mouse_unscaled_h;
GLfloat vmouse[4][5] = {
{
left, bottom, 4, 0, 1
},
{
right, bottom, 4, 1, 1
},
{
right, top, 4, 1, 0
},
{
left, top, 4, 0, 0
}
};
opengl_render_primitives_immediate(PRIM_TYPE_TRIFAN, &vert_def, 4, vmouse, sizeof(vmouse));
}
gr_end_proj_matrix();
gr_end_view_matrix();
gr_reset_clip();
glViewport(0, 0, gr_screen.max_w, gr_screen.max_h);
GL_state.Texture.Enable(0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0);
glDrawBuffer(GL_NONE);
GL_state.PopFramebufferState();
}
//If we are in stereo mode, we just need to take the current backbuffer and blit it to the proper swapchain target
else {
GR_DEBUG_SCOPE("XR Blit");
GL_state.PushFramebufferState();
GL_state.BindFrameBuffer(Cmdline_window_res ? Back_framebuffer : 0, GL_READ_FRAMEBUFFER);
GL_state.BindFrameBuffer(xr_fbo, GL_DRAW_FRAMEBUFFER);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, image.image, 0);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
glReadBuffer(Cmdline_window_res ? GL_COLOR_ATTACHMENT0 : GL_BACK);
glBlitFramebuffer(0, 0, gr_screen.max_w, gr_screen.max_h, 0, 0, xr_swapchains[i]->width, xr_swapchains[i]->height, GL_COLOR_BUFFER_BIT, GL_LINEAR);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0);
glDrawBuffer(GL_NONE);
GL_state.PopFramebufferState();
}
XrSwapchainImageReleaseInfo releaseImageInfo {
XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO,
nullptr
};
xrReleaseSwapchainImage(swapchain, &releaseImageInfo);
}
switch (xr_stage) {
case OpenXRFBStage::FIRST:
//We just rendered the first part of a stereo image. We now need to follow up with another one for the other eye
xr_stage = OpenXRFBStage::SECOND;
return true;
case OpenXRFBStage::SECOND:
case OpenXRFBStage::NONE:
//We just rendered the second part of a stereo image or a mono image. Barring further instruction, the next image may be mono again.
//Also, since that means we're done with whatever we just rendered, finish this frame
xr_stage = OpenXRFBStage::NONE;
break;
}
XrCompositionLayerProjectionView projectedViews[2];
for (uint32_t i = 0; i < 2; i++)
{
projectedViews[i].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
projectedViews[i].next = nullptr;
projectedViews[i].pose = xr_views[i].pose;
projectedViews[i].fov = xr_views[i].fov;
projectedViews[i].subImage = {
xr_swapchains[i]->swapchain,
{
{ 0, 0 },
{ (int32_t)xr_swapchains[i]->width, (int32_t)xr_swapchains[i]->height }
},
0
};
}
XrCompositionLayerProjection layer {
XR_TYPE_COMPOSITION_LAYER_PROJECTION,
nullptr,
0,
xr_space,
2,
projectedViews
};
auto pLayer = (const XrCompositionLayerBaseHeader*)&layer;
XrFrameEndInfo frameEndInfo {
XR_TYPE_FRAME_END_INFO,
nullptr,
xr_state.predictedDisplayTime,
XR_ENVIRONMENT_BLEND_MODE_OPAQUE,
0,
nullptr
};
if (xr_state.shouldRender) {
frameEndInfo.layerCount = 1;
frameEndInfo.layers = &pLayer;
}
xrEndFrame(xr_session, &frameEndInfo);
return false;
}
#else
//Stubs for Mac, as linking with OpenXR causes issues there.
SCP_vector<const char*> gr_opengl_openxr_get_extensions() { return SCP_vector<const char*>{}; }
bool gr_opengl_openxr_test_capabilities() { return false; }
bool gr_opengl_openxr_create_session() { return false; }
int64_t gr_opengl_openxr_get_swapchain_format(const SCP_vector<int64_t>& allowed) { return 0; }
bool gr_opengl_openxr_acquire_swapchain_buffers() { return false; }
bool gr_opengl_openxr_flip() { return false; }
#endif
-8
View File
@@ -1,8 +0,0 @@
#pragma once
SCP_vector<const char*> gr_opengl_openxr_get_extensions();
bool gr_opengl_openxr_test_capabilities();
bool gr_opengl_openxr_create_session();
int64_t gr_opengl_openxr_get_swapchain_format(const SCP_vector<int64_t>& allowed);
bool gr_opengl_openxr_acquire_swapchain_buffers();
bool gr_opengl_openxr_flip();
@@ -13,7 +13,6 @@
#include "cmdline/cmdline.h"
#include "def_files/def_files.h"
#include "graphics/grinternal.h"
#include "graphics/openxr.h"
#include "graphics/util/uniform_structs.h"
#include "io/timer.h"
#include "lighting/lighting.h"
@@ -67,7 +66,7 @@ void opengl_post_pass_tonemap()
GR_DEBUG_SCOPE("Tonemapping");
TRACE_SCOPE(tracing::Tonemapping);
opengl_shader_set_current(gr_opengl_maybe_create_shader(SDR_TYPE_POST_PROCESS_TONEMAPPING, openxr_enabled() ? SDR_FLAG_TONEMAPPING_LINEAR_OUT : 0));
opengl_shader_set_current(gr_opengl_maybe_create_shader(SDR_TYPE_POST_PROCESS_TONEMAPPING, 0));
Current_shader->program->Uniforms.setTextureUniform("tex", 0);
@@ -431,6 +430,7 @@ extern GLuint Cockpit_depth_texture;
extern GLuint Scene_position_texture;
extern GLuint Scene_normal_texture;
extern GLuint Scene_specular_texture;
extern bool stars_sun_has_glare(int index);
extern float Sun_spot;
void opengl_post_lightshafts()
{
@@ -451,7 +451,7 @@ void opengl_post_lightshafts()
light_get_global_dir(&light_dir, idx);
vm_vec_rotate(&local_light_dir, &light_dir, &Eye_matrix);
if ( !light_has_glare(idx) ) {
if ( !stars_sun_has_glare(idx) ) {
continue;
}
@@ -850,8 +850,8 @@ void opengl_post_shader_header(SCP_stringstream& sflags, shader_type shader_t, i
}
} else if (shader_t == SDR_TYPE_POST_PROCESS_LIGHTSHAFTS) {
char temp[64];
const auto& ls_params = graphics::Post_processing_manager->getLightshaftParams();
snprintf(temp, 64, "#define SAMPLE_NUM %d\n", ls_params.samplenum);
const auto ls_params = graphics::Post_processing_manager->getLightshaftParams();
sprintf(temp, "#define SAMPLE_NUM %d\n", ls_params.samplenum);
sflags << temp;
} else if (shader_t == SDR_TYPE_POST_PROCESS_FXAA) {
set_fxaa_defines(sflags);
+1 -8
View File
@@ -155,9 +155,6 @@ static opengl_shader_type_t GL_shader_types[] = {
{ SDR_TYPE_COPY, "post-v.sdr", "copy-f.sdr", nullptr,
{ opengl_vert_attrib::POSITION, opengl_vert_attrib::TEXCOORD }, "Texture copy", false },
{ SDR_TYPE_COPY_WORLD, "passthrough-v.sdr", "copy-f.sdr", nullptr,
{ opengl_vert_attrib::POSITION, opengl_vert_attrib::TEXCOORD }, "Texture copy world space", false },
{ SDR_TYPE_MSAA_RESOLVE, "post-v.sdr", "msaa-f.sdr", nullptr,
{ opengl_vert_attrib::POSITION, opengl_vert_attrib::TEXCOORD }, "MSAA resolve shader", false },
@@ -210,11 +207,7 @@ static opengl_shader_variant_t GL_shader_variants[] = {
{SDR_TYPE_VOLUMETRIC_FOG, false, SDR_FLAG_VOLUMETRICS_DO_EDGE_SMOOTHING, "DO_EDGE_SMOOTHING", {}, "Perform costly edge smoothing lookups"},
{SDR_TYPE_VOLUMETRIC_FOG, false, SDR_FLAG_VOLUMETRICS_NOISE, "NOISE", {}, "Add noise to volumetrics"},
{SDR_TYPE_COPY_WORLD, false, SDR_FLAG_COPY_FROM_ARRAY, "COPY_ARRAY", {}, "Expects to copy from an array texture"},
{SDR_TYPE_POST_PROCESS_TONEMAPPING, false, SDR_FLAG_TONEMAPPING_LINEAR_OUT, "LINEAR_OUT", {}, "Will make the tonemapper output in linear color space and not in sRGB"}
{SDR_TYPE_VOLUMETRIC_FOG, false, SDR_FLAG_VOLUMETRICS_NOISE, "NOISE", {}, "Add noise to volumetrics"}
};
static const int GL_num_shader_variants = sizeof(GL_shader_variants) / sizeof(opengl_shader_variant_t);
+4 -10
View File
@@ -14,7 +14,6 @@
#define BMPMAN_INTERNAL
#include "gropenglstate.h"
#include "gropengltexture.h"
#include "gropengldraw.h"
#include "bmpman/bm_internal.h"
#include "bmpman/bmpman.h"
#include "cmdline/cmdline.h"
@@ -55,7 +54,7 @@ static auto TextureFilteringOption __UNUSED = options::OptionBuilder<int>("Graph
std::pair<const char*, int>{"Texture Filtering", 1763},
std::pair<const char*, int>{"Texture filtering option", 1764})
.importance(1)
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.values(TextureFilteringValues)
.default_val(0)
.bind_to_once(&GL_mipmap_filter)
@@ -107,7 +106,7 @@ static auto AnisotropyOption = options::OptionBuilder<float>("Graphics.Anisotrop
std::pair<const char*, int>{"Anistropic filtering", 1736},
std::pair<const char*, int>{"Controls the amount of anistropic filtering of the textures", 1737})
.enumerator(anisotropic_value_enumerator)
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.display(anisotropic_display)
.default_func(anisotropic_default)
.level(options::ExpertLevel::Advanced)
@@ -1705,13 +1704,8 @@ int opengl_set_render_target( int slot, int face, int is_static )
}
}
if(Cmdline_window_res) {
GL_state.BindFrameBuffer(Back_framebuffer);
}
else {
GL_state.BindFrameBuffer(0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
}
GL_state.BindFrameBuffer(0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
// done with this render target so lets move on
render_target = NULL;
-548
View File
@@ -1,548 +0,0 @@
#include "openxr_internal.h"
#include "camera/camera.h"
#include "graphics/2d.h"
#include "globalincs/version.h"
#include "mod_table/mod_table.h"
#include "render/3d.h"
#include "starfield/starfield.h"
std::unique_ptr<star[]> Stars_XRBuffer;
#ifndef __APPLE_CC__
#define XR_MAKE_VERSION_SHORT(major, minor, patch) \
((((major) & 0x3ffU) << 20) | (((minor) & 0x3ffU) << 10) | ((patch) & 0x3ffU))
bool openxr_req = false;
bool openxr_initialized = false;
bool openxr_recieve = false;
XrInstance xr_instance;
XrSystemId xr_system;
XrSession xr_session;
XrSpace xr_space;
XrTime xr_time;
XrDebugUtilsMessengerEXT xr_debugMessenger;
std::array<std::unique_ptr<XrSwapchainHandler>, 2> xr_swapchains;
std::array<XrView, 2> xr_views;
std::array<XrViewConfigurationView, 2> xr_configurationviews;
vec3d xr_offset = ZERO_VECTOR;
XrFrameState xr_state;
OpenXRFBStage xr_stage = OpenXRFBStage::NONE;
float xr_scale = 1.0f;
#if !defined(NDEBUG) && defined(FS_OPENXR_DEBUG)
static XrBool32 handleXRError(XrDebugUtilsMessageSeverityFlagsEXT severity, XrDebugUtilsMessageTypeFlagsEXT type, const XrDebugUtilsMessengerCallbackDataEXT* callbackData, void* /*userData*/) {
SCP_string message;
switch (type)
{
case XR_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT:
message = "OpenXR: general\n%s";
break;
case XR_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT:
message = "OpenXR: validation\n%s";
break;
case XR_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT:
message = "OpenXR: performance\n%s";
break;
case XR_DEBUG_UTILS_MESSAGE_TYPE_CONFORMANCE_BIT_EXT:
message = "OpenXR: conformance\n%s";
break;
}
switch (severity)
{
case XR_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
case XR_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
Information(LOCATION, message.c_str(), callbackData->message);
break;
case XR_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
Warning(LOCATION, message.c_str(), callbackData->message);
break;
case XR_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
Error(LOCATION, message.c_str(), callbackData->message);
break;
}
return XR_FALSE;
}
#endif
void openxr_prepare(float hudscale) {
Hud_global_scale = hudscale;
openxr_req = true;
}
static bool openxr_init_instance() {
auto extensions = gr_openxr_get_extensions();
const gameversion::version& fso_version = gameversion::get_executable_version();
const gameversion::version& mod_version(Mod_version);
#if !defined(NDEBUG) && defined(FS_OPENXR_DEBUG)
extensions.emplace_back("XR_EXT_debug_utils");
#endif
XrInstanceCreateInfo instanceCreateInfo {
XR_TYPE_INSTANCE_CREATE_INFO,
nullptr,
0,
XrApplicationInfo {
"", //Modname
//Mod version. Should not contain negative numbers or only 0's.
XR_MAKE_VERSION_SHORT(mod_version.major < 1 ? 1U : static_cast<uint32_t>(mod_version.major),
mod_version.minor < 0 ? 0U : static_cast<uint32_t>(mod_version.minor),
mod_version.build < 0 ? 0U : static_cast<uint32_t>(mod_version.build)),
"FreeSpace Open",
XR_MAKE_VERSION_SHORT(static_cast<uint32_t>(fso_version.major), static_cast<uint32_t>(fso_version.minor), static_cast<uint32_t>(fso_version.build)),
XR_CURRENT_API_VERSION
},
0,
nullptr,
static_cast<uint32_t>(extensions.size()),
extensions.data()
};
strncpy_s(instanceCreateInfo.applicationInfo.applicationName, Mod_title.empty() ? "FreeSpace Open" : Mod_title.c_str(), XR_MAX_APPLICATION_NAME_SIZE);
XrResult create = xrCreateInstance(&instanceCreateInfo, &xr_instance);
if (create != XR_SUCCESS) {
if (create == XR_ERROR_EXTENSION_NOT_PRESENT) {
//This is to be expected to be one of THE common issue cases, since not all OpenXR runtimes, notably WMR, don't supply the OpenGL extensions
ReleaseWarning(LOCATION, "The OpenXR runtime does not support the required backend! Try to use a different OpenXR runtime.");
}
mprintf(("Failed to create OpenXR instance with code %d\n", static_cast<int>(create)));
return false;
}
#if !defined(NDEBUG) && defined(FS_OPENXR_DEBUG)
XrDebugUtilsMessengerCreateInfoEXT debugMessengerCreateInfo {
XR_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
nullptr,
XR_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | XR_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | XR_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
XR_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | XR_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | XR_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT | XR_DEBUG_UTILS_MESSAGE_TYPE_CONFORMANCE_BIT_EXT,
(PFN_xrDebugUtilsMessengerCallbackEXT)(&handleXRError),
nullptr
};
openxr_callExtensionFunction<PFN_xrCreateDebugUtilsMessengerEXT>("xrCreateDebugUtilsMessengerEXT", xr_instance, &debugMessengerCreateInfo, &xr_debugMessenger);
#endif
return true;
}
static bool openxr_init_system() {
XrSystemGetInfo systemGetInfo {
XR_TYPE_SYSTEM_GET_INFO,
nullptr,
XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY
};
XrResult systemInit = xrGetSystem(xr_instance, &systemGetInfo, &xr_system);
if (systemInit != XR_SUCCESS) {
mprintf(("Failed to create OpenXR system with code %d\n", static_cast<int>(systemInit)));
xr_system = XR_NULL_SYSTEM_ID;
return false;
}
return true;
}
static bool openxr_init_configuration_views() {
uint32_t configurationViewsCount = static_cast<uint32_t>(xr_configurationviews.size());
for (auto& configView : xr_configurationviews)
configView = { XR_TYPE_VIEW_CONFIGURATION_VIEW, nullptr, 0, 0, 0, 0, 0, 0 };
if (xrEnumerateViewConfigurationViews(xr_instance, xr_system, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, configurationViewsCount, &configurationViewsCount, xr_configurationviews.data()) != XR_SUCCESS) {
mprintf(("Failed to find OpenXR configuration views for stereo displays!\n"));
return false;
}
return true;
}
static bool openxr_init_swapchains() {
uint32_t formatCount = 0;
if (xrEnumerateSwapchainFormats(xr_session, 0, &formatCount, nullptr) != XR_SUCCESS) {
return false;
}
SCP_vector<int64_t> formats(formatCount);
if (xrEnumerateSwapchainFormats(xr_session, formatCount, &formatCount, formats.data()) != XR_SUCCESS) {
return false;
}
int64_t chosenFormat = gr_openxr_get_swapchain_format(formats);
std::array<XrSwapchain, 2> swapchains;
for (uint32_t i = 0; i < 2; i++)
{
XrSwapchainCreateInfo swapchainCreateInfo {
XR_TYPE_SWAPCHAIN_CREATE_INFO,
nullptr,
0,
XR_SWAPCHAIN_USAGE_TRANSFER_DST_BIT,
chosenFormat,
1,
xr_configurationviews[i].recommendedImageRectWidth,
xr_configurationviews[i].recommendedImageRectHeight,
1,
1,
1
};
XrResult swapchainInit = xrCreateSwapchain(xr_session, &swapchainCreateInfo, &swapchains[i]);
if (swapchainInit != XR_SUCCESS) {
mprintf(("Failed to create OpenXR swapchain %d with code %d\n", i, static_cast<int>(swapchainInit)));
return false;
}
xr_swapchains[i].reset(new XrSwapchainHandler {
swapchains[i],
chosenFormat,
xr_configurationviews[i].recommendedImageRectWidth,
xr_configurationviews[i].recommendedImageRectHeight
});
}
if (!gr_openxr_acquire_swapchain_buffers()) {
return false;
}
return true;
}
static bool openxr_init_space() {
XrReferenceSpaceCreateInfo spaceCreateInfo {
XR_TYPE_REFERENCE_SPACE_CREATE_INFO,
nullptr,
XR_REFERENCE_SPACE_TYPE_LOCAL,
XrPosef{ XrQuaternionf{ 0, 0, 0, 1 }, XrVector3f{ 0, 0, 0 } },
};
if (xrCreateReferenceSpace(xr_session, &spaceCreateInfo, &xr_space) != XR_SUCCESS) {
return false;
}
return true;
}
static void openxr_init_post() {
XrViewLocateInfo viewLocateInfo {
XR_TYPE_VIEW_LOCATE_INFO,
nullptr,
XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO,
xr_time,
xr_space
};
XrViewState viewState {
XR_TYPE_VIEW_STATE,
nullptr,
0
};
xr_views.fill({ XR_TYPE_VIEW, nullptr, XrPosef{}, XrFovf{} });
uint32_t views;
xrLocateViews(
xr_session,
&viewLocateInfo,
&viewState,
2,
&views,
xr_views.data()
);
openxr_reset_offset();
vec3d xr_offset_debug {{ {
(xr_views[0].pose.position.x - xr_views[1].pose.position.x) * xr_scale,
(xr_views[0].pose.position.y - xr_views[1].pose.position.y) * xr_scale,
(xr_views[0].pose.position.z - xr_views[1].pose.position.z) * xr_scale} }};
mprintf(("OpenXR HMD data:\n\tLeft Res: %dx%d\n\tLeft FoV (l|r|t|b): %f, %f, %f, %f\n\tRight Res: %dx%d\n\tRight FoV (l|r|t|b): %f, %f, %f, %f\n\tIPD: %f\n",
xr_swapchains[0]->width, xr_swapchains[0]->height,
xr_views[0].fov.angleLeft, xr_views[0].fov.angleRight, xr_views[0].fov.angleUp, xr_views[0].fov.angleDown,
xr_swapchains[1]->width, xr_swapchains[1]->height,
xr_views[1].fov.angleLeft, xr_views[1].fov.angleRight, xr_views[1].fov.angleUp, xr_views[1].fov.angleDown,
vm_vec_mag(&xr_offset_debug)));
VIEWER_ZOOM_DEFAULT = COCKPIT_ZOOM_DEFAULT = asymmetric_fov {
xr_views[0].fov.angleLeft + xr_views[1].fov.angleLeft,
xr_views[0].fov.angleRight + xr_views[1].fov.angleRight,
xr_views[0].fov.angleUp + xr_views[1].fov.angleUp,
xr_views[0].fov.angleDown + xr_views[1].fov.angleDown
} * (1.0f / (2.0f * PROJ_FOV_FACTOR));
}
float openxr_preinit(float req_ar, float scale) {
xr_scale = scale;
mprintf(("Attempting to pre-initialize OpenXR...\n"));
if (!openxr_init_instance()) {
openxr_req = false;
return req_ar;
}
if (!openxr_init_system()) {
openxr_req = false;
return req_ar;
}
if (!openxr_init_configuration_views()) {
openxr_req = false;
return req_ar;
}
return i2fl(xr_configurationviews[0].recommendedImageRectWidth) / i2fl(xr_configurationviews[0].recommendedImageRectHeight);
}
void openxr_init() {
if (!openxr_req)
return;
mprintf(("Attempting to initialize OpenXR and get a session...\n"));
if (!gr_openxr_test_capabilities())
return;
//Non OpenGL backends, like vulkan, may need to query certain extensions to be enabled here as well
if (!gr_openxr_create_session())
return;
if (!openxr_init_swapchains())
return;
if (!openxr_init_space())
return;
openxr_initialized = true;
mprintf(("OpenXR initialized!\n"));
while (openxr_initialized && !openxr_recieve) {
os_poll();
}
mprintf(("OpenXR recieving!\n"));
openxr_init_post();
}
void openxr_close() {
xrDestroySpace(xr_space);
for (auto& sc : xr_swapchains)
sc.release();
xrDestroySession(xr_session);
#if !defined(NDEBUG) && defined(FS_OPENXR_DEBUG)
openxr_callExtensionFunction<PFN_xrDestroyDebugUtilsMessengerEXT>("xrDestroyDebugUtilsMessengerEXT", xr_debugMessenger);
#endif
xrDestroyInstance(xr_instance);
}
bool openxr_enabled() {
return openxr_initialized && openxr_recieve;
}
bool openxr_requested() {
return openxr_req;
}
void openxr_reset_offset() {
xr_offset = ZERO_VECTOR;
for (uint32_t i = 0; i < 2; i++) {
const auto& pos = xr_views[i].pose.position;
xr_offset += vec3d{ { {pos.x * xr_scale, pos.y * xr_scale, pos.z * -xr_scale} } };
}
xr_offset /= 2;
}
void openxr_start_mission() {
if (!openxr_initialized)
return;
openxr_reset_offset();
if (!static_cast<bool>(Stars_XRBuffer))
Stars_XRBuffer = make_unique<star[]>(MAX_STARS);
extern std::unique_ptr<star[]> Stars;
std::copy(Stars.get(), Stars.get() + MAX_STARS, Stars_XRBuffer.get());
}
void openxr_poll() {
if (!openxr_initialized)
return;
XrEventDataBuffer eventData{
XR_TYPE_EVENT_DATA_BUFFER,
nullptr,
{0}
};
XrResult result = xrPollEvent(xr_instance, &eventData);
if (result == XR_EVENT_UNAVAILABLE) {
//No event
}
else if (result != XR_SUCCESS) {
openxr_initialized = false;
openxr_close();
}
else {
switch (eventData.type)
{
case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING:
openxr_initialized = false;
openxr_close();
break;
case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED:
{
auto event = (XrEventDataSessionStateChanged*)&eventData;
xr_time = event->time;
switch (event->state)
{
case XR_SESSION_STATE_IDLE:
openxr_recieve = false;
break;
case XR_SESSION_STATE_READY:
{
XrSessionBeginInfo sessionBeginInfo{
XR_TYPE_SESSION_BEGIN_INFO,
nullptr,
XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO
};
if (xrBeginSession(xr_session, &sessionBeginInfo) != XR_SUCCESS) {
openxr_initialized = false;
openxr_close();
}
}
/*fallthrough*/
case XR_SESSION_STATE_SYNCHRONIZED:
case XR_SESSION_STATE_VISIBLE:
case XR_SESSION_STATE_FOCUSED:
openxr_recieve = true;
break;
case XR_SESSION_STATE_STOPPING:
xrEndSession(xr_session);
/*fallthrough*/
case XR_SESSION_STATE_LOSS_PENDING:
case XR_SESSION_STATE_EXITING:
openxr_initialized = false;
openxr_close();
break;
default:
break;
}
break;
}
default:
break;
}
}
}
OpenXRTrackingInfo openxr_start_stereo_frame() {
if (!openxr_initialized)
return OpenXRTrackingInfo{};
xr_stage = OpenXRFBStage::FIRST;
openxr_start_frame();
OpenXRTrackingInfo info{};
for (uint32_t i = 0; i < 2; i++) {
const auto& pos = xr_views[i].pose.position;
const auto& ori = xr_views[i].pose.orientation;
info.eyes[i].offset = vec3d{{ {pos.x * xr_scale, pos.y * xr_scale, pos.z * -xr_scale} }} - xr_offset;
vm_quaternion_to_matrix(&info.eyes[i].orientation, ori.x, ori.y, -ori.z, -ori.w);
info.eyes[i].zoom = asymmetric_fov{ xr_views[i].fov.angleLeft, xr_views[i].fov.angleRight, xr_views[i].fov.angleUp, xr_views[i].fov.angleDown } * (1.0f / PROJ_FOV_FACTOR);
}
return info;
}
//Internal Helper functions
void openxr_start_frame() {
XrFrameWaitInfo frameWaitInfo {
XR_TYPE_FRAME_WAIT_INFO,
nullptr
};
xr_state = XrFrameState {
XR_TYPE_FRAME_STATE,
nullptr,
0,
0,
0
};
xrWaitFrame(xr_session, &frameWaitInfo, &xr_state);
XrViewLocateInfo viewLocateInfo {
XR_TYPE_VIEW_LOCATE_INFO,
nullptr,
XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO,
xr_state.predictedDisplayTime,
xr_space
};
xr_time = xr_state.predictedDisplayTime;
XrViewState viewState {
XR_TYPE_VIEW_STATE,
nullptr,
0
};
xr_views.fill({ XR_TYPE_VIEW, nullptr, XrPosef{}, XrFovf{} });
uint32_t views;
xrLocateViews(
xr_session,
&viewLocateInfo,
&viewState,
2,
&views,
xr_views.data()
);
XrFrameBeginInfo beginFrameInfo{ XR_TYPE_FRAME_BEGIN_INFO, nullptr };
xrBeginFrame(xr_session, &beginFrameInfo);
}
#else
//Stubs for Mac, as linking with OpenXR causes issues there.
void openxr_prepare(float hudscale) {}
float openxr_preinit(float req_ar, float scale) {
mprintf(("Cannot create OpenXR session on macOS.\n"));
return 0.0f;
}
void openxr_init() {}
void openxr_close() {}
void openxr_poll() {}
void openxr_start_mission() {}
bool openxr_enabled() { return false; }
bool openxr_requested() { return false; }
OpenXRTrackingInfo openxr_start_stereo_frame() { return OpenXRTrackingInfo{}; }
#endif
-64
View File
@@ -1,64 +0,0 @@
#pragma once
#include <array>
#include "camera/camera.h"
struct OpenXRTrackingInfo {
struct OpenXREyeInfo {
vec3d offset;
matrix orientation;
fov_t zoom; //zoom, not fov! difference of a factor of PROJ_FOV_FACTOR
};
std::array<OpenXREyeInfo, 2> eyes;
};
/**
* @brief Performs required Setup actions for OpenXR before actually trying to initialize the graphics
* @param hudscale Sets the scale at which the HUD is rendered. May need to be tweakable to make the hud visible to players with small FoV
*/
void openxr_prepare(float hudscale = 0.5f);
/**
* @brief Initializes the OpenXR API and opens the XR system
* @param req_ar The aspect ratio as specified by the user resolution
* @param scale Controls the scale of the OpenXR coordinates. This mainly affects eye distance and how far real movement translates to ingame movement
* @returns the expected aspect ratio of the swapchain
*/
float openxr_preinit(float req_ar, float scale = 1.0f);
/**
* @brief Opens an OpenXR session to the point that we can render. As this waits for OpenXR, this may take a while
*/
void openxr_init();
/**
* @brief Shuts down OpenXR and cleans up memory
*/
void openxr_close();
/**
* @brief Polls OpenXR state. Does NOT poll HMD position!
*/
void openxr_poll();
/**
* @brief Grabs the last known HMD position and sets it as the zero-state (whereever the specified eyepoint is in mission / ship), as well as initializing buffers for the mission
*/
void openxr_start_mission();
/**
* @brief Polls whether OpenXR is active and can render
*/
bool openxr_enabled();
/**
* @brief Polls whether OpenXR is requested to start. Required if you need to poll for OpenXR during some initialization where it might not yet be running
*/
bool openxr_requested();
/**
* @brief Polls HMD position and sets up the OpenXR state machine to wait for and accept two frames, one for each eye.
* You must ensure that after calling this, the next two gr_flip() calls correspond to the frames for each eye!
* @returns The HMD tracking data including position and rotation in FSO coordinates.
*/
OpenXRTrackingInfo openxr_start_stereo_frame();
-54
View File
@@ -1,54 +0,0 @@
#pragma once
//Don't include this file unless you know what you are doing and need to _directly_ interface with OpenXR
#include "openxr.h"
#include <type_traits>
#include <tl/optional.hpp>
#ifndef __APPLE_CC__
#include <openxr/openxr.h>
#include <openxr/openxr_platform.h>
struct XrSwapchainHandler {
XrSwapchain swapchain;
int64_t format;
uint32_t width;
uint32_t height;
~XrSwapchainHandler() {
xrDestroySwapchain(swapchain);
}
};
extern bool openxr_initialized; //is true if initialization was successfull. Does NOT imply that we can render right now!
extern XrInstance xr_instance;
extern XrSystemId xr_system;
extern XrSession xr_session;
extern XrSpace xr_space;
extern XrTime xr_time; //The last known time something happened. May be the last state change or the (predicted) time of the last frame
extern std::array<std::unique_ptr<XrSwapchainHandler>, 2> xr_swapchains;
extern std::array<XrView, 2> xr_views;
extern XrFrameState xr_state;
extern vec3d xr_offset;
enum class OpenXRFBStage { NONE, FIRST, SECOND };
extern OpenXRFBStage xr_stage; //State machine tracker for rendering. Needed since OpenXR needs to be able to tell whether this is a stereoscopic frame or not whenever the code flips
void openxr_start_frame();
void openxr_reset_offset();
template<typename openxr_fnc, typename... arg_t>
tl::optional<typename std::result_of<openxr_fnc(arg_t...)>::type> openxr_callExtensionFunction(const char* const name, arg_t&&... args) {
openxr_fnc func;
if (xrGetInstanceProcAddr(xr_instance, name, (PFN_xrVoidFunction*)&func) != XR_SUCCESS) {
return tl::nullopt;
}
return func(std::forward<arg_t>(args)...);
}
#endif
+2 -3
View File
@@ -43,7 +43,7 @@ bool Post_processing_enable_lightshafts = true;
static auto LightshaftsOption __UNUSED = options::OptionBuilder<bool>("Graphics.Lightshafts",
std::pair<const char*, int>{"Lightshafts", 1724},
std::pair<const char*, int>{"Enables or disables lightshafts (requires post-processing)", 1725})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.default_val(true)
.level(options::ExpertLevel::Advanced)
.bind_to(&Post_processing_enable_lightshafts)
@@ -55,13 +55,12 @@ int Post_processing_bloom_intensity = 25; // using default value of Cmdline_bloo
static auto BloomIntensityOption __UNUSED = options::OptionBuilder<int>("Graphics.BloomIntensity",
std::pair<const char*, int>{"Bloom intensity", 1701},
std::pair<const char*, int>{"Sets the bloom intensity (requires post-processing)", 1702})
.category(std::make_pair("Graphics", 1825))
.category("Graphics")
.range(0, 200)
.level(options::ExpertLevel::Advanced)
.default_val(25)
.bind_to(&Post_processing_bloom_intensity)
.importance(55)
.flags({options::OptionFlags::RangeTypeInteger})
.finish();
} // namespace
Loaded 100 of 866 files, more files were not shown because too many files have changed in this diff. Show more