diff --git a/.clang-format b/.clang-format index f69bef0cec8..d424ff940ab 100644 --- a/.clang-format +++ b/.clang-format @@ -28,6 +28,11 @@ AlignConsecutiveMacros: AcrossComments: false AlignCompound: false PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseColons: false AlignEscapedNewlines: Left AlignOperands: Align AlignTrailingComments: @@ -141,10 +146,13 @@ IntegerLiteralSeparator: JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: false +KeepEmptyLinesAtEOF: false LambdaBodyIndentation: Signature LineEnding: DeriveLF MacroBlockBegin: '' MacroBlockEnd: '' +Macros: + - 'HAL_ENUM(name)=enum name' MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBinPackProtocolList: Never @@ -199,6 +207,7 @@ RawStringFormats: ReferenceAlignment: Pointer ReflowComments: true RemoveBracesLLVM: false +RemoveParentheses: Leave RemoveSemicolon: false RequiresClausePosition: OwnLine RequiresExpressionIndentation: OuterScope @@ -216,6 +225,7 @@ SpaceBeforeCaseColon: false SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false SpaceBeforeParens: ControlStatements SpaceBeforeParensOptions: AfterControlStatements: true @@ -230,23 +240,28 @@ SpaceBeforeParensOptions: SpaceBeforeRangeBasedForLoopColon: true SpaceBeforeSquareBrackets: false SpaceInEmptyBlock: false -SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 2 SpacesInAngles: Never -SpacesInConditionalStatement: false SpacesInContainerLiterals: true -SpacesInCStyleCastParentheses: false SpacesInLineCommentPrefix: Minimum: 1 Maximum: -1 -SpacesInParentheses: false +SpacesInParens: Never +SpacesInParensOptions: + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false SpacesInSquareBrackets: false Standard: c++20 +StatementAttributeLikeMacros: + - Q_EMIT StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION TabWidth: 8 UseTab: Never +VerilogBreakBetweenInstancePorts: true WhitespaceSensitiveMacros: - BOOST_PP_STRINGIZE - CF_SWIFT_NAME diff --git a/.clang-tidy b/.clang-tidy index 6f1ae3a6d57..e8fe57b952a 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -49,7 +49,6 @@ Checks: google-build-namespaces, google-explicit-constructor, google-global-names-in-headers, - google-readability-avoid-underscore-in-googletest-name, google-readability-casting, google-runtime-operator, misc-definitions-in-headers, diff --git a/.gersemirc b/.gersemirc new file mode 100644 index 00000000000..19ed2c239f7 --- /dev/null +++ b/.gersemirc @@ -0,0 +1,6 @@ +color: false +definitions: [] +line_length: 100 +list_expansion: favour-inlining +quiet: false +unsafe: false diff --git a/.gitattributes b/.gitattributes index ae2ea0e0571..ab6ca853b10 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,13 @@ +*.cpp text eol=lf *.gradle text eol=lf +*.h text eol=lf +*.inc text eol=lf *.java text eol=lf *.json text eol=lf *.md text eol=lf *.xml text eol=lf + +# Generated files +hal/src/generated/** linguist-generated +ntcore/src/generated/** linguist-generated +wpimath/src/generated/** linguist-generated diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index 963dc75ef8f..e0e56438f49 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -16,11 +16,11 @@ jobs: name: Linux container: wpilib/roborio-cross-ubuntu:2024-22.04 flags: "-DCMAKE_BUILD_TYPE=Release -DWITH_EXAMPLES=ON" - - os: macOS-12 + - os: macOS-14 name: macOS container: "" - env: "PATH=\"/usr/local/opt/protobuf@3/bin:$PATH\"" - flags: "-DCMAKE_BUILD_TYPE=Release -DWITH_JAVA=OFF -DWITH_EXAMPLES=ON -DCMAKE_LIBRARY_PATH=/usr/local/opt/protobuf@3/lib -DProtobuf_INCLUDE_DIR=/usr/local/opt/protobuf@3/include -DProtobuf_PROTOC_EXECUTABLE=/usr/local/opt/protobuf@3/bin/protoc" + env: "PATH=\"/opt/homebrew/opt/protobuf@3/bin:$PATH\"" + flags: "-DCMAKE_BUILD_TYPE=Release -DWITH_JAVA=OFF -DWITH_EXAMPLES=ON -DCMAKE_LIBRARY_PATH=/opt/homebrew/opt/protobuf@3/lib -DProtobuf_INCLUDE_DIR=/opt/homebrew/opt/protobuf@3/include -DProtobuf_PROTOC_EXECUTABLE=/opt/homebrew/opt/protobuf@3/bin/protoc" name: "Build - ${{ matrix.name }}" runs-on: ${{ matrix.os }} @@ -32,17 +32,17 @@ jobs: - name: Install QuickBuffers (Linux) if: runner.os == 'Linux' - run: wget https://github.com/HebiRobotics/QuickBuffers/releases/download/1.3.2/protoc-gen-quickbuf_1.3.2_amd64.deb && sudo apt install ./protoc-gen-quickbuf_1.3.2_amd64.deb + run: wget https://github.com/HebiRobotics/QuickBuffers/releases/download/1.3.3/protoc-gen-quickbuf_1.3.3_amd64.deb && sudo apt install ./protoc-gen-quickbuf_1.3.3_amd64.deb - - name: Install opencv (macOS) + - name: Install dependencies (macOS) run: brew install opencv protobuf@3 ninja if: runner.os == 'macOS' - - name: Set up Python 3.8 (macOS) + - name: Set up Python 3.10 (macOS) if: runner.os == 'macOS' - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: - python-version: 3.8 + python-version: '3.10' - name: Run sccache-cache uses: mozilla-actions/sccache-action@v0.0.3 @@ -50,7 +50,7 @@ jobs: - name: Install jinja run: python -m pip install jinja2 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: configure run: cmake -S . -B build -G "Ninja" -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache ${{ matrix.flags }} @@ -82,34 +82,19 @@ jobs: - name: Install jinja run: python -m pip install jinja2 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Run vcpkg uses: lukka/run-vcpkg@v11.1 with: vcpkgDirectory: ${{ runner.workspace }}/vcpkg - vcpkgGitCommitId: 78b61582c9e093fda56a01ebb654be15a0033897 # HEAD on 2023-08-6 + vcpkgGitCommitId: 37c3e63a1306562f7f59c4c3c8892ddd50fdf992 # HEAD on 2024-02-24 - name: configure - run: cmake -S . -B build -G "Ninja" -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_BUILD_TYPE=Release -DWITH_JAVA=OFF -DWITH_EXAMPLES=ON -DUSE_SYSTEM_FMTLIB=ON -DUSE_SYSTEM_LIBUV=ON -DUSE_SYSTEM_EIGEN=ON -DCMAKE_TOOLCHAIN_FILE=${{ runner.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_INSTALL_OPTIONS=--clean-after-build -DVCPKG_TARGET_TRIPLET=x64-windows-release -DVCPKG_HOST_TRIPLET=x64-windows-release + run: cmake -S . -B build -G "Ninja" -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_BUILD_TYPE=Release -DWITH_JAVA=OFF -DWITH_EXAMPLES=ON -DUSE_SYSTEM_FMTLIB=ON -DUSE_SYSTEM_LIBUV=ON -DUSE_SYSTEM_EIGEN=OFF -DCMAKE_TOOLCHAIN_FILE=${{ runner.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_INSTALL_OPTIONS=--clean-after-build -DVCPKG_TARGET_TRIPLET=x64-windows-release -DVCPKG_HOST_TRIPLET=x64-windows-release env: SCCACHE_GHA_ENABLED: "true" - # Build wpiutil at full speed, wpimath depends on wpiutil - - name: build wpiutil - working-directory: build - run: cmake --build . --parallel $(nproc) --target wpiutil/all - env: - SCCACHE_GHA_ENABLED: "true" - - # Build wpimath slow to prevent OOM - - name: build wpimath - working-directory: build - run: cmake --build . --parallel 1 --target wpimath/all - env: - SCCACHE_GHA_ENABLED: "true" - - # Build everything else fast - name: build working-directory: build run: cmake --build . --parallel $(nproc) diff --git a/.github/workflows/command-robotpy-pr.yml b/.github/workflows/command-robotpy-pr.yml new file mode 100644 index 00000000000..51151098355 --- /dev/null +++ b/.github/workflows/command-robotpy-pr.yml @@ -0,0 +1,23 @@ +name: Comment on PR for robotpy + +on: + pull_request: + types: + - opened + paths: + - 'wpilibNewCommands/**' + +jobs: + comment: + runs-on: ubuntu-latest + steps: + - name: Comment on PR + uses: actions/github-script@v7 + with: + script: | + github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: 'This PR modifies commands. Please open a corresponding PR in [Python Commands](https://github.com/robotpy/robotpy-commands-v2/) and include a link to this PR.' + }) diff --git a/.github/workflows/comment-command.yml b/.github/workflows/comment-command.yml index 77ebae97503..2fdbe2e301d 100644 --- a/.github/workflows/comment-command.yml +++ b/.github/workflows/comment-command.yml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-22.04 steps: - name: React Rocket - uses: actions/github-script@v6 + uses: actions/github-script@v7 with: script: | const {owner, repo} = context.issue @@ -19,12 +19,12 @@ jobs: comment_id: context.payload.comment.id, content: "rocket", }); - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: + fetch-depth: 0 token: ${{ secrets.COMMENT_COMMAND_PAT_TOKEN }} - name: Fetch all history and metadata run: | - git fetch --prune --unshallow git checkout -b pr git branch -f main origin/main - name: Checkout PR @@ -33,17 +33,17 @@ jobs: env: GITHUB_TOKEN: "${{ secrets.COMMENT_COMMAND_PAT_TOKEN }}" NUMBER: ${{ github.event.issue.number }} - - name: Set up Python 3.8 - uses: actions/setup-python@v4 + - name: Set up Python 3.10 + uses: actions/setup-python@v5 with: - python-version: 3.8 + python-version: '3.10' - name: Setup Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: - distribution: 'zulu' - java-version: 11 + distribution: 'temurin' + java-version: 17 - name: Install wpiformat - run: pip3 install wpiformat + run: pip3 install wpiformat==2024.34 - name: Run wpiformat run: wpiformat - name: Run spotlessApply diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml index 83d74da5257..86eea417fbc 100644 --- a/.github/workflows/documentation.yml +++ b/.github/workflows/documentation.yml @@ -16,14 +16,14 @@ jobs: if: github.repository_owner == 'wpilibsuite' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) concurrency: ci-docs-publish steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 persist-credentials: false - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: - distribution: 'zulu' - java-version: 13 + distribution: 'temurin' + java-version: 17 - name: Set environment variables (Development) run: | echo "BRANCH=development" >> $GITHUB_ENV diff --git a/.github/workflows/fix_compile_commands.py b/.github/workflows/fix_compile_commands.py new file mode 100755 index 00000000000..8a52830dea2 --- /dev/null +++ b/.github/workflows/fix_compile_commands.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 + +import argparse +import json + + +def main(): + parser = argparse.ArgumentParser( + description="Fix compile_commands.json generated by Gradle" + ) + parser.add_argument("filename", help="compile_commands.json location") + cmd_args = parser.parse_args() + + # Read JSON + with open(cmd_args.filename) as f: + data = json.load(f) + + for obj in data: + out_args = [] + + # Filter out -isystem flags that cause false positives + iter_args = iter(obj["arguments"]) + for arg in iter_args: + if arg == "-isystem": + next_arg = next(iter_args) + + # /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/include/xmmintrin.h:54:1: + # error: conflicting types for '_mm_prefetch' [clang-diagnostic-error] + if not next_arg.startswith("/usr/lib/gcc/"): + out_args += ["-isystem", next_arg] + else: + out_args.append(arg) + + obj["arguments"] = out_args + + # Write JSON + with open(cmd_args.filename, "w") as f: + json.dump(data, f, indent=2) + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/gradle-wrapper-validation.yml b/.github/workflows/gradle-wrapper-validation.yml index d678bc4cf68..b92b7c62dc8 100644 --- a/.github/workflows/gradle-wrapper-validation.yml +++ b/.github/workflows/gradle-wrapper-validation.yml @@ -10,5 +10,5 @@ jobs: name: "Validation" runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: gradle/wrapper-validation-action@v1 + - uses: actions/checkout@v4 + - uses: gradle/wrapper-validation-action@v2 diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index 2334b5f028c..7f30b5b05ba 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -37,7 +37,7 @@ jobs: large-packages: false docker-images: false swap-storage: false - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Set release environment variable @@ -54,14 +54,14 @@ jobs: ARTIFACTORY_PUBLISH_PASSWORD: ${{ secrets.ARTIFACTORY_PASSWORD }} - name: Check free disk space run: df . - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: ${{ matrix.artifact-name }} path: build/allOutputs build-host: env: - MACOSX_DEPLOYMENT_TARGET: 12 + MACOSX_DEPLOYMENT_TARGET: 13 strategy: fail-fast: false matrix: @@ -70,13 +70,13 @@ jobs: artifact-name: Win64Debug architecture: x64 task: "build" - build-options: "-PciDebugOnly --max-workers 1" + build-options: "-PciDebugOnly" outputs: "build/allOutputs" build-dir: "c:\\work" - os: windows-2022 artifact-name: Win64Release architecture: x64 - build-options: "-PciReleaseOnly --max-workers 1" + build-options: "-PciReleaseOnly" task: "copyAllOutputs" outputs: "build/allOutputs" build-dir: "c:\\work" @@ -84,19 +84,19 @@ jobs: artifact-name: WinArm64Debug architecture: x64 task: "build" - build-options: "-PciDebugOnly -Pbuildwinarm64 -Ponlywindowsarm64 --max-workers 1" + build-options: "-PciDebugOnly -Pbuildwinarm64 -Ponlywindowsarm64" outputs: "build/allOutputs" build-dir: "c:\\work" - os: windows-2022 artifact-name: WinArm64Release architecture: x64 - build-options: "-PciReleaseOnly -Pbuildwinarm64 -Ponlywindowsarm64 --max-workers 1" + build-options: "-PciReleaseOnly -Pbuildwinarm64 -Ponlywindowsarm64" task: "copyAllOutputs" outputs: "build/allOutputs" build-dir: "c:\\work" - - os: macOS-12 + - os: macOS-14 artifact-name: macOS - architecture: x64 + architecture: aarch64 task: "build" outputs: "build/allOutputs" build-dir: "." @@ -109,12 +109,12 @@ jobs: name: "Build - ${{ matrix.artifact-name }}" runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: - distribution: 'zulu' + distribution: 'temurin' java-version: 17 architecture: ${{ matrix.architecture }} - name: Import Developer ID Certificate @@ -159,7 +159,7 @@ jobs: - name: Check disk free space (Windows) run: wmic logicaldisk get caption, freespace if: matrix.os == 'windows-2022' - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: ${{ matrix.artifact-name }} path: ${{ matrix.build-dir }}/${{ matrix.outputs }} @@ -168,13 +168,13 @@ jobs: name: "Build - Documentation" runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: - distribution: 'zulu' - java-version: 13 + distribution: 'temurin' + java-version: 17 - name: Set release environment variable run: echo "EXTRA_GRADLE_ARGS=-PreleaseMode" >> $GITHUB_ENV if: startsWith(github.ref, 'refs/tags/v') @@ -183,7 +183,7 @@ jobs: env: ARTIFACTORY_PUBLISH_USERNAME: ${{ secrets.ARTIFACTORY_USERNAME }} ARTIFACTORY_PUBLISH_PASSWORD: ${{ secrets.ARTIFACTORY_PASSWORD }} - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: Documentation path: docs/build/outputs @@ -206,13 +206,13 @@ jobs: large-packages: false docker-images: false swap-storage: false - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 if: | github.repository_owner == 'wpilibsuite' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) with: repository: wpilibsuite/build-tools - - uses: actions/download-artifact@v3 + - uses: actions/download-artifact@v4 if: | github.repository_owner == 'wpilibsuite' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) @@ -230,12 +230,12 @@ jobs: run: | cat combiner/products/build/allOutputs/version.txt test -s combiner/products/build/allOutputs/version.txt - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 if: | github.repository_owner == 'wpilibsuite' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) with: - distribution: 'zulu' + distribution: 'temurin' java-version: 17 - name: Combine (Main) if: | @@ -255,7 +255,7 @@ jobs: RUN_AZURE_ARTIFACTORY_RELEASE: "TRUE" ARTIFACTORY_PUBLISH_USERNAME: ${{ secrets.ARTIFACTORY_USERNAME }} ARTIFACTORY_PUBLISH_PASSWORD: ${{ secrets.ARTIFACTORY_PASSWORD }} - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 if: | github.repository_owner == 'wpilibsuite' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) diff --git a/.github/workflows/lint-format.yml b/.github/workflows/lint-format.yml index fe205377df6..723f697205c 100644 --- a/.github/workflows/lint-format.yml +++ b/.github/workflows/lint-format.yml @@ -15,19 +15,19 @@ jobs: name: "wpiformat" runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Fetch all history and metadata run: | - git config --global --add safe.directory /__w/allwpilib/allwpilib - git fetch --prune --unshallow git checkout -b pr git branch -f main origin/main - - name: Set up Python 3.8 - uses: actions/setup-python@v4 + - name: Set up Python 3.10 + uses: actions/setup-python@v5 with: - python-version: 3.8 + python-version: '3.10' - name: Install wpiformat - run: pip3 install wpiformat + run: pip3 install wpiformat==2024.34 - name: Run run: wpiformat - name: Check output @@ -35,7 +35,7 @@ jobs: - name: Generate diff run: git diff HEAD > wpiformat-fixes.patch if: ${{ failure() }} - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: wpiformat fixes path: wpiformat-fixes.patch @@ -51,37 +51,44 @@ jobs: tidy: name: "clang-tidy" runs-on: ubuntu-22.04 - container: wpilib/roborio-cross-ubuntu:2023-22.04 + container: wpilib/roborio-cross-ubuntu:2024-22.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Fetch all history and metadata run: | git config --global --add safe.directory /__w/allwpilib/allwpilib - git fetch --prune --unshallow git checkout -b pr git branch -f main origin/main - - name: Set up Python 3.8 - uses: actions/setup-python@v4 + - name: Set up Python 3.10 + uses: actions/setup-python@v5 with: - python-version: 3.8 + python-version: '3.10' - name: Install wpiformat - run: pip3 install wpiformat + run: pip3 install wpiformat==2024.34 - name: Create compile_commands.json - run: ./gradlew generateCompileCommands -Ptoolchain-optional-roboRio + run: | + ./gradlew generateCompileCommands -Ptoolchain-optional-roboRio + ./.github/workflows/fix_compile_commands.py build/TargetedCompileCommands/linuxx86-64release/compile_commands.json + ./.github/workflows/fix_compile_commands.py build/TargetedCompileCommands/linuxx86-64debug/compile_commands.json - name: List changed files run: wpiformat -list-changed-files - - name: Run clang-tidy - run: wpiformat -no-format -tidy-changed -compile-commands=build/compile_commands/linuxx86-64 -vv + - name: Run clang-tidy release + run: wpiformat -no-format -tidy-changed -compile-commands=build/TargetedCompileCommands/linuxx86-64release -vv + - name: Run clang-tidy debug + run: wpiformat -no-format -tidy-changed -compile-commands=build/TargetedCompileCommands/linuxx86-64debug -vv javaformat: name: "Java format" runs-on: ubuntu-22.04 container: wpilib/ubuntu-base:22.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Fetch all history and metadata run: | git config --global --add safe.directory /__w/allwpilib/allwpilib - git fetch --prune --unshallow git checkout -b pr git branch -f main origin/main - name: Run Java format @@ -95,12 +102,12 @@ jobs: name: "Documentation" runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: - distribution: 'zulu' - java-version: 13 + distribution: 'temurin' + java-version: 21 - name: Build with Gradle run: ./gradlew docs:zipDocs -PbuildServer -PdocWarningsAsErrors ${{ env.EXTRA_GRADLE_ARGS }} diff --git a/.github/workflows/pregenerate.yml b/.github/workflows/pregenerate.yml new file mode 100644 index 00000000000..afcf35c61ad --- /dev/null +++ b/.github/workflows/pregenerate.yml @@ -0,0 +1,46 @@ +name: Check Pregenerated Files + +on: + pull_request: + push: + branches-ignore: + - main + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.ref }} + cancel-in-progress: true + +jobs: + update: + name: "Update" + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Set up Python 3.9 + uses: actions/setup-python@v5 + with: + python-version: 3.9 + - name: Install jinja + run: python -m pip install jinja2 + - name: Install protobuf dependencies + run: sudo apt-get update && sudo apt-get install -y protobuf-compiler && wget https://github.com/HebiRobotics/QuickBuffers/releases/download/1.3.3/protoc-gen-quickbuf-1.3.3-linux-x86_64.exe && chmod +x protoc-gen-quickbuf-1.3.3-linux-x86_64.exe + - name: Run hal + run: ./hal/generate_usage_reporting.py + - name: Run ntcore + run: ./ntcore/generate_topics.py + - name: Run wpimath + run: ./wpimath/generate_numbers.py && ./wpimath/generate_quickbuf.py protoc protoc-gen-quickbuf-1.3.3-linux-x86_64.exe + - name: Add untracked files to index so they count as changes + run: git add -A + - name: Check output + run: git --no-pager diff --exit-code HEAD + - name: Generate diff + run: git diff HEAD > pregenerated-files-fixes.patch + if: ${{ failure() }} + - uses: actions/upload-artifact@v4 + with: + name: pregenerated-files-fixes + path: pregenerated-files-fixes.patch + if: ${{ failure() }} diff --git a/.github/workflows/sanitizers.yml b/.github/workflows/sanitizers.yml index c0b6ac3c892..cf4d1089f78 100644 --- a/.github/workflows/sanitizers.yml +++ b/.github/workflows/sanitizers.yml @@ -33,7 +33,7 @@ jobs: - name: Install QuickBuffers if: runner.os == 'Linux' - run: wget https://github.com/HebiRobotics/QuickBuffers/releases/download/1.3.2/protoc-gen-quickbuf_1.3.2_amd64.deb && sudo apt install ./protoc-gen-quickbuf_1.3.2_amd64.deb + run: wget https://github.com/HebiRobotics/QuickBuffers/releases/download/1.3.3/protoc-gen-quickbuf_1.3.3_amd64.deb && sudo apt install ./protoc-gen-quickbuf_1.3.3_amd64.deb - name: Run sccache-cache uses: mozilla-actions/sccache-action@v0.0.3 @@ -41,7 +41,7 @@ jobs: - name: Install jinja run: python -m pip install jinja2 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: configure run: mkdir build && cd build && cmake -G Ninja -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_C_COMPILER:FILEPATH=/usr/bin/clang-14 -DCMAKE_CXX_COMPILER:FILEPATH=/usr/bin/clang++-14 -DWITH_JAVA=OFF ${{ matrix.cmake-flags }} .. diff --git a/.github/workflows/upstream-utils.yml b/.github/workflows/upstream-utils.yml index 0e4a46f723f..102aaf621bc 100644 --- a/.github/workflows/upstream-utils.yml +++ b/.github/workflows/upstream-utils.yml @@ -15,14 +15,15 @@ jobs: name: "Update" runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Fetch all history and metadata run: | - git fetch --prune --unshallow git checkout -b pr git branch -f main origin/main - name: Set up Python 3.9 - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: 3.9 - name: Configure committer identity @@ -69,6 +70,10 @@ jobs: run: | cd upstream_utils ./update_protobuf.py + - name: Run update_sleipnir.py + run: | + cd upstream_utils + ./update_sleipnir.py - name: Add untracked files to index so they count as changes run: git add -A - name: Check output diff --git a/.styleguide b/.styleguide index 1ba4e1dccef..f67c100e088 100644 --- a/.styleguide +++ b/.styleguide @@ -10,6 +10,7 @@ cppSrcFileInclude { } modifiableFileExclude { + cmake/toolchains/ \.patch$ gradlew } diff --git a/CMakeLists.txt b/CMakeLists.txt index 3929280c997..79df35974bb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,12 +1,15 @@ # Disable in-source builds to prevent source tree corruption. if(" ${CMAKE_CURRENT_SOURCE_DIR}" STREQUAL " ${CMAKE_CURRENT_BINARY_DIR}") - message(FATAL_ERROR " + message( + FATAL_ERROR + " FATAL: In-source builds are not allowed. You should create a separate directory for build files. -") +" + ) endif() -if ("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows") +if("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows") set(CMAKE_SYSTEM_VERSION 10.0.18362.0 CACHE STRING INTERNAL FORCE) set(CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION 10.0.18362.0 CACHE STRING INTERNAL FORCE) endif() @@ -16,7 +19,7 @@ project(allwpilib) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules") # Make timestamps of extracted files from FetchContent the time of extraction -if (POLICY CMP0135) +if(POLICY CMP0135) cmake_policy(SET CMP0135 NEW) endif() @@ -24,7 +27,7 @@ message(STATUS "Platform version: ${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}") set(WPILIB_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}) -INCLUDE(CPack) +include(CPack) set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE) set_property(GLOBAL PROPERTY USE_FOLDERS ON) @@ -35,28 +38,28 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${WPILIB_BINARY_DIR}/bin) set(CMAKE_JAVA_TARGET_OUTPUT_DIR ${WPILIB_BINARY_DIR}/jar) # use, i.e. don't skip the full RPATH for the build tree -SET(CMAKE_SKIP_BUILD_RPATH FALSE) +set(CMAKE_SKIP_BUILD_RPATH FALSE) # when building, don't use the install RPATH already # (but later on when installing) -SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) +set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) -SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib") +set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib") # add the automatically determined parts of the RPATH # which point to directories outside the build tree to the install RPATH -SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) +set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) # the RPATH to be used when installing, but only if it's not a system directory -LIST(FIND CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES "${CMAKE_INSTALL_PREFIX}/lib" isSystemDir) -IF("${isSystemDir}" STREQUAL "-1") - SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib") -ENDIF("${isSystemDir}" STREQUAL "-1") +list(FIND CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES "${CMAKE_INSTALL_PREFIX}/lib" isSystemDir) +if("${isSystemDir}" STREQUAL "-1") + set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib") +endif() # Options for building certain parts of the repo. Everything is built by default. option(BUILD_SHARED_LIBS "Build with shared libs (needed for JNI)" ON) option(WITH_JAVA "Include Java and JNI in the build" ON) -option(WITH_JAVA_SOURCE "Build Java source jars" ON) +option(WITH_JAVA_SOURCE "Build Java source jars" ${WITH_JAVA}) option(WITH_CSCORE "Build cscore (needs OpenCV)" ON) option(WITH_NTCORE "Build ntcore" ON) option(WITH_WPIMATH "Build wpimath" ON) @@ -76,144 +79,154 @@ option(USE_SYSTEM_FMTLIB "Use system fmtlib" OFF) option(USE_SYSTEM_LIBUV "Use system libuv" OFF) option(USE_SYSTEM_EIGEN "Use system eigen" OFF) -# Options for installation. -option(WITH_FLAT_INSTALL "Use a flat install directory" OFF) - # Options for location of OpenCV Java. set(OPENCV_JAVA_INSTALL_DIR "" CACHE PATH "Location to search for the OpenCV jar file") +# Options for compilation flags. +option(NO_WERROR "Disable -Werror flag during compilation" OFF) + # Set default build type to release with debug info (i.e. release mode optimizations # are performed, but debug info still exists). -if (NOT CMAKE_BUILD_TYPE) - set (CMAKE_BUILD_TYPE "RelWithDebInfo" CACHE STRING "" FORCE) +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "RelWithDebInfo" CACHE STRING "" FORCE) endif() -if (WITH_JAVA AND NOT BUILD_SHARED_LIBS) - message(FATAL_ERROR " +if(WITH_JAVA AND NOT BUILD_SHARED_LIBS) + message( + FATAL_ERROR + " FATAL: Cannot build static libs with Java enabled. Static libs requires both BUILD_SHARED_LIBS=OFF and WITH_JAVA=OFF -") +" + ) endif() -if (WITH_SIMULATION_MODULES AND NOT BUILD_SHARED_LIBS) - message(FATAL_ERROR " +if(WITH_SIMULATION_MODULES AND NOT BUILD_SHARED_LIBS) + message( + FATAL_ERROR + " FATAL: Cannot build static libs with simulation modules enabled. Static libs requires both BUILD_SHARED_LIBS=OFF and WITH_SIMULATION_MODULES=OFF -") +" + ) endif() -if (NOT WITH_JAVA OR NOT WITH_CSCORE) +if(NOT WITH_JAVA OR NOT WITH_CSCORE) if(NOT "${OPENCV_JAVA_INSTALL_DIR}" STREQUAL "") - message(WARNING " + message( + WARNING + " WARNING: OpenCV Java dir set but java is not enabled! It will be ignored. -") +" + ) endif() endif() -if (NOT WITH_WPILIB AND WITH_SIMULATION_MODULES) - message(FATAL_ERROR " +if(NOT WITH_WPILIB AND WITH_SIMULATION_MODULES) + message( + FATAL_ERROR + " FATAL: Cannot build simulation modules with wpilib disabled. Enable wpilib by setting WITH_WPILIB=ON -") +" + ) endif() -if (NOT WITH_NTCORE AND WITH_CSCORE) - message(FATAL_ERROR " +if(NOT WITH_NTCORE AND WITH_CSCORE) + message( + FATAL_ERROR + " FATAL: Cannot build cameraserver without ntcore. Enable ntcore by setting WITH_NTCORE=ON -") +" + ) endif() -if (NOT WITH_NTCORE AND WITH_GUI) - message(FATAL_ERROR " +if(NOT WITH_NTCORE AND WITH_GUI) + message( + FATAL_ERROR + " FATAL: Cannot build GUI modules without ntcore. Enable ntcore by setting WITH_NTCORE=ON -") +" + ) endif() -if (NOT WITH_NTCORE AND WITH_SIMULATION_MODULES) - message(FATAL_ERROR " +if(NOT WITH_NTCORE AND WITH_SIMULATION_MODULES) + message( + FATAL_ERROR + " FATAL: Cannot build simulation modules without ntcore. Enable ntcore by setting WITH_NTCORE=ON -") +" + ) endif() -if (NOT WITH_NTCORE AND WITH_WPILIB) - message(FATAL_ERROR " +if(NOT WITH_NTCORE AND WITH_WPILIB) + message( + FATAL_ERROR + " FATAL: Cannot build wpilib without ntcore. Enable ntcore by setting WITH_NTCORE=ON -") +" + ) endif() -if (NOT WITH_WPIMATH AND WITH_WPILIB) - message(FATAL_ERROR " +if(NOT WITH_WPIMATH AND WITH_WPILIB) + message( + FATAL_ERROR + " FATAL: Cannot build wpilib without wpimath. Enable wpimath by setting WITH_WPIMATH=ON -") +" + ) endif() -if (NOT WITH_WPIUNITS AND WITH_WPIMATH AND WITH_JAVA) - message(FATAL_ERROR " +if(NOT WITH_WPIUNITS AND WITH_WPIMATH AND WITH_JAVA) + message( + FATAL_ERROR + " FATAL: Cannot build Java wpimath without wpiunits. Enable wpiunits by setting WITH_WPIUNITS=ON or disable the Java build by setting WITH_JAVA=OFF -") +" + ) endif() -set( wpilib_dest "") -set( include_dest include ) -set( java_lib_dest java ) -set( jni_lib_dest jni ) +set(include_dest include) +set(java_lib_dest java) +set(jni_lib_dest jni) -if (WITH_FLAT_INSTALL) - set (wpilib_config_dir ${wpilib_dest}) -else() - set (wpilib_config_dir share/wpilib) -endif() - -if (USE_SYSTEM_LIBUV) -set (LIBUV_SYSTEM_REPLACE " +if(USE_SYSTEM_LIBUV) + set(LIBUV_SYSTEM_REPLACE + " find_dependency(libuv CONFIG) -") +" + ) endif() -if (USE_SYSTEM_EIGEN) -set (EIGEN_SYSTEM_REPLACE "find_package(Eigen3 CONFIG)") +if(USE_SYSTEM_EIGEN) + set(EIGEN_SYSTEM_REPLACE "find_package(Eigen3 CONFIG)") endif() find_package(LIBSSH 0.7.1) find_package(Protobuf REQUIRED) -find_program(Quickbuf_EXECUTABLE - NAMES protoc-gen-quickbuf - DOC "The Quickbuf protoc plugin" -) -if (WITH_FLAT_INSTALL) -set(WPIUTIL_DEP_REPLACE "include($\{SELF_DIR\}/wpiutil-config.cmake)") -set(WPINET_DEP_REPLACE "include($\{SELF_DIR\}/wpinet-config.cmake)") -set(NTCORE_DEP_REPLACE "include($\{SELF_DIR\}/ntcore-config.cmake)") -set(CSCORE_DEP_REPLACE_IMPL "include(\${SELF_DIR}/cscore-config.cmake)") -set(CAMERASERVER_DEP_REPLACE_IMPL "include(\${SELF_DIR}/cameraserver-config.cmake)") -set(HAL_DEP_REPLACE_IMPL "include(\${SELF_DIR}/hal-config.cmake)") -set(WPIMATH_DEP_REPLACE "include($\{SELF_DIR\}/wpimath-config.cmake)") -set(WPIUNITS_DEP_REPLACE "include($\{SELF_DIR\}/wpiunits-config.cmake)") -set(WPILIBC_DEP_REPLACE_IMPL "include(\${SELF_DIR}/wpilibc-config.cmake)") -set(WPILIBNEWCOMMANDS_DEP_REPLACE "include(\${SELF_DIR}/wpilibNewcommands-config.cmake)") -else() -set(WPIUTIL_DEP_REPLACE "find_dependency(wpiutil)") -set(WPINET_DEP_REPLACE "find_dependency(wpinet)") -set(NTCORE_DEP_REPLACE "find_dependency(ntcore)") -set(CSCORE_DEP_REPLACE_IMPL "find_dependency(cscore)") +set(APRILTAG_DEP_REPLACE "find_dependency(apriltag)") set(CAMERASERVER_DEP_REPLACE_IMPL "find_dependency(cameraserver)") +set(CSCORE_DEP_REPLACE_IMPL "find_dependency(cscore)") set(HAL_DEP_REPLACE_IMPL "find_dependency(hal)") -set(WPIMATH_DEP_REPLACE "find_dependency(wpimath)") -set(WPIUNITS_DEP_REPLACE "find_dependency(wpiunits)") +set(NTCORE_DEP_REPLACE "find_dependency(ntcore)") set(WPILIBC_DEP_REPLACE_IMPL "find_dependency(wpilibc)") +set(WPILIBJ_DEP_REPLACE "find_dependency(wpilibj)") set(WPILIBNEWCOMMANDS_DEP_REPLACE "find_dependency(wpilibNewCommands)") -endif() +set(WPIMATH_DEP_REPLACE "find_dependency(wpimath)") +set(WPINET_DEP_REPLACE "find_dependency(wpinet)") +set(WPIUNITS_DEP_REPLACE "find_dependency(wpiunits)") +set(WPIUTIL_DEP_REPLACE "find_dependency(wpiutil)") set(FILENAME_DEP_REPLACE "get_filename_component(SELF_DIR \"$\{CMAKE_CURRENT_LIST_FILE\}\" PATH)") set(SELF_DIR "$\{SELF_DIR\}") @@ -231,7 +244,15 @@ if(isMultiConfig) list(APPEND CMAKE_CONFIGURATION_TYPES Ubsan) endif() else() - set(allowedBuildTypes Asan Tsan Ubsan Debug Release RelWithDebInfo MinSizeRel) + set(allowedBuildTypes + Asan + Tsan + Ubsan + Debug + Release + RelWithDebInfo + MinSizeRel + ) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "${allowedBuildTypes}") if(CMAKE_BUILD_TYPE AND NOT CMAKE_BUILD_TYPE IN_LIST allowedBuildTypes) @@ -240,54 +261,90 @@ else() endif() set(CMAKE_C_FLAGS_ASAN - "${CMAKE_C_FLAGS_DEBUG} -fsanitize=address -fno-omit-frame-pointer" CACHE STRING - "Flags used by the C compiler for Asan build type or configuration." FORCE) + "${CMAKE_C_FLAGS_DEBUG} -fsanitize=address -fno-omit-frame-pointer" + CACHE STRING + "Flags used by the C compiler for Asan build type or configuration." + FORCE +) set(CMAKE_CXX_FLAGS_ASAN - "${CMAKE_CXX_FLAGS_DEBUG} -fsanitize=address -fno-omit-frame-pointer" CACHE STRING - "Flags used by the C++ compiler for Asan build type or configuration." FORCE) + "${CMAKE_CXX_FLAGS_DEBUG} -fsanitize=address -fno-omit-frame-pointer" + CACHE STRING + "Flags used by the C++ compiler for Asan build type or configuration." + FORCE +) set(CMAKE_EXE_LINKER_FLAGS_ASAN - "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} -fsanitize=address" CACHE STRING - "Linker flags to be used to create executables for Asan build type." FORCE) + "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} -fsanitize=address" + CACHE STRING + "Linker flags to be used to create executables for Asan build type." + FORCE +) set(CMAKE_SHARED_LINKER_FLAGS_ASAN - "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} -fsanitize=address" CACHE STRING - "Linker lags to be used to create shared libraries for Asan build type." FORCE) + "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} -fsanitize=address" + CACHE STRING + "Linker lags to be used to create shared libraries for Asan build type." + FORCE +) set(CMAKE_C_FLAGS_TSAN - "${CMAKE_C_FLAGS_DEBUG} -fsanitize=thread -fno-omit-frame-pointer" CACHE STRING - "Flags used by the C compiler for Tsan build type or configuration." FORCE) + "${CMAKE_C_FLAGS_DEBUG} -fsanitize=thread -fno-omit-frame-pointer" + CACHE STRING + "Flags used by the C compiler for Tsan build type or configuration." + FORCE +) set(CMAKE_CXX_FLAGS_TSAN - "${CMAKE_CXX_FLAGS_DEBUG} -fsanitize=thread -fno-omit-frame-pointer" CACHE STRING - "Flags used by the C++ compiler for Tsan build type or configuration." FORCE) + "${CMAKE_CXX_FLAGS_DEBUG} -fsanitize=thread -fno-omit-frame-pointer" + CACHE STRING + "Flags used by the C++ compiler for Tsan build type or configuration." + FORCE +) set(CMAKE_EXE_LINKER_FLAGS_TSAN - "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} -fsanitize=thread" CACHE STRING - "Linker flags to be used to create executables for Tsan build type." FORCE) + "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} -fsanitize=thread" + CACHE STRING + "Linker flags to be used to create executables for Tsan build type." + FORCE +) set(CMAKE_SHARED_LINKER_FLAGS_TSAN - "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} -fsanitize=thread" CACHE STRING - "Linker lags to be used to create shared libraries for Tsan build type." FORCE) + "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} -fsanitize=thread" + CACHE STRING + "Linker lags to be used to create shared libraries for Tsan build type." + FORCE +) set(CMAKE_C_FLAGS_UBSAN - "${CMAKE_C_FLAGS_DEBUG} -fsanitize=undefined -fno-sanitize-recover=all -fno-omit-frame-pointer" CACHE STRING - "Flags used by the C compiler for Ubsan build type or configuration." FORCE) + "${CMAKE_C_FLAGS_DEBUG} -fsanitize=undefined -fno-sanitize-recover=all -fno-omit-frame-pointer" + CACHE STRING + "Flags used by the C compiler for Ubsan build type or configuration." + FORCE +) set(CMAKE_CXX_FLAGS_UBSAN - "${CMAKE_CXX_FLAGS_DEBUG} -fsanitize=undefined -fno-sanitize-recover=all -fno-omit-frame-pointer" CACHE STRING - "Flags used by the C++ compiler for Ubsan build type or configuration." FORCE) + "${CMAKE_CXX_FLAGS_DEBUG} -fsanitize=undefined -fno-sanitize-recover=all -fno-omit-frame-pointer" + CACHE STRING + "Flags used by the C++ compiler for Ubsan build type or configuration." + FORCE +) set(CMAKE_EXE_LINKER_FLAGS_UBSAN - "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} -fsanitize=undefined -fno-sanitize-recover=all" CACHE STRING - "Linker flags to be used to create executables for Ubsan build type." FORCE) + "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} -fsanitize=undefined -fno-sanitize-recover=all" + CACHE STRING + "Linker flags to be used to create executables for Ubsan build type." + FORCE +) set(CMAKE_SHARED_LINKER_FLAGS_UBSAN - "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} -fsanitize=undefined" CACHE STRING - "Linker lags to be used to create shared libraries for Ubsan build type." FORCE) + "${CMAKE_SHARED_LINKER_FLAGS_DEBUG} -fsanitize=undefined" + CACHE STRING + "Linker lags to be used to create shared libraries for Ubsan build type." + FORCE +) -if (WITH_TESTS) +if(WITH_TESTS) enable_testing() add_subdirectory(googletest) include(GoogleTest) @@ -295,49 +352,49 @@ endif() add_subdirectory(wpiutil) -if (WITH_NTCORE) +if(WITH_NTCORE) add_subdirectory(wpinet) add_subdirectory(ntcore) endif() -if (WITH_WPIMATH) - if (WITH_JAVA) +if(WITH_WPIMATH) + if(WITH_JAVA) add_subdirectory(wpiunits) endif() add_subdirectory(wpimath) endif() -if (WITH_WPIUNITS AND NOT WITH_WPIMATH) +if(WITH_WPIUNITS AND NOT WITH_WPIMATH) # In case of building wpiunits standalone add_subdirectory(wpiunits) endif() -if (WITH_GUI) +if(WITH_GUI) add_subdirectory(fieldImages) add_subdirectory(imgui) add_subdirectory(wpigui) add_subdirectory(glass) add_subdirectory(outlineviewer) add_subdirectory(sysid) - if (LIBSSH_FOUND) + if(LIBSSH_FOUND) add_subdirectory(roborioteamnumbersetter) add_subdirectory(datalogtool) endif() endif() -if (WITH_WPILIB OR WITH_SIMULATION_MODULES) +if(WITH_WPILIB OR WITH_SIMULATION_MODULES) set(HAL_DEP_REPLACE ${HAL_DEP_REPLACE_IMPL}) add_subdirectory(hal) endif() -if (WITH_CSCORE) +if(WITH_CSCORE) set(CSCORE_DEP_REPLACE ${CSCORE_DEP_REPLACE_IMPL}) set(CAMERASERVER_DEP_REPLACE ${CAMERASERVER_DEP_REPLACE_IMPL}) add_subdirectory(cscore) add_subdirectory(cameraserver) endif() -if (WITH_WPILIB) +if(WITH_WPILIB) set(WPILIBC_DEP_REPLACE ${WPILIBC_DEP_REPLACE_IMPL}) add_subdirectory(apriltag) add_subdirectory(wpilibj) @@ -345,15 +402,15 @@ if (WITH_WPILIB) add_subdirectory(wpilibNewCommands) add_subdirectory(romiVendordep) add_subdirectory(xrpVendordep) - if (WITH_EXAMPLES) + if(WITH_EXAMPLES) add_subdirectory(wpilibcExamples) endif() add_subdirectory(myRobot) endif() -if (WITH_SIMULATION_MODULES AND NOT WITH_EXTERNAL_HAL) +if(WITH_SIMULATION_MODULES AND NOT WITH_EXTERNAL_HAL) add_subdirectory(simulation) endif() -configure_file(wpilib-config.cmake.in ${WPILIB_BINARY_DIR}/wpilib-config.cmake ) -install(FILES ${WPILIB_BINARY_DIR}/wpilib-config.cmake DESTINATION ${wpilib_config_dir}) +configure_file(wpilib-config.cmake.in ${WPILIB_BINARY_DIR}/wpilib-config.cmake) +install(FILES ${WPILIB_BINARY_DIR}/wpilib-config.cmake DESTINATION share/wpilib) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 763521a0220..1ab9b13252b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,11 +12,11 @@ So you want to contribute your changes back to WPILib. Great! We have a few cont ## General Contribution Rules -- Everything in the library must work for the 3000+ teams that will be using it. +- Everything in the library must work for the 4000+ teams that will be using it. - We need to be able to maintain submitted changes, even if you are no longer working on the project. - Tool suite changes must be generally useful to a broad range of teams - Excluding bug fixes, changes in one language generally need to have corresponding changes in other languages. - - Some features, such the addition of C++11 for WPILibC or Functional Interfaces for WPILibJ, are specific to that version of WPILib only. + - Some features, such the addition of C++23 for WPILibC or Functional Interfaces for WPILibJ, are specific to that version of WPILib only. New language features added to C++ must be wrappable in Python for [RobotPy](https://github.com/robotpy). - Substantial changes often need to have corresponding LabVIEW changes. To do this, we will work with NI on these large changes. - Changes should have tests. - Code should be well documented. @@ -27,7 +27,8 @@ So you want to contribute your changes back to WPILib. Great! We have a few cont - Bug reports and fixes - We will generally accept bug fixes without too much question. If they are only implemented for one language, we will implement them for any other necessary languages. Bug reports are also welcome, please submit them to our GitHub issue tracker. - While we do welcome improvements to the API, there are a few important rules to consider: - - Features must be added to both WPILibC and WPILibJ, with rare exceptions. + - Features must be added to Java (WPILibJ), C++ (WPILibC), with rare exceptions. + - Most of Python (RobotPy) is created by wrapping WPILibC with pybind11 via robotpy-build. However, new features to the command framework should also be submitted to [robotpy-commands-v2](https://github.com/robotpy/robotpy-commands-v2) as the command framework is reimplemented in Python. - During competition season, we will not merge any new feature additions. We want to ensure that the API is stable during the season to help minimize issues for teams. - Ask about large changes before spending a bunch of time on them! You can create a new issue on our GitHub tracker for feature request/discussion and talk about it with us there. - Features that make it easier for teams with less experience to be more successful are more likely to be accepted. @@ -79,6 +80,8 @@ xₖ₊₁ = Axₖ + Buₖ Changes should be submitted as a Pull Request against the main branch of WPILib. For most changes, commits will be squashed upon merge. For particularly large changes, multiple commits are ok, but assume one commit unless asked otherwise. We may ask you to break a PR into multiple standalone PRs or commits for rebase within one PR to separate unrelated changes. No change will be merged unless it is up to date with the current main branch. We do this to make sure that the git history isn't too cluttered. +During the build season, breaking changes or other changes intended for the next season can be created as a pull request against the development branch of WPILib. After the season is over, the changes in the development branch will be merged into main. + ### Merge Process When you first submit changes, GitHub Actions will attempt to run `./gradlew check` on your change. If this fails, you will need to fix any issues that it sees. Once Actions passes, we will begin the review process in more earnest. One or more WPILib team members will review your change. This will be a back-and-forth process with the WPILib team and the greater community. Once we are satisfied that your change is ready, we will allow our hosted instance to test it. This will run the full gamut of checks, including integration tests on actual hardware. Once all tests have passed and the team is satisfied, we will merge your change into the WPILib repository. diff --git a/LICENSE.md b/LICENSE.md index 43b62ec2e32..645e54253ad 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,4 +1,4 @@ -Copyright (c) 2009-2023 FIRST and other WPILib contributors +Copyright (c) 2009-2024 FIRST and other WPILib contributors All rights reserved. Redistribution and use in source and binary forms, with or without diff --git a/MAINTAINERS.md b/MAINTAINERS.md index d4c34909b20..045aa6d282d 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -1,5 +1,5 @@ ## Publishing Third Party Dependencies -Currently the 3rd party deps are imgui, opencv, and google test +Currently the 3rd party deps are imgui, opencv, google test, libssh, and apriltaglib For publishing these dependencies, the version needs to be manually updated in the publish.gradle file of their respective repository. Then, in the azure build for the dependency you want to build for, manually start a pipeline build (As of current, this is the `Run Pipeline` button). @@ -18,10 +18,10 @@ Desktop tools publish to the development repo on every push to main. To publish ## Publishing VS Code Before publishing, make sure to update the gradlerio version in `vscode-wpilib/resources/gradle/version.txt` Also make sure the gradle wrapper version matches the wrapper required by gradlerio. -Upon pushing a tag, a release will be built, and the files will be uploaded to the releases on GitHub. For publishing to the marketplace, you need a Microsoft account and to be added as a maintainer. +Upon pushing a tag, a release will be built, and the files will be uploaded to the releases on GitHub. ## Publishing GradleRIO Before publishing, make sure to update the version in build.gradle. Publishing must happen locally, using the command `./gradlew publishPlugin`. This does require your API key for publishing to be set. ## Building the installer -Update the GradleRIO version in gradle.properties, and in the scripts folder in vscode, update the vscode extension. Then push, it will build the installer on azure. +Update the GradleRIO version in gradle.properties, and in the scripts folder in vscode, update the vscode extension. To publish a release build, upload a new tag, and a release will automatically be built and published to artifactory and cloudflare. diff --git a/MavenArtifacts.md b/MavenArtifacts.md index 655f9c5a363..9870028183a 100644 --- a/MavenArtifacts.md +++ b/MavenArtifacts.md @@ -145,6 +145,11 @@ All artifacts are based at `edu.wpi.first.artifactname` in the repository. * wpinet * wpiutil +* wpiunits + +* apriltag + * wpiutil + * wpimath ### Third Party Artifacts @@ -152,6 +157,7 @@ This repository provides the builds of the following third party software. All artifacts are based at `edu.wpi.first.thirdparty.frcYEAR` in the repository. +* apriltaglib * googletest * imgui * opencv diff --git a/README-CMAKE.md b/README-CMAKE.md index a2750bd70d6..9c378321e11 100644 --- a/README-CMAKE.md +++ b/README-CMAKE.md @@ -1,31 +1,41 @@ # WPILib CMake Support -WPILib is normally built with Gradle, however for some systems, such as Linux based coprocessors, Gradle doesn't work correctly, especially if cscore is needed, which requires OpenCV. Furthermore, the CMake build can be used for C++ development because it provides better build caching compared to Gradle. We provide the CMake build for these cases. Although it is supported on Windows, these docs will only go over Linux builds. +WPILib is normally built with Gradle, however for some systems, such as Linux based coprocessors, Gradle doesn't work correctly, especially if cscore is needed, which requires OpenCV. Furthermore, the CMake build can be used for C++ development because it provides better build caching compared to Gradle. We provide the CMake build for these cases. Although macOS is supported, these docs will only go over Linux and Windows builds, but should mostly work for macOS as well. If you are stuck, you can look at the GitHub workflows for any OS to see how it works. ## Libraries that get built -* wpiutil -* ntcore -* cscore +* apriltag * cameraserver -* hal -* wpilib -* halsim +* cscore +* hal (simulation HAL only) +* ntcore +* romiVendordep +* simulation extensions * wpigui +* wpilib (wpilibc, wpilibj, and myRobot) +* wpilibNewCommands * wpimath +* wpinet * wpiunits -* wpilibNewCommands +* wpiutil +* xrpVendordep -By default, all libraries except for the HAL and WPILib get built with a default CMake setup. The libraries are built as shared libraries, and include the JNI libraries as well as building the Java JARs. +## GUI apps that get built +* datalogtool +* glass +* outlineviewer +* roborioteamnumbersetter +* sysid +* halsim_gui (if simulation extensions are enabled) -## Prerequisites +By default, all libraries get built with a default CMake setup. The libraries are built as shared libraries, and include the JNI libraries as well as building the Java JARs. Data Log Tool and the roboRIO Team Number Setter are only built if libssh is available. -The jinja2 pip package is needed to generate classes for NT4's pubsub. +## Prerequisites -The protobuf library and compiler are needed for protobuf generation. The QuickBuffers protoc-gen package is also required when Java is being built; this can be obtained from https://github.com/HebiRobotics/QuickBuffers/releases/. +The protobuf library and compiler are needed for protobuf generation. OpenCV needs to be findable by CMake. On systems like the Jetson, this is installed by default. Otherwise, you will need to build OpenCV from source and install it. -If you want JNI and Java, you will need a JDK of at least version 11 installed. In addition, you need a `JAVA_HOME` environment variable set properly and set to the JDK directory. +If you want JNI and Java, you will need a JDK of at least version 17 installed. In addition, you need a `JAVA_HOME` environment variable set properly and set to the JDK directory. If you are building with unit tests or simulation modules, you will also need an Internet connection for the initial setup process, as CMake will clone google-test and imgui from GitHub. @@ -33,36 +43,38 @@ If you are building with unit tests or simulation modules, you will also need an The following build options are available: +* `BUILD_SHARED_LIBS` (ON Default) + * This option will cause CMake to build static libraries instead of shared libraries. If this is off, `WITH_JAVA` must be off. Otherwise CMake will error. +* `WITH_CSCORE` (ON Default) + * This option will cause cscore to be built. Turning this off will implicitly disable cameraserver. If this is off, the OpenCV build requirement is removed. +* `WITH_EXAMPLES` (OFF Default) + * This option will build C++ examples. +* `WITH_GUI` (ON Default) + * This option will build GUI items. If this is off, and `WITH_SIMULATION_MODULES` is on, the simulation GUI will not be built. * `WITH_JAVA` (ON Default) - * This option will enable Java and JNI builds. If this is on, `WITH_SHARED_LIBS` must be on. Otherwise CMake will error. -* `WITH_JAVA_SOURCE` (ON Default) + * This option will enable Java and JNI builds. If this is on, `BUILD_SHARED_LIBS` must be on. Otherwise CMake will error. +* `WITH_JAVA_SOURCE` (`WITH_JAVA` Default) * This option will build Java source JARs for each enabled Java library. This does not require `WITH_JAVA` to be on, allowing source JARs to be built without the compiled JARs if desired. -* `WITH_SHARED_LIBS` (ON Default) - * This option will cause cmake to build static libraries instead of shared libraries. If this is off, `WITH_JAVA` must be off. Otherwise CMake will error. -* `WITH_CSCORE` (ON Default) - * This option will cause cscore to be built. Turning this off will implicitly disable cameraserver, the hal and wpilib as well, irrespective of their specific options. If this is off, the OpenCV build requirement is removed. * `WITH_NTCORE` (ON Default) - * This option will cause ntcore to be built. Turning this off will implicitly disable wpinet and wpilib as well, irrespective of their specific options. + * This option will cause ntcore to be built. Turning this off will implicitly disable wpinet, and will cause an error if `WITH_WPILIB` is enabled. +* `WITH_SIMULATION_MODULES` (ON Default) + * This option will build simulation modules. +* `WITH_TESTS` (ON Default) + * This option will build C++ unit tests. These can be run via `ctest -C `, where `` is the build configuration, e.g. `Debug` or `Release`. +* `WITH_WPILIB` (ON Default) + * This option will build the HAL and wpilibc/j during the build. The HAL is the simulation HAL, unless the external HAL options are used. The CMake build has no capability to build for the roboRIO. * `WITH_WPIMATH` (ON Default) * This option will build the wpimath library. This option must be on to build wpilib. * `WITH_WPIUNITS` (ON Default) * This option will build the wpiunits library. This option must be on to build the Java wpimath library and requires `WITH_JAVA` to also be on. -* `WITH_WPILIB` (ON Default) - * This option will build the hal and wpilibc/j during the build. The HAL is the simulator hal, unless the external hal options are used. The cmake build has no capability to build for the RoboRIO. -* `WITH_EXAMPLES` (ON Default) - * This option will build C++ examples. -* `WITH_TESTS` (ON Default) - * This option will build C++ unit tests. These can be run via `make test`. -* `WITH_GUI` (ON Default) - * This option will build GUI items. -* `WITH_SIMULATION_MODULES` (ON Default) - * This option will build simulation modules, including wpigui and the HALSim plugins. * `WITH_EXTERNAL_HAL` (OFF Default) - * TODO + * This option will build wpilib with an externally built HAL. * `EXTERNAL_HAL_FILE` - * TODO + * Set this option to the CMake File of the externally built HAL. NOTE: set it to the file itself, not the folder the file is located in! * `OPENCV_JAVA_INSTALL_DIR` * Set this option to the location of the archive of the OpenCV Java bindings (it should be called opencv-xxx.jar, with the x'es being version numbers). NOTE: set it to the LOCATION of the file, not the file itself! +* `NO_WERROR` (OFF Default) + * This option will disable the `-Werror` compilation flag for non-MSVC builds. ## Build Setup @@ -76,24 +88,28 @@ cmake path/to/allwpilib/root If you want to change any of the options, add `-DOPTIONHERE=VALUE` to the `cmake` command. This will check for any dependencies. If everything works properly this will succeed. If not, please check out the troubleshooting section for help. -If you want, you can also use `ccmake` in order to visually set these properties as well. [Here](https://cmake.org/cmake/help/v3.0/manual/ccmake.1.html) is the link to the documentation for that program. +If you want, you can also use `ccmake` in order to visually set these properties as well. [Here](https://cmake.org/cmake/help/v3.0/manual/ccmake.1.html) is the link to the documentation for that program. On Windows, you can use `cmake-gui` instead. + +Note that if you are cross-compiling, you will need to override the protobuf options manually to point to the libraries for the target platform. Leave the protoc binary location as the path to the binary for the host platform, since protoc needs to execute on the host platform. ## Building -Once you have cmake setup. run `make` from the directory you configured CMake in. This will build all libraries possible. If you have a multicore system, we recommend running `make` with multiple jobs. The usual rule of thumb is 1.5x the number of cores you have. To run a multiple job build, run the following command with x being the number of jobs you want. +Once you have CMake setup. run `cmake --build .` from the directory you configured CMake in. This will build all libraries possible. We recommend running `cmake --build .` with multiple jobs. For allwpilib, a good rule of thumb is one worker for every 2 GB of available RAM. To run a multiple job build, run the following command with x being the number of jobs you want. ``` -make -jx +cmake --build . --parallel x ``` -The `ninja` generator is also supported, and can be enabled by passing `-GNinja` to the initial `cmake` command. +Note: wpimath takes gigabytes of RAM to compile. Because of this, the compilers may crash while building due to a lack of memory and your computer may slow down. If you have less than 16 GB of RAM available, you may want to consider building it separately first by adding `--target wpimath` and running it with ~3 jobs to prevent crashes from running out of memory. + +To build with a certain configuration, like `Debug` or `Release`, add `--config `, where `` is the name of the configuration you want to build with. ## Installing -After build, the easiest way to use the libraries is to install them. Run the following command to install the libraries. This will install them so that they can be used from external cmake projects. +After build, the easiest way to use the libraries is to install them. Run the following command to install the libraries. This will install them so that they can be used from external CMake projects. ``` -sudo make install +sudo cmake --build . --target install ``` ## Using the installed libraries for C++. @@ -102,7 +118,7 @@ Using the libraries from C++ is the easiest way to use the built libraries. To do so, create a new folder to contain your project. Add the following code below to a `CMakeLists.txt` file in that directory. -``` +```cmake cmake_minimum_required(VERSION 3.11) project(vision_app) # Project Name Here @@ -112,7 +128,7 @@ add_executable(my_vision_app main.cpp) # executable name as first parameter target_link_libraries(my_vision_app cameraserver ntcore cscore wpiutil) ``` -If you are using them, `wpilibc` and `hal` should be added before the `cameraserver` declaration in the `target_link_libraries` function. +If you want to use other libraries or are building a robot program, `wpilibc` and `hal` should be added in the `target_link_libraries` function, along with any other libraries you plan on using, e.g. `wpimath`. Add a `main.cpp` file to contain your code, and create a build folder. Move into the build folder, and run @@ -120,11 +136,43 @@ Add a `main.cpp` file to contain your code, and create a build folder. Move into cmake /path/to/folder/containing/CMakeLists ``` -After that, run `make`. That will create your executable. Then you should be able to run `./my_vision_app` to run your application. +After that, run `cmake --build .`. That will create your executable. Then you should be able to run `./my_vision_app` to run your application. ## Using the installed libraries for Java -TODO + +Using the built JARs is move involved than using the C++ libraries, but mostly consists of adding the correct directories to PATH. + +Add the directory where the JARs are located (e.g, `/usr/local/java`) to PATH. If you are on Windows, you also need to add the `lib`, `bin`, and `share` directories to PATH. Then, create a new folder to contain your project. Add the following code below to a `CMakeLists.txt` file in that directory. + +```cmake +cmake_minimum_required(VERSION 3.11) +project(robot) + +find_package(Java REQUIRED COMPONENTS Development) +include(UseJava) +find_package(wpilib REQUIRED) +find_jar(opencvJar opencv-xxx PATHS ENV PATH) # Change to OpenCV version + +file(GLOB_RECURSE JAVA_SOURCES *.java) +# If you want Gradle compatibility or you are using one of the templates/examples, comment out the above line and uncomment this line instead: +# file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java) +add_jar(robot ${JAVA_SOURCES} + INCLUDE_JARS apriltag_jar cscore_jar hal_jar ntcore_jar wpilibNewCommands_jar wpimath_jar wpinet_jar wpiutil_jar wpiunits_jar wpilibj_jar ${opencvJar}) +export_jars(TARGETS robot FILE robot.jar) +``` +This includes all the built JARs except for the vendordeps. If you are not using a JAR/library, you may remove it. +Add a `Main.java` file to contain your code, and create a build folder. Move into the build folder, and run + +``` +cmake /path/to/folder/containing/CMakeLists +``` + +After that, run `cmake --build .` to create your JAR file. To execute the JAR file, you need to include the wpilib JARs and your JAR in the classpath, and execute your Java program's entry point. If you are using cscore or cameraserver, you also need to include the path to the OpenCV JAR. If you built it from source, it will be in your OpenCV build directory. If it's installed on the system, CMake may find it from PATH, but you will likely need to locate the JAR and manually give CMake the JAR directory. If you are on Linux, you will also need to add the path of the libraries to `LD_LIBRARY_PATH`. This can be done by prepending `LD_LIBRARY_PATH=/path/to/libraries` to the Java command. If you need to add more paths, separate them with colons. The final command should look like `java -cp "robot.jar:/path/to/library_jars/*" main.package.Main`, using a semicolon to separate paths instead of a colon if you are on Windows. If you are on Linux, the final command should look more like `LD_LIBRARY_PATH=/path/to/libraries java -cp robot.jar:/path/to/library_jars/* main.package.Main`. + +## Using vendordeps + +Vendordeps are not included as part of the `wpilib` CMake package. However, if you want to use a vendordep, you need to use `find_package(VENDORDEP)`, where `VENDORDEP` is the name of the vendordep (case-sensitive), like `xrpVendordep` or `romiVenderdep`. Note that wpilibNewCommands, while a vendordep in normal robot projects, is not built as a vendordep in CMake, and is instead included as part of the `wpilib` CMake package. After you used `find_package`, you can reference the vendordep library like normal, either by using `target_link_libraries` for C++ or `add_jar` for Java. ## Troubleshooting Below are some common issues that are run into when building. @@ -151,7 +199,7 @@ CMake Error at cscore/CMakeLists.txt:3 (find_package): installed. ``` -If you get that, you need make sure opencv was installed, and then reattempt to configure. If that doesn't work, set the `OpenCV_DIR` variable to the directory where you built OpenCV. +If you get that, you need make sure OpenCV was installed, and then reattempt to configure. If that doesn't work, set the `OpenCV_DIR` variable to the directory where you built OpenCV. #### Missing Java @@ -165,3 +213,18 @@ CMake Error at /usr/share/cmake-3.5/Modules/FindPackageHandleStandardArgs.cmake: If this happens, make sure you have a JDK of at least version 8 installed, and that your JAVA_HOME variable is set properly to point to the JDK. In addition, if you do not need Java, you can disable it with `-DWITH_JAVA=OFF`. + +#### Java: Can't find dependent libraries + +If one of the libraries can't be found, you will get an error similar to this one: + +``` +java.io.IOException: wpiHaljni could not be loaded from path or an embedded resource. + attempted to load for platform /windows/x86-64/ +Last Load Error: +C:\Program Files (x86)\allwpilib\bin\wpiHaljni.dll: Can't find dependent libraries +``` + +If you get this error, that's usually an indication that not all your libraries are in your PATH. The two libraries that should be in your PATH are OpenCV and protobuf. If the error is coming from cscore, it's likely you're missing OpenCV. Otherwise, it's likely you're missing protobuf. + +Note that Linux will not have this specific type of error, as it will usually tell you the dependent library you are missing. In that case, you most likely need to add the library to `LD_LIBRARY_PATH`. diff --git a/README.md b/README.md index 78f248652ef..8d4b4792c60 100644 --- a/README.md +++ b/README.md @@ -20,11 +20,11 @@ Welcome to the WPILib project. This repository contains the HAL, WPILibJ, and WP - [Running examples in simulation](#running-examples-in-simulation) - [Publishing](#publishing) - [Structure and Organization](#structure-and-organization) -- [Contributing to WPILib](#contributing-to-wpilib) +- [Contributing to WPILib](./CONTRIBUTING.md) ## WPILib Mission -The WPILib Mission is to enable FIRST Robotics teams to focus on writing game-specific software rather than focusing on hardware details - "raise the floor, don't lower the ceiling". We work to enable teams with limited programming knowledge and/or mentor experience to be as successful as possible, while not hampering the abilities of teams with more advanced programming capabilities. We support Kit of Parts control system components directly in the library. We also strive to keep parity between major features of each language (Java, C++, and NI's LabVIEW), so that teams aren't at a disadvantage for choosing a specific programming language. WPILib is an open source project, licensed under the BSD 3-clause license. You can find a copy of the license [here](LICENSE.md). +The WPILib Mission is to enable FIRST Robotics teams to focus on writing game-specific software rather than focusing on hardware details - "raise the floor, don't lower the ceiling". We work to enable teams with limited programming knowledge and/or mentor experience to be as successful as possible, while not hampering the abilities of teams with more advanced programming capabilities. We support Kit of Parts control system components directly in the library. We also strive to keep parity between major features of each language (Java, C++, Python, and NI's LabVIEW), so that teams aren't at a disadvantage for choosing a specific programming language. WPILib is an open source project, licensed under the BSD 3-clause license. You can find a copy of the license [here](LICENSE.md). # Quick Start @@ -41,11 +41,11 @@ Using Gradle makes building WPILib very straightforward. It only has a few depen ## Requirements -- [JDK 11](https://adoptium.net/temurin/releases/?version=11) +- [JDK 17](https://adoptium.net/temurin/releases/?version=17) - Note that the JRE is insufficient; the full JDK is required - - On Ubuntu, run `sudo apt install openjdk-11-jdk` - - On Windows, install the JDK 11 .msi from the link above - - On macOS, install the JDK 11 .pkg from the link above + - On Ubuntu, run `sudo apt install openjdk-17-jdk` + - On Windows, install the JDK 17 .msi from the link above + - On macOS, install the JDK 17 .pkg from the link above - C++ compiler - On Linux, install GCC 11 or greater - On Windows, install [Visual Studio Community 2022](https://visualstudio.microsoft.com/vs/community/) and select the C++ programming language during installation (Gradle can't use the build tools for Visual Studio) @@ -60,7 +60,7 @@ On macOS ARM, run `softwareupdate --install-rosetta`. This is necessary to be ab ## Setup -Clone the WPILib repository and follow the instructions above for installing any required tooling. +Clone the WPILib repository and follow the instructions above for installing any required tooling. The build process uses versioning information from git. Downloading the source is not sufficient to run the build. See the [styleguide README](https://github.com/wpilibsuite/styleguide/blob/main/README.md) for wpiformat setup instructions. @@ -179,7 +179,3 @@ The hal directory contains more C++ code meant to run on the roboRIO. HAL is an The upstream_utils directory contains scripts for updating copies of thirdparty code in the repository. The [styleguide repository](https://github.com/wpilibsuite/styleguide) contains our style guides for C++ and Java code. Anything submitted to the WPILib project needs to follow the code style guides outlined in there. For details about the style, please see the contributors document [here](CONTRIBUTING.md#coding-guidelines). - -# Contributing to WPILib - -See [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 3eaf7b99889..c561c8a322d 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -43,6 +43,7 @@ Team 254 Library wpilibj/src/main/java/edu/wpi/first/wpilibj/spline/SplineP Portable File Dialogs wpigui/src/main/native/include/portable-file-dialogs.h V8 export-template wpiutil/src/main/native/include/wpi/SymbolExports.h GCEM wpimath/src/main/native/thirdparty/gcem/include/ +Sleipnir wpimath/src/main/native/thirdparty/sleipnir ============================================================================== Google Test License @@ -1204,3 +1205,23 @@ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +================ +2024 Field Image +================ +2024 Field Image from MikLast: https://www.chiefdelphi.com/t/2024-crescendo-top-down-field-renders/447764 + +================ +Sleipnir License +================ +Copyright (c) Sleipnir contributors + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/apriltag/CMakeLists.txt b/apriltag/CMakeLists.txt index e86c47f5ed5..7c0e0000e4a 100644 --- a/apriltag/CMakeLists.txt +++ b/apriltag/CMakeLists.txt @@ -4,121 +4,148 @@ include(CompileWarnings) include(GenResources) include(FetchContent) -FetchContent_Declare( +fetchcontent_declare( apriltaglib - GIT_REPOSITORY https://github.com/wpilibsuite/apriltag.git - GIT_TAG 64be6ab26abf5e995321997fd0752c609a7e30f4 + GIT_REPOSITORY https://github.com/wpilibsuite/apriltag.git + GIT_TAG 64be6ab26abf5e995321997fd0752c609a7e30f4 ) # Don't use apriltag's CMakeLists.txt due to conflicting naming and JNI -FetchContent_GetProperties(apriltaglib) +fetchcontent_getproperties(apriltaglib) if(NOT apriltaglib_POPULATED) - FetchContent_Populate(apriltaglib) + fetchcontent_populate(apriltaglib) endif() aux_source_directory(${apriltaglib_SOURCE_DIR}/common APRILTAGLIB_COMMON_SRC) file(GLOB TAG_FILES ${apriltaglib_SOURCE_DIR}/tag*.c) -set(APRILTAGLIB_SRCS ${apriltaglib_SOURCE_DIR}/apriltag.c ${apriltaglib_SOURCE_DIR}/apriltag_pose.c ${apriltaglib_SOURCE_DIR}/apriltag_quad_thresh.c) +set(APRILTAGLIB_SRCS + ${apriltaglib_SOURCE_DIR}/apriltag.c + ${apriltaglib_SOURCE_DIR}/apriltag_pose.c + ${apriltaglib_SOURCE_DIR}/apriltag_quad_thresh.c +) file(GLOB apriltag_jni_src src/main/native/cpp/jni/AprilTagJNI.cpp) -if (WITH_JAVA) - find_package(Java REQUIRED) - find_package(JNI REQUIRED) - include(UseJava) - set(CMAKE_JAVA_COMPILE_FLAGS "-encoding" "UTF8" "-Xlint:unchecked") - - set(CMAKE_JNI_TARGET true) - - file(GLOB EJML_JARS "${WPILIB_BINARY_DIR}/wpimath/thirdparty/ejml/*.jar") - file(GLOB JACKSON_JARS "${WPILIB_BINARY_DIR}/wpiutil/thirdparty/jackson/*.jar") - find_file(OPENCV_JAR_FILE - NAMES opencv-${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.jar - PATHS ${OPENCV_JAVA_INSTALL_DIR} ${OpenCV_INSTALL_PATH}/bin ${OpenCV_INSTALL_PATH}/share/java - NO_DEFAULT_PATH) - - set(CMAKE_JAVA_INCLUDE_PATH apriltag.jar ${EJML_JARS} ${JACKSON_JARS}) - - file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java) - file(GLOB_RECURSE JAVA_RESOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} src/main/native/resources/*.json) - add_jar(apriltag_jar - SOURCES ${JAVA_SOURCES} - RESOURCES NAMESPACE "edu/wpi/first/apriltag" ${JAVA_RESOURCES} - INCLUDE_JARS wpimath_jar wpiunits_jar ${EJML_JARS} wpiutil_jar ${OPENCV_JAR_FILE} - OUTPUT_NAME apriltag - GENERATE_NATIVE_HEADERS apriltag_jni_headers) - - get_property(APRILTAG_JAR_FILE TARGET apriltag_jar PROPERTY JAR_FILE) - install(FILES ${APRILTAG_JAR_FILE} DESTINATION "${java_lib_dest}") - - set_property(TARGET apriltag_jar PROPERTY FOLDER "java") - - add_library(apriltagjni ${apriltag_jni_src}) - wpilib_target_warnings(apriltagjni) - target_link_libraries(apriltagjni PUBLIC apriltag) - - set_property(TARGET apriltagjni PROPERTY FOLDER "libraries") - - target_link_libraries(apriltagjni PRIVATE apriltag_jni_headers) - add_dependencies(apriltagjni apriltag_jar) - - install(TARGETS apriltagjni EXPORT apriltagjni) - +if(WITH_JAVA) + find_package(Java REQUIRED) + find_package(JNI REQUIRED) + include(UseJava) + set(CMAKE_JAVA_COMPILE_FLAGS "-encoding" "UTF8" "-Xlint:unchecked") + + set(CMAKE_JNI_TARGET true) + + file(GLOB EJML_JARS "${WPILIB_BINARY_DIR}/wpimath/thirdparty/ejml/*.jar") + file(GLOB JACKSON_JARS "${WPILIB_BINARY_DIR}/wpiutil/thirdparty/jackson/*.jar") + find_file( + OPENCV_JAR_FILE + NAMES opencv-${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.jar + PATHS + ${OPENCV_JAVA_INSTALL_DIR} + ${OpenCV_INSTALL_PATH}/bin + ${OpenCV_INSTALL_PATH}/share/java + NO_DEFAULT_PATH + ) + + set(CMAKE_JAVA_INCLUDE_PATH apriltag.jar ${EJML_JARS} ${JACKSON_JARS}) + + file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java) + file( + GLOB_RECURSE JAVA_RESOURCES + RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} + src/main/native/resources/*.json + ) + add_jar( + apriltag_jar + SOURCES ${JAVA_SOURCES} + RESOURCES + NAMESPACE "edu/wpi/first/apriltag" ${JAVA_RESOURCES} + INCLUDE_JARS wpimath_jar wpiunits_jar ${EJML_JARS} wpiutil_jar ${OPENCV_JAR_FILE} + OUTPUT_NAME apriltag + GENERATE_NATIVE_HEADERS apriltag_jni_headers + ) + + install_jar(apriltag_jar DESTINATION ${java_lib_dest}) + install_jar_exports(TARGETS apriltag_jar FILE apriltag_jar.cmake DESTINATION share/apriltag) + + add_library(apriltagjni ${apriltag_jni_src}) + wpilib_target_warnings(apriltagjni) + target_link_libraries(apriltagjni PUBLIC apriltag) + + set_property(TARGET apriltagjni PROPERTY FOLDER "libraries") + + target_link_libraries(apriltagjni PRIVATE apriltag_jni_headers) + add_dependencies(apriltagjni apriltag_jar) + + install(TARGETS apriltagjni EXPORT apriltagjni) + export(TARGETS apriltagjni FILE apriltagjni.cmake NAMESPACE apriltagjni::) endif() -if (WITH_JAVA_SOURCE) - find_package(Java REQUIRED) - include(UseJava) - file(GLOB APRILTAG_SOURCES src/main/java/edu/wpi/first/apriltag/*.java) - add_jar(apriltag_src_jar - RESOURCES NAMESPACE "edu/wpi/first/apriltag" ${APRILTAG_SOURCES} - NAMESPACE "edu/wpi/first/apriltag/jni" src/main/java/edu/wpi/first/apriltag/jni/AprilTagJNI.java - OUTPUT_NAME apriltag-sources) - - get_property(APRILTAG_SRC_JAR_FILE TARGET apriltag_src_jar PROPERTY JAR_FILE) - install(FILES ${APRILTAG_SRC_JAR_FILE} DESTINATION "${java_lib_dest}") - - set_property(TARGET apriltag_src_jar PROPERTY FOLDER "java") +if(WITH_JAVA_SOURCE) + find_package(Java REQUIRED) + include(UseJava) + file(GLOB APRILTAG_SOURCES src/main/java/edu/wpi/first/apriltag/*.java) + add_jar( + apriltag_src_jar + RESOURCES + NAMESPACE "edu/wpi/first/apriltag" ${APRILTAG_SOURCES} + NAMESPACE + "edu/wpi/first/apriltag/jni" + src/main/java/edu/wpi/first/apriltag/jni/AprilTagJNI.java + OUTPUT_NAME apriltag-sources + ) + + get_property(APRILTAG_SRC_JAR_FILE TARGET apriltag_src_jar PROPERTY JAR_FILE) + install(FILES ${APRILTAG_SRC_JAR_FILE} DESTINATION "${java_lib_dest}") + + set_property(TARGET apriltag_src_jar PROPERTY FOLDER "java") endif() generate_resources(src/main/native/resources/edu/wpi/first/apriltag generated/main/cpp APRILTAG frc apriltag_resources_src) file(GLOB apriltag_native_src src/main/native/cpp/*.cpp) -add_library(apriltag ${apriltag_native_src} ${apriltag_resources_src} ${APRILTAGLIB_SRCS} ${APRILTAGLIB_COMMON_SRC} ${TAG_FILES}) +add_library( + apriltag + ${apriltag_native_src} + ${apriltag_resources_src} + ${APRILTAGLIB_SRCS} + ${APRILTAGLIB_COMMON_SRC} + ${TAG_FILES} +) set_target_properties(apriltag PROPERTIES DEBUG_POSTFIX "d") set_property(TARGET apriltag PROPERTY FOLDER "libraries") target_compile_features(apriltag PUBLIC cxx_std_20) wpilib_target_warnings(apriltag) # disable warnings that apriltaglib can't handle -if (MSVC) - target_compile_options(apriltag PRIVATE /wd4018 /wd4005 /wd4996) +if(MSVC) + target_compile_options(apriltag PRIVATE /wd4018 /wd4005 /wd4996) else() - target_compile_options(apriltag PRIVATE -Wno-sign-compare -Wno-gnu-zero-variadic-macro-arguments -Wno-type-limits) + target_compile_options( + apriltag + PRIVATE -Wno-sign-compare -Wno-gnu-zero-variadic-macro-arguments -Wno-type-limits + ) endif() target_link_libraries(apriltag wpimath) -target_include_directories(apriltag PUBLIC - $ - $ - $) +target_include_directories( + apriltag + PUBLIC + $ + $ + $ +) install(TARGETS apriltag EXPORT apriltag) +export(TARGETS apriltag FILE apriltag.cmake NAMESPACE apriltag::) install(DIRECTORY src/main/native/include/ DESTINATION "${include_dest}/apriltag") -if (WITH_FLAT_INSTALL) - set (apriltag_config_dir ${wpilib_dest}) -else() - set (apriltag_config_dir share/apriltag) -endif() - -configure_file(apriltag-config.cmake.in ${WPILIB_BINARY_DIR}/apriltag-config.cmake ) -install(FILES ${WPILIB_BINARY_DIR}/apriltag-config.cmake DESTINATION ${apriltag_config_dir}) -install(EXPORT apriltag DESTINATION ${apriltag_config_dir}) +configure_file(apriltag-config.cmake.in ${WPILIB_BINARY_DIR}/apriltag-config.cmake) +install(FILES ${WPILIB_BINARY_DIR}/apriltag-config.cmake DESTINATION share/apriltag) +install(EXPORT apriltag DESTINATION share/apriltag) -if (WITH_TESTS) +if(WITH_TESTS) wpilib_add_test(apriltag src/test/native/cpp) target_include_directories(apriltag_test PRIVATE src/test/native/include) target_link_libraries(apriltag_test apriltag gmock_main) diff --git a/apriltag/README.md b/apriltag/README.md new file mode 100644 index 00000000000..5bf1d6778ed --- /dev/null +++ b/apriltag/README.md @@ -0,0 +1,28 @@ +# AprilTag + +## Adding new field to AprilTagFields + +### Adding field JSON + +1. Add a field layout CSV file to `src/main/native/resources/edu/wpi/first/apriltag` + 1. See docstring in `convert_apriltag_layouts.py` for more +2. Run `convert_apriltag_layouts.py` in the same directory as this readme to generate the JSON +3. That script overwrites all generated JSONs, so undo undesired changes if necessary +4. Update the field dimensions at the bottom of the JSON + 1. Length should be in meters from alliance wall to alliance wall + 2. Width should be in meters from inside guardrail plastic to plastic + +### Java updates + +1. Update `src/main/java/edu/wpi/first/apriltag/AprilTagFields.java` + 1. Add enum value for new field to `AprilTagFields` + 2. Update `AprilTagFields.kDefaultField` if necessary + +### C++ updates + +1. Update `src/main/native/include/frc/apriltag/AprilTagFields.h` + 1. Add enum value for new field to `AprilTagFields` + 2. Update `AprilTagFields::kDefaultField` if necessary +2. Update `src/main/native/cpp/AprilTagFields.cpp` + 1. Add resource getter prototype like `std::string_view GetResource_2024_crescendo_json()` + 2. Add case for new field to switch in `LoadAprilTagLayoutField()` diff --git a/apriltag/apriltag-config.cmake.in b/apriltag/apriltag-config.cmake.in index 7477a0eff63..9cb609335a5 100644 --- a/apriltag/apriltag-config.cmake.in +++ b/apriltag/apriltag-config.cmake.in @@ -5,3 +5,6 @@ include(CMakeFindDependencyMacro) @FILENAME_DEP_REPLACE@ include(${SELF_DIR}/apriltag.cmake) +if(@WITH_JAVA@) + include(${SELF_DIR}/apriltag_jar.cmake) +endif() diff --git a/apriltag/convert_apriltag_layouts.py b/apriltag/convert_apriltag_layouts.py new file mode 100755 index 00000000000..b89f666cf35 --- /dev/null +++ b/apriltag/convert_apriltag_layouts.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 + +""" +This script converts all AprilTag field layout CSV files in +src/main/native/resources/edu/wpi/first/apriltag to the JSON format +AprilTagFields expects. + +The input CSV has the following format: + +* Columns: ID, X, Y, Z, Rotation +* ID is a positive integer +* X, Y, and Z are decimal inches +* Rotation is yaw in degrees + +The values come from a table in the layout marking diagram (e.g., +https://firstfrc.blob.core.windows.net/frc2024/FieldAssets/2024LayoutMarkingDiagram.pdf). +""" + +import csv +import json +import os + +from wpimath import geometry, units +import numpy as np + + +def main(): + # Find AprilTag field layout CSVs + filenames = [ + os.path.join(dp, f) + for dp, dn, fn in os.walk("src/main/native/resources/edu/wpi/first/apriltag") + for f in fn + if f.endswith(".csv") + ] + + for filename in filenames: + json_data = {"tags": [], "field": {"length": 0.0, "width": 0.0}} + + # Read CSV and fill in JSON data + with open(filename, newline="") as csvfile: + reader = csv.reader(csvfile, delimiter=",") + + # Skip header + next(reader) + + for row in reader: + # Unpack row elements + id = int(row[0]) + x = float(row[1]) + y = float(row[2]) + z = float(row[3]) + rotation = float(row[4]) + + # Turn yaw into quaternion + q = geometry.Rotation3d( + units.radians(0.0), + units.radians(0.0), + units.degreesToRadians(rotation), + ).getQuaternion() + + json_data["tags"].append( + { + "ID": id, + "pose": { + "translation": { + "x": units.inchesToMeters(x), + "y": units.inchesToMeters(y), + "z": units.inchesToMeters(z), + }, + "rotation": { + "quaternion": { + "W": q.W(), + "X": q.X(), + "Y": q.Y(), + "Z": q.Z(), + } + }, + }, + } + ) + + # Write JSON + with open(filename.replace(".csv", ".json"), "w") as f: + json.dump(json_data, f, indent=2) + f.write("\n") + + +if __name__ == "__main__": + main() diff --git a/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTag.java b/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTag.java index 8e455f6dc95..9ee0207fedc 100644 --- a/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTag.java +++ b/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTag.java @@ -6,17 +6,28 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; +import edu.wpi.first.apriltag.jni.AprilTagJNI; import edu.wpi.first.math.geometry.Pose3d; +import edu.wpi.first.util.RawFrame; import java.util.Objects; +/** Represents an AprilTag's metadata. */ @SuppressWarnings("MemberName") public class AprilTag { + /** The tag's ID. */ @JsonProperty(value = "ID") public int ID; + /** The tag's pose. */ @JsonProperty(value = "pose") public Pose3d pose; + /** + * Constructs an AprilTag. + * + * @param ID The tag's ID. + * @param pose The tag's pose. + */ @SuppressWarnings("ParameterName") @JsonCreator public AprilTag( @@ -44,4 +55,28 @@ public int hashCode() { public String toString() { return "AprilTag(ID: " + ID + ", pose: " + pose + ")"; } + + /** + * Generates a RawFrame containing the apriltag with the id with family 16h5 passed in. + * + * @param id id + * @return A RawFrame containing the AprilTag image + */ + public static RawFrame generate16h5AprilTagImage(int id) { + RawFrame frame = new RawFrame(); + AprilTagJNI.generate16h5AprilTagImage(frame, frame.getNativeObj(), id); + return frame; + } + + /** + * Generates a RawFrame containing the apriltag with the id with family 36h11 passed in. + * + * @param id id + * @return A RawFrame containing the AprilTag image + */ + public static RawFrame generate36h11AprilTagImage(int id) { + RawFrame frame = new RawFrame(); + AprilTagJNI.generate36h11AprilTagImage(frame, frame.getNativeObj(), id); + return frame; + } } diff --git a/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagDetector.java b/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagDetector.java index c62edfa5076..a0774da171a 100644 --- a/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagDetector.java +++ b/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagDetector.java @@ -57,8 +57,21 @@ public static class Config { */ public boolean debug; + /** Default constructor. */ public Config() {} + /** + * Constructs a detector configuration. + * + * @param numThreads How many threads should be used for computation. + * @param quadDecimate Quad decimation. + * @param quadSigma What Gaussian blur should be applied to the segmented image (used for quad + * detection). + * @param refineEdges When true, the edges of the each quad are adjusted to "snap to" strong + * gradients nearby. + * @param decodeSharpening How much sharpening should be done to decoded images. + * @param debug Debug mode. + */ Config( int numThreads, float quadDecimate, @@ -139,8 +152,21 @@ public static class QuadThresholdParameters { */ public boolean deglitch; + /** Default constructor. */ public QuadThresholdParameters() {} + /** + * Constructs quad threshold parameters. + * + * @param minClusterPixels Threshold used to reject quads containing too few pixels. + * @param maxNumMaxima How many corner candidates to consider when segmenting a group of pixels + * into a quad. + * @param criticalAngle Critical angle, in radians. + * @param maxLineFitMSE When fitting lines to the contours, the maximum mean squared error + * allowed. + * @param minWhiteBlackDiff Minimum brightness offset. + * @param deglitch Whether the thresholded image be should be deglitched. + */ QuadThresholdParameters( int minClusterPixels, int maxNumMaxima, @@ -182,6 +208,7 @@ public boolean equals(Object obj) { } } + /** Constructs an AprilTagDetector. */ public AprilTagDetector() { m_native = AprilTagJNI.createDetector(); } diff --git a/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagFieldLayout.java b/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagFieldLayout.java index ce2336c6b15..f09d2626f1f 100644 --- a/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagFieldLayout.java +++ b/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagFieldLayout.java @@ -16,6 +16,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.io.UncheckedIOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; @@ -44,8 +45,11 @@ @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) public class AprilTagFieldLayout { + /** Common origin positions for the AprilTag coordinate system. */ public enum OriginPosition { + /** Blue alliance wall, right side. */ kBlueAllianceWallRightSide, + /** Red alliance wall, right side. */ kRedAllianceWallRightSide, } @@ -143,10 +147,10 @@ public double getFieldWidth() { * @param origin The predefined origin */ @JsonIgnore - public void setOrigin(OriginPosition origin) { + public final void setOrigin(OriginPosition origin) { switch (origin) { case kBlueAllianceWallRightSide: - setOrigin(new Pose3d()); + setOrigin(Pose3d.kZero); break; case kRedAllianceWallRightSide: setOrigin( @@ -168,7 +172,7 @@ public void setOrigin(OriginPosition origin) { * @param origin The new origin for tag transformations */ @JsonIgnore - public void setOrigin(Pose3d origin) { + public final void setOrigin(Pose3d origin) { m_origin = origin; } @@ -218,6 +222,29 @@ public void serialize(Path path) throws IOException { new ObjectMapper().writeValue(path.toFile(), this); } + /** + * Get an official {@link AprilTagFieldLayout}. + * + * @param field The loadable AprilTag field layout. + * @return AprilTagFieldLayout of the field. + * @throws UncheckedIOException If the layout does not exist. + */ + public static AprilTagFieldLayout loadField(AprilTagFields field) { + if (field.m_fieldLayout == null) { + try { + field.m_fieldLayout = loadFromResource(field.m_resourceFile); + } catch (IOException e) { + throw new UncheckedIOException( + "Could not load AprilTagFieldLayout from " + field.m_resourceFile, e); + } + } + // Copy layout because the layout's origin is mutable + return new AprilTagFieldLayout( + field.m_fieldLayout.getTags(), + field.m_fieldLayout.getFieldLength(), + field.m_fieldLayout.getFieldWidth()); + } + /** * Deserializes a field layout from a resource within a internal jar file. * diff --git a/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagFields.java b/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagFields.java index dda8d343c52..016c982fe7e 100644 --- a/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagFields.java +++ b/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagFields.java @@ -4,20 +4,28 @@ package edu.wpi.first.apriltag; -import java.io.IOException; import java.io.UncheckedIOException; +/** Loadable AprilTag field layouts. */ public enum AprilTagFields { + /** 2022 Rapid React. */ k2022RapidReact("2022-rapidreact.json"), - k2023ChargedUp("2023-chargedup.json"); + /** 2023 Charged Up. */ + k2023ChargedUp("2023-chargedup.json"), + /** 2024 Crescendo. */ + k2024Crescendo("2024-crescendo.json"); + /** Base resource directory. */ public static final String kBaseResourceDir = "/edu/wpi/first/apriltag/"; /** Alias to the current game. */ - public static final AprilTagFields kDefaultField = k2023ChargedUp; + public static final AprilTagFields kDefaultField = k2024Crescendo; + /** Resource filename. */ public final String m_resourceFile; + AprilTagFieldLayout m_fieldLayout; + AprilTagFields(String resourceFile) { m_resourceFile = kBaseResourceDir + resourceFile; } @@ -27,13 +35,10 @@ public enum AprilTagFields { * * @return AprilTagFieldLayout of the field * @throws UncheckedIOException If the layout does not exist + * @deprecated Use {@link AprilTagFieldLayout#loadField(AprilTagFields)} instead. */ + @Deprecated(forRemoval = true, since = "2025") public AprilTagFieldLayout loadAprilTagLayoutField() { - try { - return AprilTagFieldLayout.loadFromResource(m_resourceFile); - } catch (IOException e) { - throw new UncheckedIOException( - "Could not load AprilTagFieldLayout from " + m_resourceFile, e); - } + return AprilTagFieldLayout.loadField(this); } } diff --git a/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagPoseEstimator.java b/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagPoseEstimator.java index 2b7f68a5267..182f394a319 100644 --- a/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagPoseEstimator.java +++ b/apriltag/src/main/java/edu/wpi/first/apriltag/AprilTagPoseEstimator.java @@ -29,10 +29,19 @@ public Config(double tagSize, double fx, double fy, double cx, double cy) { this.cy = cy; } + /** Tag size, in meters. */ public double tagSize; + + /** Camera horizontal focal length, in pixels. */ public double fx; + + /** Camera vertical focal length, in pixels. */ public double fy; + + /** Camera horizontal focal center, in pixels. */ public double cx; + + /** Camera vertical focal center, in pixels. */ public double cy; @Override diff --git a/apriltag/src/main/java/edu/wpi/first/apriltag/jni/AprilTagJNI.java b/apriltag/src/main/java/edu/wpi/first/apriltag/jni/AprilTagJNI.java index f0a23fce41b..6aabbf9ddad 100644 --- a/apriltag/src/main/java/edu/wpi/first/apriltag/jni/AprilTagJNI.java +++ b/apriltag/src/main/java/edu/wpi/first/apriltag/jni/AprilTagJNI.java @@ -8,25 +8,41 @@ import edu.wpi.first.apriltag.AprilTagDetector; import edu.wpi.first.apriltag.AprilTagPoseEstimate; import edu.wpi.first.math.geometry.Transform3d; +import edu.wpi.first.util.RawFrame; import edu.wpi.first.util.RuntimeLoader; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; +/** AprilTag JNI. */ public class AprilTagJNI { static boolean libraryLoaded = false; static RuntimeLoader loader = null; + /** Sets whether JNI should be loaded in the static block. */ public static class Helper { private static AtomicBoolean extractOnStaticLoad = new AtomicBoolean(true); + /** + * Returns true if the JNI should be loaded in the static block. + * + * @return True if the JNI should be loaded in the static block. + */ public static boolean getExtractOnStaticLoad() { return extractOnStaticLoad.get(); } + /** + * Sets whether the JNI should be loaded in the static block. + * + * @param load Whether the JNI should be loaded in the static block. + */ public static void setExtractOnStaticLoad(boolean load) { extractOnStaticLoad.set(load); } + + /** Utility class. */ + private Helper() {} } static { @@ -189,4 +205,25 @@ public static native Transform3d estimatePose( double fy, double cx, double cy); + + /** + * Generates a RawFrame containing the apriltag with the id with family 16h5 passed in. + * + * @param frameObj generated frame (output parameter). + * @param frame raw frame handle + * @param id id + */ + public static native void generate16h5AprilTagImage(RawFrame frameObj, long frame, int id); + + /** + * Generates a RawFrame containing the apriltag with the id with family 36h11 passed in. + * + * @param frameObj generated frame (output parameter). + * @param frame raw frame handle + * @param id id + */ + public static native void generate36h11AprilTagImage(RawFrame frameObj, long frame, int id); + + /** Utility class. */ + private AprilTagJNI() {} } diff --git a/apriltag/src/main/native/cpp/AprilTag.cpp b/apriltag/src/main/native/cpp/AprilTag.cpp index 38055736e1e..99ac81b49cf 100644 --- a/apriltag/src/main/native/cpp/AprilTag.cpp +++ b/apriltag/src/main/native/cpp/AprilTag.cpp @@ -4,10 +4,53 @@ #include "frc/apriltag/AprilTag.h" +#include + #include +#ifdef _WIN32 +#pragma warning(disable : 4200) +#elif defined(__clang__) +#pragma clang diagnostic ignored "-Wc99-extensions" +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wpedantic" +#endif + +#include "apriltag.h" +#include "tag16h5.h" +#include "tag36h11.h" + using namespace frc; +static bool FamilyToImage(wpi::RawFrame* frame, apriltag_family_t* family, + int id) { + image_u8_t* image = apriltag_to_image(family, id); + size_t totalDataSize = image->height * image->stride; + bool rv = frame->Reserve(totalDataSize); + std::memcpy(frame->data, image->buf, totalDataSize); + frame->size = totalDataSize; + frame->width = image->width; + frame->height = image->height; + frame->stride = image->stride; + frame->pixelFormat = WPI_PIXFMT_GRAY; + image_u8_destroy(image); + return rv; +} + +bool AprilTag::Generate36h11AprilTagImage(wpi::RawFrame* frame, int id) { + apriltag_family_t* tagFamily = tag36h11_create(); + bool rv = FamilyToImage(frame, tagFamily, id); + tag36h11_destroy(tagFamily); + return rv; +} + +bool AprilTag::Generate16h5AprilTagImage(wpi::RawFrame* frame, int id) { + apriltag_family_t* tagFamily = tag16h5_create(); + bool rv = FamilyToImage(frame, tagFamily, id); + tag16h5_destroy(tagFamily); + return rv; +} + void frc::to_json(wpi::json& json, const AprilTag& apriltag) { json = wpi::json{{"ID", apriltag.ID}, {"pose", apriltag.pose}}; } diff --git a/apriltag/src/main/native/cpp/AprilTagFieldLayout.cpp b/apriltag/src/main/native/cpp/AprilTagFieldLayout.cpp index 59b30ec30eb..c0b4ca233bb 100644 --- a/apriltag/src/main/native/cpp/AprilTagFieldLayout.cpp +++ b/apriltag/src/main/native/cpp/AprilTagFieldLayout.cpp @@ -125,3 +125,37 @@ void frc::from_json(const wpi::json& json, AprilTagFieldLayout& layout) { layout.m_fieldWidth = units::meter_t{json.at("field").at("width").get()}; } + +// Use namespace declaration for forward declaration +namespace frc { + +// C++ generated from resource files +std::string_view GetResource_2022_rapidreact_json(); +std::string_view GetResource_2023_chargedup_json(); +std::string_view GetResource_2024_crescendo_json(); + +} // namespace frc + +AprilTagFieldLayout AprilTagFieldLayout::LoadField(AprilTagField field) { + std::string_view fieldString; + switch (field) { + case AprilTagField::k2022RapidReact: + fieldString = GetResource_2022_rapidreact_json(); + break; + case AprilTagField::k2023ChargedUp: + fieldString = GetResource_2023_chargedup_json(); + break; + case AprilTagField::k2024Crescendo: + fieldString = GetResource_2024_crescendo_json(); + break; + case AprilTagField::kNumFields: + throw std::invalid_argument("Invalid Field"); + } + + wpi::json json = wpi::json::parse(fieldString); + return json.get(); +} + +AprilTagFieldLayout frc::LoadAprilTagLayoutField(AprilTagField field) { + return AprilTagFieldLayout::LoadField(field); +} diff --git a/apriltag/src/main/native/cpp/AprilTagFields.cpp b/apriltag/src/main/native/cpp/AprilTagFields.cpp deleted file mode 100644 index 2f929378ba2..00000000000 --- a/apriltag/src/main/native/cpp/AprilTagFields.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "frc/apriltag/AprilTagFields.h" - -#include - -namespace frc { - -// C++ generated from resource files -std::string_view GetResource_2022_rapidreact_json(); -std::string_view GetResource_2023_chargedup_json(); - -AprilTagFieldLayout LoadAprilTagLayoutField(AprilTagField field) { - std::string_view fieldString; - switch (field) { - case AprilTagField::k2022RapidReact: - fieldString = GetResource_2022_rapidreact_json(); - break; - case AprilTagField::k2023ChargedUp: - fieldString = GetResource_2023_chargedup_json(); - break; - case AprilTagField::kNumFields: - throw std::invalid_argument("Invalid Field"); - } - - wpi::json json = wpi::json::parse(fieldString); - return json.get(); -} - -} // namespace frc diff --git a/apriltag/src/main/native/cpp/jni/AprilTagJNI.cpp b/apriltag/src/main/native/cpp/jni/AprilTagJNI.cpp index c957b2da8d9..b68b131087d 100644 --- a/apriltag/src/main/native/cpp/jni/AprilTagJNI.cpp +++ b/apriltag/src/main/native/cpp/jni/AprilTagJNI.cpp @@ -2,12 +2,17 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +#include + #include #include +#define WPI_RAWFRAME_JNI +#include #include #include "edu_wpi_first_apriltag_jni_AprilTagJNI.h" +#include "frc/apriltag/AprilTag.h" #include "frc/apriltag/AprilTagDetector.h" #include "frc/apriltag/AprilTagPoseEstimator.h" @@ -24,6 +29,7 @@ static JClass quaternionCls; static JClass rotation3dCls; static JClass transform3dCls; static JClass translation3dCls; +static JClass rawFrameCls; static JException illegalArgEx; static JException nullPointerEx; @@ -36,7 +42,8 @@ static const JClassInit classes[] = { {"edu/wpi/first/math/geometry/Quaternion", &quaternionCls}, {"edu/wpi/first/math/geometry/Rotation3d", &rotation3dCls}, {"edu/wpi/first/math/geometry/Transform3d", &transform3dCls}, - {"edu/wpi/first/math/geometry/Translation3d", &translation3dCls}}; + {"edu/wpi/first/math/geometry/Translation3d", &translation3dCls}, + {"edu/wpi/first/util/RawFrame", &rawFrameCls}}; static const JExceptionInit exceptions[] = { {"java/lang/IllegalArgumentException", &illegalArgEx}, @@ -587,4 +594,41 @@ Java_edu_wpi_first_apriltag_jni_AprilTagJNI_estimatePose return MakeJObject(env, estimator.Estimate(harr, carr)); } +/* + * Class: edu_wpi_first_apriltag_jni_AprilTagJNI + * Method: generate16h5AprilTagImage + * Signature: (Ljava/lang/Object;JI)V + */ +JNIEXPORT void JNICALL +Java_edu_wpi_first_apriltag_jni_AprilTagJNI_generate16h5AprilTagImage + (JNIEnv* env, jclass, jobject frameObj, jlong framePtr, jint id) +{ + auto* frame = reinterpret_cast(framePtr); + if (!frame) { + nullPointerEx.Throw(env, "frame is null"); + return; + } + bool newData = AprilTag::Generate16h5AprilTagImage(frame, id); + wpi::SetFrameData(env, rawFrameCls, frameObj, *frame, newData); +} + +/* + * Class: edu_wpi_first_apriltag_jni_AprilTagJNI + * Method: generate36h11AprilTagImage + * Signature: (Ljava/lang/Object;JI)V + */ +JNIEXPORT void JNICALL +Java_edu_wpi_first_apriltag_jni_AprilTagJNI_generate36h11AprilTagImage + (JNIEnv* env, jclass, jobject frameObj, jlong framePtr, jint id) +{ + auto* frame = reinterpret_cast(framePtr); + if (!frame) { + nullPointerEx.Throw(env, "frame is null"); + return; + } + // function might reallocate + bool newData = AprilTag::Generate36h11AprilTagImage(frame, id); + wpi::SetFrameData(env, rawFrameCls, frameObj, *frame, newData); +} + } // extern "C" diff --git a/apriltag/src/main/native/include/frc/apriltag/AprilTag.h b/apriltag/src/main/native/include/frc/apriltag/AprilTag.h index ba2453020fd..a9ef78cc458 100644 --- a/apriltag/src/main/native/include/frc/apriltag/AprilTag.h +++ b/apriltag/src/main/native/include/frc/apriltag/AprilTag.h @@ -4,6 +4,7 @@ #pragma once +#include #include #include @@ -11,15 +12,20 @@ namespace frc { +/** + * Represents an AprilTag's metadata. + */ struct WPILIB_DLLEXPORT AprilTag { + /// The tag's ID. int ID; + /// The tag's pose. Pose3d pose; - /** - * Checks equality between this AprilTag and another object. - */ bool operator==(const AprilTag&) const = default; + + static bool Generate36h11AprilTagImage(wpi::RawFrame* frame, int id); + static bool Generate16h5AprilTagImage(wpi::RawFrame* frame, int id); }; WPILIB_DLLEXPORT diff --git a/apriltag/src/main/native/include/frc/apriltag/AprilTagFieldLayout.h b/apriltag/src/main/native/include/frc/apriltag/AprilTagFieldLayout.h index 2b57d2ce4aa..c2e73c78c4d 100644 --- a/apriltag/src/main/native/include/frc/apriltag/AprilTagFieldLayout.h +++ b/apriltag/src/main/native/include/frc/apriltag/AprilTagFieldLayout.h @@ -14,6 +14,7 @@ #include #include "frc/apriltag/AprilTag.h" +#include "frc/apriltag/AprilTagFields.h" #include "frc/geometry/Pose3d.h" namespace frc { @@ -38,11 +39,24 @@ namespace frc { * towards the opposing alliance). */ class WPILIB_DLLEXPORT AprilTagFieldLayout { public: + /** + * Common origin positions for the AprilTag coordinate system. + */ enum class OriginPosition { + /// Blue alliance wall, right side. kBlueAllianceWallRightSide, + /// Red alliance wall, right side. kRedAllianceWallRightSide, }; + /** + * Loads an AprilTagFieldLayout from a predefined field + * + * @param field The predefined field + * @return AprilTagFieldLayout of the field + */ + static AprilTagFieldLayout LoadField(AprilTagField field); + AprilTagFieldLayout() = default; /** @@ -147,4 +161,15 @@ void to_json(wpi::json& json, const AprilTagFieldLayout& layout); WPILIB_DLLEXPORT void from_json(const wpi::json& json, AprilTagFieldLayout& layout); +/** + * Loads an AprilTagFieldLayout from a predefined field + * + * @param field The predefined field + * @return AprilTagFieldLayout of the field + * @deprecated Use AprilTagFieldLayout::LoadField() instead + */ +[[deprecated("Use AprilTagFieldLayout::LoadField() instead")]] +WPILIB_DLLEXPORT AprilTagFieldLayout +LoadAprilTagLayoutField(AprilTagField field); + } // namespace frc diff --git a/apriltag/src/main/native/include/frc/apriltag/AprilTagFields.h b/apriltag/src/main/native/include/frc/apriltag/AprilTagFields.h index 4bab29919c7..6ef0930e9b6 100644 --- a/apriltag/src/main/native/include/frc/apriltag/AprilTagFields.h +++ b/apriltag/src/main/native/include/frc/apriltag/AprilTagFields.h @@ -8,25 +8,22 @@ #include -#include "frc/apriltag/AprilTagFieldLayout.h" - namespace frc { +/** + * Loadable AprilTag field layouts. + */ enum class AprilTagField { + /// 2022 Rapid React. k2022RapidReact, + /// 2023 Charged Up. k2023ChargedUp, + /// 2024 Crescendo. + k2024Crescendo, // This is a placeholder for denoting the last supported field. This should // always be the last entry in the enum and should not be used by users kNumFields, }; -/** - * Loads an AprilTagFieldLayout from a predefined field - * - * @param field The predefined field - */ -WPILIB_DLLEXPORT AprilTagFieldLayout -LoadAprilTagLayoutField(AprilTagField field); - } // namespace frc diff --git a/apriltag/src/main/native/resources/edu/wpi/first/apriltag/2024-crescendo.csv b/apriltag/src/main/native/resources/edu/wpi/first/apriltag/2024-crescendo.csv new file mode 100644 index 00000000000..cf570ce1b51 --- /dev/null +++ b/apriltag/src/main/native/resources/edu/wpi/first/apriltag/2024-crescendo.csv @@ -0,0 +1,17 @@ +ID,X,Y,Z,Rotation +1,593.68,9.68,53.38,120 +2,637.21,34.79,53.38,120 +3,652.73,196.17,57.13,180 +4,652.73,218.42,57.13,180 +5,578.77,323.00,53.38,270 +6,72.5,323.00,53.38,270 +7,-1.50,218.42,57.13,0 +8,-1.50,196.17,57.13,0 +9,14.02,34.79,53.38,60 +10,57.54,9.68,53.38,60 +11,468.69,146.19,52.00,300 +12,468.69,177.10,52.00,60 +13,441.74,161.62,52.00,180 +14,209.48,161.62,52.00,0 +15,182.73,177.10,52.00,120 +16,182.73,146.19,52.00,240 diff --git a/apriltag/src/main/native/resources/edu/wpi/first/apriltag/2024-crescendo.json b/apriltag/src/main/native/resources/edu/wpi/first/apriltag/2024-crescendo.json new file mode 100644 index 00000000000..8cb837a5023 --- /dev/null +++ b/apriltag/src/main/native/resources/edu/wpi/first/apriltag/2024-crescendo.json @@ -0,0 +1,296 @@ +{ + "tags": [ + { + "ID": 1, + "pose": { + "translation": { + "x": 15.079471999999997, + "y": 0.24587199999999998, + "z": 1.355852 + }, + "rotation": { + "quaternion": { + "W": 0.5000000000000001, + "X": 0.0, + "Y": 0.0, + "Z": 0.8660254037844386 + } + } + } + }, + { + "ID": 2, + "pose": { + "translation": { + "x": 16.185134, + "y": 0.883666, + "z": 1.355852 + }, + "rotation": { + "quaternion": { + "W": 0.5000000000000001, + "X": 0.0, + "Y": 0.0, + "Z": 0.8660254037844386 + } + } + } + }, + { + "ID": 3, + "pose": { + "translation": { + "x": 16.579342, + "y": 4.982717999999999, + "z": 1.4511020000000001 + }, + "rotation": { + "quaternion": { + "W": 6.123233995736766e-17, + "X": 0.0, + "Y": 0.0, + "Z": 1.0 + } + } + } + }, + { + "ID": 4, + "pose": { + "translation": { + "x": 16.579342, + "y": 5.547867999999999, + "z": 1.4511020000000001 + }, + "rotation": { + "quaternion": { + "W": 6.123233995736766e-17, + "X": 0.0, + "Y": 0.0, + "Z": 1.0 + } + } + } + }, + { + "ID": 5, + "pose": { + "translation": { + "x": 14.700757999999999, + "y": 8.2042, + "z": 1.355852 + }, + "rotation": { + "quaternion": { + "W": -0.7071067811865475, + "X": -0.0, + "Y": 0.0, + "Z": 0.7071067811865476 + } + } + } + }, + { + "ID": 6, + "pose": { + "translation": { + "x": 1.8415, + "y": 8.2042, + "z": 1.355852 + }, + "rotation": { + "quaternion": { + "W": -0.7071067811865475, + "X": -0.0, + "Y": 0.0, + "Z": 0.7071067811865476 + } + } + } + }, + { + "ID": 7, + "pose": { + "translation": { + "x": -0.038099999999999995, + "y": 5.547867999999999, + "z": 1.4511020000000001 + }, + "rotation": { + "quaternion": { + "W": 1.0, + "X": 0.0, + "Y": 0.0, + "Z": 0.0 + } + } + } + }, + { + "ID": 8, + "pose": { + "translation": { + "x": -0.038099999999999995, + "y": 4.982717999999999, + "z": 1.4511020000000001 + }, + "rotation": { + "quaternion": { + "W": 1.0, + "X": 0.0, + "Y": 0.0, + "Z": 0.0 + } + } + } + }, + { + "ID": 9, + "pose": { + "translation": { + "x": 0.356108, + "y": 0.883666, + "z": 1.355852 + }, + "rotation": { + "quaternion": { + "W": 0.8660254037844387, + "X": 0.0, + "Y": 0.0, + "Z": 0.49999999999999994 + } + } + } + }, + { + "ID": 10, + "pose": { + "translation": { + "x": 1.4615159999999998, + "y": 0.24587199999999998, + "z": 1.355852 + }, + "rotation": { + "quaternion": { + "W": 0.8660254037844387, + "X": 0.0, + "Y": 0.0, + "Z": 0.49999999999999994 + } + } + } + }, + { + "ID": 11, + "pose": { + "translation": { + "x": 11.904726, + "y": 3.7132259999999997, + "z": 1.3208 + }, + "rotation": { + "quaternion": { + "W": -0.8660254037844387, + "X": -0.0, + "Y": 0.0, + "Z": 0.49999999999999994 + } + } + } + }, + { + "ID": 12, + "pose": { + "translation": { + "x": 11.904726, + "y": 4.49834, + "z": 1.3208 + }, + "rotation": { + "quaternion": { + "W": 0.8660254037844387, + "X": 0.0, + "Y": 0.0, + "Z": 0.49999999999999994 + } + } + } + }, + { + "ID": 13, + "pose": { + "translation": { + "x": 11.220196, + "y": 4.105148, + "z": 1.3208 + }, + "rotation": { + "quaternion": { + "W": 6.123233995736766e-17, + "X": 0.0, + "Y": 0.0, + "Z": 1.0 + } + } + } + }, + { + "ID": 14, + "pose": { + "translation": { + "x": 5.320792, + "y": 4.105148, + "z": 1.3208 + }, + "rotation": { + "quaternion": { + "W": 1.0, + "X": 0.0, + "Y": 0.0, + "Z": 0.0 + } + } + } + }, + { + "ID": 15, + "pose": { + "translation": { + "x": 4.641342, + "y": 4.49834, + "z": 1.3208 + }, + "rotation": { + "quaternion": { + "W": 0.5000000000000001, + "X": 0.0, + "Y": 0.0, + "Z": 0.8660254037844386 + } + } + } + }, + { + "ID": 16, + "pose": { + "translation": { + "x": 4.641342, + "y": 3.7132259999999997, + "z": 1.3208 + }, + "rotation": { + "quaternion": { + "W": -0.4999999999999998, + "X": -0.0, + "Y": 0.0, + "Z": 0.8660254037844387 + } + } + } + } + ], + "field": { + "length": 16.541, + "width": 8.211 + } +} diff --git a/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagDetectorTest.java b/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagDetectorTest.java index dc97c1bb7e5..2ace7a0ef69 100644 --- a/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagDetectorTest.java +++ b/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagDetectorTest.java @@ -158,7 +158,7 @@ void testDecodeAndPose() { var estimator = new AprilTagPoseEstimator(new AprilTagPoseEstimator.Config(0.2, 500, 500, 320, 240)); AprilTagPoseEstimate est = estimator.estimateOrthogonalIteration(results[0], 200); - assertEquals(new Transform3d(), est.pose2); + assertEquals(Transform3d.kZero, est.pose2); Transform3d pose = estimator.estimate(results[0]); assertEquals(est.pose1, pose); } finally { diff --git a/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagGenerationTest.java b/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagGenerationTest.java new file mode 100644 index 00000000000..3f3a9e65d98 --- /dev/null +++ b/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagGenerationTest.java @@ -0,0 +1,34 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.apriltag; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import edu.wpi.first.util.PixelFormat; +import org.junit.jupiter.api.Test; + +class AprilTagGenerationTest { + @Test + void test36h11() { + var frame = AprilTag.generate36h11AprilTagImage(1); + assertEquals(PixelFormat.kGray, frame.getPixelFormat()); + assertEquals(10, frame.getWidth()); + assertEquals(10, frame.getHeight()); + int stride = frame.getStride(); + assertEquals(stride * 10, frame.getSize()); + // check the diagonal values + var data = frame.getData(); + assertEquals(-1, data.get(stride * 0 + 0)); // outer border is white + assertEquals(0, data.get(stride * 1 + 1)); // inner border is black + assertEquals(-1, data.get(stride * 2 + 2)); + assertEquals(-1, data.get(stride * 3 + 3)); + assertEquals(-1, data.get(stride * 4 + 4)); + assertEquals(0, data.get(stride * 5 + 5)); + assertEquals(0, data.get(stride * 6 + 6)); + assertEquals(-1, data.get(stride * 7 + 7)); + assertEquals(0, data.get(stride * 8 + 8)); // inner border + assertEquals(-1, data.get(stride * 9 + 9)); // outer border + } +} diff --git a/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagPoseSetOriginTest.java b/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagPoseSetOriginTest.java index 999fe8717de..8f373b363d2 100644 --- a/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagPoseSetOriginTest.java +++ b/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagPoseSetOriginTest.java @@ -19,7 +19,7 @@ void transformationMatches() { var layout = new AprilTagFieldLayout( List.of( - new AprilTag(1, new Pose3d(new Translation3d(0, 0, 0), new Rotation3d(0, 0, 0))), + new AprilTag(1, Pose3d.kZero), new AprilTag( 2, new Pose3d( @@ -40,7 +40,7 @@ void transformationMatches() { new Pose3d( new Translation3d( Units.feetToMeters(50.0), Units.feetToMeters(23.0), Units.feetToMeters(4)), - new Rotation3d(0.0, 0.0, 0)), + Rotation3d.kZero), layout.getTagPose(2).orElse(null)); } } diff --git a/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagSerializationTest.java b/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagSerializationTest.java index 5f5d1fde66e..df734f3766e 100644 --- a/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagSerializationTest.java +++ b/apriltag/src/test/java/edu/wpi/first/apriltag/AprilTagSerializationTest.java @@ -20,8 +20,8 @@ void deserializeMatches() { var layout = new AprilTagFieldLayout( List.of( - new AprilTag(1, new Pose3d(0, 0, 0, new Rotation3d(0, 0, 0))), - new AprilTag(3, new Pose3d(0, 1, 0, new Rotation3d(0, 0, 0)))), + new AprilTag(1, Pose3d.kZero), + new AprilTag(3, new Pose3d(0, 1, 0, Rotation3d.kZero))), Units.feetToMeters(54.0), Units.feetToMeters(27.0)); diff --git a/apriltag/src/test/java/edu/wpi/first/apriltag/LoadConfigTest.java b/apriltag/src/test/java/edu/wpi/first/apriltag/LoadConfigTest.java index 901c72bd89b..66923f4401c 100644 --- a/apriltag/src/test/java/edu/wpi/first/apriltag/LoadConfigTest.java +++ b/apriltag/src/test/java/edu/wpi/first/apriltag/LoadConfigTest.java @@ -12,7 +12,6 @@ import edu.wpi.first.math.geometry.Pose3d; import edu.wpi.first.math.geometry.Rotation3d; import edu.wpi.first.math.util.Units; -import java.io.IOException; import java.util.Optional; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -23,13 +22,14 @@ class LoadConfigTest { @ParameterizedTest @EnumSource(AprilTagFields.class) void testLoad(AprilTagFields field) { - AprilTagFieldLayout layout = Assertions.assertDoesNotThrow(field::loadAprilTagLayoutField); + AprilTagFieldLayout layout = + Assertions.assertDoesNotThrow(() -> AprilTagFieldLayout.loadField(field)); assertNotNull(layout); } @Test - void test2022RapidReact() throws IOException { - AprilTagFieldLayout layout = AprilTagFields.k2022RapidReact.loadAprilTagLayoutField(); + void test2022RapidReact() { + AprilTagFieldLayout layout = AprilTagFieldLayout.loadField(AprilTagFields.k2022RapidReact); // Blue Hangar Truss - Hub Pose3d expectedPose = @@ -37,7 +37,7 @@ void test2022RapidReact() throws IOException { Units.inchesToMeters(127.272), Units.inchesToMeters(216.01), Units.inchesToMeters(67.932), - new Rotation3d(0, 0, 0)); + Rotation3d.kZero); Optional maybePose = layout.getTagPose(1); assertTrue(maybePose.isPresent()); assertEquals(expectedPose, maybePose.get()); diff --git a/apriltag/src/test/native/cpp/LoadConfigTest.cpp b/apriltag/src/test/native/cpp/LoadConfigTest.cpp index c3ff7c03c40..ba6fe81ff96 100644 --- a/apriltag/src/test/native/cpp/LoadConfigTest.cpp +++ b/apriltag/src/test/native/cpp/LoadConfigTest.cpp @@ -4,6 +4,7 @@ #include +#include "frc/apriltag/AprilTagFieldLayout.h" #include "frc/apriltag/AprilTagFields.h" namespace frc { @@ -20,7 +21,7 @@ std::vector GetAllFields() { TEST(AprilTagFieldsTest, TestLoad2022RapidReact) { AprilTagFieldLayout layout = - LoadAprilTagLayoutField(AprilTagField::k2022RapidReact); + AprilTagFieldLayout::LoadField(AprilTagField::k2022RapidReact); // Blue Hangar Truss - Hub auto expectedPose = @@ -53,7 +54,7 @@ class AllFieldsFixtureTest : public ::testing::TestWithParam {}; TEST_P(AllFieldsFixtureTest, CheckEntireEnum) { AprilTagField field = GetParam(); - EXPECT_NO_THROW(LoadAprilTagLayoutField(field)); + EXPECT_NO_THROW(AprilTagFieldLayout::LoadField(field)); } INSTANTIATE_TEST_SUITE_P(ValuesEnumTestInstTests, AllFieldsFixtureTest, diff --git a/build.gradle b/build.gradle index b1c3ca2e6df..013c2e2a82b 100644 --- a/build.gradle +++ b/build.gradle @@ -23,7 +23,7 @@ plugins { id 'net.ltgt.errorprone' version '3.1.0' apply false id 'com.github.johnrengelman.shadow' version '8.1.1' apply false id 'com.diffplug.spotless' version '6.20.0' apply false - id 'com.github.spotbugs' version '5.1.3' apply false + id 'com.github.spotbugs' version '6.0.2' apply false id 'com.google.protobuf' version '0.9.3' apply false } @@ -50,6 +50,9 @@ buildScan { publishAlways() } +import com.github.spotbugs.snom.Effort +ext.spotbugsEffort = Effort.MAX + ext.licenseFile = files("$rootDir/LICENSE.md", "$rootDir/ThirdPartyNotices.txt") if (project.hasProperty("publishVersion")) { @@ -111,8 +114,8 @@ subprojects { plugins.withType(JavaPlugin) { java { - sourceCompatibility = 11 - targetCompatibility = 11 + sourceCompatibility = 17 + targetCompatibility = 17 } } @@ -171,5 +174,5 @@ ext.getCurrentArch = { } wrapper { - gradleVersion = '8.4' + gradleVersion = '8.5' } diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index 1e5d02cdee3..a4dc19848fd 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -9,5 +9,5 @@ repositories { } } dependencies { - implementation "edu.wpi.first:native-utils:2024.3.2" + implementation "edu.wpi.first:native-utils:2024.7.2" } diff --git a/cameraserver/CMakeLists.txt b/cameraserver/CMakeLists.txt index 177e009eef9..41d132793b6 100644 --- a/cameraserver/CMakeLists.txt +++ b/cameraserver/CMakeLists.txt @@ -3,10 +3,10 @@ project(cameraserver) include(CompileWarnings) include(AddTest) -find_package( OpenCV REQUIRED ) +find_package(OpenCV REQUIRED) # Java bindings -if (WITH_JAVA) +if(WITH_JAVA) find_package(Java REQUIRED) include(UseJava) set(CMAKE_JAVA_COMPILE_FLAGS "-encoding" "UTF8" "-Xlint:unchecked") @@ -15,28 +15,42 @@ if (WITH_JAVA) set(OPENCV_JAVA_INSTALL_DIR ${OpenCV_INSTALL_PATH}/share/OpenCV/java/) - find_file(OPENCV_JAR_FILE NAMES opencv-${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.jar PATHS ${OPENCV_JAVA_INSTALL_DIR} ${OpenCV_INSTALL_PATH}/bin NO_DEFAULT_PATH) + find_file( + OPENCV_JAR_FILE + NAMES opencv-${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.jar + PATHS ${OPENCV_JAVA_INSTALL_DIR} ${OpenCV_INSTALL_PATH}/bin + NO_DEFAULT_PATH + ) file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java) - add_jar(cameraserver_jar ${JAVA_SOURCES} INCLUDE_JARS wpiutil_jar cscore_jar ntcore_jar ${OPENCV_JAR_FILE} OUTPUT_NAME cameraserver) - - get_property(CAMERASERVER_JAR_FILE TARGET cameraserver_jar PROPERTY JAR_FILE) - install(FILES ${CAMERASERVER_JAR_FILE} DESTINATION "${java_lib_dest}") - - set_property(TARGET cameraserver_jar PROPERTY FOLDER "java") - + add_jar( + cameraserver_jar + ${JAVA_SOURCES} + INCLUDE_JARS wpiutil_jar cscore_jar ntcore_jar ${OPENCV_JAR_FILE} + OUTPUT_NAME cameraserver + ) + + install_jar(cameraserver_jar DESTINATION ${java_lib_dest}) + install_jar_exports( + TARGETS cameraserver_jar + FILE cameraserver_jar.cmake + DESTINATION share/cameraserver + ) endif() -if (WITH_JAVA_SOURCE) +if(WITH_JAVA_SOURCE) find_package(Java REQUIRED) include(UseJava) file(GLOB CAMERASERVER_SOURCES src/main/java/edu/wpi/first/cameraserver/*.java) file(GLOB VISION_SOURCES src/main/java/edu/wpi/first/vision/*.java) - add_jar(cameraserver_src_jar - RESOURCES NAMESPACE "edu/wpi/first/cameraserver" ${CAMERASERVER_SOURCES} - NAMESPACE "edu/wpi/first/vision" ${VISION_SOURCES} - OUTPUT_NAME cameraserver-sources) + add_jar( + cameraserver_src_jar + RESOURCES + NAMESPACE "edu/wpi/first/cameraserver" ${CAMERASERVER_SOURCES} + NAMESPACE "edu/wpi/first/vision" ${VISION_SOURCES} + OUTPUT_NAME cameraserver-sources + ) get_property(CAMERASERVER_SRC_JAR_FILE TARGET cameraserver_src_jar PROPERTY JAR_FILE) install(FILES ${CAMERASERVER_SRC_JAR_FILE} DESTINATION "${java_lib_dest}") @@ -44,30 +58,27 @@ if (WITH_JAVA_SOURCE) set_property(TARGET cameraserver_src_jar PROPERTY FOLDER "java") endif() -file(GLOB_RECURSE - cameraserver_native_src src/main/native/cpp/*.cpp) +file(GLOB_RECURSE cameraserver_native_src src/main/native/cpp/*.cpp) add_library(cameraserver ${cameraserver_native_src}) set_target_properties(cameraserver PROPERTIES DEBUG_POSTFIX "d") -target_include_directories(cameraserver PUBLIC - $ - $) +target_include_directories( + cameraserver + PUBLIC + $ + $ +) wpilib_target_warnings(cameraserver) target_link_libraries(cameraserver PUBLIC ntcore cscore wpiutil ${OpenCV_LIBS}) set_property(TARGET cameraserver PROPERTY FOLDER "libraries") install(TARGETS cameraserver EXPORT cameraserver) +export(TARGETS cameraserver FILE cameraserver.cmake NAMESPACE cameraserver::) install(DIRECTORY src/main/native/include/ DESTINATION "${include_dest}/cameraserver") -if (WITH_FLAT_INSTALL) - set (cameraserver_config_dir ${wpilib_dest}) -else() - set (cameraserver_config_dir share/cameraserver) -endif() - -configure_file(cameraserver-config.cmake.in ${WPILIB_BINARY_DIR}/cameraserver-config.cmake ) -install(FILES ${WPILIB_BINARY_DIR}/cameraserver-config.cmake DESTINATION ${cameraserver_config_dir}) -install(EXPORT cameraserver DESTINATION ${cameraserver_config_dir}) +configure_file(cameraserver-config.cmake.in ${WPILIB_BINARY_DIR}/cameraserver-config.cmake) +install(FILES ${WPILIB_BINARY_DIR}/cameraserver-config.cmake DESTINATION share/cameraserver) +install(EXPORT cameraserver DESTINATION share/cameraserver) file(GLOB multiCameraServer_src multiCameraServer/src/main/native/cpp/*.cpp) add_executable(multiCameraServer ${multiCameraServer_src}) @@ -76,7 +87,7 @@ target_link_libraries(multiCameraServer cameraserver) set_property(TARGET multiCameraServer PROPERTY FOLDER "examples") -if (WITH_TESTS) +if(WITH_TESTS) wpilib_add_test(cameraserver src/test/native/cpp) target_link_libraries(cameraserver_test cameraserver gtest) endif() diff --git a/cameraserver/cameraserver-config.cmake.in b/cameraserver/cameraserver-config.cmake.in index 94d681389c9..46d522d121c 100644 --- a/cameraserver/cameraserver-config.cmake.in +++ b/cameraserver/cameraserver-config.cmake.in @@ -7,3 +7,6 @@ find_dependency(OpenCV) @FILENAME_DEP_REPLACE@ include(${SELF_DIR}/cameraserver.cmake) +if(@WITH_JAVA@) + include(${SELF_DIR}/cameraserver_jar.cmake) +endif() diff --git a/cameraserver/multiCameraServer/src/main/java/edu/wpi/Main.java b/cameraserver/multiCameraServer/src/main/java/edu/wpi/Main.java index 1f791821898..f69a6feec53 100644 --- a/cameraserver/multiCameraServer/src/main/java/edu/wpi/Main.java +++ b/cameraserver/multiCameraServer/src/main/java/edu/wpi/Main.java @@ -98,7 +98,7 @@ public static boolean readConfig() { // parse file JsonElement top; try { - top = new JsonParser().parse(Files.newBufferedReader(Paths.get(configFile))); + top = JsonParser.parseReader(Files.newBufferedReader(Paths.get(configFile))); } catch (IOException ex) { System.err.println("could not open '" + configFile + "': " + ex); return false; diff --git a/cameraserver/multiCameraServer/src/main/native/cpp/main.cpp b/cameraserver/multiCameraServer/src/main/native/cpp/main.cpp index 706e2a26566..adf4122d835 100644 --- a/cameraserver/multiCameraServer/src/main/native/cpp/main.cpp +++ b/cameraserver/multiCameraServer/src/main/native/cpp/main.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include "cameraserver/CameraServer.h" @@ -71,7 +72,7 @@ bool ReadCameraConfig(const wpi::json& config) { try { c.name = config.at("name").get(); } catch (const wpi::json::exception& e) { - fmt::print(stderr, "config error in '{}': could not read camera name: {}\n", + wpi::print(stderr, "config error in '{}': could not read camera name: {}\n", configFile, e.what()); return false; } @@ -80,7 +81,7 @@ bool ReadCameraConfig(const wpi::json& config) { try { c.path = config.at("path").get(); } catch (const wpi::json::exception& e) { - fmt::print(stderr, + wpi::print(stderr, "config error in '{}': camera '{}': could not read path: {}\n", configFile, c.name, e.what()); return false; @@ -98,7 +99,7 @@ bool ReadConfig() { std::unique_ptr fileBuffer = wpi::MemoryBuffer::GetFile(configFile, ec); if (fileBuffer == nullptr || ec) { - fmt::print(stderr, "could not open '{}': {}\n", configFile, ec.message()); + wpi::print(stderr, "could not open '{}': {}\n", configFile, ec.message()); return false; } @@ -107,14 +108,14 @@ bool ReadConfig() { try { j = wpi::json::parse(fileBuffer->GetCharBuffer()); } catch (const wpi::json::parse_error& e) { - fmt::print(stderr, "config error in '{}': byte {}: {}\n", configFile, + wpi::print(stderr, "config error in '{}': byte {}: {}\n", configFile, e.byte, e.what()); return false; } // top level must be an object if (!j.is_object()) { - fmt::print(stderr, "config error in '{}': must be JSON object\n", + wpi::print(stderr, "config error in '{}': must be JSON object\n", configFile); return false; } @@ -123,7 +124,7 @@ bool ReadConfig() { try { team = j.at("team").get(); } catch (const wpi::json::exception& e) { - fmt::print(stderr, "config error in '{}': could not read team number: {}\n", + wpi::print(stderr, "config error in '{}': could not read team number: {}\n", configFile, e.what()); return false; } @@ -137,13 +138,13 @@ bool ReadConfig() { } else if (wpi::equals_lower(str, "server")) { server = true; } else { - fmt::print( + wpi::print( stderr, "config error in '{}': could not understand ntmode value '{}'\n", configFile, str); } } catch (const wpi::json::exception& e) { - fmt::print(stderr, "config error in '{}': could not read ntmode: {}\n", + wpi::print(stderr, "config error in '{}': could not read ntmode: {}\n", configFile, e.what()); } } @@ -156,7 +157,7 @@ bool ReadConfig() { } } } catch (const wpi::json::exception& e) { - fmt::print(stderr, "config error in '{}': could not read cameras: {}\n", + wpi::print(stderr, "config error in '{}': could not read cameras: {}\n", configFile, e.what()); return false; } @@ -165,7 +166,7 @@ bool ReadConfig() { } void StartCamera(const CameraConfig& config) { - fmt::print("Starting camera '{}' on {}\n", config.name, config.path); + wpi::print("Starting camera '{}' on {}\n", config.name, config.path); auto camera = frc::CameraServer::StartAutomaticCapture(config.name, config.path); @@ -189,7 +190,7 @@ int main(int argc, char* argv[]) { std::puts("Setting up NetworkTables server"); ntinst.StartServer(); } else { - fmt::print("Setting up NetworkTables client for team {}\n", team); + wpi::print("Setting up NetworkTables client for team {}\n", team); ntinst.StartClient4("multicameraserver"); ntinst.SetServerTeam(team); } diff --git a/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServer.java b/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServer.java index d4a1dd64cae..b0c01469d69 100644 --- a/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServer.java +++ b/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServer.java @@ -14,7 +14,6 @@ import edu.wpi.first.cscore.VideoException; import edu.wpi.first.cscore.VideoListener; import edu.wpi.first.cscore.VideoMode; -import edu.wpi.first.cscore.VideoMode.PixelFormat; import edu.wpi.first.cscore.VideoSink; import edu.wpi.first.cscore.VideoSource; import edu.wpi.first.networktables.BooleanEntry; @@ -27,6 +26,8 @@ import edu.wpi.first.networktables.StringArrayTopic; import edu.wpi.first.networktables.StringEntry; import edu.wpi.first.networktables.StringPublisher; +import edu.wpi.first.util.PixelFormat; +import java.lang.ref.Reference; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -39,6 +40,7 @@ * NetworkTables. */ public final class CameraServer { + /** CameraServer base port. */ public static final int kBasePort = 1181; private static final String kPublishName = "/CameraPublisher"; @@ -114,7 +116,7 @@ void update(VideoEvent event) { } @Override - public void close() throws Exception { + public void close() { if (m_booleanValueEntry != null) { m_booleanValueEntry.close(); } @@ -139,6 +141,7 @@ public void close() throws Exception { if (m_choicesPublisher != null) { m_choicesPublisher.close(); } + Reference.reachabilityFence(m_videoListener); } BooleanEntry m_booleanValueEntry; @@ -222,7 +225,7 @@ public void close() throws Exception { // - "PropertyInfo/{Property}" - Property supporting information // Listener for video events - @SuppressWarnings({"PMD.UnusedPrivateField", "PMD.AvoidCatchingGenericException"}) + @SuppressWarnings("PMD.AvoidCatchingGenericException") private static final VideoListener m_videoListener = new VideoListener( event -> { @@ -363,6 +366,8 @@ private static String makeSourceValue(int source) { } case kCv: return "cv:"; + case kRaw: + return "raw:"; default: return "unknown:"; } @@ -629,7 +634,10 @@ public static MjpegServer startAutomaticCapture(VideoSource camera) { * * @param host Camera host IP or DNS name (e.g. "10.x.y.11") * @return The Axis camera capturing images. + * @deprecated Call startAutomaticCapture with a HttpCamera instead. */ + @Deprecated(forRemoval = true, since = "2025") + @SuppressWarnings("removal") public static AxisCamera addAxisCamera(String host) { return addAxisCamera("Axis Camera", host); } @@ -641,7 +649,10 @@ public static AxisCamera addAxisCamera(String host) { * * @param hosts Array of Camera host IPs/DNS names * @return The Axis camera capturing images. + * @deprecated Call startAutomaticCapture with a HttpCamera instead. */ + @Deprecated(forRemoval = true, since = "2025") + @SuppressWarnings("removal") public static AxisCamera addAxisCamera(String[] hosts) { return addAxisCamera("Axis Camera", hosts); } @@ -652,7 +663,10 @@ public static AxisCamera addAxisCamera(String[] hosts) { * @param name The name to give the camera * @param host Camera host IP or DNS name (e.g. "10.x.y.11") * @return The Axis camera capturing images. + * @deprecated Call startAutomaticCapture with a HttpCamera instead. */ + @Deprecated(forRemoval = true, since = "2025") + @SuppressWarnings("removal") public static AxisCamera addAxisCamera(String name, String host) { AxisCamera camera = new AxisCamera(name, host); // Create a passthrough MJPEG server for USB access @@ -667,7 +681,10 @@ public static AxisCamera addAxisCamera(String name, String host) { * @param name The name to give the camera * @param hosts Array of Camera host IPs/DNS names * @return The Axis camera capturing images. + * @deprecated Call startAutomaticCapture with a HttpCamera instead. */ + @Deprecated(forRemoval = true, since = "2025") + @SuppressWarnings("removal") public static AxisCamera addAxisCamera(String name, String[] hosts) { AxisCamera camera = new AxisCamera(name, hosts); // Create a passthrough MJPEG server for USB access @@ -686,7 +703,7 @@ public static AxisCamera addAxisCamera(String name, String[] hosts) { */ public static MjpegServer addSwitchedCamera(String name) { // create a dummy CvSource - CvSource source = new CvSource(name, VideoMode.PixelFormat.kMJPEG, 160, 120, 30); + CvSource source = new CvSource(name, PixelFormat.kMJPEG, 160, 120, 30); MjpegServer server = startAutomaticCapture(source); synchronized (CameraServer.class) { m_fixedSources.put(server.getHandle(), source.getHandle()); @@ -745,6 +762,34 @@ public static CvSink getVideo(VideoSource camera) { return newsink; } + /** + * Get OpenCV access to the specified camera. This allows you to get images from the camera for + * image processing on the roboRIO. + * + * @param camera Camera (e.g. as returned by startAutomaticCapture). + * @param pixelFormat Desired pixelFormat of the camera + * @return OpenCV sink for the specified camera + */ + public static CvSink getVideo(VideoSource camera, PixelFormat pixelFormat) { + String name = "opencv_" + camera.getName(); + + synchronized (CameraServer.class) { + VideoSink sink = m_sinks.get(name); + if (sink != null) { + VideoSink.Kind kind = sink.getKind(); + if (kind != VideoSink.Kind.kCv) { + throw new VideoException("expected OpenCV sink, but got " + kind); + } + return (CvSink) sink; + } + } + + CvSink newsink = new CvSink(name, pixelFormat); + newsink.setSource(camera); + addServer(newsink); + return newsink; + } + /** * Get OpenCV access to the specified camera. This allows you to get images from the camera for * image processing on the roboRIO. @@ -773,7 +818,7 @@ public static CvSink getVideo(String name) { * @return OpenCV source for the MJPEG stream */ public static CvSource putVideo(String name, int width, int height) { - CvSource source = new CvSource(name, VideoMode.PixelFormat.kMJPEG, width, height, 30); + CvSource source = new CvSource(name, PixelFormat.kMJPEG, width, height, 30); startAutomaticCapture(source); return source; } diff --git a/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServerShared.java b/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServerShared.java index 4726de184fd..dfa570f85c2 100644 --- a/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServerShared.java +++ b/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServerShared.java @@ -4,6 +4,7 @@ package edu.wpi.first.cameraserver; +/** CameraServer shared functions. */ public interface CameraServerShared { /** * get the main thread id func. diff --git a/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServerSharedStore.java b/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServerSharedStore.java index 3d9e1194066..b129d55291d 100644 --- a/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServerSharedStore.java +++ b/cameraserver/src/main/java/edu/wpi/first/cameraserver/CameraServerSharedStore.java @@ -4,6 +4,7 @@ package edu.wpi.first.cameraserver; +/** Storage for CameraServerShared instance. */ public final class CameraServerSharedStore { private static CameraServerShared cameraServerShared; diff --git a/cameraserver/src/main/java/edu/wpi/first/vision/VisionRunner.java b/cameraserver/src/main/java/edu/wpi/first/vision/VisionRunner.java index ab7072f6c99..b9459cb00c4 100644 --- a/cameraserver/src/main/java/edu/wpi/first/vision/VisionRunner.java +++ b/cameraserver/src/main/java/edu/wpi/first/vision/VisionRunner.java @@ -14,6 +14,7 @@ * code. The easiest way to use this is to run it in a {@link VisionThread} and use the listener to * take snapshots of the pipeline's outputs. * + * @param

Vision pipeline type. * @see VisionPipeline * @see VisionThread * @see vision diff --git a/cameraserver/src/main/java/edu/wpi/first/vision/VisionThread.java b/cameraserver/src/main/java/edu/wpi/first/vision/VisionThread.java index 6f1a1e35b58..93d4e83758e 100644 --- a/cameraserver/src/main/java/edu/wpi/first/vision/VisionThread.java +++ b/cameraserver/src/main/java/edu/wpi/first/vision/VisionThread.java @@ -21,6 +21,7 @@ public class VisionThread extends Thread { * * @param visionRunner the runner for a vision pipeline */ + @SuppressWarnings("this-escape") public VisionThread(VisionRunner visionRunner) { super(visionRunner::runForever, "WPILib Vision Thread"); setDaemon(true); diff --git a/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp b/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp index d6014fa5a0d..c13c113c563 100644 --- a/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp +++ b/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp @@ -113,6 +113,8 @@ static std::string_view MakeSourceValue(CS_Source source, } case CS_SOURCE_CV: return "cv:"; + case CS_SOURCE_RAW: + return "raw:"; default: return "unknown:"; } @@ -502,6 +504,7 @@ cs::UsbCamera CameraServer::StartAutomaticCapture(std::string_view name, return camera; } +WPI_IGNORE_DEPRECATED cs::AxisCamera CameraServer::AddAxisCamera(std::string_view host) { return AddAxisCamera("Axis Camera", host); } @@ -557,7 +560,7 @@ cs::AxisCamera CameraServer::AddAxisCamera(std::string_view name, csShared->ReportAxisCamera(camera.GetHandle()); return camera; } - +WPI_UNIGNORE_DEPRECATED cs::MjpegServer CameraServer::AddSwitchedCamera(std::string_view name) { auto& inst = ::GetInstance(); // create a dummy CvSource @@ -622,6 +625,33 @@ cs::CvSink CameraServer::GetVideo(const cs::VideoSource& camera) { return newsink; } +cs::CvSink CameraServer::GetVideo(const cs::VideoSource& camera, + cs::VideoMode::PixelFormat pixelFormat) { + auto& inst = ::GetInstance(); + wpi::SmallString<64> name{"opencv_"}; + name += camera.GetName(); + + { + std::scoped_lock lock(inst.m_mutex); + auto it = inst.m_sinks.find(name); + if (it != inst.m_sinks.end()) { + auto kind = it->second.GetKind(); + if (kind != cs::VideoSink::kCv) { + auto csShared = GetCameraServerShared(); + csShared->SetCameraServerError("expected OpenCV sink, but got {}", + static_cast(kind)); + return cs::CvSink{}; + } + return *static_cast(&it->second); + } + } + + cs::CvSink newsink{name.str(), pixelFormat}; + newsink.SetSource(camera); + AddServer(newsink); + return newsink; +} + cs::CvSink CameraServer::GetVideo(std::string_view name) { auto& inst = ::GetInstance(); cs::VideoSource source; @@ -638,6 +668,23 @@ cs::CvSink CameraServer::GetVideo(std::string_view name) { return GetVideo(source); } +cs::CvSink CameraServer::GetVideo(std::string_view name, + cs::VideoMode::PixelFormat pixelFormat) { + auto& inst = ::GetInstance(); + cs::VideoSource source; + { + std::scoped_lock lock(inst.m_mutex); + auto it = inst.m_sources.find(name); + if (it == inst.m_sources.end()) { + auto csShared = GetCameraServerShared(); + csShared->SetCameraServerError("could not find camera {}", name); + return cs::CvSink{}; + } + source = it->second; + } + return GetVideo(source, pixelFormat); +} + cs::CvSource CameraServer::PutVideo(std::string_view name, int width, int height) { ::GetInstance(); diff --git a/cameraserver/src/main/native/include/cameraserver/CameraServer.h b/cameraserver/src/main/native/include/cameraserver/CameraServer.h index 29e16d7e75c..0dfa97f178a 100644 --- a/cameraserver/src/main/native/include/cameraserver/CameraServer.h +++ b/cameraserver/src/main/native/include/cameraserver/CameraServer.h @@ -10,6 +10,8 @@ #include #include +#include + #include "cscore.h" #include "cscore_cv.h" @@ -22,10 +24,8 @@ namespace frc { */ class CameraServer { public: + /// CameraServer base port. static constexpr uint16_t kBasePort = 1181; - static constexpr int kSize640x480 = 0; - static constexpr int kSize320x240 = 1; - static constexpr int kSize160x120 = 2; /** * Start automatically capturing images to send to the dashboard. @@ -75,13 +75,16 @@ class CameraServer { */ static cs::MjpegServer StartAutomaticCapture(const cs::VideoSource& camera); + WPI_IGNORE_DEPRECATED /** * Adds an Axis IP camera. * * This overload calls AddAxisCamera() with name "Axis Camera". * * @param host Camera host IP or DNS name (e.g. "10.x.y.11") + * @deprecated Call StartAutomaticCapture with a HttpCamera instead. */ + [[deprecated("Call StartAutomaticCapture with a HttpCamera instead.")]] static cs::AxisCamera AddAxisCamera(std::string_view host); /** @@ -90,7 +93,9 @@ class CameraServer { * This overload calls AddAxisCamera() with name "Axis Camera". * * @param host Camera host IP or DNS name (e.g. "10.x.y.11") + * @deprecated Call StartAutomaticCapture with a HttpCamera instead. */ + [[deprecated("Call StartAutomaticCapture with a HttpCamera instead.")]] static cs::AxisCamera AddAxisCamera(const char* host); /** @@ -99,7 +104,9 @@ class CameraServer { * This overload calls AddAxisCamera() with name "Axis Camera". * * @param host Camera host IP or DNS name (e.g. "10.x.y.11") + * @deprecated Call StartAutomaticCapture with a HttpCamera instead. */ + [[deprecated("Call StartAutomaticCapture with a HttpCamera instead.")]] static cs::AxisCamera AddAxisCamera(const std::string& host); /** @@ -108,7 +115,9 @@ class CameraServer { * This overload calls AddAxisCamera() with name "Axis Camera". * * @param hosts Array of Camera host IPs/DNS names + * @deprecated Call StartAutomaticCapture with a HttpCamera instead. */ + [[deprecated("Call StartAutomaticCapture with a HttpCamera instead.")]] static cs::AxisCamera AddAxisCamera(std::span hosts); /** @@ -117,8 +126,10 @@ class CameraServer { * This overload calls AddAxisCamera() with name "Axis Camera". * * @param hosts Array of Camera host IPs/DNS names + * @deprecated Call StartAutomaticCapture with a HttpCamera instead. */ template + [[deprecated("Call StartAutomaticCapture with a HttpCamera instead.")]] static cs::AxisCamera AddAxisCamera(std::initializer_list hosts); /** @@ -126,7 +137,9 @@ class CameraServer { * * @param name The name to give the camera * @param host Camera host IP or DNS name (e.g. "10.x.y.11") + * @deprecated Call StartAutomaticCapture with a HttpCamera instead. */ + [[deprecated("Call StartAutomaticCapture with a HttpCamera instead.")]] static cs::AxisCamera AddAxisCamera(std::string_view name, std::string_view host); @@ -135,7 +148,9 @@ class CameraServer { * * @param name The name to give the camera * @param host Camera host IP or DNS name (e.g. "10.x.y.11") + * @deprecated Call StartAutomaticCapture with a HttpCamera instead. */ + [[deprecated("Call StartAutomaticCapture with a HttpCamera instead.")]] static cs::AxisCamera AddAxisCamera(std::string_view name, const char* host); /** @@ -143,7 +158,9 @@ class CameraServer { * * @param name The name to give the camera * @param host Camera host IP or DNS name (e.g. "10.x.y.11") + * @deprecated Call StartAutomaticCapture with a HttpCamera instead. */ + [[deprecated("Call StartAutomaticCapture with a HttpCamera instead.")]] static cs::AxisCamera AddAxisCamera(std::string_view name, const std::string& host); @@ -152,7 +169,9 @@ class CameraServer { * * @param name The name to give the camera * @param hosts Array of Camera host IPs/DNS names + * @deprecated Call StartAutomaticCapture with a HttpCamera instead. */ + [[deprecated("Call StartAutomaticCapture with a HttpCamera instead.")]] static cs::AxisCamera AddAxisCamera(std::string_view name, std::span hosts); @@ -161,10 +180,13 @@ class CameraServer { * * @param name The name to give the camera * @param hosts Array of Camera host IPs/DNS names + * @deprecated Call StartAutomaticCapture with a HttpCamera instead. */ template + [[deprecated("Call StartAutomaticCapture with a HttpCamera instead.")]] static cs::AxisCamera AddAxisCamera(std::string_view name, std::initializer_list hosts); + WPI_UNIGNORE_DEPRECATED /** * Adds a virtual camera for switching between two streams. Unlike the @@ -191,6 +213,17 @@ class CameraServer { */ static cs::CvSink GetVideo(const cs::VideoSource& camera); + /** + * Get OpenCV access to the specified camera. This allows you to get + * images from the camera for image processing on the roboRIO. + * + * @param camera Camera (e.g. as returned by startAutomaticCapture). + * @param pixelFormat The desired pixelFormat of captured frames from the + * camera + */ + static cs::CvSink GetVideo(const cs::VideoSource& camera, + cs::VideoMode::PixelFormat pixelFormat); + /** * Get OpenCV access to the specified camera. This allows you to get * images from the camera for image processing on the roboRIO. @@ -199,6 +232,17 @@ class CameraServer { */ static cs::CvSink GetVideo(std::string_view name); + /** + * Get OpenCV access to the specified camera. This allows you to get + * images from the camera for image processing on the roboRIO. + * + * @param name Camera name + * @param pixelFormat The desired pixelFormat of captured frames from the + * camera + */ + static cs::CvSink GetVideo(std::string_view name, + cs::VideoMode::PixelFormat pixelFormat); + /** * Create a MJPEG stream with OpenCV input. This can be called to pass custom * annotated images to the dashboard. diff --git a/cameraserver/src/main/native/include/cameraserver/CameraServer.inc b/cameraserver/src/main/native/include/cameraserver/CameraServer.inc index 8c8ec21cf98..5ae14f7f9a9 100644 --- a/cameraserver/src/main/native/include/cameraserver/CameraServer.inc +++ b/cameraserver/src/main/native/include/cameraserver/CameraServer.inc @@ -11,6 +11,7 @@ namespace frc { +WPI_IGNORE_DEPRECATED template inline cs::AxisCamera CameraServer::AddAxisCamera( std::initializer_list hosts) { @@ -27,5 +28,6 @@ inline cs::AxisCamera CameraServer::AddAxisCamera( } return AddAxisCamera(name, vec); } +WPI_UNIGNORE_DEPRECATED } // namespace frc diff --git a/cmake/modules/AddTest.cmake b/cmake/modules/AddTest.cmake index eef41131e22..4896c4a222e 100644 --- a/cmake/modules/AddTest.cmake +++ b/cmake/modules/AddTest.cmake @@ -4,10 +4,10 @@ macro(wpilib_add_test name srcdir) file(GLOB_RECURSE test_src ${srcdir}/*.cpp) add_executable(${name}_test ${test_src}) wpilib_target_warnings(${name}_test) - if (BUILD_SHARED_LIBS) + if(BUILD_SHARED_LIBS) target_compile_definitions(${name}_test PRIVATE -DGTEST_LINKED_AS_SHARED_LIBRARY) endif() - if (MSVC) + if(MSVC) target_compile_options(${name}_test PRIVATE /wd4101 /wd4251) endif() add_test(NAME ${name} COMMAND ${name}_test) diff --git a/cmake/modules/CompileWarnings.cmake b/cmake/modules/CompileWarnings.cmake index 8f5d54ea6c9..5de103201e2 100644 --- a/cmake/modules/CompileWarnings.cmake +++ b/cmake/modules/CompileWarnings.cmake @@ -1,28 +1,56 @@ macro(wpilib_target_warnings target) if(NOT MSVC) - target_compile_options(${target} PRIVATE -Wall -pedantic -Wextra -Werror -Wno-unused-parameter ${WPILIB_TARGET_WARNINGS}) + set(WARNING_FLAGS + -Wall + -pedantic + -Wextra + -Wno-unused-parameter + ${WPILIB_TARGET_WARNINGS} + ) + if(NOT NO_WERROR) + set(WARNING_FLAGS ${WARNING_FLAGS} -Werror) + endif() + + target_compile_options(${target} PRIVATE ${WARNING_FLAGS}) else() - target_compile_options(${target} PRIVATE /wd4146 /wd4244 /wd4251 /wd4267 /WX /D_CRT_SECURE_NO_WARNINGS ${WPILIB_TARGET_WARNINGS}) + target_compile_options( + ${target} + PRIVATE + /wd4146 + /wd4244 + /wd4251 + /wd4267 + /WX + /D_CRT_SECURE_NO_WARNINGS + ${WPILIB_TARGET_WARNINGS} + ) endif() # Suppress C++-specific OpenCV warning; C compiler rejects it with an error # https://github.com/opencv/opencv/issues/20269 if(UNIX AND NOT APPLE) - target_compile_options(${target} PRIVATE $<$:-Wno-deprecated-enum-enum-conversion>) + target_compile_options( + ${target} + PRIVATE $<$:-Wno-deprecated-enum-enum-conversion> + ) elseif(UNIX AND APPLE) - target_compile_options(${target} PRIVATE $<$:-Wno-deprecated-anon-enum-enum-conversion>) + target_compile_options( + ${target} + PRIVATE $<$:-Wno-deprecated-anon-enum-enum-conversion> + ) endif() # Suppress warning "enumeration types with a fixed underlying type are a # Clang extension" if(APPLE) - target_compile_options(${target} PRIVATE $<$:-Wno-fixed-enum-extension>) + target_compile_options(${target} PRIVATE $<$:-Wno-fixed-enum-extension>) endif() # Compress debug info with GCC - if ((${CMAKE_BUILD_TYPE} STREQUAL "Debug" OR - ${CMAKE_BUILD_TYPE} STREQUAL "RelWithDebInfo") AND - ${CMAKE_CXX_COMPILER_ID} STREQUAL "GNU") - target_compile_options(${target} PRIVATE -gz=zlib) + if( + (${CMAKE_BUILD_TYPE} STREQUAL "Debug" OR ${CMAKE_BUILD_TYPE} STREQUAL "RelWithDebInfo") + AND ${CMAKE_CXX_COMPILER_ID} STREQUAL "GNU" + ) + target_compile_options(${target} PRIVATE -gz=zlib) endif() endmacro() diff --git a/cmake/modules/DownloadAndCheck.cmake b/cmake/modules/DownloadAndCheck.cmake index 59c87998e95..a1807d590dd 100644 --- a/cmake/modules/DownloadAndCheck.cmake +++ b/cmake/modules/DownloadAndCheck.cmake @@ -1,11 +1,11 @@ macro(download_and_check source destination) - file(DOWNLOAD ${source} ${destination} STATUS download_status) - list(GET download_status 0 status_code) - list(GET download_status 1 status_message) + file(DOWNLOAD ${source} ${destination} STATUS download_status) + list(GET download_status 0 status_code) + list(GET download_status 1 status_message) - if(${status_code} EQUAL 0) - message(VERBOSE "Download of \"${source}\" successful.") - else() - message(FATAL_ERROR "Download of \"${source}\" failed: ${status_message}") - endif() + if(${status_code} EQUAL 0) + message(VERBOSE "Download of \"${source}\" successful.") + else() + message(FATAL_ERROR "Download of \"${source}\" failed: ${status_message}") + endif() endmacro() diff --git a/cmake/modules/FindLIBSSH.cmake b/cmake/modules/FindLIBSSH.cmake index ba2d7783811..6578aa99761 100644 --- a/cmake/modules/FindLIBSSH.cmake +++ b/cmake/modules/FindLIBSSH.cmake @@ -38,30 +38,28 @@ if(LIBSSH_LIBRARIES AND LIBSSH_INCLUDE_DIRS) # in cache already set(LIBSSH_FOUND TRUE) else() - find_path(LIBSSH_INCLUDE_DIR - NAMES - libssh/libssh.h + find_path( + LIBSSH_INCLUDE_DIR + NAMES libssh/libssh.h PATHS - /usr/include - /usr/local/include - /opt/local/include - /sw/include - ${CMAKE_INCLUDE_PATH} - ${CMAKE_INSTALL_PREFIX}/include + /usr/include + /usr/local/include + /opt/local/include + /sw/include + ${CMAKE_INCLUDE_PATH} + ${CMAKE_INSTALL_PREFIX}/include ) - find_library(LIBSSH_LIBRARY - NAMES - ssh.so - libssh.so - libssh.dylib + find_library( + LIBSSH_LIBRARY + NAMES ssh.so libssh.so libssh.dylib PATHS - /usr/lib - /usr/local/lib - /opt/local/lib - /sw/lib - ${CMAKE_LIBRARY_PATH} - ${CMAKE_INSTALL_PREFIX}/lib + /usr/lib + /usr/local/lib + /opt/local/lib + /sw/lib + ${CMAKE_LIBRARY_PATH} + ${CMAKE_INSTALL_PREFIX}/lib ) if(LIBSSH_INCLUDE_DIR AND LIBSSH_LIBRARY) @@ -71,34 +69,60 @@ else() else() set(LIBSSH_HEADER_PATH ${LIBSSH_INCLUDE_DIR}/libssh/libssh.h) endif() - file(STRINGS ${LIBSSH_HEADER_PATH} LIBSSH_VERSION_MAJOR - REGEX "#define[ ]+LIBSSH_VERSION_MAJOR[ ]+[0-9]+") + file( + STRINGS + ${LIBSSH_HEADER_PATH} + LIBSSH_VERSION_MAJOR + REGEX "#define[ ]+LIBSSH_VERSION_MAJOR[ ]+[0-9]+" + ) if(NOT LIBSSH_VERSION_MAJOR) - message(STATUS "LIBSSH_VERSION_MAJOR not found, assuming libssh is too old and cannot be used!") + message( + STATUS + "LIBSSH_VERSION_MAJOR not found, assuming libssh is too old and cannot be used!" + ) set(LIBSSH_INCLUDE_DIR "LIBSSH_INCLUDE_DIR-NOTFOUND") set(LIBSSH_LIBRARY "LIBSSH_LIBRARY-NOTFOUND") else() string(REGEX MATCH "[0-9]+" LIBSSH_VERSION_MAJOR ${LIBSSH_VERSION_MAJOR}) - file(STRINGS ${LIBSSH_HEADER_PATH} LIBSSH_VERSION_MINOR - REGEX "#define[ ]+LIBSSH_VERSION_MINOR[ ]+[0-9]+") + file( + STRINGS + ${LIBSSH_HEADER_PATH} + LIBSSH_VERSION_MINOR + REGEX "#define[ ]+LIBSSH_VERSION_MINOR[ ]+[0-9]+" + ) string(REGEX MATCH "[0-9]+" LIBSSH_VERSION_MINOR ${LIBSSH_VERSION_MINOR}) - file(STRINGS ${LIBSSH_HEADER_PATH} LIBSSH_VERSION_PATCH - REGEX "#define[ ]+LIBSSH_VERSION_MICRO[ ]+[0-9]+") + file( + STRINGS + ${LIBSSH_HEADER_PATH} + LIBSSH_VERSION_PATCH + REGEX "#define[ ]+LIBSSH_VERSION_MICRO[ ]+[0-9]+" + ) string(REGEX MATCH "[0-9]+" LIBSSH_VERSION_PATCH ${LIBSSH_VERSION_PATCH}) - set(LIBSSH_VERSION ${LIBSSH_VERSION_MAJOR}.${LIBSSH_VERSION_MINOR}.${LIBSSH_VERSION_PATCH}) + set(LIBSSH_VERSION + ${LIBSSH_VERSION_MAJOR}.${LIBSSH_VERSION_MINOR}.${LIBSSH_VERSION_PATCH} + ) if(LIBSSH_VERSION VERSION_LESS 0.8.0) # libssh_threads also needs to be linked for these versions - string(REPLACE "libssh.so" "libssh_threads.so" + string( + REPLACE + "libssh.so" + "libssh_threads.so" LIBSSH_THREADS_LIBRARY ${LIBSSH_LIBRARY} ) - string(REPLACE "libssh.dylib" "libssh_threads.dylib" + string( + REPLACE + "libssh.dylib" + "libssh_threads.dylib" LIBSSH_THREADS_LIBRARY ${LIBSSH_THREADS_LIBRARY} ) - string(REPLACE "ssh.so" "ssh_threads.so" + string( + REPLACE + "ssh.so" + "ssh_threads.so" LIBSSH_THREADS_LIBRARY ${LIBSSH_THREADS_LIBRARY} ) @@ -110,7 +134,10 @@ else() set(LIBSSH_LIBRARIES ${LIBSSH_LIBRARY} ${LIBSSH_THREADS_LIBRARY}) mark_as_advanced(LIBSSH_INCLUDE_DIRS LIBSSH_LIBRARIES) - find_package_handle_standard_args(LIBSSH FOUND_VAR LIBSSH_FOUND + find_package_handle_standard_args( + LIBSSH + FOUND_VAR LIBSSH_FOUND REQUIRED_VARS LIBSSH_INCLUDE_DIRS LIBSSH_LIBRARIES - VERSION_VAR LIBSSH_VERSION) + VERSION_VAR LIBSSH_VERSION + ) endif() diff --git a/cmake/modules/GenResources.cmake b/cmake/modules/GenResources.cmake index d80a3640663..c7d9f92f8e1 100644 --- a/cmake/modules/GenResources.cmake +++ b/cmake/modules/GenResources.cmake @@ -1,26 +1,30 @@ set(scripts_dir "${CMAKE_CURRENT_LIST_DIR}/../scripts") -macro(generate_resources inputDir outputDir prefix namespace outputFiles) - file(GLOB inputFiles ${inputDir}/*) - set(${outputFiles}) - foreach(input ${inputFiles}) - get_filename_component(inputBase ${input} NAME) - if("${inputBase}" MATCHES "^\\.") - continue() - endif() - set(output "${outputDir}/${inputBase}.cpp") - list(APPEND ${outputFiles} "${output}") +macro( + generate_resources + inputDir + outputDir + prefix + namespace + outputFiles +) + file(GLOB inputFiles ${inputDir}/*) + set(${outputFiles}) + foreach(input ${inputFiles}) + get_filename_component(inputBase ${input} NAME) + if("${inputBase}" MATCHES "^\\.") + continue() + endif() + set(output "${outputDir}/${inputBase}.cpp") + list(APPEND ${outputFiles} "${output}") - add_custom_command( - OUTPUT ${output} - COMMAND ${CMAKE_COMMAND} - "-Dinput=${input}" - "-Doutput=${output}" - "-Dprefix=${prefix}" - "-Dnamespace=${namespace}" - -P "${scripts_dir}/GenResource.cmake" - MAIN_DEPENDENCY ${input} - DEPENDS ${scripts_dir}/GenResource.cmake - VERBATIM - ) - endforeach() + add_custom_command( + OUTPUT ${output} + COMMAND + ${CMAKE_COMMAND} "-Dinput=${input}" "-Doutput=${output}" "-Dprefix=${prefix}" + "-Dnamespace=${namespace}" -P "${scripts_dir}/GenResource.cmake" + MAIN_DEPENDENCY ${input} + DEPENDS ${scripts_dir}/GenResource.cmake + VERBATIM + ) + endforeach() endmacro() diff --git a/cmake/modules/LinkMacOSGUI.cmake b/cmake/modules/LinkMacOSGUI.cmake index f76554eee8f..6bfe5403fd9 100644 --- a/cmake/modules/LinkMacOSGUI.cmake +++ b/cmake/modules/LinkMacOSGUI.cmake @@ -1,5 +1,8 @@ macro(wpilib_link_macos_gui target) - if (APPLE) - set_target_properties(${target} PROPERTIES LINK_FLAGS "-framework Metal -framework QuartzCore") + if(APPLE) + set_target_properties( + ${target} + PROPERTIES LINK_FLAGS "-framework Metal -framework QuartzCore" + ) endif() endmacro() diff --git a/cmake/modules/SubDirList.cmake b/cmake/modules/SubDirList.cmake index 0776098fffc..409eb189145 100644 --- a/cmake/modules/SubDirList.cmake +++ b/cmake/modules/SubDirList.cmake @@ -1,17 +1,17 @@ macro(subdir_list result curdir) - file(GLOB children RELATIVE ${curdir} ${curdir}/*) - set(dirlist "") - foreach(child ${children}) - if(IS_DIRECTORY ${curdir}/${child}) - list(APPEND dirlist ${child}) - endif() - endforeach() - set(${result} ${dirlist}) + file(GLOB children RELATIVE ${curdir} ${curdir}/*) + set(dirlist "") + foreach(child ${children}) + if(IS_DIRECTORY ${curdir}/${child}) + list(APPEND dirlist ${child}) + endif() + endforeach() + set(${result} ${dirlist}) endmacro() macro(add_all_subdirectories curdir) - subdir_list(_SUBPROJECTS ${curdir}) - foreach(dir ${_SUBPROJECTS}) - add_subdirectory(${dir}) - endforeach() + subdir_list(_SUBPROJECTS ${curdir}) + foreach(dir ${_SUBPROJECTS}) + add_subdirectory(${dir}) + endforeach() endmacro() diff --git a/cmake/scripts/GenResource.cmake b/cmake/scripts/GenResource.cmake index 3c6e2515e29..ad9ca913d13 100644 --- a/cmake/scripts/GenResource.cmake +++ b/cmake/scripts/GenResource.cmake @@ -1,23 +1,35 @@ # Parameters: input output prefix namespace -FILE(READ ${input} fileHex HEX) -STRING(LENGTH "${fileHex}" fileHexSize) -MATH(EXPR fileSize "${fileHexSize} / 2") +file(READ ${input} fileHex HEX) +string(LENGTH "${fileHex}" fileHexSize) +math(EXPR fileSize "${fileHexSize} / 2") -GET_FILENAME_COMPONENT(inputBase ${input} NAME) -STRING(REGEX REPLACE "[^a-zA-Z0-9]" "_" funcName "${inputBase}") -SET(funcName "GetResource_${funcName}") +get_filename_component(inputBase ${input} NAME) +string(REGEX REPLACE "[^a-zA-Z0-9]" "_" funcName "${inputBase}") +set(funcName "GetResource_${funcName}") -FILE(WRITE "${output}" "#include \n#include \nextern \"C\" {\nstatic const unsigned char contents[] = {") +file( + WRITE + "${output}" + "#include \n#include \nextern \"C\" {\nstatic const unsigned char contents[] = {" +) -STRING(REGEX MATCHALL ".." outputData "${fileHex}") -STRING(REGEX REPLACE ";" ", 0x" outputData "${outputData}") -FILE(APPEND "${output}" " 0x${outputData} };\n") -FILE(APPEND "${output}" "const unsigned char* ${prefix}${funcName}(size_t* len) {\n *len = ${fileSize};\n return contents;\n}\n}\n") +string(REGEX MATCHALL ".." outputData "${fileHex}") +string(REGEX REPLACE ";" ", 0x" outputData "${outputData}") +file(APPEND "${output}" " 0x${outputData} };\n") +file( + APPEND + "${output}" + "const unsigned char* ${prefix}${funcName}(size_t* len) {\n *len = ${fileSize};\n return contents;\n}\n}\n" +) -IF(NOT namespace STREQUAL "") - FILE(APPEND "${output}" "namespace ${namespace} {\n") -ENDIF() -FILE(APPEND "${output}" "std::string_view ${funcName}() {\n return std::string_view(reinterpret_cast(contents), ${fileSize});\n}\n") -IF(NOT namespace STREQUAL "") - FILE(APPEND "${output}" "}\n") -ENDIF() +if(NOT namespace STREQUAL "") + file(APPEND "${output}" "namespace ${namespace} {\n") +endif() +file( + APPEND + "${output}" + "std::string_view ${funcName}() {\n return std::string_view(reinterpret_cast(contents), ${fileSize});\n}\n" +) +if(NOT namespace STREQUAL "") + file(APPEND "${output}" "}\n") +endif() diff --git a/crossConnIntegrationTests/src/main/native/cpp/TestEnvironment.cpp b/crossConnIntegrationTests/src/main/native/cpp/TestEnvironment.cpp index 8ef19227172..79313c2a11a 100644 --- a/crossConnIntegrationTests/src/main/native/cpp/TestEnvironment.cpp +++ b/crossConnIntegrationTests/src/main/native/cpp/TestEnvironment.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include "mockds/MockDS.h" @@ -27,7 +28,7 @@ class TestEnvironment : public testing::Environment { m_alreadySetUp = true; if (!HAL_Initialize(500, 0)) { - fmt::print(stderr, "FATAL ERROR: HAL could not be initialized\n"); + wpi::print(stderr, "FATAL ERROR: HAL could not be initialized\n"); std::exit(-1); } @@ -39,7 +40,7 @@ class TestEnvironment : public testing::Environment { // able to run on the hardware. HAL_ObserveUserProgramStarting(); - fmt::print("Started coms\n"); + wpi::print("Started coms\n"); int enableCounter = 0; @@ -54,13 +55,13 @@ class TestEnvironment : public testing::Environment { if (enableCounter > 50) { // Robot did not enable properly after 5 seconds. // Force exit - fmt::print(stderr, " Failed to enable. Aborting\n"); + wpi::print(stderr, " Failed to enable. Aborting\n"); std::terminate(); } std::this_thread::sleep_for(100ms); - fmt::print("Waiting for enable: {}\n", enableCounter++); + wpi::print("Waiting for enable: {}\n", enableCounter++); HAL_RefreshDSData(); } std::this_thread::sleep_for(500ms); diff --git a/crossConnIntegrationTests/src/main/native/cpp/mockds/MockDS.cpp b/crossConnIntegrationTests/src/main/native/cpp/mockds/MockDS.cpp index 2e53a9ab5e0..f711134ed24 100644 --- a/crossConnIntegrationTests/src/main/native/cpp/mockds/MockDS.cpp +++ b/crossConnIntegrationTests/src/main/native/cpp/mockds/MockDS.cpp @@ -12,12 +12,13 @@ #include #include #include +#include #include static void LoggerFunc(unsigned int level, const char* file, unsigned int line, const char* msg) { if (level == 20) { - fmt::print(stderr, "DS: {}\n", msg); + wpi::print(stderr, "DS: {}\n", msg); return; } @@ -31,7 +32,7 @@ static void LoggerFunc(unsigned int level, const char* file, unsigned int line, } else { return; } - fmt::print(stderr, "DS: {}: {} ({}:{})\n", levelmsg, msg, file, line); + wpi::print(stderr, "DS: {}: {} ({}:{})\n", levelmsg, msg, file, line); } static void generateEnabledDsPacket(wpi::SmallVectorImpl& data, diff --git a/crossConnIntegrationTests/src/main/native/include/LifetimeWrappers.h b/crossConnIntegrationTests/src/main/native/include/LifetimeWrappers.h index e196d84e770..7546bfa0595 100644 --- a/crossConnIntegrationTests/src/main/native/include/LifetimeWrappers.h +++ b/crossConnIntegrationTests/src/main/native/include/LifetimeWrappers.h @@ -190,12 +190,12 @@ struct RelayHandle { HAL_RelayHandle handle = 0; }; -#define ASSERT_LAST_ERROR_STATUS(status, x) \ - do { \ - ASSERT_EQ(status, HAL_USE_LAST_ERROR); \ - [[maybe_unused]] const char* lastErrorMessageInMacro = \ - HAL_GetLastError(&status); \ - ASSERT_EQ(status, x); \ +#define ASSERT_LAST_ERROR_STATUS(status, x) \ + do { \ + ASSERT_EQ(status, HAL_USE_LAST_ERROR); \ + [[maybe_unused]] \ + const char* lastErrorMessageInMacro = HAL_GetLastError(&status); \ + ASSERT_EQ(status, x); \ } while (0) } // namespace hlt diff --git a/cscore/CMakeLists.txt b/cscore/CMakeLists.txt index a6a89b36352..94338ea44bc 100644 --- a/cscore/CMakeLists.txt +++ b/cscore/CMakeLists.txt @@ -5,10 +5,9 @@ include(CompileWarnings) include(AddTest) include(LinkMacOSGUI) -find_package( OpenCV REQUIRED ) +find_package(OpenCV REQUIRED) -file(GLOB - cscore_native_src src/main/native/cpp/*.cpp) +file(GLOB cscore_native_src src/main/native/cpp/*.cpp) file(GLOB cscore_linux_src src/main/native/linux/*.cpp) file(GLOB cscore_osx_src src/main/native/osx/*.cpp) file(GLOB cscore_osx_objc_src src/main/native/objcpp/*.mm) @@ -18,10 +17,15 @@ add_library(cscore ${cscore_native_src}) set_target_properties(cscore PROPERTIES DEBUG_POSTFIX "d") if(NOT MSVC) - if (APPLE) + if(APPLE) target_sources(cscore PRIVATE ${cscore_osx_src} ${cscore_osx_objc_src}) target_compile_options(cscore PRIVATE "-fobjc-arc") - set_target_properties(cscore PROPERTIES LINK_FLAGS "-framework CoreFoundation -framework AVFoundation -framework Foundation -framework CoreMedia -framework CoreVideo") + set_target_properties( + cscore + PROPERTIES + LINK_FLAGS + "-framework CoreFoundation -framework AVFoundation -framework Foundation -framework CoreMedia -framework CoreVideo" + ) else() target_sources(cscore PRIVATE ${cscore_linux_src}) endif() @@ -31,9 +35,12 @@ else() target_compile_definitions(cscore PRIVATE -D_CRT_SECURE_NO_WARNINGS) endif() -target_include_directories(cscore PUBLIC - $ - $) +target_include_directories( + cscore + PUBLIC + $ + $ +) target_include_directories(cscore PRIVATE src/main/native/cpp) wpilib_target_warnings(cscore) target_link_libraries(cscore PUBLIC wpinet wpiutil ${OpenCV_LIBS}) @@ -41,17 +48,12 @@ target_link_libraries(cscore PUBLIC wpinet wpiutil ${OpenCV_LIBS}) set_property(TARGET cscore PROPERTY FOLDER "libraries") install(TARGETS cscore EXPORT cscore) +export(TARGETS cscore FILE cscore.cmake NAMESPACE cscore::) install(DIRECTORY src/main/native/include/ DESTINATION "${include_dest}/cscore") -if (WITH_FLAT_INSTALL) - set (cscore_config_dir ${wpilib_dest}) -else() - set (cscore_config_dir share/cscore) -endif() - -configure_file(cscore-config.cmake.in ${WPILIB_BINARY_DIR}/cscore-config.cmake ) -install(FILES ${WPILIB_BINARY_DIR}/cscore-config.cmake DESTINATION ${cscore_config_dir}) -install(EXPORT cscore DESTINATION ${cscore_config_dir}) +configure_file(cscore-config.cmake.in ${WPILIB_BINARY_DIR}/cscore-config.cmake) +install(FILES ${WPILIB_BINARY_DIR}/cscore-config.cmake DESTINATION share/cscore) +install(EXPORT cscore DESTINATION share/cscore) subdir_list(cscore_examples "${CMAKE_CURRENT_SOURCE_DIR}/examples") foreach(example ${cscore_examples}) @@ -68,7 +70,7 @@ foreach(example ${cscore_examples}) add_executable(cscore_${example} ${cscore_example_src}) wpilib_target_warnings(cscore_${example}) - if (${example} STREQUAL "usbviewer") + if(${example} STREQUAL "usbviewer") wpilib_link_macos_gui(cscore_${example}) endif() @@ -78,7 +80,7 @@ foreach(example ${cscore_examples}) endforeach() # Java bindings -if (WITH_JAVA) +if(WITH_JAVA) find_package(Java REQUIRED) find_package(JNI REQUIRED) include(UseJava) @@ -90,36 +92,68 @@ if (WITH_JAVA) set(OPENCV_JAVA_INSTALL_DIR ${OpenCV_INSTALL_PATH}/share/OpenCV/java/) endif() - find_file(OPENCV_JAR_FILE NAMES opencv-${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.jar PATHS ${OPENCV_JAVA_INSTALL_DIR} ${OpenCV_INSTALL_PATH}/bin ${OpenCV_INSTALL_PATH}/share/java NO_DEFAULT_PATH) - find_file(OPENCV_JNI_FILE NAMES libopencv_java${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.so - libopencv_java${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dylib - opencv_java${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll - PATHS ${OPENCV_JAVA_INSTALL_DIR} ${OpenCV_INSTALL_PATH}/bin ${OpenCV_INSTALL_PATH}/bin/Release ${OpenCV_INSTALL_PATH}/bin/Debug ${OpenCV_INSTALL_PATH}/lib ${OpenCV_INSTALL_PATH}/lib/jni NO_DEFAULT_PATH) - - file(GLOB - cscore_jni_src src/main/native/cpp/jni/CameraServerJNI.cpp) + find_file( + OPENCV_JAR_FILE + NAMES opencv-${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.jar + PATHS + ${OPENCV_JAVA_INSTALL_DIR} + ${OpenCV_INSTALL_PATH}/bin + ${OpenCV_INSTALL_PATH}/share/java + NO_DEFAULT_PATH + ) + find_file( + OPENCV_JNI_FILE + NAMES + libopencv_java${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.so + libopencv_java${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dylib + opencv_java${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll + PATHS + ${OPENCV_JAVA_INSTALL_DIR} + ${OpenCV_INSTALL_PATH}/bin + ${OpenCV_INSTALL_PATH}/bin/Release + ${OpenCV_INSTALL_PATH}/bin/Debug + ${OpenCV_INSTALL_PATH}/lib + ${OpenCV_INSTALL_PATH}/lib/jni + NO_DEFAULT_PATH + ) + + file(GLOB cscore_jni_src src/main/native/cpp/jni/CameraServerJNI.cpp) file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java) set(CMAKE_JNI_TARGET true) - add_jar(cscore_jar ${JAVA_SOURCES} INCLUDE_JARS wpiutil_jar ${OPENCV_JAR_FILE} OUTPUT_NAME cscore GENERATE_NATIVE_HEADERS cscore_jni_headers) + add_jar( + cscore_jar + ${JAVA_SOURCES} + INCLUDE_JARS wpiutil_jar ${OPENCV_JAR_FILE} + OUTPUT_NAME cscore + GENERATE_NATIVE_HEADERS cscore_jni_headers + ) - get_property(CSCORE_JAR_FILE TARGET cscore_jar PROPERTY JAR_FILE) - install(FILES ${CSCORE_JAR_FILE} DESTINATION "${java_lib_dest}") + install_jar(cscore_jar DESTINATION ${java_lib_dest}) + install_jar_exports(TARGETS cscore_jar FILE cscore_jar.cmake DESTINATION share/cscore) install(FILES ${OPENCV_JAR_FILE} DESTINATION "${java_lib_dest}") - if (MSVC) + if(MSVC) install(FILES ${OPENCV_JNI_FILE} DESTINATION "${jni_lib_dest}") foreach(cvFile ${OpenCV_LIBS}) - find_file(${cvFile}Loc NAMES ${cvFile}${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll - PATHS ${OPENCV_JAVA_INSTALL_DIR} ${OpenCV_INSTALL_PATH}/bin ${OpenCV_INSTALL_PATH}/bin/Release ${OpenCV_INSTALL_PATH}/bin/Debug ${OpenCV_INSTALL_PATH}/lib NO_DEFAULT_PATH) + find_file( + ${cvFile}Loc + NAMES + ${cvFile}${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll + PATHS + ${OPENCV_JAVA_INSTALL_DIR} + ${OpenCV_INSTALL_PATH}/bin + ${OpenCV_INSTALL_PATH}/bin/Release + ${OpenCV_INSTALL_PATH}/bin/Debug + ${OpenCV_INSTALL_PATH}/lib + NO_DEFAULT_PATH + ) install(FILES ${${cvFile}Loc} DESTINATION "${jni_lib_dest}") endforeach() endif() - set_property(TARGET cscore_jar PROPERTY FOLDER "java") - add_library(cscorejni ${cscore_jni_src}) wpilib_target_warnings(cscorejni) target_link_libraries(cscorejni PUBLIC cscore wpiutil ${OpenCV_LIBS}) @@ -130,18 +164,21 @@ if (WITH_JAVA) add_dependencies(cscorejni cscore_jar) install(TARGETS cscorejni EXPORT cscorejni) - + export(TARGETS cscorejni FILE cscorejni.cmake NAMESPACE cscorejni::) endif() -if (WITH_JAVA_SOURCE) +if(WITH_JAVA_SOURCE) find_package(Java REQUIRED) include(UseJava) file(GLOB CSCORE_SOURCES src/main/java/edu/wpi/first/cscore/*.java) file(GLOB CSCORE_RAW_SOURCES src/main/java/edu/wpi/first/cscore/raw/*.java) - add_jar(cscore_src_jar - RESOURCES NAMESPACE "edu/wpi/first/cscore" ${CSCORE_SOURCES} - NAMESPACE "edu/wpi/first/cscore/raw" ${CSCORE_RAW_SOURCES} - OUTPUT_NAME cscore-sources) + add_jar( + cscore_src_jar + RESOURCES + NAMESPACE "edu/wpi/first/cscore" ${CSCORE_SOURCES} + NAMESPACE "edu/wpi/first/cscore/raw" ${CSCORE_RAW_SOURCES} + OUTPUT_NAME cscore-sources + ) get_property(CSCORE_SRC_JAR_FILE TARGET cscore_src_jar PROPERTY JAR_FILE) install(FILES ${CSCORE_SRC_JAR_FILE} DESTINATION "${java_lib_dest}") @@ -149,7 +186,7 @@ if (WITH_JAVA_SOURCE) set_property(TARGET cscore_src_jar PROPERTY FOLDER "java") endif() -if (WITH_TESTS) +if(WITH_TESTS) wpilib_add_test(cscore src/test/native/cpp) target_link_libraries(cscore_test cscore gmock) endif() diff --git a/cscore/cscore-config.cmake.in b/cscore/cscore-config.cmake.in index 33e0af365ed..b9f28615113 100644 --- a/cscore/cscore-config.cmake.in +++ b/cscore/cscore-config.cmake.in @@ -1,7 +1,11 @@ include(CMakeFindDependencyMacro) @FILENAME_DEP_REPLACE@ @WPIUTIL_DEP_REPLACE@ +@WPINET_DEP_REPLACE@ find_dependency(OpenCV) @FILENAME_DEP_REPLACE@ include(${SELF_DIR}/cscore.cmake) +if(@WITH_JAVA@) + include(${SELF_DIR}/cscore_jar.cmake) +endif() diff --git a/cscore/examples/enum_usb/enum_usb.cpp b/cscore/examples/enum_usb/enum_usb.cpp index e9c1225a8c4..348c049b6e8 100644 --- a/cscore/examples/enum_usb/enum_usb.cpp +++ b/cscore/examples/enum_usb/enum_usb.cpp @@ -4,7 +4,7 @@ #include -#include +#include #include "cscore.h" @@ -12,11 +12,11 @@ int main() { CS_Status status = 0; for (const auto& caminfo : cs::EnumerateUsbCameras(&status)) { - fmt::print("{}: {} ({})\n", caminfo.dev, caminfo.path, caminfo.name); + wpi::print("{}: {} ({})\n", caminfo.dev, caminfo.path, caminfo.name); if (!caminfo.otherPaths.empty()) { std::puts("Other device paths:"); for (auto&& path : caminfo.otherPaths) { - fmt::print(" {}\n", path); + wpi::print(" {}\n", path); } } @@ -24,26 +24,26 @@ int main() { std::puts("Properties:"); for (const auto& prop : camera.EnumerateProperties()) { - fmt::print(" {}", prop.GetName()); + wpi::print(" {}", prop.GetName()); switch (prop.GetKind()) { case cs::VideoProperty::kBoolean: - fmt::print(" (bool): value={} default={}", prop.Get(), + wpi::print(" (bool): value={} default={}", prop.Get(), prop.GetDefault()); break; case cs::VideoProperty::kInteger: - fmt::print(" (int): value={} min={} max={} step={} default={}", + wpi::print(" (int): value={} min={} max={} step={} default={}", prop.Get(), prop.GetMin(), prop.GetMax(), prop.GetStep(), prop.GetDefault()); break; case cs::VideoProperty::kString: - fmt::print(" (string): {}", prop.GetString()); + wpi::print(" (string): {}", prop.GetString()); break; case cs::VideoProperty::kEnum: { - fmt::print(" (enum): value={}", prop.Get()); + wpi::print(" (enum): value={}", prop.Get()); auto choices = prop.GetChoices(); for (size_t i = 0; i < choices.size(); ++i) { if (!choices[i].empty()) { - fmt::print("\n {}: {}", i, choices[i]); + wpi::print("\n {}: {}", i, choices[i]); } } break; @@ -71,7 +71,7 @@ int main() { pixelFormat = "Unknown"; break; } - fmt::print(" PixelFormat:{} Width:{} Height:{} FPS:{}\n", pixelFormat, + wpi::print(" PixelFormat:{} Width:{} Height:{} FPS:{}\n", pixelFormat, mode.width, mode.height, mode.fps); } } diff --git a/cscore/examples/httpcvstream/httpcvstream.cpp b/cscore/examples/httpcvstream/httpcvstream.cpp index 38a00dbbf96..a0546d37e05 100644 --- a/cscore/examples/httpcvstream/httpcvstream.cpp +++ b/cscore/examples/httpcvstream/httpcvstream.cpp @@ -4,8 +4,8 @@ #include -#include #include +#include #include "cscore.h" #include "cscore_cv.h" @@ -24,10 +24,10 @@ int main() { for (;;) { uint64_t time = cvsink.GrabFrame(test); if (time == 0) { - fmt::print("error: {}\n", cvsink.GetError()); + wpi::print("error: {}\n", cvsink.GetError()); continue; } - fmt::print("got frame at time {} size ({}, {})\n", time, test.size().width, + wpi::print("got frame at time {} size ({}, {})\n", time, test.size().width, test.size().height); cv::flip(test, flip, 0); cvsource.PutFrame(flip); diff --git a/cscore/examples/settings/settings.cpp b/cscore/examples/settings/settings.cpp index 40961b45eae..777a8ccf6e1 100644 --- a/cscore/examples/settings/settings.cpp +++ b/cscore/examples/settings/settings.cpp @@ -6,8 +6,8 @@ #include #include -#include #include +#include #include "cscore.h" @@ -73,26 +73,26 @@ int main(int argc, char** argv) { // Print settings std::puts("Properties:"); for (const auto& prop : camera.EnumerateProperties()) { - fmt::print(" {}", prop.GetName()); + wpi::print(" {}", prop.GetName()); switch (prop.GetKind()) { case cs::VideoProperty::kBoolean: - fmt::print(" (bool): value={} default={}", prop.Get(), + wpi::print(" (bool): value={} default={}", prop.Get(), prop.GetDefault()); break; case cs::VideoProperty::kInteger: - fmt::print(" (int): value={} min={} max={} step={} default={}", + wpi::print(" (int): value={} min={} max={} step={} default={}", prop.Get(), prop.GetMin(), prop.GetMax(), prop.GetStep(), prop.GetDefault()); break; case cs::VideoProperty::kString: - fmt::print(" (string): {}", prop.GetString()); + wpi::print(" (string): {}", prop.GetString()); break; case cs::VideoProperty::kEnum: { - fmt::print(" (enum): value={}", prop.Get()); + wpi::print(" (enum): value={}", prop.Get()); auto choices = prop.GetChoices(); for (size_t i = 0; i < choices.size(); ++i) { if (!choices[i].empty()) { - fmt::print("\n {}: {}", i, choices[i]); + wpi::print("\n {}: {}", i, choices[i]); } } break; diff --git a/cscore/examples/usbcvstream/usbcvstream.cpp b/cscore/examples/usbcvstream/usbcvstream.cpp index 3635221abcd..ae37d3726c5 100644 --- a/cscore/examples/usbcvstream/usbcvstream.cpp +++ b/cscore/examples/usbcvstream/usbcvstream.cpp @@ -2,8 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -#include #include +#include #include "cscore.h" #include "cscore_cv.h" @@ -24,10 +24,10 @@ int main() { for (;;) { uint64_t time = cvsink.GrabFrame(test); if (time == 0) { - fmt::print("error: {}\n", cvsink.GetError()); + wpi::print("error: {}\n", cvsink.GetError()); continue; } - fmt::print("got frame at time {} size ({}, {})\n", time, test.size().width, + wpi::print("got frame at time {} size ({}, {})\n", time, test.size().width, test.size().height); cv::flip(test, flip, 0); cvsource.PutFrame(flip); diff --git a/cscore/examples/usbstream/usbstream.cpp b/cscore/examples/usbstream/usbstream.cpp index 7a57e8d9a3e..42b371fadb0 100644 --- a/cscore/examples/usbstream/usbstream.cpp +++ b/cscore/examples/usbstream/usbstream.cpp @@ -4,15 +4,15 @@ #include -#include +#include #include "cscore.h" int main() { - fmt::print("hostname: {}\n", cs::GetHostname()); + wpi::print("hostname: {}\n", cs::GetHostname()); std::puts("IPv4 network addresses:"); for (const auto& addr : cs::GetNetworkInterfaces()) { - fmt::print(" {}\n", addr); + wpi::print(" {}\n", addr); } cs::UsbCamera camera{"usbcam", 0}; camera.SetVideoMode(cs::VideoMode::kMJPEG, 320, 240, 30); @@ -22,7 +22,7 @@ int main() { CS_Status status = 0; cs::AddListener( [&](const cs::RawEvent& event) { - fmt::print("FPS={} MBPS={}\n", camera.GetActualFPS(), + wpi::print("FPS={} MBPS={}\n", camera.GetActualFPS(), (camera.GetActualDataRate() / 1000000.0)); }, cs::RawEvent::kTelemetryUpdated, false, &status); diff --git a/cscore/examples/usbviewer/usbviewer.cpp b/cscore/examples/usbviewer/usbviewer.cpp index 5c2e7c94c4e..4653c516cd4 100644 --- a/cscore/examples/usbviewer/usbviewer.cpp +++ b/cscore/examples/usbviewer/usbviewer.cpp @@ -6,13 +6,12 @@ #include #include -#include - #define IMGUI_DEFINE_MATH_OPERATORS #include #include #include #include +#include #include #include @@ -39,7 +38,7 @@ int main() { // get frame from camera uint64_t time = cvsink.GrabFrame(frame); if (time == 0) { - fmt::print("error: {}\n", cvsink.GetError()); + wpi::print("error: {}\n", cvsink.GetError()); continue; } diff --git a/cscore/src/dev/native/cpp/main.cpp b/cscore/src/dev/native/cpp/main.cpp index 279d72a5e81..9f7630525e0 100644 --- a/cscore/src/dev/native/cpp/main.cpp +++ b/cscore/src/dev/native/cpp/main.cpp @@ -2,10 +2,10 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -#include +#include #include "cscore.h" int main() { - fmt::print("{}\n", cs::GetHostname()); + wpi::print("{}\n", cs::GetHostname()); } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/AxisCamera.java b/cscore/src/main/java/edu/wpi/first/cscore/AxisCamera.java index 296bd6bd14f..6165fb545d3 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/AxisCamera.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/AxisCamera.java @@ -4,7 +4,12 @@ package edu.wpi.first.cscore; -/** A source that represents an Axis IP camera. */ +/** + * A source that represents an Axis IP camera. + * + * @deprecated Use HttpCamera instead. + */ +@Deprecated(forRemoval = true, since = "2025") public class AxisCamera extends HttpCamera { private static String hostToUrl(String host) { return "http://" + host + "/mjpg/video.mjpg"; diff --git a/cscore/src/main/java/edu/wpi/first/cscore/CameraServerJNI.java b/cscore/src/main/java/edu/wpi/first/cscore/CameraServerJNI.java index 148be68cfca..0d874a7dd83 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/CameraServerJNI.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/CameraServerJNI.java @@ -4,28 +4,43 @@ package edu.wpi.first.cscore; -import edu.wpi.first.cscore.raw.RawFrame; +import edu.wpi.first.util.RawFrame; import edu.wpi.first.util.RuntimeLoader; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; +/** CameraServer JNI. */ public class CameraServerJNI { static boolean libraryLoaded = false; static RuntimeLoader loader = null; + /** Sets whether JNI should be loaded in the static block. */ public static class Helper { private static AtomicBoolean extractOnStaticLoad = new AtomicBoolean(true); + /** + * Returns true if the JNI should be loaded in the static block. + * + * @return True if the JNI should be loaded in the static block. + */ public static boolean getExtractOnStaticLoad() { return extractOnStaticLoad.get(); } + /** + * Sets whether the JNI should be loaded in the static block. + * + * @param load Whether the JNI should be loaded in the static block. + */ public static void setExtractOnStaticLoad(boolean load) { extractOnStaticLoad.set(load); } + + /** Utility class. */ + private Helper() {} } static { @@ -62,148 +77,522 @@ public static synchronized void forceLoad() throws IOException { // // Property Functions // + + /** + * Returns property kind. + * + * @param property Property handle. + * @return Property kind. + */ public static native int getPropertyKind(int property); + /** + * Returns property name. + * + * @param property Property handle. + * @return Property name. + */ public static native String getPropertyName(int property); + /** + * Returns property value. + * + * @param property Property handle. + * @return Property value. + */ public static native int getProperty(int property); + /** + * Sets property value. + * + * @param property Property handle. + * @param value Property value. + */ public static native void setProperty(int property, int value); + /** + * Returns property minimum. + * + * @param property Property handle. + * @return Property minimum. + */ public static native int getPropertyMin(int property); + /** + * Returns property maximum. + * + * @param property Property handle. + * @return Property maximum. + */ public static native int getPropertyMax(int property); + /** + * Returns property step. + * + * @param property Property handle. + * @return Property step. + */ public static native int getPropertyStep(int property); + /** + * Returns property default value. + * + * @param property Property handle. + * @return Property default value. + */ public static native int getPropertyDefault(int property); + /** + * Returns property value as a string. + * + * @param property Property handle. + * @return Property value as a string. + */ public static native String getStringProperty(int property); + /** + * Sets property value to a string. + * + * @param property Property handle. + * @param value Property value string. + */ public static native void setStringProperty(int property, String value); + /** + * Returns enum of possible property value strings. + * + * @param property Property handle. + * @return Enum of possible property value strings. + */ public static native String[] getEnumPropertyChoices(int property); // // Source Creation Functions // + + /** + * Creates a new USB camera by device. + * + * @param name USB camera name. + * @param dev USB camera device number. + * @return USB camera handle. + */ public static native int createUsbCameraDev(String name, int dev); + /** + * Creates a new USB camera by path. + * + * @param name USB camera name. + * @param path USB camera path. + * @return USB camera handle. + */ public static native int createUsbCameraPath(String name, String path); + /** + * Creates an HTTP camera. + * + * @param name HTTP camera name. + * @param url HTTP camera stream URL. + * @param kind HTTP camera kind. + * @return HTTP camera handle. + */ public static native int createHttpCamera(String name, String url, int kind); + /** + * Creates an HTTP camera from multiple URLs. + * + * @param name HTTP camera name. + * @param urls HTTP camera stream URLs. + * @param kind HTTP camera kind. + * @return HTTP camera handle. + */ public static native int createHttpCameraMulti(String name, String[] urls, int kind); + /** + * Creates a raw source. + * + * @param name Source name. + * @param isCv true for a Cv source. + * @param pixelFormat Pixel format. + * @param width Image width. + * @param height Image height. + * @param fps Source frames per second. + * @return Raw source handle. + */ public static native int createRawSource( - String name, int pixelFormat, int width, int height, int fps); + String name, boolean isCv, int pixelFormat, int width, int height, int fps); // // Source Functions // + + /** + * Returns source kind. + * + * @param source Source handle. + * @return Source kind. + */ public static native int getSourceKind(int source); + /** + * Returns source name. + * + * @param source Source handle. + * @return Source name. + */ public static native String getSourceName(int source); + /** + * Returns source description. + * + * @param source Source handle. + * @return Source description. + */ public static native String getSourceDescription(int source); + /** + * Returns source's last frame time. + * + * @param source Source handle. + * @return Source's last frame time. + */ public static native long getSourceLastFrameTime(int source); + /** + * Sets source connection strategy. + * + * @param source Source handle. + * @param strategy Connection strategy. + */ public static native void setSourceConnectionStrategy(int source, int strategy); + /** + * Returns true if source is connected. + * + * @param source Source handle. + * @return True if source is connected. + */ public static native boolean isSourceConnected(int source); + /** + * Returns true if source is enabled. + * + * @param source Source handle. + * @return True if source is enabled. + */ public static native boolean isSourceEnabled(int source); + /** + * Returns source property. + * + * @param source Source handle. + * @param name Source property name. + * @return Source property. + */ public static native int getSourceProperty(int source, String name); + /** + * Returns list of source property handles. + * + * @param source Source handle. + * @return List of source property handles. + */ public static native int[] enumerateSourceProperties(int source); + /** + * Returns source video mode. + * + * @param source Source handle. + * @return Source video mode. + */ public static native VideoMode getSourceVideoMode(int source); + /** + * Sets source video mode. + * + * @param source Source handle. + * @param pixelFormat Pixel format. + * @param width Image width. + * @param height Image height. + * @param fps Source frames per second. + * @return True if set succeeded. + */ public static native boolean setSourceVideoMode( int source, int pixelFormat, int width, int height, int fps); + /** + * Sets source pixel format. + * + * @param source Source handle. + * @param pixelFormat Source pixel format. + * @return True if set succeeded. + */ public static native boolean setSourcePixelFormat(int source, int pixelFormat); + /** + * Sets source resolution. + * + * @param source Source handle. + * @param width Image width. + * @param height Image height. + * @return True if set succeeded. + */ public static native boolean setSourceResolution(int source, int width, int height); + /** + * Sets source FPS. + * + * @param source Source handle. + * @param fps Source frames per second. + * @return True if set succeeded. + */ public static native boolean setSourceFPS(int source, int fps); + /** + * Sets source configuration JSON. + * + * @param source Source handle. + * @param config Configuration JSON. + * @return True if set succeeded. + */ public static native boolean setSourceConfigJson(int source, String config); + /** + * Returns source configuration JSON. + * + * @param source Source handle. + * @return Source configuration JSON. + */ public static native String getSourceConfigJson(int source); + /** + * Returns list of source's supported video modes. + * + * @param source Source handle. + * @return List of source's supported video modes. + */ public static native VideoMode[] enumerateSourceVideoModes(int source); + /** + * Returns list of source sinks. + * + * @param source Source handle. + * @return List of source sinks. + */ public static native int[] enumerateSourceSinks(int source); + /** + * Copies source. + * + * @param source Source handle. + * @return New source handle. + */ public static native int copySource(int source); + /** + * Releases source. + * + * @param source Source handle. + */ public static native void releaseSource(int source); // // Camera Source Common Property Functions // + + /** + * Sets camera brightness. + * + * @param source Source handle. + * @param brightness Brightness. + */ public static native void setCameraBrightness(int source, int brightness); + /** + * Returns camera brightness. + * + * @param source Source handle. + * @return Camera brightness. + */ public static native int getCameraBrightness(int source); + /** + * Sets camera white balance to auto. + * + * @param source Source handle. + */ public static native void setCameraWhiteBalanceAuto(int source); + /** + * Sets camera white balance to "hold current". + * + * @param source Source handle. + */ public static native void setCameraWhiteBalanceHoldCurrent(int source); + /** + * Sets camera white balance to the given value. + * + * @param source Source handle. + * @param value White balance. + */ public static native void setCameraWhiteBalanceManual(int source, int value); + /** + * Sets camera exposure to auto. + * + * @param source Source handle. + */ public static native void setCameraExposureAuto(int source); + /** + * Sets camera exposure to "hold current". + * + * @param source Source handle. + */ public static native void setCameraExposureHoldCurrent(int source); + /** + * Sets camera exposure to the given value. + * + * @param source Source handle. + * @param value Exposure. + */ public static native void setCameraExposureManual(int source, int value); // // UsbCamera Source Functions // + + /** + * Sets USB camera path. + * + * @param source Source handle. + * @param path USB camera path. + */ public static native void setUsbCameraPath(int source, String path); + /** + * Returns USB camera path. + * + * @param source Source handle. + * @return USB camera path. + */ public static native String getUsbCameraPath(int source); + /** + * Returns USB camera info. + * + * @param source Source handle. + * @return USB camera info. + */ public static native UsbCameraInfo getUsbCameraInfo(int source); // // HttpCamera Source Functions // + + /** + * Returns HTTP camera kind. + * + * @param source Source handle. + * @return HTTP camera kind. + */ public static native int getHttpCameraKind(int source); + /** + * Sets HTTP camera URLs. + * + * @param source Source handle. + * @param urls HTTP camera URLs. + */ public static native void setHttpCameraUrls(int source, String[] urls); + /** + * Returns HTTP camera URLs. + * + * @param source Source handle. + * @return HTTP camera URLs. + */ public static native String[] getHttpCameraUrls(int source); // // Image Source Functions // + + /** + * Puts raw frame into source. + * + * @param source Source handle. + * @param frame Frame handle. + */ + public static native void putRawSourceFrame(int source, long frame); + + /** + * Puts raw frame into source. + * + * @param source Source handle. + * @param data Frame byte buffer. + * @param size Frame size. + * @param width Frame width. + * @param height Frame height. + * @param stride Frame stride. + * @param pixelFormat Frame pixel format. + */ public static native void putRawSourceFrameBB( - int source, ByteBuffer data, int width, int height, int pixelFormat, int totalData); - - public static native void putRawSourceFrame( - int source, long data, int width, int height, int pixelFormat, int totalData); - - public static void putRawSourceFrame(int source, RawFrame raw) { - putRawSourceFrame( - source, - raw.getDataPtr(), - raw.getWidth(), - raw.getHeight(), - raw.getPixelFormat(), - raw.getTotalData()); - } + int source, ByteBuffer data, int size, int width, int height, int stride, int pixelFormat); + /** + * Puts raw frame into source. + * + * @param source Source handle. + * @param data Frame handle. + * @param size Frame size. + * @param width Frame width. + * @param height Frame height. + * @param stride Frame stride. + * @param pixelFormat Frame pixel format. + */ + public static native void putRawSourceFrameData( + int source, long data, int size, int width, int height, int stride, int pixelFormat); + + /** + * Notify source error. + * + * @param source Source handle. + * @param msg Error message. + */ public static native void notifySourceError(int source, String msg); + /** + * Sets whether source is connected. + * + * @param source Source handle. + * @param connected True if source is connected. + */ public static native void setSourceConnected(int source, boolean connected); + /** + * Sets source description. + * + * @param source Source handle. + * @param description Source description. + */ public static native void setSourceDescription(int source, String description); + /** + * Creates a source property. + * + * @param source Source handle. + * @param name Property name. + * @param kind Property kind. + * @param minimum Property minimum. + * @param maximum Property maximum. + * @param step Property step. + * @param defaultValue Property default value. + * @param value Property value. + * @return Source property handle. + */ public static native int createSourceProperty( int source, String name, @@ -214,127 +603,293 @@ public static native int createSourceProperty( int defaultValue, int value); + /** + * Sets list of possible property values. + * + * @param source Source handle. + * @param property Property handle. + * @param choices List of possible property values. + */ public static native void setSourceEnumPropertyChoices( int source, int property, String[] choices); // // Sink Creation Functions // + + /** + * Creates an MJPEG server. + * + * @param name MJPEG server name. + * @param listenAddress IP address at which server should listen. + * @param port Port on which server should listen. + * @return MJPEG server handle. + */ public static native int createMjpegServer(String name, String listenAddress, int port); - public static native int createRawSink(String name); + /** + * Creates a raw sink. + * + * @param name Sink name. + * @param isCv true for a Cv source. + * @return Raw sink handle. + */ + public static native int createRawSink(String name, boolean isCv); // // Sink Functions // + + /** + * Returns sink kind. + * + * @param sink Sink handle. + * @return Sink kind. + */ public static native int getSinkKind(int sink); + /** + * Returns sink name. + * + * @param sink Sink handle. + * @return Sink name. + */ public static native String getSinkName(int sink); + /** + * Returns sink description. + * + * @param sink Sink handle. + * @return Sink description. + */ public static native String getSinkDescription(int sink); + /** + * Returns sink property. + * + * @param sink Sink handle. + * @param name Property name. + * @return Sink property handle. + */ public static native int getSinkProperty(int sink, String name); + /** + * Returns list of sink property handles. + * + * @param sink Sink handle. + * @return List of sink property handles. + */ public static native int[] enumerateSinkProperties(int sink); + /** + * Sets sink configuration JSON. + * + * @param sink Sink handle. + * @param config Configuration JSON. + * @return True if set succeeded. + */ public static native boolean setSinkConfigJson(int sink, String config); + /** + * Returns sink configuration JSON. + * + * @param sink Sink handle. + * @return Sink configuration JSON. + */ public static native String getSinkConfigJson(int sink); + /** + * Sets sink source. + * + * @param sink Sink handle. + * @param source Source handle. + */ public static native void setSinkSource(int sink, int source); + /** + * Returns sink source property. + * + * @param sink Sink handle. + * @param name Property name. + * @return Sink source property handle. + */ public static native int getSinkSourceProperty(int sink, String name); + /** + * Returns sink source. + * + * @param sink Sink handle. + * @return Sink source handle. + */ public static native int getSinkSource(int sink); + /** + * Copies sink. + * + * @param sink Sink handle. + * @return New sink handle. + */ public static native int copySink(int sink); + /** + * Releases sink. + * + * @param sink Sink handle. + */ public static native void releaseSink(int sink); // // MjpegServer Sink Functions // + + /** + * Returns MJPEG server listen address. + * + * @param sink Sink handle. + * @return MJPEG server listen address. + */ public static native String getMjpegServerListenAddress(int sink); + /** + * Returns MJPEG server port. + * + * @param sink Sink handle. + * @return MJPEG server port. + */ public static native int getMjpegServerPort(int sink); // // Image Sink Functions // + + /** + * Sets sink description. + * + * @param sink Sink handle. + * @param description Sink description. + */ public static native void setSinkDescription(int sink, String description); - private static native long grabRawSinkFrameImpl( - int sink, - RawFrame rawFrame, - long rawFramePtr, - ByteBuffer byteBuffer, - int width, - int height, - int pixelFormat); - - private static native long grabRawSinkFrameTimeoutImpl( - int sink, - RawFrame rawFrame, - long rawFramePtr, - ByteBuffer byteBuffer, - int width, - int height, - int pixelFormat, - double timeout); - - public static long grabSinkFrame(int sink, RawFrame rawFrame) { - return grabRawSinkFrameImpl( - sink, - rawFrame, - rawFrame.getFramePtr(), - rawFrame.getDataByteBuffer(), - rawFrame.getWidth(), - rawFrame.getHeight(), - rawFrame.getPixelFormat()); - } + /** + * Returns raw sink frame. + * + * @param sink Sink handle. + * @param frame Raw frame. + * @param nativeObj Native object. + * @return Raw sink frame handle. + */ + public static native long grabRawSinkFrame(int sink, RawFrame frame, long nativeObj); - public static long grabSinkFrameTimeout(int sink, RawFrame rawFrame, double timeout) { - return grabRawSinkFrameTimeoutImpl( - sink, - rawFrame, - rawFrame.getFramePtr(), - rawFrame.getDataByteBuffer(), - rawFrame.getWidth(), - rawFrame.getHeight(), - rawFrame.getPixelFormat(), - timeout); - } + /** + * Returns raw sink frame timeout. + * + * @param sink Sink handle. + * @param frame Raw frame. + * @param nativeObj Native object. + * @param timeout Timeout in seconds. + * @return Raw sink frame timeout. + */ + public static native long grabRawSinkFrameTimeout( + int sink, RawFrame frame, long nativeObj, double timeout); + /** + * Returns sink error message. + * + * @param sink Sink handle. + * @return Sink error message. + */ public static native String getSinkError(int sink); + /** + * Sets sink enable. + * + * @param sink Sink handle. + * @param enabled True if sink should be enabled. + */ public static native void setSinkEnabled(int sink, boolean enabled); // // Listener Functions // + + /** + * Adds listener. + * + * @param listener Video event callback. + * @param eventMask Event mask. + * @param immediateNotify True to immediately notify on event. + * @return Listener handle. + */ public static native int addListener( Consumer listener, int eventMask, boolean immediateNotify); + /** + * Removes listener. + * + * @param handle Listener handle. + */ public static native void removeListener(int handle); + /** + * Creates listener poller. + * + * @return Listener poller handle. + */ public static native int createListenerPoller(); + /** + * Destroys listener poller. + * + * @param poller Listener poller handle. + */ public static native void destroyListenerPoller(int poller); + /** + * Add polled listener. + * + * @param poller Poller handle. + * @param eventMask Event mask. + * @param immediateNotify True to immediately notify on event. + * @return Polled listener handle. + */ public static native int addPolledListener(int poller, int eventMask, boolean immediateNotify); + /** + * Polls listener. + * + * @param poller Poller handle. + * @return List of video events. + * @throws InterruptedException if polling was interrupted. + */ public static native VideoEvent[] pollListener(int poller) throws InterruptedException; + /** + * Polls listener with timeout. + * + * @param poller Poller handle. + * @param timeout Timeout in seconds. + * @return List of video events. + * @throws InterruptedException if polling was interrupted. + */ public static native VideoEvent[] pollListenerTimeout(int poller, double timeout) throws InterruptedException; + /** + * Cancels poll listener. + * + * @param poller Poller handle. + */ public static native void cancelPollListener(int poller); // // Telemetry Functions // + + /** Telemetry kind. */ public enum TelemetryKind { + /** kSourceBytesReceived. */ kSourceBytesReceived(1), + /** kSourceFramesReceived. */ kSourceFramesReceived(2); private final int value; @@ -343,23 +898,66 @@ public enum TelemetryKind { this.value = value; } + /** + * Returns telemetry kind value. + * + * @return Telemetry kind value. + */ public int getValue() { return value; } } + /** + * Sets telemetry period. + * + * @param seconds Telemetry period in seconds. + */ public static native void setTelemetryPeriod(double seconds); + /** + * Returns telemetry elapsed time. + * + * @return Telemetry elapsed time. + */ public static native double getTelemetryElapsedTime(); + /** + * Returns telemetry value. + * + * @param handle Telemetry handle. + * @param kind Telemetry kind. + * @return Telemetry value. + */ public static native long getTelemetryValue(int handle, int kind); + /** + * Returns telemetry value. + * + * @param handle Telemetry handle. + * @param kind Telemetry kind. + * @return Telemetry value. + */ public static long getTelemetryValue(int handle, TelemetryKind kind) { return getTelemetryValue(handle, kind.getValue()); } + /** + * Returns telemetry average value. + * + * @param handle Telemetry handle. + * @param kind Telemetry kind. + * @return Telemetry average value. + */ public static native double getTelemetryAverageValue(int handle, int kind); + /** + * Returns telemetry average value. + * + * @param handle Telemetry handle. + * @param kind Telemetry kind. + * @return Telemetry average value. + */ public static double getTelemetryAverageValue(int handle, TelemetryKind kind) { return getTelemetryAverageValue(handle, kind.getValue()); } @@ -367,33 +965,82 @@ public static double getTelemetryAverageValue(int handle, TelemetryKind kind) { // // Logging Functions // + + /** Logger functional interface. */ @FunctionalInterface public interface LoggerFunction { + /** + * Log a string. + * + * @param level Log level. + * @param file Log file. + * @param line Line number. + * @param msg Log message. + */ void apply(int level, String file, int line, String msg); } + /** + * Sets logger. + * + * @param func Logger function. + * @param minLevel Minimum logging level. + */ public static native void setLogger(LoggerFunction func, int minLevel); // // Utility Functions // + + /** + * Returns list of USB cameras. + * + * @return List of USB cameras. + */ public static native UsbCameraInfo[] enumerateUsbCameras(); + /** + * Returns list of sources. + * + * @return List of sources. + */ public static native int[] enumerateSources(); + /** + * Returns list of sinks. + * + * @return List of sinks. + */ public static native int[] enumerateSinks(); + /** + * Returns hostname. + * + * @return Hostname. + */ public static native String getHostname(); + /** + * Returns list of network interfaces. + * + * @return List of network interfaces. + */ public static native String[] getNetworkInterfaces(); - public static native long allocateRawFrame(); - - public static native void freeRawFrame(long frame); - + /** Runs main run loop. */ public static native void runMainRunLoop(); + /** + * Runs main run loop with timeout. + * + * @param timeoutSeconds Timeout in seconds. + * @return 3 on timeout, 2 on signal, 1 on other. + */ public static native int runMainRunLoopTimeout(double timeoutSeconds); + /** Stops main run loop. */ public static native void stopMainRunLoop(); + + /** Utility class. */ + private CameraServerJNI() {} } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/CvSink.java b/cscore/src/main/java/edu/wpi/first/cscore/CvSink.java index 88ca8b1b548..a6db5978da9 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/CvSink.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/CvSink.java @@ -4,6 +4,10 @@ package edu.wpi.first.cscore; +import edu.wpi.first.util.PixelFormat; +import edu.wpi.first.util.RawFrame; +import java.nio.ByteBuffer; +import org.opencv.core.CvType; import org.opencv.core.Mat; /** @@ -11,32 +15,72 @@ * OpenCV builds. For an alternate OpenCV, see the documentation how to build your own with RawSink. */ public class CvSink extends ImageSink { + private final RawFrame m_frame = new RawFrame(); + private Mat m_tmpMat; + private ByteBuffer m_origByteBuffer; + private int m_width; + private int m_height; + private PixelFormat m_pixelFormat; + + @Override + public void close() { + if (m_tmpMat != null) { + m_tmpMat.release(); + } + m_frame.close(); + super.close(); + } + + private int getCVFormat(PixelFormat pixelFormat) { + int type = 0; + switch (pixelFormat) { + case kYUYV: + case kRGB565: + case kY16: + case kUYVY: + type = CvType.CV_8UC2; + break; + case kBGR: + type = CvType.CV_8UC3; + break; + case kBGRA: + type = CvType.CV_8UC4; + break; + case kGray: + case kMJPEG: + default: + type = CvType.CV_8UC1; + break; + } + return type; + } + /** - * Create a sink for accepting OpenCV images. WaitForFrame() must be called on the created sink to + * Create a sink for accepting OpenCV images. grabFrame() must be called on the created sink to * get each new image. * * @param name Source name (arbitrary unique identifier) + * @param pixelFormat Source pixel format */ - public CvSink(String name) { - super(CameraServerCvJNI.createCvSink(name)); + public CvSink(String name, PixelFormat pixelFormat) { + super(CameraServerJNI.createRawSink(name, true)); + m_pixelFormat = pixelFormat; + OpenCvLoader.forceStaticLoad(); } - /// Create a sink for accepting OpenCV images in a separate thread. - /// A thread will be created that calls WaitForFrame() and calls the - /// processFrame() callback each time a new frame arrives. - /// @param name Source name (arbitrary unique identifier) - /// @param processFrame Frame processing function; will be called with a - /// time=0 if an error occurred. processFrame should call GetImage() - /// or GetError() as needed, but should not call (except in very - /// unusual circumstances) WaitForImage(). - // public CvSink(wpi::StringRef name, - // std::function processFrame) { - // super(CameraServerJNI.createCvSinkCallback(name, processFrame)); - // } + /** + * Create a sink for accepting OpenCV images. WaitForFrame() must be called on the created sink to + * get each new image. Defaults to kBGR for pixelFormat + * + * @param name Source name (arbitrary unique identifier) + */ + public CvSink(String name) { + this(name, PixelFormat.kBGR); + } /** * Wait for the next frame and get the image. Times out (returning 0) after 0.225 seconds. The - * provided image will have three 3-bit channels stored in BGR order. + * provided image will have the pixelFormat this class was constructed with. * * @param image Where to store the image. * @return Frame time, or 0 on error (call GetError() to obtain the error message) @@ -47,7 +91,7 @@ public long grabFrame(Mat image) { /** * Wait for the next frame and get the image. Times out (returning 0) after timeout seconds. The - * provided image will have three 3-bit channels stored in BGR order. + * provided image will have the pixelFormat this class was constructed with. * * @param image Where to store the image. * @param timeout Retrieval timeout in seconds. @@ -55,18 +99,140 @@ public long grabFrame(Mat image) { * is in 1 us increments. */ public long grabFrame(Mat image, double timeout) { - return CameraServerCvJNI.grabSinkFrameTimeout(m_handle, image.nativeObj, timeout); + long rv = grabFrameDirect(timeout); + if (rv <= 0) { + return rv; + } + m_tmpMat.copyTo(image); + return rv; } /** - * Wait for the next frame and get the image. May block forever. The provided image will have - * three 3-bit channels stored in BGR order. + * Wait for the next frame and get the image. May block forever. The provided image will have the + * pixelFormat this class was constructed with. * * @param image Where to store the image. * @return Frame time, or 0 on error (call GetError() to obtain the error message); the frame time * is in 1 us increments. */ public long grabFrameNoTimeout(Mat image) { - return CameraServerCvJNI.grabSinkFrame(m_handle, image.nativeObj); + long rv = grabFrameNoTimeoutDirect(); + if (rv <= 0) { + return rv; + } + m_tmpMat.copyTo(image); + return rv; + } + + /** + * Get the direct backing mat for this sink. + * + *

This mat can be invalidated any time any of the grab* methods are called, or when the CvSink + * is closed. + * + * @return The backing mat. + */ + public Mat getDirectMat() { + return m_tmpMat; + } + + /** + * Wait for the next frame and store the image. Times out (returning 0) after 0.225 seconds. The + * provided image will have the pixelFormat this class was constructed with. Use getDirectMat() to + * grab the image. + * + * @return Frame time, or 0 on error (call GetError() to obtain the error message) + */ + public long grabFrameDirect() { + return grabFrameDirect(0.225); + } + + /** + * Wait for the next frame and store the image. Times out (returning 0) after timeout seconds. The + * provided image will have the pixelFormat this class was constructed with. Use getDirectMat() to + * grab the image. + * + * @param timeout Retrieval timeout in seconds. + * @return Frame time, or 0 on error (call GetError() to obtain the error message); the frame time + * is in 1 us increments. + */ + @SuppressWarnings("PMD.CompareObjectsWithEquals") + public long grabFrameDirect(double timeout) { + m_frame.setInfo(0, 0, 0, m_pixelFormat); + long rv = + CameraServerJNI.grabRawSinkFrameTimeout(m_handle, m_frame, m_frame.getNativeObj(), timeout); + if (rv <= 0) { + return rv; + } + + if (m_frame.getData() != m_origByteBuffer + || m_width != m_frame.getWidth() + || m_height != m_frame.getHeight() + || m_pixelFormat != m_frame.getPixelFormat()) { + m_origByteBuffer = m_frame.getData(); + m_height = m_frame.getHeight(); + m_width = m_frame.getWidth(); + m_pixelFormat = m_frame.getPixelFormat(); + if (m_frame.getStride() == 0) { + m_tmpMat = + new Mat( + m_frame.getHeight(), + m_frame.getWidth(), + getCVFormat(m_pixelFormat), + m_origByteBuffer); + } else { + m_tmpMat = + new Mat( + m_frame.getHeight(), + m_frame.getWidth(), + getCVFormat(m_pixelFormat), + m_origByteBuffer, + m_frame.getStride()); + } + } + return rv; + } + + /** + * Wait for the next frame and store the image. May block forever. The provided image will have + * the pixelFormat this class was constructed with. Use getDirectMat() to grab the image. + * + * @return Frame time, or 0 on error (call GetError() to obtain the error message); the frame time + * is in 1 us increments. + */ + @SuppressWarnings("PMD.CompareObjectsWithEquals") + public long grabFrameNoTimeoutDirect() { + m_frame.setInfo(0, 0, 0, m_pixelFormat); + long rv = CameraServerJNI.grabRawSinkFrame(m_handle, m_frame, m_frame.getNativeObj()); + if (rv <= 0) { + return rv; + } + + if (m_frame.getData() != m_origByteBuffer + || m_width != m_frame.getWidth() + || m_height != m_frame.getHeight() + || m_pixelFormat != m_frame.getPixelFormat()) { + m_origByteBuffer = m_frame.getData(); + m_height = m_frame.getHeight(); + m_width = m_frame.getWidth(); + m_pixelFormat = m_frame.getPixelFormat(); + if (m_frame.getStride() == 0) { + m_tmpMat = + new Mat( + m_frame.getHeight(), + m_frame.getWidth(), + getCVFormat(m_pixelFormat), + m_origByteBuffer); + } else { + m_tmpMat = + new Mat( + m_frame.getHeight(), + m_frame.getWidth(), + getCVFormat(m_pixelFormat), + m_origByteBuffer, + m_frame.getStride()); + } + } + return rv; } } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/CvSource.java b/cscore/src/main/java/edu/wpi/first/cscore/CvSource.java index 3934a09c0b4..f3bd147274e 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/CvSource.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/CvSource.java @@ -4,6 +4,7 @@ package edu.wpi.first.cscore; +import edu.wpi.first.util.PixelFormat; import org.opencv.core.Mat; /** @@ -19,8 +20,9 @@ public class CvSource extends ImageSource { */ public CvSource(String name, VideoMode mode) { super( - CameraServerCvJNI.createCvSource( - name, mode.pixelFormat.getValue(), mode.width, mode.height, mode.fps)); + CameraServerJNI.createRawSource( + name, true, mode.pixelFormat.getValue(), mode.width, mode.height, mode.fps)); + OpenCvLoader.forceStaticLoad(); } /** @@ -32,20 +34,148 @@ public CvSource(String name, VideoMode mode) { * @param height height * @param fps fps */ - public CvSource(String name, VideoMode.PixelFormat pixelFormat, int width, int height, int fps) { - super(CameraServerCvJNI.createCvSource(name, pixelFormat.getValue(), width, height, fps)); + public CvSource(String name, PixelFormat pixelFormat, int width, int height, int fps) { + super(CameraServerJNI.createRawSource(name, true, pixelFormat.getValue(), width, height, fps)); + OpenCvLoader.forceStaticLoad(); + } + + /** + * Put an OpenCV image and notify sinks + * + *

The image format is guessed from the number of channels. The channel mapping is as follows. + * 1: kGray 2: kYUYV 3: BGR 4: BGRA Any other channel numbers will throw an error. If your image + * is an in alternate format, use the overload that takes a PixelFormat. + * + * @param image OpenCV Image + */ + public void putFrame(Mat image) { + // We only support 8 bit channels + boolean cleanupRequired = false; + Mat finalImage; + if (image.depth() == 0) { + finalImage = image; + } else { + finalImage = new Mat(); + image.convertTo(finalImage, 0); + cleanupRequired = true; + } + + try { + int channels = finalImage.channels(); + PixelFormat format; + if (channels == 1) { + // 1 channel is assumed Graysacle + format = PixelFormat.kGray; + } else if (channels == 2) { + // 2 channels is assumed YUYV + format = PixelFormat.kYUYV; + } else if (channels == 3) { + // 3 channels is assumed BGR + format = PixelFormat.kBGR; + } else if (channels == 4) { + // 4 channels is assumed BGRA + format = PixelFormat.kBGRA; + } else { + throw new VideoException("Unable to get pixel format for " + channels + " channels"); + } + + putFrame(finalImage, format, true); + } finally { + if (cleanupRequired) { + finalImage.release(); + } + } } /** * Put an OpenCV image and notify sinks. * - *

Only 8-bit single-channel or 3-channel (with BGR channel order) images are supported. If the - * format, depth or channel order is different, use Mat.convertTo() and/or cvtColor() to convert - * it first. + *

The format of the Mat must match the PixelFormat. You will corrupt memory if they dont. With + * skipVerification false, we will verify the number of channels matches the pixel format. If + * skipVerification is true, this step is skipped and is passed straight through. * * @param image OpenCV image + * @param format The pixel format of the image + * @param skipVerification skip verifying pixel format */ - public void putFrame(Mat image) { - CameraServerCvJNI.putSourceFrame(m_handle, image.nativeObj); + public void putFrame(Mat image, PixelFormat format, boolean skipVerification) { + // We only support 8-bit images, convert if necessary + boolean cleanupRequired = false; + Mat finalImage; + if (image.depth() == 0) { + finalImage = image; + } else { + finalImage = new Mat(); + image.convertTo(finalImage, 0); + cleanupRequired = true; + } + + try { + if (!skipVerification) { + verifyFormat(finalImage, format); + } + long step = image.step1() * image.elemSize1(); + CameraServerJNI.putRawSourceFrameData( + m_handle, + finalImage.dataAddr(), + (int) finalImage.total() * finalImage.channels(), + finalImage.width(), + finalImage.height(), + (int) step, + format.getValue()); + + } finally { + if (cleanupRequired) { + finalImage.release(); + } + } + } + + private void verifyFormat(Mat image, PixelFormat pixelFormat) { + int channels = image.channels(); + switch (pixelFormat) { + case kBGR: + if (channels == 3) { + return; + } + break; + case kBGRA: + if (channels == 4) { + return; + } + break; + case kGray: + if (channels == 1) { + return; + } + break; + case kRGB565: + if (channels == 2) { + return; + } + break; + case kUYVY: + if (channels == 2) { + return; + } + break; + case kY16: + if (channels == 2) { + return; + } + break; + case kYUYV: + if (channels == 2) { + return; + } + break; + case kMJPEG: + if (channels == 1) { + return; + } + break; + default: + break; + } } } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/HttpCamera.java b/cscore/src/main/java/edu/wpi/first/cscore/HttpCamera.java index 8c72350e635..e34bf8455d3 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/HttpCamera.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/HttpCamera.java @@ -6,10 +6,15 @@ /** A source that represents a MJPEG-over-HTTP (IP) camera. */ public class HttpCamera extends VideoCamera { + /** HTTP camera kind. */ public enum HttpCameraKind { + /** Unknown camera kind. */ kUnknown(0), + /** MJPG Streamer camera. */ kMJPGStreamer(1), + /** CS Core camera. */ kCSCore(2), + /** Axis camera. */ kAxis(3); private final int value; @@ -18,6 +23,11 @@ public enum HttpCameraKind { this.value = value; } + /** + * Returns HttpCameraKind value. + * + * @return HttpCameraKind value. + */ public int getValue() { return value; } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/ImageSink.java b/cscore/src/main/java/edu/wpi/first/cscore/ImageSink.java index 1c4cac2f18e..701488da17b 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/ImageSink.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/ImageSink.java @@ -4,7 +4,13 @@ package edu.wpi.first.cscore; +/** A base class for single image reading sinks. */ public abstract class ImageSink extends VideoSink { + /** + * Constructs an ImageSink. + * + * @param handle The image sink handle. + */ protected ImageSink(int handle) { super(handle); } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/ImageSource.java b/cscore/src/main/java/edu/wpi/first/cscore/ImageSource.java index 6bebed811a1..cde0aaca1e2 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/ImageSource.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/ImageSource.java @@ -4,7 +4,13 @@ package edu.wpi.first.cscore; +/** A base class for single image providing sources. */ public abstract class ImageSource extends VideoSource { + /** + * Constructs an ImageSource. + * + * @param handle The image source handle. + */ protected ImageSource(int handle) { super(handle); } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/CameraServerCvJNI.java b/cscore/src/main/java/edu/wpi/first/cscore/OpenCvLoader.java similarity index 63% rename from cscore/src/main/java/edu/wpi/first/cscore/CameraServerCvJNI.java rename to cscore/src/main/java/edu/wpi/first/cscore/OpenCvLoader.java index 66195221f89..0ca098c282c 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/CameraServerCvJNI.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/OpenCvLoader.java @@ -9,28 +9,44 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.opencv.core.Core; -public class CameraServerCvJNI { - static boolean libraryLoaded = false; +/** OpenCV Native Loader. */ +public final class OpenCvLoader { + @SuppressWarnings("PMD.MutableStaticState") + static boolean libraryLoaded; - static RuntimeLoader loader = null; + @SuppressWarnings("PMD.MutableStaticState") + static RuntimeLoader loader; + /** Sets whether JNI should be loaded in the static block. */ public static class Helper { private static AtomicBoolean extractOnStaticLoad = new AtomicBoolean(true); + /** + * Returns true if the JNI should be loaded in the static block. + * + * @return True if the JNI should be loaded in the static block. + */ public static boolean getExtractOnStaticLoad() { return extractOnStaticLoad.get(); } + /** + * Sets whether the JNI should be loaded in the static block. + * + * @param load Whether the JNI should be loaded in the static block. + */ public static void setExtractOnStaticLoad(boolean load) { extractOnStaticLoad.set(load); } + + /** Utility class. */ + private Helper() {} } static { String opencvName = Core.NATIVE_LIBRARY_NAME; if (Helper.getExtractOnStaticLoad()) { try { - CameraServerJNI.forceLoad(); loader = new RuntimeLoader<>(opencvName, RuntimeLoader.getDefaultExtractionRoot(), Core.class); loader.loadLibraryHashed(); @@ -42,6 +58,15 @@ public static void setExtractOnStaticLoad(boolean load) { } } + /** + * Forces a static load. + * + * @return a garbage value + */ + public static int forceStaticLoad() { + return libraryLoaded ? 1 : 0; + } + /** * Force load the library. * @@ -51,7 +76,6 @@ public static synchronized void forceLoad() throws IOException { if (libraryLoaded) { return; } - CameraServerJNI.forceLoad(); loader = new RuntimeLoader<>( Core.NATIVE_LIBRARY_NAME, RuntimeLoader.getDefaultExtractionRoot(), Core.class); @@ -59,17 +83,6 @@ public static synchronized void forceLoad() throws IOException { libraryLoaded = true; } - public static native int createCvSource( - String name, int pixelFormat, int width, int height, int fps); - - public static native void putSourceFrame(int source, long imageNativeObj); - - public static native int createCvSink(String name); - - // public static native int createCvSinkCallback(String name, - // void (*processFrame)(long time)); - - public static native long grabSinkFrame(int sink, long imageNativeObj); - - public static native long grabSinkFrameTimeout(int sink, long imageNativeObj, double timeout); + /** Utility class. */ + private OpenCvLoader() {} } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/VideoCamera.java b/cscore/src/main/java/edu/wpi/first/cscore/VideoCamera.java index 23cf7d6e980..089c77f7304 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/VideoCamera.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/VideoCamera.java @@ -6,14 +6,32 @@ /** A source that represents a video camera. */ public class VideoCamera extends VideoSource { + /** White balance. */ public static class WhiteBalance { + /** Fixed indoor white balance. */ public static final int kFixedIndoor = 3000; + + /** Fixed outdoor white balance 1. */ public static final int kFixedOutdoor1 = 4000; + + /** Fixed outdoor white balance 2. */ public static final int kFixedOutdoor2 = 5000; + + /** Fixed fluorescent white balance 1. */ public static final int kFixedFluorescent1 = 5100; + + /** Fixed fluorescent white balance 2. */ public static final int kFixedFlourescent2 = 5200; + + /** Default constructor. */ + public WhiteBalance() {} } + /** + * Constructs a VideoCamera. + * + * @param handle The video camera handle. + */ protected VideoCamera(int handle) { super(handle); } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/VideoEvent.java b/cscore/src/main/java/edu/wpi/first/cscore/VideoEvent.java index 0c60d6df327..03e9a34fb52 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/VideoEvent.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/VideoEvent.java @@ -7,27 +7,49 @@ /** Video event. */ @SuppressWarnings("MemberName") public class VideoEvent { + /** VideoEvent kind. */ public enum Kind { + /** Unknown video event. */ kUnknown(0x0000), + /** Source Created event. */ kSourceCreated(0x0001), + /** Source Destroyed event. */ kSourceDestroyed(0x0002), + /** Source Connected event. */ kSourceConnected(0x0004), + /** Source Disconnected event. */ kSourceDisconnected(0x0008), + /** Source Video Modes Updated event. */ kSourceVideoModesUpdated(0x0010), + /** Source VideoMode Changed event. */ kSourceVideoModeChanged(0x0020), + /** Source Property Created event. */ kSourcePropertyCreated(0x0040), + /** Source Property Value Updated event. */ kSourcePropertyValueUpdated(0x0080), + /** Source Property Choices Updated event. */ kSourcePropertyChoicesUpdated(0x0100), + /** Sink Source Changed event. */ kSinkSourceChanged(0x0200), + /** Sink Created event. */ kSinkCreated(0x0400), + /** Sink Destroyed event. */ kSinkDestroyed(0x0800), + /** Sink Enabled event. */ kSinkEnabled(0x1000), + /** Sink Disabled event. */ kSinkDisabled(0x2000), + /** Network Interfaces Changed event. */ kNetworkInterfacesChanged(0x4000), + /** Telemetry Updated event. */ kTelemetryUpdated(0x8000), + /** Sink Property Created event. */ kSinkPropertyCreated(0x10000), + /** Sink Property Value Updated event. */ kSinkPropertyValueUpdated(0x20000), + /** Sink Property Choices Updated event. */ kSinkPropertyChoicesUpdated(0x40000), + /** Usb Cameras Changed event. */ kUsbCamerasChanged(0x80000); private final int value; @@ -36,6 +58,11 @@ public enum Kind { this.value = value; } + /** + * Returns the kind value. + * + * @return The kind value. + */ public int getValue() { return value; } @@ -118,39 +145,67 @@ public static Kind getKindFromInt(int kind) { this.listener = listener; } + /** The video event kind. */ public Kind kind; - // Valid for kSource* and kSink* respectively + /** + * The source handle. + * + *

Valid for kSource* and kSink* respectively. + */ public int sourceHandle; + /** The sink handle. */ public int sinkHandle; - // Source/sink/property name + /** Source/sink/property name. */ public String name; - // Fields for kSourceVideoModeChanged event + // Fields for kSourceVideoModeChanged event. + + /** New source video mode. */ public VideoMode mode; - // Fields for kSourceProperty* events + // Fields for kSourceProperty* events. + + /** Source property handle. */ public int propertyHandle; + /** Source property kind. */ public VideoProperty.Kind propertyKind; + /** Event value. */ public int value; + /** Event value as a string. */ public String valueStr; - // Listener that was triggered + /** Listener that was triggered. */ public int listener; + /** + * Returns the source associated with the event (if any). + * + * @return The source associated with the event (if any). + */ public VideoSource getSource() { return new VideoSource(CameraServerJNI.copySource(sourceHandle)); } + /** + * Returns the sink associated with the event (if any). + * + * @return The sink associated with the event (if any). + */ public VideoSink getSink() { return new VideoSink(CameraServerJNI.copySink(sinkHandle)); } + /** + * Returns the property associated with the event (if any). + * + * @return The property associated with the event (if any). + */ public VideoProperty getProperty() { return new VideoProperty(propertyHandle, propertyKind); } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/VideoException.java b/cscore/src/main/java/edu/wpi/first/cscore/VideoException.java index 1c445c6f77f..8b481a77e22 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/VideoException.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/VideoException.java @@ -8,6 +8,11 @@ public class VideoException extends RuntimeException { private static final long serialVersionUID = -9155939328084105145L; + /** + * Constructs the exception with the given message. + * + * @param msg The exception message. + */ public VideoException(String msg) { super(msg); } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/VideoListener.java b/cscore/src/main/java/edu/wpi/first/cscore/VideoListener.java index 652d12db763..80236b27719 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/VideoListener.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/VideoListener.java @@ -51,6 +51,11 @@ public synchronized void close() { } } + /** + * Returns true if the video listener handle is valid. + * + * @return True if the video listener handle is valid. + */ public boolean isValid() { return m_handle != 0; } @@ -102,7 +107,7 @@ private static void startThread() { listener.accept(event); } catch (Throwable throwable) { System.err.println( - "Unhandled exception during listener callback: " + throwable.toString()); + "Unhandled exception during listener callback: " + throwable); throwable.printStackTrace(); } } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/VideoMode.java b/cscore/src/main/java/edu/wpi/first/cscore/VideoMode.java index b818c7e4665..712f695bb68 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/VideoMode.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/VideoMode.java @@ -4,38 +4,12 @@ package edu.wpi.first.cscore; +import edu.wpi.first.util.PixelFormat; import java.util.Objects; /** Video mode. */ @SuppressWarnings("MemberName") public class VideoMode { - public enum PixelFormat { - kUnknown(0), - kMJPEG(1), - kYUYV(2), - kRGB565(3), - kBGR(4), - kGray(5), - kY16(6), - kUYVY(7); - - private final int value; - - PixelFormat(int value) { - this.value = value; - } - - public int getValue() { - return value; - } - } - - private static final PixelFormat[] m_pixelFormatValues = PixelFormat.values(); - - public static PixelFormat getPixelFormatFromInt(int pixelFormat) { - return m_pixelFormatValues[pixelFormat]; - } - /** * Create a new video mode. * @@ -45,7 +19,7 @@ public static PixelFormat getPixelFormatFromInt(int pixelFormat) { * @param fps The camera's frames per second. */ public VideoMode(int pixelFormat, int width, int height, int fps) { - this.pixelFormat = getPixelFormatFromInt(pixelFormat); + this.pixelFormat = PixelFormat.getFromInt(pixelFormat); this.width = width; this.height = height; this.fps = fps; diff --git a/cscore/src/main/java/edu/wpi/first/cscore/VideoProperty.java b/cscore/src/main/java/edu/wpi/first/cscore/VideoProperty.java index 8179ba3c3da..6679ab0af94 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/VideoProperty.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/VideoProperty.java @@ -6,11 +6,17 @@ /** A source or sink property. */ public class VideoProperty { + /** VideoProperty property types. */ public enum Kind { + /** No specific property. */ kNone(0), + /** Boolean property. */ kBoolean(1), + /** Integer property. */ kInteger(2), + /** String property. */ kString(4), + /** Enum property. */ kEnum(8); private final int value; @@ -19,6 +25,11 @@ public enum Kind { this.value = value; } + /** + * Returns the Kind value. + * + * @return The Kind value. + */ public int getValue() { return value; } @@ -45,69 +56,152 @@ public static Kind getKindFromInt(int kind) { } } + /** + * Returns property name. + * + * @return Property name. + */ public String getName() { return CameraServerJNI.getPropertyName(m_handle); } + /** + * Returns property kind. + * + * @return Property kind. + */ public Kind getKind() { return m_kind; } + /** + * Returns true if property is valid. + * + * @return True if property is valid. + */ public boolean isValid() { return m_kind != Kind.kNone; } - // Kind checkers + /** + * Returns true if property is a boolean. + * + * @return True if property is a boolean. + */ public boolean isBoolean() { return m_kind == Kind.kBoolean; } + /** + * Returns true if property is an integer. + * + * @return True if property is an integer. + */ public boolean isInteger() { return m_kind == Kind.kInteger; } + /** + * Returns true if property is a string. + * + * @return True if property is a string. + */ public boolean isString() { return m_kind == Kind.kString; } + /** + * Returns true if property is an enum. + * + * @return True if property is an enum. + */ public boolean isEnum() { return m_kind == Kind.kEnum; } + /** + * Returns property value. + * + * @return Property value. + */ public int get() { return CameraServerJNI.getProperty(m_handle); } + /** + * Sets property value. + * + * @param value Property value. + */ public void set(int value) { CameraServerJNI.setProperty(m_handle, value); } + /** + * Returns property minimum value. + * + * @return Property minimum value. + */ public int getMin() { return CameraServerJNI.getPropertyMin(m_handle); } + /** + * Returns property maximum value. + * + * @return Property maximum value. + */ public int getMax() { return CameraServerJNI.getPropertyMax(m_handle); } + /** + * Returns property step size. + * + * @return Property step size. + */ public int getStep() { return CameraServerJNI.getPropertyStep(m_handle); } + /** + * Returns property default value. + * + * @return Property default value. + */ public int getDefault() { return CameraServerJNI.getPropertyDefault(m_handle); } - // String-specific functions + /** + * Returns the string property value. + * + *

This function is string-specific. + * + * @return The string property value. + */ public String getString() { return CameraServerJNI.getStringProperty(m_handle); } + /** + * Sets the string property value. + * + *

This function is string-specific. + * + * @param value String property value. + */ public void setString(String value) { CameraServerJNI.setStringProperty(m_handle, value); } - // Enum-specific functions + /** + * Returns the possible values for the enum property value. + * + *

This function is enum-specific. + * + * @return The possible values for the enum property value. + */ public String[] getChoices() { return CameraServerJNI.getEnumPropertyChoices(m_handle); } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/VideoSink.java b/cscore/src/main/java/edu/wpi/first/cscore/VideoSink.java index 8b07f4634f4..5eced4c6227 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/VideoSink.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/VideoSink.java @@ -9,10 +9,15 @@ * (e.g. from a stereo or depth camera); these are called channels. */ public class VideoSink implements AutoCloseable { + /** Video sink types. */ public enum Kind { + /** Unknown video sink type. */ kUnknown(0), + /** MJPEG video sink. */ kMjpeg(2), + /** CV video sink. */ kCv(4), + /** Raw video sink. */ kRaw(8); private final int value; @@ -21,6 +26,11 @@ public enum Kind { this.value = value; } + /** + * Returns the Kind value. + * + * @return The Kind value. + */ public int getValue() { return value; } @@ -38,11 +48,18 @@ public static Kind getKindFromInt(int kind) { return Kind.kMjpeg; case 4: return Kind.kCv; + case 8: + return Kind.kRaw; default: return Kind.kUnknown; } } + /** + * Constructs a VideoSink. + * + * @param handle The video sink handle. + */ protected VideoSink(int handle) { m_handle = handle; } @@ -55,10 +72,20 @@ public synchronized void close() { m_handle = 0; } + /** + * Returns true if the VideoSink is valid. + * + * @return True if the VideoSink is valid. + */ public boolean isValid() { return m_handle != 0; } + /** + * Returns the video sink handle. + * + * @return The video sink handle. + */ public int getHandle() { return m_handle; } @@ -217,5 +244,6 @@ public static VideoSink[] enumerateSinks() { return rv; } + /** The VideoSink handle. */ protected int m_handle; } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/VideoSource.java b/cscore/src/main/java/edu/wpi/first/cscore/VideoSource.java index 0ae5adddc66..7657eafa561 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/VideoSource.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/VideoSource.java @@ -4,16 +4,24 @@ package edu.wpi.first.cscore; +import edu.wpi.first.util.PixelFormat; + /** * A source for video that provides a sequence of frames. Each frame may consist of multiple images * (e.g. from a stereo or depth camera); these are called channels. */ public class VideoSource implements AutoCloseable { + /** Video source kind. */ public enum Kind { + /** Unknown video source. */ kUnknown(0), + /** USB video source. */ kUsb(1), + /** HTTP video source. */ kHttp(2), + /** CV video source. */ kCv(4), + /** Raw video source. */ kRaw(8); private final int value; @@ -22,6 +30,11 @@ public enum Kind { this.value = value; } + /** + * Returns the Kind value. + * + * @return The Kind value. + */ public int getValue() { return value; } @@ -49,6 +62,11 @@ public enum ConnectionStrategy { this.value = value; } + /** + * Returns the ConnectionStrategy value. + * + * @return The ConnectionStrategy value. + */ public int getValue() { return value; } @@ -68,11 +86,18 @@ public static Kind getKindFromInt(int kind) { return Kind.kHttp; case 4: return Kind.kCv; + case 8: + return Kind.kRaw; default: return Kind.kUnknown; } } + /** + * Constructs a VideoSource. + * + * @param handle The video source handle. + */ protected VideoSource(int handle) { m_handle = handle; } @@ -85,10 +110,20 @@ public synchronized void close() { m_handle = 0; } + /** + * Returns true if the VideoSource is valid. + * + * @return True if the VideoSource is valid. + */ public boolean isValid() { return m_handle != 0; } + /** + * Returns the video source handle. + * + * @return The video source handle. + */ public int getHandle() { return m_handle; } @@ -235,7 +270,7 @@ public boolean setVideoMode(VideoMode mode) { * @param fps desired FPS * @return True if set successfully */ - public boolean setVideoMode(VideoMode.PixelFormat pixelFormat, int width, int height, int fps) { + public boolean setVideoMode(PixelFormat pixelFormat, int width, int height, int fps) { return CameraServerJNI.setSourceVideoMode(m_handle, pixelFormat.getValue(), width, height, fps); } @@ -245,7 +280,7 @@ public boolean setVideoMode(VideoMode.PixelFormat pixelFormat, int width, int he * @param pixelFormat desired pixel format * @return True if set successfully */ - public boolean setPixelFormat(VideoMode.PixelFormat pixelFormat) { + public boolean setPixelFormat(PixelFormat pixelFormat) { return CameraServerJNI.setSourcePixelFormat(m_handle, pixelFormat.getValue()); } @@ -372,5 +407,6 @@ public static VideoSource[] enumerateSources() { return rv; } + /** Video source handle. */ protected int m_handle; } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/raw/RawFrame.java b/cscore/src/main/java/edu/wpi/first/cscore/raw/RawFrame.java deleted file mode 100644 index 5f62481c86d..00000000000 --- a/cscore/src/main/java/edu/wpi/first/cscore/raw/RawFrame.java +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.cscore.raw; - -import edu.wpi.first.cscore.CameraServerJNI; -import java.nio.ByteBuffer; - -/** - * Class for storing raw frame data between image read call. - * - *

Data is reused for each frame read, rather then reallocating every frame. - */ -public class RawFrame implements AutoCloseable { - private final long m_framePtr; - private ByteBuffer m_dataByteBuffer; - private long m_dataPtr; - private int m_totalData; - private int m_width; - private int m_height; - private int m_pixelFormat; - - /** Construct a new RawFrame. */ - public RawFrame() { - m_framePtr = CameraServerJNI.allocateRawFrame(); - } - - /** - * Close the RawFrame, releasing native resources. Any images currently using the data will be - * invalidated. - */ - @Override - public void close() { - CameraServerJNI.freeRawFrame(m_framePtr); - } - - /** - * Called from JNI to set data in class. - * - * @param dataByteBuffer A ByteBuffer pointing to the frame data. - * @param dataPtr A long (a char* in native code) pointing to the frame data. - * @param totalData The total length of the data stored in the frame. - * @param width The width of the frame. - * @param height The height of the frame. - * @param pixelFormat The PixelFormat of the frame. - */ - public void setData( - ByteBuffer dataByteBuffer, - long dataPtr, - int totalData, - int width, - int height, - int pixelFormat) { - m_dataByteBuffer = dataByteBuffer; - m_dataPtr = dataPtr; - m_totalData = totalData; - m_width = width; - m_height = height; - m_pixelFormat = pixelFormat; - } - - /** - * Get the pointer to native representation of this frame. - * - * @return The pointer to native representation of this frame. - */ - public long getFramePtr() { - return m_framePtr; - } - - /** - * Get a ByteBuffer pointing to the frame data. This ByteBuffer is backed by the frame directly. - * Its lifetime is controlled by the frame. If a new frame gets read, it will overwrite the - * current one. - * - * @return A ByteBuffer pointing to the frame data. - */ - public ByteBuffer getDataByteBuffer() { - return m_dataByteBuffer; - } - - /** - * Get a long (is a char* in native code) pointing to the frame data. This pointer is backed by - * the frame directly. Its lifetime is controlled by the frame. If a new frame gets read, it will - * overwrite the current one. - * - * @return A long pointing to the frame data. - */ - public long getDataPtr() { - return m_dataPtr; - } - - /** - * Get the total length of the data stored in the frame. - * - * @return The total length of the data stored in the frame. - */ - public int getTotalData() { - return m_totalData; - } - - /** - * Get the width of the frame. - * - * @return The width of the frame. - */ - public int getWidth() { - return m_width; - } - - /** - * Set the width of the frame. - * - * @param width The width of the frame. - */ - public void setWidth(int width) { - this.m_width = width; - } - - /** - * Get the height of the frame. - * - * @return The height of the frame. - */ - public int getHeight() { - return m_height; - } - - /** - * Set the height of the frame. - * - * @param height The height of the frame. - */ - public void setHeight(int height) { - this.m_height = height; - } - - /** - * Get the PixelFormat of the frame. - * - * @return The PixelFormat of the frame. - */ - public int getPixelFormat() { - return m_pixelFormat; - } - - /** - * Set the PixelFormat of the frame. - * - * @param pixelFormat The PixelFormat of the frame. - */ - public void setPixelFormat(int pixelFormat) { - this.m_pixelFormat = pixelFormat; - } -} diff --git a/cscore/src/main/java/edu/wpi/first/cscore/raw/RawSink.java b/cscore/src/main/java/edu/wpi/first/cscore/raw/RawSink.java index ae5b0ef94c7..ba567a98e3e 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/raw/RawSink.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/raw/RawSink.java @@ -6,6 +6,7 @@ import edu.wpi.first.cscore.CameraServerJNI; import edu.wpi.first.cscore.ImageSink; +import edu.wpi.first.util.RawFrame; /** * A sink for user code to accept video frames as raw bytes. @@ -21,7 +22,7 @@ public class RawSink extends ImageSink { * @param name Source name (arbitrary unique identifier) */ public RawSink(String name) { - super(CameraServerJNI.createRawSink(name)); + super(CameraServerJNI.createRawSink(name, false)); } /** @@ -32,7 +33,7 @@ public RawSink(String name) { * @return Frame time, or 0 on error (call getError() to obtain the error message); the frame time * is in the same time base as wpi::Now(), and is in 1 us increments. */ - protected long grabFrame(RawFrame frame) { + public long grabFrame(RawFrame frame) { return grabFrame(frame, 0.225); } @@ -45,8 +46,8 @@ protected long grabFrame(RawFrame frame) { * @return Frame time, or 0 on error (call getError() to obtain the error message); the frame time * is in the same time base as wpi::Now(), and is in 1 us increments. */ - protected long grabFrame(RawFrame frame, double timeout) { - return CameraServerJNI.grabSinkFrameTimeout(m_handle, frame, timeout); + public long grabFrame(RawFrame frame, double timeout) { + return CameraServerJNI.grabRawSinkFrameTimeout(m_handle, frame, frame.getNativeObj(), timeout); } /** @@ -57,7 +58,7 @@ protected long grabFrame(RawFrame frame, double timeout) { * @return Frame time, or 0 on error (call getError() to obtain the error message); the frame time * is in the same time base as wpi::Now(), and is in 1 us increments. */ - protected long grabFrameNoTimeout(RawFrame frame) { - return CameraServerJNI.grabSinkFrame(m_handle, frame); + public long grabFrameNoTimeout(RawFrame frame) { + return CameraServerJNI.grabRawSinkFrame(m_handle, frame, frame.getNativeObj()); } } diff --git a/cscore/src/main/java/edu/wpi/first/cscore/raw/RawSource.java b/cscore/src/main/java/edu/wpi/first/cscore/raw/RawSource.java index f1be05065b3..f1dafd9a012 100644 --- a/cscore/src/main/java/edu/wpi/first/cscore/raw/RawSource.java +++ b/cscore/src/main/java/edu/wpi/first/cscore/raw/RawSource.java @@ -7,6 +7,9 @@ import edu.wpi.first.cscore.CameraServerJNI; import edu.wpi.first.cscore.ImageSource; import edu.wpi.first.cscore.VideoMode; +import edu.wpi.first.util.PixelFormat; +import edu.wpi.first.util.RawFrame; +import java.nio.ByteBuffer; /** * A source for user code to provide video frames as raw bytes. @@ -23,7 +26,7 @@ public class RawSource extends ImageSource { public RawSource(String name, VideoMode mode) { super( CameraServerJNI.createRawSource( - name, mode.pixelFormat.getValue(), mode.width, mode.height, mode.fps)); + name, false, mode.pixelFormat.getValue(), mode.width, mode.height, mode.fps)); } /** @@ -35,8 +38,8 @@ public RawSource(String name, VideoMode mode) { * @param height height * @param fps fps */ - public RawSource(String name, VideoMode.PixelFormat pixelFormat, int width, int height, int fps) { - super(CameraServerJNI.createRawSource(name, pixelFormat.getValue(), width, height, fps)); + public RawSource(String name, PixelFormat pixelFormat, int width, int height, int fps) { + super(CameraServerJNI.createRawSource(name, false, pixelFormat.getValue(), width, height, fps)); } /** @@ -44,35 +47,41 @@ public RawSource(String name, VideoMode.PixelFormat pixelFormat, int width, int * * @param image raw frame image */ - protected void putFrame(RawFrame image) { - CameraServerJNI.putRawSourceFrame(m_handle, image); + public void putFrame(RawFrame image) { + CameraServerJNI.putRawSourceFrame(m_handle, image.getNativeObj()); } /** * Put a raw image and notify sinks. * - * @param data raw frame data pointer + * @param data raw frame native data pointer + * @param size total size in bytes * @param width frame width * @param height frame height + * @param stride size of each row in bytes * @param pixelFormat pixel format - * @param totalData length of data in total */ - protected void putFrame(long data, int width, int height, int pixelFormat, int totalData) { - CameraServerJNI.putRawSourceFrame(m_handle, data, width, height, pixelFormat, totalData); + protected void putFrame( + long data, int size, int width, int height, int stride, PixelFormat pixelFormat) { + CameraServerJNI.putRawSourceFrameData( + m_handle, data, size, width, height, stride, pixelFormat.getValue()); } /** * Put a raw image and notify sinks. * - * @param data raw frame data pointer + * @param data raw frame native ByteBuffer * @param width frame width * @param height frame height + * @param stride size of each row in bytes * @param pixelFormat pixel format - * @param totalData length of data in total */ - protected void putFrame( - long data, int width, int height, VideoMode.PixelFormat pixelFormat, int totalData) { - CameraServerJNI.putRawSourceFrame( - m_handle, data, width, height, pixelFormat.getValue(), totalData); + public void putFrame( + ByteBuffer data, int width, int height, int stride, PixelFormat pixelFormat) { + if (!data.isDirect()) { + throw new UnsupportedOperationException("ByteBuffer must be direct"); + } + CameraServerJNI.putRawSourceFrameBB( + m_handle, data, data.limit(), width, height, stride, pixelFormat.getValue()); } } diff --git a/cscore/src/main/native/cpp/ConfigurableSourceImpl.cpp b/cscore/src/main/native/cpp/ConfigurableSourceImpl.cpp index 48677a6319e..e7e8721d9f4 100644 --- a/cscore/src/main/native/cpp/ConfigurableSourceImpl.cpp +++ b/cscore/src/main/native/cpp/ConfigurableSourceImpl.cpp @@ -104,3 +104,144 @@ void ConfigurableSourceImpl::SetEnumPropertyChoices( prop->name, property, CS_PROP_ENUM, prop->value, {}); } + +namespace cs { +static constexpr unsigned SourceMask = CS_SOURCE_CV | CS_SOURCE_RAW; + +void NotifySourceError(CS_Source source, std::string_view msg, + CS_Status* status) { + auto data = Instance::GetInstance().GetSource(source); + if (!data || (data->kind & SourceMask) == 0) { + *status = CS_INVALID_HANDLE; + return; + } + static_cast(*data->source).NotifyError(msg); +} + +void SetSourceConnected(CS_Source source, bool connected, CS_Status* status) { + auto data = Instance::GetInstance().GetSource(source); + if (!data || (data->kind & SourceMask) == 0) { + *status = CS_INVALID_HANDLE; + return; + } + static_cast(*data->source).SetConnected(connected); +} + +void SetSourceDescription(CS_Source source, std::string_view description, + CS_Status* status) { + auto data = Instance::GetInstance().GetSource(source); + if (!data || (data->kind & SourceMask) == 0) { + *status = CS_INVALID_HANDLE; + return; + } + static_cast(*data->source) + .SetDescription(description); +} + +CS_Property CreateSourceProperty(CS_Source source, std::string_view name, + CS_PropertyKind kind, int minimum, int maximum, + int step, int defaultValue, int value, + CS_Status* status) { + auto data = Instance::GetInstance().GetSource(source); + if (!data || (data->kind & SourceMask) == 0) { + *status = CS_INVALID_HANDLE; + return -1; + } + int property = static_cast(*data->source) + .CreateProperty(name, kind, minimum, maximum, step, + defaultValue, value); + return Handle{source, property, Handle::kProperty}; +} + +CS_Property CreateSourcePropertyCallback( + CS_Source source, std::string_view name, CS_PropertyKind kind, int minimum, + int maximum, int step, int defaultValue, int value, + std::function onChange, CS_Status* status) { + auto data = Instance::GetInstance().GetSource(source); + if (!data || (data->kind & SourceMask) == 0) { + *status = CS_INVALID_HANDLE; + return -1; + } + int property = static_cast(*data->source) + .CreateProperty(name, kind, minimum, maximum, step, + defaultValue, value, onChange); + return Handle{source, property, Handle::kProperty}; +} + +void SetSourceEnumPropertyChoices(CS_Source source, CS_Property property, + std::span choices, + CS_Status* status) { + auto data = Instance::GetInstance().GetSource(source); + if (!data || (data->kind & SourceMask) == 0) { + *status = CS_INVALID_HANDLE; + return; + } + + // Get property index; also validate the source owns this property + Handle handle{property}; + int i = handle.GetParentIndex(); + if (i < 0) { + *status = CS_INVALID_HANDLE; + return; + } + auto data2 = Instance::GetInstance().GetSource(Handle{i, Handle::kSource}); + if (!data2 || data->source.get() != data2->source.get()) { + *status = CS_INVALID_HANDLE; + return; + } + int propertyIndex = handle.GetIndex(); + static_cast(*data->source) + .SetEnumPropertyChoices(propertyIndex, choices, status); +} + +} // namespace cs + +extern "C" { +void CS_NotifySourceError(CS_Source source, const struct WPI_String* msg, + CS_Status* status) { + return cs::NotifySourceError(source, wpi::to_string_view(msg), status); +} + +void CS_SetSourceConnected(CS_Source source, CS_Bool connected, + CS_Status* status) { + return cs::SetSourceConnected(source, connected, status); +} + +void CS_SetSourceDescription(CS_Source source, + const struct WPI_String* description, + CS_Status* status) { + return cs::SetSourceDescription(source, wpi::to_string_view(description), + status); +} + +CS_Property CS_CreateSourceProperty(CS_Source source, + const struct WPI_String* name, + enum CS_PropertyKind kind, int minimum, + int maximum, int step, int defaultValue, + int value, CS_Status* status) { + return cs::CreateSourceProperty(source, wpi::to_string_view(name), kind, + minimum, maximum, step, defaultValue, value, + status); +} + +CS_Property CS_CreateSourcePropertyCallback( + CS_Source source, const char* name, enum CS_PropertyKind kind, int minimum, + int maximum, int step, int defaultValue, int value, void* data, + void (*onChange)(void* data, CS_Property property), CS_Status* status) { + return cs::CreateSourcePropertyCallback( + source, name, kind, minimum, maximum, step, defaultValue, value, + [=](CS_Property property) { onChange(data, property); }, status); +} + +void CS_SetSourceEnumPropertyChoices(CS_Source source, CS_Property property, + const struct WPI_String* choices, + int count, CS_Status* status) { + wpi::SmallVector vec; + vec.reserve(count); + for (int i = 0; i < count; ++i) { + vec.emplace_back(wpi::to_string_view(&choices[i])); + } + return cs::SetSourceEnumPropertyChoices(source, property, vec, status); +} + +} // extern "C" diff --git a/cscore/src/main/native/cpp/ConfigurableSourceImpl.h b/cscore/src/main/native/cpp/ConfigurableSourceImpl.h index 31236f53172..570ab21ead8 100644 --- a/cscore/src/main/native/cpp/ConfigurableSourceImpl.h +++ b/cscore/src/main/native/cpp/ConfigurableSourceImpl.h @@ -33,7 +33,7 @@ class ConfigurableSourceImpl : public SourceImpl { void NumSinksChanged() override; void NumSinksEnabledChanged() override; - // OpenCV-specific functions + // Frame based specific functions void NotifyError(std::string_view msg); int CreateProperty(std::string_view name, CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value); diff --git a/cscore/src/main/native/cpp/CvSinkImpl.cpp b/cscore/src/main/native/cpp/CvSinkImpl.cpp deleted file mode 100644 index 942fdaf3266..00000000000 --- a/cscore/src/main/native/cpp/CvSinkImpl.cpp +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "CvSinkImpl.h" - -#include -#include -#include -#include - -#include "Handle.h" -#include "Instance.h" -#include "Log.h" -#include "Notifier.h" -#include "c_util.h" -#include "cscore_cpp.h" - -using namespace cs; - -CvSinkImpl::CvSinkImpl(std::string_view name, wpi::Logger& logger, - Notifier& notifier, Telemetry& telemetry) - : SinkImpl{name, logger, notifier, telemetry} { - m_active = true; - // m_thread = std::thread(&CvSinkImpl::ThreadMain, this); -} - -CvSinkImpl::CvSinkImpl(std::string_view name, wpi::Logger& logger, - Notifier& notifier, Telemetry& telemetry, - std::function processFrame) - : SinkImpl{name, logger, notifier, telemetry} {} - -CvSinkImpl::~CvSinkImpl() { - Stop(); -} - -void CvSinkImpl::Stop() { - m_active = false; - - // wake up any waiters by forcing an empty frame to be sent - if (auto source = GetSource()) { - source->Wakeup(); - } - - // join thread - if (m_thread.joinable()) { - m_thread.join(); - } -} - -uint64_t CvSinkImpl::GrabFrame(cv::Mat& image) { - SetEnabled(true); - - auto source = GetSource(); - if (!source) { - // Source disconnected; sleep for one second - std::this_thread::sleep_for(std::chrono::seconds(1)); - return 0; - } - - auto frame = source->GetNextFrame(); // blocks - if (!frame) { - // Bad frame; sleep for 20 ms so we don't consume all processor time. - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - return 0; // signal error - } - - if (!frame.GetCv(image)) { - // Shouldn't happen, but just in case... - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - return 0; - } - - return frame.GetTime(); -} - -uint64_t CvSinkImpl::GrabFrame(cv::Mat& image, double timeout) { - SetEnabled(true); - - auto source = GetSource(); - if (!source) { - // Source disconnected; sleep for one second - std::this_thread::sleep_for(std::chrono::seconds(1)); - return 0; - } - - auto frame = source->GetNextFrame(timeout); // blocks - if (!frame) { - // Bad frame; sleep for 20 ms so we don't consume all processor time. - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - return 0; // signal error - } - - if (!frame.GetCv(image)) { - // Shouldn't happen, but just in case... - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - return 0; - } - - return frame.GetTime(); -} - -// Send HTTP response and a stream of JPG-frames -void CvSinkImpl::ThreadMain() { - Enable(); - while (m_active) { - auto source = GetSource(); - if (!source) { - // Source disconnected; sleep for one second - std::this_thread::sleep_for(std::chrono::seconds(1)); - continue; - } - SDEBUG4("waiting for frame"); - Frame frame = source->GetNextFrame(); // blocks - if (!m_active) { - break; - } - if (!frame) { - // Bad frame; sleep for 10 ms so we don't consume all processor time. - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - continue; - } - // TODO m_processFrame(); - } - Disable(); -} - -namespace cs { - -CS_Sink CreateCvSink(std::string_view name, CS_Status* status) { - auto& inst = Instance::GetInstance(); - return inst.CreateSink( - CS_SINK_CV, std::make_shared(name, inst.logger, inst.notifier, - inst.telemetry)); -} - -CS_Sink CreateCvSinkCallback(std::string_view name, - std::function processFrame, - CS_Status* status) { - auto& inst = Instance::GetInstance(); - return inst.CreateSink( - CS_SINK_CV, std::make_shared(name, inst.logger, inst.notifier, - inst.telemetry, processFrame)); -} - -static constexpr unsigned SinkMask = CS_SINK_CV | CS_SINK_RAW; - -void SetSinkDescription(CS_Sink sink, std::string_view description, - CS_Status* status) { - auto data = Instance::GetInstance().GetSink(sink); - if (!data || (data->kind & SinkMask) == 0) { - *status = CS_INVALID_HANDLE; - return; - } - static_cast(*data->sink).SetDescription(description); -} - -uint64_t GrabSinkFrame(CS_Sink sink, cv::Mat& image, CS_Status* status) { - auto data = Instance::GetInstance().GetSink(sink); - if (!data || data->kind != CS_SINK_CV) { - *status = CS_INVALID_HANDLE; - return 0; - } - return static_cast(*data->sink).GrabFrame(image); -} - -uint64_t GrabSinkFrameTimeout(CS_Sink sink, cv::Mat& image, double timeout, - CS_Status* status) { - auto data = Instance::GetInstance().GetSink(sink); - if (!data || data->kind != CS_SINK_CV) { - *status = CS_INVALID_HANDLE; - return 0; - } - return static_cast(*data->sink).GrabFrame(image, timeout); -} - -std::string GetSinkError(CS_Sink sink, CS_Status* status) { - auto data = Instance::GetInstance().GetSink(sink); - if (!data || (data->kind & SinkMask) == 0) { - *status = CS_INVALID_HANDLE; - return std::string{}; - } - return static_cast(*data->sink).GetError(); -} - -std::string_view GetSinkError(CS_Sink sink, wpi::SmallVectorImpl& buf, - CS_Status* status) { - auto data = Instance::GetInstance().GetSink(sink); - if (!data || (data->kind & SinkMask) == 0) { - *status = CS_INVALID_HANDLE; - return {}; - } - return static_cast(*data->sink).GetError(buf); -} - -void SetSinkEnabled(CS_Sink sink, bool enabled, CS_Status* status) { - auto data = Instance::GetInstance().GetSink(sink); - if (!data || (data->kind & SinkMask) == 0) { - *status = CS_INVALID_HANDLE; - return; - } - static_cast(*data->sink).SetEnabled(enabled); -} - -} // namespace cs - -extern "C" { - -CS_Sink CS_CreateCvSink(const char* name, CS_Status* status) { - return cs::CreateCvSink(name, status); -} - -CS_Sink CS_CreateCvSinkCallback(const char* name, void* data, - void (*processFrame)(void* data, uint64_t time), - CS_Status* status) { - return cs::CreateCvSinkCallback( - name, [=](uint64_t time) { processFrame(data, time); }, status); -} - -void CS_SetSinkDescription(CS_Sink sink, const char* description, - CS_Status* status) { - return cs::SetSinkDescription(sink, description, status); -} - -#if CV_VERSION_MAJOR < 4 -uint64_t CS_GrabSinkFrame(CS_Sink sink, struct CvMat* image, - CS_Status* status) { - auto mat = cv::cvarrToMat(image); - return cs::GrabSinkFrame(sink, mat, status); -} - -uint64_t CS_GrabSinkFrameTimeout(CS_Sink sink, struct CvMat* image, - double timeout, CS_Status* status) { - auto mat = cv::cvarrToMat(image); - return cs::GrabSinkFrameTimeout(sink, mat, timeout, status); -} -#endif // CV_VERSION_MAJOR < 4 - -uint64_t CS_GrabSinkFrameCpp(CS_Sink sink, cv::Mat* image, CS_Status* status) { - return cs::GrabSinkFrame(sink, *image, status); -} - -uint64_t CS_GrabSinkFrameTimeoutCpp(CS_Sink sink, cv::Mat* image, - double timeout, CS_Status* status) { - return cs::GrabSinkFrameTimeout(sink, *image, timeout, status); -} - -char* CS_GetSinkError(CS_Sink sink, CS_Status* status) { - wpi::SmallString<128> buf; - auto str = cs::GetSinkError(sink, buf, status); - if (*status != 0) { - return nullptr; - } - return cs::ConvertToC(str); -} - -void CS_SetSinkEnabled(CS_Sink sink, CS_Bool enabled, CS_Status* status) { - return cs::SetSinkEnabled(sink, enabled, status); -} - -} // extern "C" diff --git a/cscore/src/main/native/cpp/CvSinkImpl.h b/cscore/src/main/native/cpp/CvSinkImpl.h deleted file mode 100644 index ad63a20f1ae..00000000000 --- a/cscore/src/main/native/cpp/CvSinkImpl.h +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#ifndef CSCORE_CVSINKIMPL_H_ -#define CSCORE_CVSINKIMPL_H_ - -#include - -#include -#include -#include -#include - -#include -#include - -#include "Frame.h" -#include "SinkImpl.h" - -namespace cs { - -class SourceImpl; - -class CvSinkImpl : public SinkImpl { - public: - CvSinkImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, - Telemetry& telemetry); - CvSinkImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, - Telemetry& telemetry, - std::function processFrame); - ~CvSinkImpl() override; - - void Stop(); - - uint64_t GrabFrame(cv::Mat& image); - uint64_t GrabFrame(cv::Mat& image, double timeout); - - private: - void ThreadMain(); - - std::atomic_bool m_active; // set to false to terminate threads - std::thread m_thread; - std::function m_processFrame; -}; - -} // namespace cs - -#endif // CSCORE_CVSINKIMPL_H_ diff --git a/cscore/src/main/native/cpp/CvSourceImpl.cpp b/cscore/src/main/native/cpp/CvSourceImpl.cpp deleted file mode 100644 index 511cf6ceb20..00000000000 --- a/cscore/src/main/native/cpp/CvSourceImpl.cpp +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "CvSourceImpl.h" - -#include -#include -#include -#include - -#include "Handle.h" -#include "Instance.h" -#include "Log.h" -#include "Notifier.h" -#include "c_util.h" -#include "cscore_cpp.h" - -using namespace cs; - -CvSourceImpl::CvSourceImpl(std::string_view name, wpi::Logger& logger, - Notifier& notifier, Telemetry& telemetry, - const VideoMode& mode) - : ConfigurableSourceImpl{name, logger, notifier, telemetry, mode} {} - -CvSourceImpl::~CvSourceImpl() = default; - -void CvSourceImpl::PutFrame(cv::Mat& image) { - // We only support 8-bit images; convert if necessary. - cv::Mat finalImage; - if (image.depth() == CV_8U) { - finalImage = image; - } else { - image.convertTo(finalImage, CV_8U); - } - - std::unique_ptr dest; - switch (image.channels()) { - case 1: - dest = - AllocImage(VideoMode::kGray, image.cols, image.rows, image.total()); - finalImage.copyTo(dest->AsMat()); - break; - case 3: - dest = AllocImage(VideoMode::kBGR, image.cols, image.rows, - image.total() * 3); - finalImage.copyTo(dest->AsMat()); - break; - case 4: - dest = AllocImage(VideoMode::kBGR, image.cols, image.rows, - image.total() * 3); - cv::cvtColor(finalImage, dest->AsMat(), cv::COLOR_BGRA2BGR); - break; - default: - SERROR("PutFrame: {}-channel images not supported", image.channels()); - return; - } - SourceImpl::PutFrame(std::move(dest), wpi::Now()); -} - -namespace cs { - -CS_Source CreateCvSource(std::string_view name, const VideoMode& mode, - CS_Status* status) { - auto& inst = Instance::GetInstance(); - return inst.CreateSource(CS_SOURCE_CV, std::make_shared( - name, inst.logger, inst.notifier, - inst.telemetry, mode)); -} - -void PutSourceFrame(CS_Source source, cv::Mat& image, CS_Status* status) { - auto data = Instance::GetInstance().GetSource(source); - if (!data || data->kind != CS_SOURCE_CV) { - *status = CS_INVALID_HANDLE; - return; - } - static_cast(*data->source).PutFrame(image); -} - -static constexpr unsigned SourceMask = CS_SINK_CV | CS_SINK_RAW; - -void NotifySourceError(CS_Source source, std::string_view msg, - CS_Status* status) { - auto data = Instance::GetInstance().GetSource(source); - if (!data || (data->kind & SourceMask) == 0) { - *status = CS_INVALID_HANDLE; - return; - } - static_cast(*data->source).NotifyError(msg); -} - -void SetSourceConnected(CS_Source source, bool connected, CS_Status* status) { - auto data = Instance::GetInstance().GetSource(source); - if (!data || (data->kind & SourceMask) == 0) { - *status = CS_INVALID_HANDLE; - return; - } - static_cast(*data->source).SetConnected(connected); -} - -void SetSourceDescription(CS_Source source, std::string_view description, - CS_Status* status) { - auto data = Instance::GetInstance().GetSource(source); - if (!data || (data->kind & SourceMask) == 0) { - *status = CS_INVALID_HANDLE; - return; - } - static_cast(*data->source).SetDescription(description); -} - -CS_Property CreateSourceProperty(CS_Source source, std::string_view name, - CS_PropertyKind kind, int minimum, int maximum, - int step, int defaultValue, int value, - CS_Status* status) { - auto data = Instance::GetInstance().GetSource(source); - if (!data || (data->kind & SourceMask) == 0) { - *status = CS_INVALID_HANDLE; - return -1; - } - int property = static_cast(*data->source) - .CreateProperty(name, kind, minimum, maximum, step, - defaultValue, value); - return Handle{source, property, Handle::kProperty}; -} - -CS_Property CreateSourcePropertyCallback( - CS_Source source, std::string_view name, CS_PropertyKind kind, int minimum, - int maximum, int step, int defaultValue, int value, - std::function onChange, CS_Status* status) { - auto data = Instance::GetInstance().GetSource(source); - if (!data || (data->kind & SourceMask) == 0) { - *status = CS_INVALID_HANDLE; - return -1; - } - int property = static_cast(*data->source) - .CreateProperty(name, kind, minimum, maximum, step, - defaultValue, value, onChange); - return Handle{source, property, Handle::kProperty}; -} - -void SetSourceEnumPropertyChoices(CS_Source source, CS_Property property, - std::span choices, - CS_Status* status) { - auto data = Instance::GetInstance().GetSource(source); - if (!data || (data->kind & SourceMask) == 0) { - *status = CS_INVALID_HANDLE; - return; - } - - // Get property index; also validate the source owns this property - Handle handle{property}; - int i = handle.GetParentIndex(); - if (i < 0) { - *status = CS_INVALID_HANDLE; - return; - } - auto data2 = Instance::GetInstance().GetSource(Handle{i, Handle::kSource}); - if (!data2 || data->source.get() != data2->source.get()) { - *status = CS_INVALID_HANDLE; - return; - } - int propertyIndex = handle.GetIndex(); - static_cast(*data->source) - .SetEnumPropertyChoices(propertyIndex, choices, status); -} - -} // namespace cs - -extern "C" { - -CS_Source CS_CreateCvSource(const char* name, const CS_VideoMode* mode, - CS_Status* status) { - return cs::CreateCvSource(name, static_cast(*mode), - status); -} - -#if CV_VERSION_MAJOR < 4 -void CS_PutSourceFrame(CS_Source source, struct CvMat* image, - CS_Status* status) { - auto mat = cv::cvarrToMat(image); - return cs::PutSourceFrame(source, mat, status); -} -#endif // CV_VERSION_MAJOR < 4 - -void CS_PutSourceFrameCpp(CS_Source source, cv::Mat* image, CS_Status* status) { - return cs::PutSourceFrame(source, *image, status); -} - -void CS_NotifySourceError(CS_Source source, const char* msg, - CS_Status* status) { - return cs::NotifySourceError(source, msg, status); -} - -void CS_SetSourceConnected(CS_Source source, CS_Bool connected, - CS_Status* status) { - return cs::SetSourceConnected(source, connected, status); -} - -void CS_SetSourceDescription(CS_Source source, const char* description, - CS_Status* status) { - return cs::SetSourceDescription(source, description, status); -} - -CS_Property CS_CreateSourceProperty(CS_Source source, const char* name, - enum CS_PropertyKind kind, int minimum, - int maximum, int step, int defaultValue, - int value, CS_Status* status) { - return cs::CreateSourceProperty(source, name, kind, minimum, maximum, step, - defaultValue, value, status); -} - -CS_Property CS_CreateSourcePropertyCallback( - CS_Source source, const char* name, enum CS_PropertyKind kind, int minimum, - int maximum, int step, int defaultValue, int value, void* data, - void (*onChange)(void* data, CS_Property property), CS_Status* status) { - return cs::CreateSourcePropertyCallback( - source, name, kind, minimum, maximum, step, defaultValue, value, - [=](CS_Property property) { onChange(data, property); }, status); -} - -void CS_SetSourceEnumPropertyChoices(CS_Source source, CS_Property property, - const char** choices, int count, - CS_Status* status) { - wpi::SmallVector vec; - vec.reserve(count); - for (int i = 0; i < count; ++i) { - vec.push_back(choices[i]); - } - return cs::SetSourceEnumPropertyChoices(source, property, vec, status); -} - -} // extern "C" diff --git a/cscore/src/main/native/cpp/CvSourceImpl.h b/cscore/src/main/native/cpp/CvSourceImpl.h deleted file mode 100644 index fba7131b43e..00000000000 --- a/cscore/src/main/native/cpp/CvSourceImpl.h +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#ifndef CSCORE_CVSOURCEIMPL_H_ -#define CSCORE_CVSOURCEIMPL_H_ - -#include -#include -#include -#include -#include -#include - -#include - -#include "ConfigurableSourceImpl.h" -#include "SourceImpl.h" - -namespace cs { - -class CvSourceImpl : public ConfigurableSourceImpl { - public: - CvSourceImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, - Telemetry& telemetry, const VideoMode& mode); - ~CvSourceImpl() override; - - // OpenCV-specific functions - void PutFrame(cv::Mat& image); - - private: - std::atomic_bool m_connected{true}; -}; - -} // namespace cs - -#endif // CSCORE_CVSOURCEIMPL_H_ diff --git a/cscore/src/main/native/cpp/Frame.cpp b/cscore/src/main/native/cpp/Frame.cpp index e6f8e7c683d..af108f46a72 100644 --- a/cscore/src/main/native/cpp/Frame.cpp +++ b/cscore/src/main/native/cpp/Frame.cpp @@ -314,6 +314,54 @@ Image* Frame::ConvertImpl(Image* image, VideoMode::PixelFormat pixelFormat, } } break; + case VideoMode::kBGRA: + // If source is RGB565, YUYV, UYVY, Gray or Y16, need to convert to BGR + // first + if (cur->pixelFormat == VideoMode::kRGB565) { + // Check to see if BGR version already exists... + if (Image* newImage = + GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) { + cur = newImage; + } else { + cur = ConvertRGB565ToBGR(cur); + } + } else if (cur->pixelFormat == VideoMode::kYUYV) { + // Check to see if BGR version already exists... + if (Image* newImage = + GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) { + cur = newImage; + } else { + cur = ConvertYUYVToBGR(cur); + } + } else if (cur->pixelFormat == VideoMode::kUYVY) { + // Check to see if BGR version already exists... + if (Image* newImage = + GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) { + cur = newImage; + } else { + cur = ConvertUYVYToBGR(cur); + } + } else if (cur->pixelFormat == VideoMode::kGray) { + // Check to see if BGR version already exists... + if (Image* newImage = + GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) { + cur = newImage; + } else { + cur = ConvertGrayToBGR(cur); + } + } else if (cur->pixelFormat == VideoMode::kY16) { + // Check to see if BGR version already exists... + if (Image* newImage = + GetExistingImage(cur->width, cur->height, VideoMode::kBGR)) { + cur = newImage; + } else if (Image* newImage = GetExistingImage(cur->width, cur->height, + VideoMode::kGray)) { + cur = ConvertGrayToBGR(newImage); + } else { + cur = ConvertGrayToBGR(ConvertY16ToGray(cur)); + } + } + return ConvertBGRToBGRA(cur); case VideoMode::kYUYV: case VideoMode::kUYVY: default: @@ -664,6 +712,28 @@ Image* Frame::ConvertY16ToGray(Image* image) { return rv; } +Image* Frame::ConvertBGRToBGRA(Image* image) { + if (!image || image->pixelFormat != VideoMode::kBGR) { + return nullptr; + } + + // Allocate a RGB565 image + auto newImage = + m_impl->source.AllocImage(VideoMode::kBGRA, image->width, image->height, + image->width * image->height * 4); + + // Convert + cv::cvtColor(image->AsMat(), newImage->AsMat(), cv::COLOR_BGR2BGRA); + + // Save the result + Image* rv = newImage.release(); + if (m_impl) { + std::scoped_lock lock(m_impl->mutex); + m_impl->images.push_back(rv); + } + return rv; +} + Image* Frame::GetImageImpl(int width, int height, VideoMode::PixelFormat pixelFormat, int requiredJpegQuality, int defaultJpegQuality) { @@ -709,8 +779,9 @@ Image* Frame::GetImageImpl(int width, int height, return ConvertImpl(cur, pixelFormat, requiredJpegQuality, defaultJpegQuality); } -bool Frame::GetCv(cv::Mat& image, int width, int height) { - Image* rawImage = GetImage(width, height, VideoMode::kBGR); +bool Frame::GetCv(cv::Mat& image, int width, int height, + VideoMode::PixelFormat pixelFormat) { + Image* rawImage = GetImage(width, height, pixelFormat); if (!rawImage) { return false; } @@ -726,3 +797,16 @@ void Frame::ReleaseFrame() { m_impl->source.ReleaseFrameImpl(std::unique_ptr(m_impl)); m_impl = nullptr; } + +namespace cs { +std::unique_ptr CreateImageFromBGRA(cs::SourceImpl* source, size_t width, + size_t height, size_t stride, + const uint8_t* data) { + cv::Mat finalImage{static_cast(height), static_cast(width), CV_8UC4, + const_cast(data), stride}; + std::unique_ptr dest = source->AllocImage( + VideoMode::PixelFormat::kBGR, width, height, width * height * 3); + cv::cvtColor(finalImage, dest->AsMat(), cv::COLOR_BGRA2BGR); + return dest; +} +} // namespace cs diff --git a/cscore/src/main/native/cpp/Frame.h b/cscore/src/main/native/cpp/Frame.h index d5f537331e3..d835de9efc2 100644 --- a/cscore/src/main/native/cpp/Frame.h +++ b/cscore/src/main/native/cpp/Frame.h @@ -22,6 +22,10 @@ namespace cs { class SourceImpl; +std::unique_ptr CreateImageFromBGRA(cs::SourceImpl* source, size_t width, + size_t height, size_t stride, + const uint8_t* data); + class Frame { friend class SourceImpl; @@ -206,6 +210,7 @@ class Frame { Image* ConvertGrayToMJPEG(Image* image, int quality); Image* ConvertGrayToY16(Image* image); Image* ConvertY16ToGray(Image* image); + Image* ConvertBGRToBGRA(Image* image); Image* GetImage(int width, int height, VideoMode::PixelFormat pixelFormat) { if (pixelFormat == VideoMode::kMJPEG) { @@ -219,10 +224,11 @@ class Frame { defaultQuality); } - bool GetCv(cv::Mat& image) { - return GetCv(image, GetOriginalWidth(), GetOriginalHeight()); + bool GetCv(cv::Mat& image, VideoMode::PixelFormat pixelFormat) { + return GetCv(image, GetOriginalWidth(), GetOriginalHeight(), pixelFormat); } - bool GetCv(cv::Mat& image, int width, int height); + bool GetCv(cv::Mat& image, int width, int height, + VideoMode::PixelFormat pixelFormat); private: Image* ConvertImpl(Image* image, VideoMode::PixelFormat pixelFormat, diff --git a/cscore/src/main/native/cpp/HttpCameraImpl.cpp b/cscore/src/main/native/cpp/HttpCameraImpl.cpp index da60d77f291..05a5c90cafe 100644 --- a/cscore/src/main/native/cpp/HttpCameraImpl.cpp +++ b/cscore/src/main/native/cpp/HttpCameraImpl.cpp @@ -634,55 +634,47 @@ std::vector GetHttpCameraUrls(CS_Source source, extern "C" { -CS_Source CS_CreateHttpCamera(const char* name, const char* url, +CS_Source CS_CreateHttpCamera(const struct WPI_String* name, + const struct WPI_String* url, CS_HttpCameraKind kind, CS_Status* status) { - return cs::CreateHttpCamera(name, url, kind, status); + return cs::CreateHttpCamera(wpi::to_string_view(name), + wpi::to_string_view(url), kind, status); } -CS_Source CS_CreateHttpCameraMulti(const char* name, const char** urls, - int count, CS_HttpCameraKind kind, - CS_Status* status) { +CS_Source CS_CreateHttpCameraMulti(const struct WPI_String* name, + const struct WPI_String* urls, int count, + CS_HttpCameraKind kind, CS_Status* status) { wpi::SmallVector vec; vec.reserve(count); for (int i = 0; i < count; ++i) { - vec.push_back(urls[i]); + vec.emplace_back(wpi::to_string_view(&urls[i])); } - return cs::CreateHttpCamera(name, vec, kind, status); + return cs::CreateHttpCamera(wpi::to_string_view(name), vec, kind, status); } CS_HttpCameraKind CS_GetHttpCameraKind(CS_Source source, CS_Status* status) { return cs::GetHttpCameraKind(source, status); } -void CS_SetHttpCameraUrls(CS_Source source, const char** urls, int count, - CS_Status* status) { +void CS_SetHttpCameraUrls(CS_Source source, const struct WPI_String* urls, + int count, CS_Status* status) { wpi::SmallVector vec; vec.reserve(count); for (int i = 0; i < count; ++i) { - vec.push_back(urls[i]); + vec.emplace_back(wpi::to_string_view(&urls[i])); } cs::SetHttpCameraUrls(source, vec, status); } -char** CS_GetHttpCameraUrls(CS_Source source, int* count, CS_Status* status) { +WPI_String* CS_GetHttpCameraUrls(CS_Source source, int* count, + CS_Status* status) { auto urls = cs::GetHttpCameraUrls(source, status); - char** out = - static_cast(wpi::safe_malloc(urls.size() * sizeof(char*))); + WPI_String* out = WPI_AllocateStringArray(urls.size()); *count = urls.size(); for (size_t i = 0; i < urls.size(); ++i) { - out[i] = cs::ConvertToC(urls[i]); + cs::ConvertToC(&out[i], urls[i]); } return out; } -void CS_FreeHttpCameraUrls(char** urls, int count) { - if (!urls) { - return; - } - for (int i = 0; i < count; ++i) { - std::free(urls[i]); - } - std::free(urls); -} - } // extern "C" diff --git a/cscore/src/main/native/cpp/Image.h b/cscore/src/main/native/cpp/Image.h index 83cbe899747..27d34a7cf29 100644 --- a/cscore/src/main/native/cpp/Image.h +++ b/cscore/src/main/native/cpp/Image.h @@ -63,6 +63,9 @@ class Image { case VideoMode::kBGR: type = CV_8UC3; break; + case VideoMode::kBGRA: + type = CV_8UC4; + break; case VideoMode::kGray: case VideoMode::kMJPEG: default: @@ -72,6 +75,25 @@ class Image { return cv::Mat{height, width, type, m_data.data()}; } + int GetStride() const { + switch (pixelFormat) { + case VideoMode::kYUYV: + case VideoMode::kRGB565: + case VideoMode::kY16: + case VideoMode::kUYVY: + return 2 * width; + case VideoMode::kBGR: + return 3 * width; + case VideoMode::kBGRA: + return 4 * width; + case VideoMode::kGray: + return width; + case VideoMode::kMJPEG: + default: + return 0; + } + } + cv::_InputArray AsInputArray() { return cv::_InputArray{m_data}; } bool Is(int width_, int height_) { diff --git a/cscore/src/main/native/cpp/Instance.cpp b/cscore/src/main/native/cpp/Instance.cpp index 3b81f016587..979c80adcfb 100644 --- a/cscore/src/main/native/cpp/Instance.cpp +++ b/cscore/src/main/native/cpp/Instance.cpp @@ -8,13 +8,14 @@ #include #include +#include using namespace cs; static void def_log_func(unsigned int level, const char* file, unsigned int line, const char* msg) { if (level == 20) { - fmt::print(stderr, "CS: {}\n", msg); + wpi::print(stderr, "CS: {}\n", msg); return; } @@ -28,7 +29,7 @@ static void def_log_func(unsigned int level, const char* file, } else { return; } - fmt::print(stderr, "CS: {}: {} ({}:{})\n", levelmsg, msg, + wpi::print(stderr, "CS: {}: {} ({}:{})\n", levelmsg, msg, fs::path{file}.filename().string(), line); } diff --git a/cscore/src/main/native/cpp/MjpegServerImpl.cpp b/cscore/src/main/native/cpp/MjpegServerImpl.cpp index 82273e598da..f6f63d6673d 100644 --- a/cscore/src/main/native/cpp/MjpegServerImpl.cpp +++ b/cscore/src/main/native/cpp/MjpegServerImpl.cpp @@ -6,10 +6,10 @@ #include -#include #include #include #include +#include #include #include #include @@ -135,7 +135,7 @@ class MjpegServerImpl::ConnThread : public wpi::SafeThread { static void SendHeader(wpi::raw_ostream& os, int code, std::string_view codeText, std::string_view contentType, std::string_view extra = {}) { - fmt::print(os, "HTTP/1.0 {} {}\r\n", code, codeText); + wpi::print(os, "HTTP/1.0 {} {}\r\n", code, codeText); os << "Connection: close\r\n" "Server: CameraServer/1.0\r\n" "Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, " @@ -302,7 +302,7 @@ bool MjpegServerImpl::ConnThread::ProcessCommand(wpi::raw_ostream& os, case CS_PROP_INTEGER: case CS_PROP_ENUM: { if (auto v = wpi::parse_integer(value, 10)) { - fmt::print(response, "{}: {}\r\n", param, v.value()); + wpi::print(response, "{}: {}\r\n", param, v.value()); SDEBUG4("HTTP parameter \"{}\" value {}", param, value); source.SetProperty(prop, v.value(), &status); } else { @@ -356,10 +356,10 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, continue; } auto kind = source.GetPropertyKind(prop); - fmt::print(os, "

\n", name); + wpi::print(os, "

\n", name); switch (kind) { case CS_PROP_BOOLEAN: - fmt::print(os, + wpi::print(os, "\n", name, min, max, valI, step); - fmt::print(os, "{1}\n", name, + wpi::print(os, "{1}\n", name, valI); break; } @@ -397,25 +397,25 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, for (char ch : *choice) { ch_name.push_back(wpi::isPrint(ch) ? ch : ' '); } - fmt::print(os, + wpi::print(os, "\n", name, j, + wpi::print(os, " />\n", name, j, ch_name.str()); } break; } case CS_PROP_STRING: { wpi::SmallString<128> strval_buf; - fmt::print(os, + wpi::print(os, "\n", name, source.GetStringProperty(prop, strval_buf, &status)); - fmt::print(os, + wpi::print(os, "\n", name); @@ -438,9 +438,7 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, os << "

Supported Video Modes:

\n"; os << "\n"; - os << "" - << "" - << "" + os << "" << "" << "" << ""; for (auto mode : source.EnumerateVideoModes(&status)) { os << "", mode.width, + wpi::print(os, "", mode.width, mode.height, mode.fps); } os << "
Pixel FormatWidthHeight
Pixel FormatWidthHeightFPS
"; @@ -457,6 +455,9 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, case VideoMode::kBGR: os << "BGR"; break; + case VideoMode::kBGRA: + os << "BGRA"; + break; case VideoMode::kGray: os << "gray"; break; @@ -470,7 +471,7 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, os << "unknown"; break; } - fmt::print(os, "{}{}{}
{}{}{}
\n"; @@ -499,21 +500,21 @@ void MjpegServerImpl::ConnThread::SendJSON(wpi::raw_ostream& os, wpi::SmallString<128> name_buf; auto name = source.GetPropertyName(prop, name_buf, &status); auto kind = source.GetPropertyKind(prop); - fmt::print(os, "\n\"name\": \"{}\"", name); - fmt::print(os, ",\n\"id\": \"{}\"", prop); - fmt::print(os, ",\n\"type\": \"{}\"", static_cast(kind)); - fmt::print(os, ",\n\"min\": \"{}\"", source.GetPropertyMin(prop, &status)); - fmt::print(os, ",\n\"max\": \"{}\"", source.GetPropertyMax(prop, &status)); - fmt::print(os, ",\n\"step\": \"{}\"", + wpi::print(os, "\n\"name\": \"{}\"", name); + wpi::print(os, ",\n\"id\": \"{}\"", prop); + wpi::print(os, ",\n\"type\": \"{}\"", static_cast(kind)); + wpi::print(os, ",\n\"min\": \"{}\"", source.GetPropertyMin(prop, &status)); + wpi::print(os, ",\n\"max\": \"{}\"", source.GetPropertyMax(prop, &status)); + wpi::print(os, ",\n\"step\": \"{}\"", source.GetPropertyStep(prop, &status)); - fmt::print(os, ",\n\"default\": \"{}\"", + wpi::print(os, ",\n\"default\": \"{}\"", source.GetPropertyDefault(prop, &status)); os << ",\n\"value\": \""; switch (kind) { case CS_PROP_BOOLEAN: case CS_PROP_INTEGER: case CS_PROP_ENUM: - fmt::print(os, "{}", source.GetProperty(prop, &status)); + wpi::print(os, "{}", source.GetProperty(prop, &status)); break; case CS_PROP_STRING: { wpi::SmallString<128> strval_buf; @@ -543,7 +544,7 @@ void MjpegServerImpl::ConnThread::SendJSON(wpi::raw_ostream& os, for (char ch : *choice) { ch_name.push_back(std::isprint(ch) ? ch : ' '); } - fmt::print(os, "\"{}\": \"{}\"", j, ch_name.str()); + wpi::print(os, "\"{}\": \"{}\"", j, ch_name.str()); } os << "}\n"; } @@ -585,9 +586,9 @@ void MjpegServerImpl::ConnThread::SendJSON(wpi::raw_ostream& os, os << "unknown"; break; } - fmt::print(os, "\",\n\"width\": \"{}\"", mode.width); - fmt::print(os, ",\n\"height\": \"{}\"", mode.height); - fmt::print(os, ",\n\"fps\": \"{}\"", mode.fps); + wpi::print(os, "\",\n\"width\": \"{}\"", mode.width); + wpi::print(os, ",\n\"height\": \"{}\"", mode.height); + wpi::print(os, ",\n\"fps\": \"{}\"", mode.fps); os << '}'; } os << "\n]\n}\n"; @@ -772,8 +773,8 @@ void MjpegServerImpl::ConnThread::SendStream(wpi::raw_socket_ostream& os) { header.clear(); oss << "\r\n--" BOUNDARY "\r\n" << "Content-Type: image/jpeg\r\n"; - fmt::print(oss, "Content-Length: {}\r\n", size); - fmt::print(oss, "X-Timestamp: {}\r\n", timestamp); + wpi::print(oss, "Content-Length: {}\r\n", size); + wpi::print(oss, "X-Timestamp: {}\r\n", timestamp); oss << "\r\n"; os << oss.str(); if (addDHT) { @@ -878,8 +879,7 @@ void MjpegServerImpl::ConnThread::ProcessRequest() { ProcessCommand(os, *source, parameters, true); } else { SendHeader(os, 200, "OK", "text/plain"); - os << "Ignored due to no connected source." - << "\r\n"; + os << "Ignored due to no connected source." << "\r\n"; SDEBUG("Ignored due to no connected source."); } break; @@ -1047,13 +1047,17 @@ int GetMjpegServerPort(CS_Sink sink, CS_Status* status) { extern "C" { -CS_Sink CS_CreateMjpegServer(const char* name, const char* listenAddress, - int port, CS_Status* status) { - return cs::CreateMjpegServer(name, listenAddress, port, status); +CS_Sink CS_CreateMjpegServer(const struct WPI_String* name, + const struct WPI_String* listenAddress, int port, + CS_Status* status) { + return cs::CreateMjpegServer(wpi::to_string_view(name), + wpi::to_string_view(listenAddress), port, + status); } -char* CS_GetMjpegServerListenAddress(CS_Sink sink, CS_Status* status) { - return ConvertToC(cs::GetMjpegServerListenAddress(sink, status)); +void CS_GetMjpegServerListenAddress(CS_Sink sink, WPI_String* listenAddress, + CS_Status* status) { + cs::ConvertToC(listenAddress, cs::GetMjpegServerListenAddress(sink, status)); } int CS_GetMjpegServerPort(CS_Sink sink, CS_Status* status) { diff --git a/cscore/src/main/native/cpp/RawSinkImpl.cpp b/cscore/src/main/native/cpp/RawSinkImpl.cpp index 31c57d2cecd..bdbf2c1a9a6 100644 --- a/cscore/src/main/native/cpp/RawSinkImpl.cpp +++ b/cscore/src/main/native/cpp/RawSinkImpl.cpp @@ -40,7 +40,7 @@ void RawSinkImpl::Stop() { } } -uint64_t RawSinkImpl::GrabFrame(CS_RawFrame& image) { +uint64_t RawSinkImpl::GrabFrame(WPI_RawFrame& image) { SetEnabled(true); auto source = GetSource(); @@ -60,7 +60,7 @@ uint64_t RawSinkImpl::GrabFrame(CS_RawFrame& image) { return GrabFrameImpl(image, frame); } -uint64_t RawSinkImpl::GrabFrame(CS_RawFrame& image, double timeout) { +uint64_t RawSinkImpl::GrabFrame(WPI_RawFrame& image, double timeout) { SetEnabled(true); auto source = GetSource(); @@ -80,11 +80,11 @@ uint64_t RawSinkImpl::GrabFrame(CS_RawFrame& image, double timeout) { return GrabFrameImpl(image, frame); } -uint64_t RawSinkImpl::GrabFrameImpl(CS_RawFrame& rawFrame, +uint64_t RawSinkImpl::GrabFrameImpl(WPI_RawFrame& rawFrame, Frame& incomingFrame) { Image* newImage = nullptr; - if (rawFrame.pixelFormat == CS_PixelFormat::CS_PIXFMT_UNKNOWN) { + if (rawFrame.pixelFormat == WPI_PixelFormat::WPI_PIXFMT_UNKNOWN) { // Always get incoming image directly on unknown newImage = incomingFrame.GetExistingImage(0); } else { @@ -106,13 +106,13 @@ uint64_t RawSinkImpl::GrabFrameImpl(CS_RawFrame& rawFrame, return 0; } - CS_AllocateRawFrameData(&rawFrame, newImage->size()); + WPI_AllocateRawFrameData(&rawFrame, newImage->size()); rawFrame.height = newImage->height; rawFrame.width = newImage->width; + rawFrame.stride = newImage->GetStride(); rawFrame.pixelFormat = newImage->pixelFormat; - rawFrame.totalData = newImage->size(); - std::copy(newImage->data(), newImage->data() + rawFrame.totalData, - rawFrame.data); + rawFrame.size = newImage->size(); + std::copy(newImage->data(), newImage->data() + rawFrame.size, rawFrame.data); return incomingFrame.GetTime(); } @@ -143,62 +143,68 @@ void RawSinkImpl::ThreadMain() { } namespace cs { -CS_Sink CreateRawSink(std::string_view name, CS_Status* status) { +static constexpr unsigned SinkMask = CS_SINK_CV | CS_SINK_RAW; + +CS_Sink CreateRawSink(std::string_view name, bool isCv, CS_Status* status) { auto& inst = Instance::GetInstance(); - return inst.CreateSink(CS_SINK_RAW, + return inst.CreateSink(isCv ? CS_SINK_CV : CS_SINK_RAW, std::make_shared( name, inst.logger, inst.notifier, inst.telemetry)); } -CS_Sink CreateRawSinkCallback(std::string_view name, +CS_Sink CreateRawSinkCallback(std::string_view name, bool isCv, std::function processFrame, CS_Status* status) { auto& inst = Instance::GetInstance(); - return inst.CreateSink(CS_SINK_RAW, std::make_shared( - name, inst.logger, inst.notifier, - inst.telemetry, processFrame)); + return inst.CreateSink( + isCv ? CS_SINK_CV : CS_SINK_RAW, + std::make_shared(name, inst.logger, inst.notifier, + inst.telemetry, processFrame)); } -uint64_t GrabSinkFrame(CS_Sink sink, CS_RawFrame& image, CS_Status* status) { +uint64_t GrabSinkFrame(CS_Sink sink, WPI_RawFrame& image, CS_Status* status) { auto data = Instance::GetInstance().GetSink(sink); - if (!data || data->kind != CS_SINK_RAW) { + if (!data || (data->kind & SinkMask) == 0) { *status = CS_INVALID_HANDLE; return 0; } return static_cast(*data->sink).GrabFrame(image); } -uint64_t GrabSinkFrameTimeout(CS_Sink sink, CS_RawFrame& image, double timeout, +uint64_t GrabSinkFrameTimeout(CS_Sink sink, WPI_RawFrame& image, double timeout, CS_Status* status) { auto data = Instance::GetInstance().GetSink(sink); - if (!data || data->kind != CS_SINK_RAW) { + if (!data || (data->kind & SinkMask) == 0) { *status = CS_INVALID_HANDLE; return 0; } return static_cast(*data->sink).GrabFrame(image, timeout); } + } // namespace cs extern "C" { -CS_Sink CS_CreateRawSink(const char* name, CS_Status* status) { - return cs::CreateRawSink(name, status); +CS_Sink CS_CreateRawSink(const struct WPI_String* name, CS_Bool isCv, + CS_Status* status) { + return cs::CreateRawSink(wpi::to_string_view(name), isCv, status); } -CS_Sink CS_CreateRawSinkCallback(const char* name, void* data, - void (*processFrame)(void* data, - uint64_t time), - CS_Status* status) { +CS_Sink CS_CreateRawSinkCallback( + const struct WPI_String* name, CS_Bool isCv, void* data, + void (*processFrame)(void* data, uint64_t time), CS_Status* status) { return cs::CreateRawSinkCallback( - name, [=](uint64_t time) { processFrame(data, time); }, status); + wpi::to_string_view(name), isCv, + [=](uint64_t time) { processFrame(data, time); }, status); } -uint64_t CS_GrabRawSinkFrame(CS_Sink sink, struct CS_RawFrame* image, +uint64_t CS_GrabRawSinkFrame(CS_Sink sink, struct WPI_RawFrame* image, CS_Status* status) { return cs::GrabSinkFrame(sink, *image, status); } -uint64_t CS_GrabRawSinkFrameTimeout(CS_Sink sink, struct CS_RawFrame* image, +uint64_t CS_GrabRawSinkFrameTimeout(CS_Sink sink, struct WPI_RawFrame* image, double timeout, CS_Status* status) { return cs::GrabSinkFrameTimeout(sink, *image, timeout, status); } + } // extern "C" diff --git a/cscore/src/main/native/cpp/RawSinkImpl.h b/cscore/src/main/native/cpp/RawSinkImpl.h index 6e8032a1016..ac719764ec2 100644 --- a/cscore/src/main/native/cpp/RawSinkImpl.h +++ b/cscore/src/main/native/cpp/RawSinkImpl.h @@ -32,13 +32,13 @@ class RawSinkImpl : public SinkImpl { void Stop(); - uint64_t GrabFrame(CS_RawFrame& frame); - uint64_t GrabFrame(CS_RawFrame& frame, double timeout); + uint64_t GrabFrame(WPI_RawFrame& frame); + uint64_t GrabFrame(WPI_RawFrame& frame, double timeout); private: void ThreadMain(); - uint64_t GrabFrameImpl(CS_RawFrame& rawFrame, Frame& incomingFrame); + uint64_t GrabFrameImpl(WPI_RawFrame& rawFrame, Frame& incomingFrame); std::atomic_bool m_active; // set to false to terminate threads std::thread m_thread; diff --git a/cscore/src/main/native/cpp/RawSourceImpl.cpp b/cscore/src/main/native/cpp/RawSourceImpl.cpp index bad26a05cfc..aad27b240ef 100644 --- a/cscore/src/main/native/cpp/RawSourceImpl.cpp +++ b/cscore/src/main/native/cpp/RawSourceImpl.cpp @@ -21,62 +21,47 @@ RawSourceImpl::RawSourceImpl(std::string_view name, wpi::Logger& logger, RawSourceImpl::~RawSourceImpl() = default; -void RawSourceImpl::PutFrame(const CS_RawFrame& image) { - int type; - switch (image.pixelFormat) { - case VideoMode::kYUYV: - case VideoMode::kRGB565: - case VideoMode::kY16: - case VideoMode::kUYVY: - type = CV_8UC2; - break; - case VideoMode::kBGR: - type = CV_8UC3; - break; - case VideoMode::kGray: - case VideoMode::kMJPEG: - default: - type = CV_8UC1; - break; - } - cv::Mat finalImage{image.height, image.width, type, image.data}; - std::unique_ptr dest = - AllocImage(static_cast(image.pixelFormat), - image.width, image.height, image.totalData); - finalImage.copyTo(dest->AsMat()); - - SourceImpl::PutFrame(std::move(dest), wpi::Now()); +void RawSourceImpl::PutFrame(const WPI_RawFrame& image) { + auto currentTime = wpi::Now(); + std::string_view data_view{reinterpret_cast(image.data), image.size}; + SourceImpl::PutFrame(static_cast(image.pixelFormat), + image.width, image.height, data_view, currentTime); } namespace cs { -CS_Source CreateRawSource(std::string_view name, const VideoMode& mode, - CS_Status* status) { +static constexpr unsigned SourceMask = CS_SOURCE_CV | CS_SOURCE_RAW; + +CS_Source CreateRawSource(std::string_view name, bool isCv, + const VideoMode& mode, CS_Status* status) { auto& inst = Instance::GetInstance(); - return inst.CreateSource(CS_SOURCE_RAW, std::make_shared( - name, inst.logger, inst.notifier, - inst.telemetry, mode)); + return inst.CreateSource( + isCv ? CS_SOURCE_CV : CS_SOURCE_RAW, + std::make_shared(name, inst.logger, inst.notifier, + inst.telemetry, mode)); } -void PutSourceFrame(CS_Source source, const CS_RawFrame& image, +void PutSourceFrame(CS_Source source, const WPI_RawFrame& image, CS_Status* status) { auto data = Instance::GetInstance().GetSource(source); - if (!data || data->kind != CS_SOURCE_RAW) { + if (!data || (data->kind & SourceMask) == 0) { *status = CS_INVALID_HANDLE; return; } static_cast(*data->source).PutFrame(image); } + } // namespace cs extern "C" { -CS_Source CS_CreateRawSource(const char* name, const CS_VideoMode* mode, - CS_Status* status) { - return cs::CreateRawSource(name, static_cast(*mode), - status); +CS_Source CS_CreateRawSource(const struct WPI_String* name, CS_Bool isCv, + const CS_VideoMode* mode, CS_Status* status) { + return cs::CreateRawSource(wpi::to_string_view(name), isCv, + static_cast(*mode), status); } -void CS_PutRawSourceFrame(CS_Source source, const struct CS_RawFrame* image, +void CS_PutRawSourceFrame(CS_Source source, const struct WPI_RawFrame* image, CS_Status* status) { return cs::PutSourceFrame(source, *image, status); } + } // extern "C" diff --git a/cscore/src/main/native/cpp/RawSourceImpl.h b/cscore/src/main/native/cpp/RawSourceImpl.h index 5887ed42032..44a20b90c0e 100644 --- a/cscore/src/main/native/cpp/RawSourceImpl.h +++ b/cscore/src/main/native/cpp/RawSourceImpl.h @@ -25,7 +25,7 @@ class RawSourceImpl : public ConfigurableSourceImpl { ~RawSourceImpl() override; // Raw-specific functions - void PutFrame(const CS_RawFrame& image); + void PutFrame(const WPI_RawFrame& image); private: std::atomic_bool m_connected{true}; diff --git a/cscore/src/main/native/cpp/SinkImpl.cpp b/cscore/src/main/native/cpp/SinkImpl.cpp index 93a625f814a..0897bb8d6a5 100644 --- a/cscore/src/main/native/cpp/SinkImpl.cpp +++ b/cscore/src/main/native/cpp/SinkImpl.cpp @@ -4,11 +4,13 @@ #include "SinkImpl.h" +#include #include #include "Instance.h" #include "Notifier.h" #include "SourceImpl.h" +#include "c_util.h" using namespace cs; @@ -195,3 +197,64 @@ void SinkImpl::UpdatePropertyValue(int property, bool setString, int value, } void SinkImpl::SetSourceImpl(std::shared_ptr source) {} + +namespace cs { +static constexpr unsigned SinkMask = CS_SINK_CV | CS_SINK_RAW; + +void SetSinkDescription(CS_Sink sink, std::string_view description, + CS_Status* status) { + auto data = Instance::GetInstance().GetSink(sink); + if (!data || (data->kind & SinkMask) == 0) { + *status = CS_INVALID_HANDLE; + return; + } + data->sink->SetDescription(description); +} + +std::string GetSinkError(CS_Sink sink, CS_Status* status) { + auto data = Instance::GetInstance().GetSink(sink); + if (!data || (data->kind & SinkMask) == 0) { + *status = CS_INVALID_HANDLE; + return std::string{}; + } + return data->sink->GetError(); +} + +std::string_view GetSinkError(CS_Sink sink, wpi::SmallVectorImpl& buf, + CS_Status* status) { + auto data = Instance::GetInstance().GetSink(sink); + if (!data || (data->kind & SinkMask) == 0) { + *status = CS_INVALID_HANDLE; + return {}; + } + return data->sink->GetError(buf); +} + +void SetSinkEnabled(CS_Sink sink, bool enabled, CS_Status* status) { + auto data = Instance::GetInstance().GetSink(sink); + if (!data || (data->kind & SinkMask) == 0) { + *status = CS_INVALID_HANDLE; + return; + } + data->sink->SetEnabled(enabled); +} + +} // namespace cs + +extern "C" { +void CS_SetSinkDescription(CS_Sink sink, const struct WPI_String* description, + CS_Status* status) { + return cs::SetSinkDescription(sink, wpi::to_string_view(description), status); +} + +void CS_GetSinkError(CS_Sink sink, struct WPI_String* error, + CS_Status* status) { + wpi::SmallString<128> buf; + cs::ConvertToC(error, cs::GetSinkError(sink, buf, status)); +} + +void CS_SetSinkEnabled(CS_Sink sink, CS_Bool enabled, CS_Status* status) { + return cs::SetSinkEnabled(sink, enabled, status); +} + +} // extern "C" diff --git a/cscore/src/main/native/cpp/SourceImpl.cpp b/cscore/src/main/native/cpp/SourceImpl.cpp index 045bdd46923..e30821064ae 100644 --- a/cscore/src/main/native/cpp/SourceImpl.cpp +++ b/cscore/src/main/native/cpp/SourceImpl.cpp @@ -196,6 +196,8 @@ bool SourceImpl::SetConfigJson(const wpi::json& config, CS_Status* status) { mode.pixelFormat = cs::VideoMode::kRGB565; } else if (wpi::equals_lower(str, "bgr")) { mode.pixelFormat = cs::VideoMode::kBGR; + } else if (wpi::equals_lower(str, "bgra")) { + mode.pixelFormat = cs::VideoMode::kBGRA; } else if (wpi::equals_lower(str, "gray")) { mode.pixelFormat = cs::VideoMode::kGray; } else if (wpi::equals_lower(str, "y16")) { @@ -361,6 +363,9 @@ wpi::json SourceImpl::GetConfigJsonObject(CS_Status* status) { case VideoMode::kBGR: pixelFormat = "bgr"; break; + case VideoMode::kBGRA: + pixelFormat = "bgra"; + break; case VideoMode::kGray: pixelFormat = "gray"; break; @@ -450,6 +455,15 @@ std::unique_ptr SourceImpl::AllocImage( void SourceImpl::PutFrame(VideoMode::PixelFormat pixelFormat, int width, int height, std::string_view data, Frame::Time time) { + if (pixelFormat == VideoMode::PixelFormat::kBGRA) { + // Write BGRA as BGR to save a copy + auto image = + CreateImageFromBGRA(this, width, height, width * 4, + reinterpret_cast(data.data())); + PutFrame(std::move(image), time); + return; + } + auto image = AllocImage(pixelFormat, width, height, data.size()); // Copy in image data diff --git a/cscore/src/main/native/cpp/UsbCameraImplCommon.cpp b/cscore/src/main/native/cpp/UsbCameraImplCommon.cpp index 5731f1f1b6b..81afcc10563 100644 --- a/cscore/src/main/native/cpp/UsbCameraImplCommon.cpp +++ b/cscore/src/main/native/cpp/UsbCameraImplCommon.cpp @@ -4,6 +4,8 @@ #include "cscore_c.h" // NOLINT(build/include_order) +#include + #include "c_util.h" #include "cscore_cpp.h" @@ -11,56 +13,53 @@ using namespace cs; static void ConvertToC(CS_UsbCameraInfo* out, const UsbCameraInfo& in) { out->dev = in.dev; - out->path = ConvertToC(in.path); - out->name = ConvertToC(in.name); - out->otherPaths = static_cast( - wpi::safe_malloc(in.otherPaths.size() * sizeof(char*))); + cs::ConvertToC(&out->path, in.path); + cs::ConvertToC(&out->name, in.name); + out->otherPaths = WPI_AllocateStringArray(in.otherPaths.size()); out->otherPathsCount = in.otherPaths.size(); for (size_t i = 0; i < in.otherPaths.size(); ++i) { - out->otherPaths[i] = cs::ConvertToC(in.otherPaths[i]); + cs::ConvertToC(&out->otherPaths[i], in.otherPaths[i]); } out->vendorId = in.vendorId; out->productId = in.productId; } static void FreeUsbCameraInfo(CS_UsbCameraInfo* info) { - std::free(info->path); - std::free(info->name); + WPI_FreeString(&info->path); + WPI_FreeString(&info->name); for (int i = 0; i < info->otherPathsCount; ++i) { - std::free(info->otherPaths[i]); + WPI_FreeString(&info->otherPaths[i]); } - std::free(info->otherPaths); } extern "C" { -CS_Source CS_CreateUsbCameraDev(const char* name, int dev, CS_Status* status) { - return cs::CreateUsbCameraDev(name, dev, status); +CS_Source CS_CreateUsbCameraDev(const struct WPI_String* name, int dev, + CS_Status* status) { + return cs::CreateUsbCameraDev(wpi::to_string_view(name), dev, status); } -CS_Source CS_CreateUsbCameraPath(const char* name, const char* path, +CS_Source CS_CreateUsbCameraPath(const struct WPI_String* name, + const struct WPI_String* path, CS_Status* status) { - return cs::CreateUsbCameraPath(name, path, status); + return cs::CreateUsbCameraPath(wpi::to_string_view(name), + wpi::to_string_view(path), status); } -void CS_SetUsbCameraPath(CS_Source source, const char* path, +void CS_SetUsbCameraPath(CS_Source source, const struct WPI_String* path, CS_Status* status) { - cs::SetUsbCameraPath(source, path, status); + cs::SetUsbCameraPath(source, wpi::to_string_view(path), status); } -char* CS_GetUsbCameraPath(CS_Source source, CS_Status* status) { - return ConvertToC(cs::GetUsbCameraPath(source, status)); +void CS_GetUsbCameraPath(CS_Source source, WPI_String* path, + CS_Status* status) { + ConvertToC(path, cs::GetUsbCameraPath(source, status)); } -CS_UsbCameraInfo* CS_GetUsbCameraInfo(CS_Source source, CS_Status* status) { - auto info = cs::GetUsbCameraInfo(source, status); - if (*status != CS_OK) { - return nullptr; - } - CS_UsbCameraInfo* out = static_cast( - wpi::safe_malloc(sizeof(CS_UsbCameraInfo))); - ConvertToC(out, info); - return out; +void CS_GetUsbCameraInfo(CS_Source source, CS_UsbCameraInfo* info, + CS_Status* status) { + auto info_cpp = cs::GetUsbCameraInfo(source, status); + ConvertToC(info, info_cpp); } CS_UsbCameraInfo* CS_EnumerateUsbCameras(int* count, CS_Status* status) { @@ -89,7 +88,6 @@ void CS_FreeUsbCameraInfo(CS_UsbCameraInfo* info) { return; } FreeUsbCameraInfo(info); - std::free(info); } } // extern "C" diff --git a/cscore/src/main/native/cpp/c_util.h b/cscore/src/main/native/cpp/c_util.h index 904d049ef6f..a81f4287168 100644 --- a/cscore/src/main/native/cpp/c_util.h +++ b/cscore/src/main/native/cpp/c_util.h @@ -5,19 +5,16 @@ #ifndef CSCORE_C_UTIL_H_ #define CSCORE_C_UTIL_H_ -#include #include #include -#include +#include namespace cs { -inline char* ConvertToC(std::string_view in) { - char* out = static_cast(wpi::safe_malloc(in.size() + 1)); - std::memmove(out, in.data(), in.size()); - out[in.size()] = '\0'; - return out; +inline void ConvertToC(struct WPI_String* output, std::string_view str) { + char* write = WPI_AllocateString(output, str.size()); + std::memcpy(write, str.data(), str.size()); } } // namespace cs diff --git a/cscore/src/main/native/cpp/cscore_c.cpp b/cscore/src/main/native/cpp/cscore_c.cpp index 3fbbfcda375..521a1ffa501 100644 --- a/cscore/src/main/native/cpp/cscore_c.cpp +++ b/cscore/src/main/native/cpp/cscore_c.cpp @@ -7,7 +7,6 @@ #include #include -#include #include #include @@ -20,12 +19,12 @@ static CS_Event ConvertToC(const cs::RawEvent& rawEvent) { event.kind = static_cast(static_cast(rawEvent.kind)); event.source = rawEvent.sourceHandle; event.sink = rawEvent.sinkHandle; - event.name = rawEvent.name.c_str(); + cs::ConvertToC(&event.name, rawEvent.name); event.mode = rawEvent.mode; event.property = rawEvent.propertyHandle; event.propertyKind = rawEvent.propertyKind; event.value = rawEvent.value; - event.valueStr = rawEvent.valueStr.c_str(); + cs::ConvertToC(&event.name, rawEvent.valueStr); event.listener = rawEvent.listener; return event; } @@ -54,13 +53,10 @@ CS_PropertyKind CS_GetPropertyKind(CS_Property property, CS_Status* status) { return cs::GetPropertyKind(property, status); } -char* CS_GetPropertyName(CS_Property property, CS_Status* status) { +void CS_GetPropertyName(CS_Property property, WPI_String* name, + CS_Status* status) { wpi::SmallString<128> buf; - auto str = cs::GetPropertyName(property, buf, status); - if (*status != 0) { - return nullptr; - } - return cs::ConvertToC(str); + cs::ConvertToC(name, cs::GetPropertyName(property, buf, status)); } int CS_GetProperty(CS_Property property, CS_Status* status) { @@ -87,28 +83,24 @@ int CS_GetPropertyDefault(CS_Property property, CS_Status* status) { return cs::GetPropertyDefault(property, status); } -char* CS_GetStringProperty(CS_Property property, CS_Status* status) { +void CS_GetStringProperty(CS_Property property, WPI_String* value, + CS_Status* status) { wpi::SmallString<128> buf; - auto str = cs::GetStringProperty(property, buf, status); - if (*status != 0) { - return nullptr; - } - return cs::ConvertToC(str); + cs::ConvertToC(value, cs::GetStringProperty(property, buf, status)); } -void CS_SetStringProperty(CS_Property property, const char* value, +void CS_SetStringProperty(CS_Property property, const struct WPI_String* value, CS_Status* status) { - return cs::SetStringProperty(property, value, status); + return cs::SetStringProperty(property, wpi::to_string_view(value), status); } -char** CS_GetEnumPropertyChoices(CS_Property property, int* count, - CS_Status* status) { +WPI_String* CS_GetEnumPropertyChoices(CS_Property property, int* count, + CS_Status* status) { auto choices = cs::GetEnumPropertyChoices(property, status); - char** out = - static_cast(wpi::safe_malloc(choices.size() * sizeof(char*))); + WPI_String* out = WPI_AllocateStringArray(choices.size()); *count = choices.size(); for (size_t i = 0; i < choices.size(); ++i) { - out[i] = cs::ConvertToC(choices[i]); + cs::ConvertToC(&out[i], choices[i]); } return out; } @@ -117,22 +109,15 @@ CS_SourceKind CS_GetSourceKind(CS_Source source, CS_Status* status) { return cs::GetSourceKind(source, status); } -char* CS_GetSourceName(CS_Source source, CS_Status* status) { +void CS_GetSourceName(CS_Source source, WPI_String* name, CS_Status* status) { wpi::SmallString<128> buf; - auto str = cs::GetSourceName(source, buf, status); - if (*status != 0) { - return nullptr; - } - return cs::ConvertToC(str); + cs::ConvertToC(name, cs::GetSourceName(source, buf, status)); } -char* CS_GetSourceDescription(CS_Source source, CS_Status* status) { +void CS_GetSourceDescription(CS_Source source, WPI_String* description, + CS_Status* status) { wpi::SmallString<128> buf; - auto str = cs::GetSourceDescription(source, buf, status); - if (*status != 0) { - return nullptr; - } - return cs::ConvertToC(str); + cs::ConvertToC(description, cs::GetSourceDescription(source, buf, status)); } uint64_t CS_GetSourceLastFrameTime(CS_Source source, CS_Status* status) { @@ -153,9 +138,10 @@ CS_Bool CS_IsSourceEnabled(CS_Source source, CS_Status* status) { return cs::IsSourceEnabled(source, status); } -CS_Property CS_GetSourceProperty(CS_Source source, const char* name, +CS_Property CS_GetSourceProperty(CS_Source source, + const struct WPI_String* name, CS_Status* status) { - return cs::GetSourceProperty(source, name, status); + return cs::GetSourceProperty(source, wpi::to_string_view(name), status); } CS_Property* CS_EnumerateSourceProperties(CS_Source source, int* count, @@ -181,7 +167,7 @@ CS_Bool CS_SetSourceVideoMode(CS_Source source, const CS_VideoMode* mode, } CS_Bool CS_SetSourceVideoModeDiscrete(CS_Source source, - enum CS_PixelFormat pixelFormat, + enum WPI_PixelFormat pixelFormat, int width, int height, int fps, CS_Status* status) { return cs::SetSourceVideoMode( @@ -193,7 +179,7 @@ CS_Bool CS_SetSourceVideoModeDiscrete(CS_Source source, } CS_Bool CS_SetSourcePixelFormat(CS_Source source, - enum CS_PixelFormat pixelFormat, + enum WPI_PixelFormat pixelFormat, CS_Status* status) { return cs::SetSourcePixelFormat( source, @@ -210,13 +196,15 @@ CS_Bool CS_SetSourceFPS(CS_Source source, int fps, CS_Status* status) { return cs::SetSourceFPS(source, fps, status); } -CS_Bool CS_SetSourceConfigJson(CS_Source source, const char* config, +CS_Bool CS_SetSourceConfigJson(CS_Source source, + const struct WPI_String* config, CS_Status* status) { - return cs::SetSourceConfigJson(source, config, status); + return cs::SetSourceConfigJson(source, wpi::to_string_view(config), status); } -char* CS_GetSourceConfigJson(CS_Source source, CS_Status* status) { - return cs::ConvertToC(cs::GetSourceConfigJson(source, status)); +void CS_GetSourceConfigJson(CS_Source source, WPI_String* config, + CS_Status* status) { + cs::ConvertToC(config, cs::GetSourceConfigJson(source, status)); } CS_VideoMode* CS_EnumerateSourceVideoModes(CS_Source source, int* count, @@ -287,27 +275,20 @@ CS_SinkKind CS_GetSinkKind(CS_Sink sink, CS_Status* status) { return cs::GetSinkKind(sink, status); } -char* CS_GetSinkName(CS_Sink sink, CS_Status* status) { +void CS_GetSinkName(CS_Sink sink, WPI_String* name, CS_Status* status) { wpi::SmallString<128> buf; - auto str = cs::GetSinkName(sink, buf, status); - if (*status != 0) { - return nullptr; - } - return cs::ConvertToC(str); + cs::ConvertToC(name, cs::GetSinkName(sink, buf, status)); } -char* CS_GetSinkDescription(CS_Sink sink, CS_Status* status) { +void CS_GetSinkDescription(CS_Sink sink, WPI_String* description, + CS_Status* status) { wpi::SmallString<128> buf; - auto str = cs::GetSinkDescription(sink, buf, status); - if (*status != 0) { - return nullptr; - } - return cs::ConvertToC(str); + cs::ConvertToC(description, cs::GetSinkDescription(sink, buf, status)); } -CS_Property CS_GetSinkProperty(CS_Sink sink, const char* name, +CS_Property CS_GetSinkProperty(CS_Sink sink, const struct WPI_String* name, CS_Status* status) { - return cs::GetSinkProperty(sink, name, status); + return cs::GetSinkProperty(sink, wpi::to_string_view(name), status); } CS_Property* CS_EnumerateSinkProperties(CS_Sink sink, int* count, @@ -321,13 +302,13 @@ CS_Property* CS_EnumerateSinkProperties(CS_Sink sink, int* count, return out; } -CS_Bool CS_SetSinkConfigJson(CS_Sink sink, const char* config, +CS_Bool CS_SetSinkConfigJson(CS_Sink sink, const struct WPI_String* config, CS_Status* status) { - return cs::SetSinkConfigJson(sink, config, status); + return cs::SetSinkConfigJson(sink, wpi::to_string_view(config), status); } -char* CS_GetSinkConfigJson(CS_Sink sink, CS_Status* status) { - return cs::ConvertToC(cs::GetSinkConfigJson(sink, status)); +void CS_GetSinkConfigJson(CS_Sink sink, WPI_String* config, CS_Status* status) { + cs::ConvertToC(config, cs::GetSinkConfigJson(sink, status)); } void CS_SetSinkSource(CS_Sink sink, CS_Source source, CS_Status* status) { @@ -338,9 +319,10 @@ CS_Source CS_GetSinkSource(CS_Sink sink, CS_Status* status) { return cs::GetSinkSource(sink, status); } -CS_Property CS_GetSinkSourceProperty(CS_Sink sink, const char* name, +CS_Property CS_GetSinkSourceProperty(CS_Sink sink, + const struct WPI_String* name, CS_Status* status) { - return cs::GetSinkSourceProperty(sink, name, status); + return cs::GetSinkSourceProperty(sink, wpi::to_string_view(name), status); } CS_Sink CS_CopySink(CS_Sink sink, CS_Status* status) { @@ -361,7 +343,7 @@ void CS_SetListenerOnExit(void (*onExit)(void* data), void* data) { CS_Listener CS_AddListener(void* data, void (*callback)(void* data, const CS_Event* event), - int eventMask, int immediateNotify, + int eventMask, CS_Bool immediateNotify, CS_Status* status) { return cs::AddListener( [=](const cs::RawEvent& rawEvent) { @@ -436,8 +418,15 @@ double CS_GetTelemetryAverageValue(CS_Handle handle, CS_TelemetryKind kind, return cs::GetTelemetryAverageValue(handle, kind, status); } -void CS_SetLogger(CS_LogFunc func, unsigned int min_level) { - cs::SetLogger(func, min_level); +void CS_SetLogger(CS_LogFunc func, void* data, unsigned int min_level) { + cs::SetLogger( + [=](unsigned int level, const char* file, unsigned int line, + const char* msg) { + auto fileStr = wpi::make_string(file); + auto msgStr = wpi::make_string(msg); + func(data, level, &fileStr, line, &msgStr); + }, + min_level); } void CS_SetDefaultLogger(unsigned int min_level) { @@ -494,20 +483,6 @@ void CS_ReleaseEnumeratedSinks(CS_Sink* sinks, int count) { std::free(sinks); } -void CS_FreeString(char* str) { - std::free(str); -} - -void CS_FreeEnumPropertyChoices(char** choices, int count) { - if (!choices) { - return; - } - for (int i = 0; i < count; ++i) { - std::free(choices[i]); - } - std::free(choices); -} - void CS_FreeEnumeratedProperties(CS_Property* properties, int count) { std::free(properties); } @@ -516,50 +491,18 @@ void CS_FreeEnumeratedVideoModes(CS_VideoMode* modes, int count) { std::free(modes); } -char* CS_GetHostname(void) { - return cs::ConvertToC(cs::GetHostname()); +void CS_GetHostname(struct WPI_String* hostname) { + cs::ConvertToC(hostname, cs::GetHostname()); } -char** CS_GetNetworkInterfaces(int* count) { +WPI_String* CS_GetNetworkInterfaces(int* count) { auto interfaces = cs::GetNetworkInterfaces(); - char** out = - static_cast(wpi::safe_malloc(interfaces.size() * sizeof(char*))); + WPI_String* out = WPI_AllocateStringArray(interfaces.size()); *count = interfaces.size(); for (size_t i = 0; i < interfaces.size(); ++i) { - out[i] = cs::ConvertToC(interfaces[i]); + cs::ConvertToC(&out[i], interfaces[i]); } return out; } -void CS_FreeNetworkInterfaces(char** interfaces, int count) { - if (!interfaces) { - return; - } - for (int i = 0; i < count; ++i) { - std::free(interfaces[i]); - } - std::free(interfaces); -} - -void CS_AllocateRawFrameData(CS_RawFrame* frame, int requestedSize) { - if (frame->dataLength >= requestedSize) { - return; - } - if (frame->data) { - frame->data = - static_cast(wpi::safe_realloc(frame->data, requestedSize)); - } else { - frame->data = static_cast(wpi::safe_malloc(requestedSize)); - } - frame->dataLength = requestedSize; -} - -void CS_FreeRawFrameData(CS_RawFrame* frame) { - if (frame->data) { - std::free(frame->data); - frame->data = nullptr; - frame->dataLength = 0; - } -} - } // extern "C" diff --git a/cscore/src/main/native/cpp/jni/CameraServerJNI.cpp b/cscore/src/main/native/cpp/jni/CameraServerJNI.cpp index ddd0ff542dd..6c133762122 100644 --- a/cscore/src/main/native/cpp/jni/CameraServerJNI.cpp +++ b/cscore/src/main/native/cpp/jni/CameraServerJNI.cpp @@ -6,12 +6,12 @@ #include #include -#include + +#define WPI_RAWFRAME_JNI +#include #include #include -#include "cscore_cpp.h" -#include "cscore_cv.h" #include "cscore_raw.h" #include "cscore_runloop.h" #include "edu_wpi_first_cscore_CameraServerJNI.h" @@ -44,7 +44,7 @@ static const JClassInit classes[] = { {"edu/wpi/first/cscore/UsbCameraInfo", &usbCameraInfoCls}, {"edu/wpi/first/cscore/VideoMode", &videoModeCls}, {"edu/wpi/first/cscore/VideoEvent", &videoEventCls}, - {"edu/wpi/first/cscore/raw/RawFrame", &rawFrameCls}}; + {"edu/wpi/first/util/RawFrame", &rawFrameCls}}; static const JExceptionInit exceptions[] = { {"edu/wpi/first/cscore/VideoException", &videoEx}, @@ -80,32 +80,6 @@ static void ListenerOnExit() { jvm->DetachCurrentThread(); } -/// throw java exception -static void ThrowJavaException(JNIEnv* env, const std::exception* e) { - wpi::SmallString<128> what; - jclass je = nullptr; - - if (e) { - const char* exception_type = "std::exception"; - - if (dynamic_cast(e)) { - exception_type = "cv::Exception"; - je = env->FindClass("org/opencv/core/CvException"); - } - - what = exception_type; - what += ": "; - what += e->what(); - } else { - what = "unknown exception"; - } - - if (!je) { - je = exceptionEx; - } - env->ThrowNew(je, what.c_str()); -} - extern "C" { JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { @@ -591,40 +565,15 @@ Java_edu_wpi_first_cscore_CameraServerJNI_createHttpCameraMulti return val; } -/* - * Class: edu_wpi_first_cscore_CameraServerCvJNI - * Method: createCvSource - * Signature: (Ljava/lang/String;IIII)I - */ -JNIEXPORT jint JNICALL -Java_edu_wpi_first_cscore_CameraServerCvJNI_createCvSource - (JNIEnv* env, jclass, jstring name, jint pixelFormat, jint width, jint height, - jint fps) -{ - if (!name) { - nullPointerEx.Throw(env, "name cannot be null"); - return 0; - } - CS_Status status = 0; - auto val = cs::CreateCvSource( - JStringRef{env, name}.str(), - cs::VideoMode{static_cast(pixelFormat), - static_cast(width), static_cast(height), - static_cast(fps)}, - &status); - CheckStatus(env, status); - return val; -} - /* * Class: edu_wpi_first_cscore_CameraServerJNI * Method: createRawSource - * Signature: (Ljava/lang/String;IIII)I + * Signature: (Ljava/lang/String;ZIIII)I */ JNIEXPORT jint JNICALL Java_edu_wpi_first_cscore_CameraServerJNI_createRawSource - (JNIEnv* env, jclass, jstring name, jint pixelFormat, jint width, jint height, - jint fps) + (JNIEnv* env, jclass, jstring name, jboolean isCv, jint pixelFormat, + jint width, jint height, jint fps) { if (!name) { nullPointerEx.Throw(env, "name cannot be null"); @@ -632,7 +581,7 @@ Java_edu_wpi_first_cscore_CameraServerJNI_createRawSource } CS_Status status = 0; auto val = cs::CreateRawSource( - JStringRef{env, name}.str(), + JStringRef{env, name}.str(), isCv, cs::VideoMode{static_cast(pixelFormat), static_cast(width), static_cast(height), static_cast(fps)}, @@ -1201,68 +1150,77 @@ Java_edu_wpi_first_cscore_CameraServerJNI_getHttpCameraUrls } /* - * Class: edu_wpi_first_cscore_CameraServerCvJNI - * Method: putSourceFrame + * Class: edu_wpi_first_cscore_CameraServerJNI + * Method: putRawSourceFrame * Signature: (IJ)V */ JNIEXPORT void JNICALL -Java_edu_wpi_first_cscore_CameraServerCvJNI_putSourceFrame - (JNIEnv* env, jclass, jint source, jlong imageNativeObj) +Java_edu_wpi_first_cscore_CameraServerJNI_putRawSourceFrame + (JNIEnv* env, jclass, jint source, jlong framePtr) { - try { - cv::Mat& image = *((cv::Mat*)imageNativeObj); - CS_Status status = 0; - cs::PutSourceFrame(source, image, &status); - CheckStatus(env, status); - } catch (const std::exception& e) { - ThrowJavaException(env, &e); - } catch (...) { - ThrowJavaException(env, nullptr); + auto* frame = reinterpret_cast(framePtr); + if (!frame) { + nullPointerEx.Throw(env, "frame is null"); + return; } + CS_Status status = 0; + cs::PutSourceFrame(source, *frame, &status); + CheckStatus(env, status); } -// int width, int height, int pixelFormat, int totalData - /* * Class: edu_wpi_first_cscore_CameraServerJNI * Method: putRawSourceFrameBB - * Signature: (ILjava/lang/Object;IIII)V + * Signature: (ILjava/lang/Object;IIIII)V */ JNIEXPORT void JNICALL Java_edu_wpi_first_cscore_CameraServerJNI_putRawSourceFrameBB - (JNIEnv* env, jclass, jint source, jobject byteBuffer, jint width, - jint height, jint pixelFormat, jint totalData) -{ - CS_RawFrame rawFrame; - rawFrame.data = - reinterpret_cast(env->GetDirectBufferAddress(byteBuffer)); - rawFrame.totalData = totalData; - rawFrame.pixelFormat = pixelFormat; - rawFrame.width = width; - rawFrame.height = height; - CS_Status status = 0; - cs::PutSourceFrame(source, rawFrame, &status); + (JNIEnv* env, jclass, jint source, jobject data, jint size, jint width, + jint height, jint stride, jint pixelFormat) +{ + WPI_RawFrame frame; // use WPI_Frame because we don't want the destructor + frame.data = static_cast(env->GetDirectBufferAddress(data)); + if (!frame.data) { + nullPointerEx.Throw(env, "data is null"); + return; + } + frame.freeFunc = nullptr; + frame.freeCbData = nullptr; + frame.size = size; + frame.width = width; + frame.height = height; + frame.stride = stride; + frame.pixelFormat = pixelFormat; + CS_Status status = 0; + cs::PutSourceFrame(source, frame, &status); CheckStatus(env, status); } /* * Class: edu_wpi_first_cscore_CameraServerJNI - * Method: putRawSourceFrame - * Signature: (IJIIII)V + * Method: putRawSourceFrameData + * Signature: (IJIIIII)V */ JNIEXPORT void JNICALL -Java_edu_wpi_first_cscore_CameraServerJNI_putRawSourceFrame - (JNIEnv* env, jclass, jint source, jlong ptr, jint width, jint height, - jint pixelFormat, jint totalData) -{ - CS_RawFrame rawFrame; - rawFrame.data = reinterpret_cast(static_cast(ptr)); - rawFrame.totalData = totalData; - rawFrame.pixelFormat = pixelFormat; - rawFrame.width = width; - rawFrame.height = height; +Java_edu_wpi_first_cscore_CameraServerJNI_putRawSourceFrameData + (JNIEnv* env, jclass, jint source, jlong data, jint size, jint width, + jint height, jint stride, jint pixelFormat) +{ + WPI_RawFrame frame; // use WPI_Frame because we don't want the destructor + frame.data = reinterpret_cast(data); + if (!frame.data) { + nullPointerEx.Throw(env, "data is null"); + return; + } + frame.freeFunc = nullptr; + frame.freeCbData = nullptr; + frame.size = size; + frame.width = width; + frame.height = height; + frame.stride = stride; + frame.pixelFormat = pixelFormat; CS_Status status = 0; - cs::PutSourceFrame(source, rawFrame, &status); + cs::PutSourceFrame(source, frame, &status); CheckStatus(env, status); } @@ -1389,40 +1347,21 @@ Java_edu_wpi_first_cscore_CameraServerJNI_createMjpegServer return val; } -/* - * Class: edu_wpi_first_cscore_CameraServerCvJNI - * Method: createCvSink - * Signature: (Ljava/lang/String;)I - */ -JNIEXPORT jint JNICALL -Java_edu_wpi_first_cscore_CameraServerCvJNI_createCvSink - (JNIEnv* env, jclass, jstring name) -{ - if (!name) { - nullPointerEx.Throw(env, "name cannot be null"); - return 0; - } - CS_Status status = 0; - auto val = cs::CreateCvSink(JStringRef{env, name}.str(), &status); - CheckStatus(env, status); - return val; -} - /* * Class: edu_wpi_first_cscore_CameraServerJNI * Method: createRawSink - * Signature: (Ljava/lang/String;)I + * Signature: (Ljava/lang/String;Z)I */ JNIEXPORT jint JNICALL Java_edu_wpi_first_cscore_CameraServerJNI_createRawSink - (JNIEnv* env, jclass, jstring name) + (JNIEnv* env, jclass, jstring name, jboolean isCv) { if (!name) { nullPointerEx.Throw(env, "name cannot be null"); return 0; } CS_Status status = 0; - auto val = cs::CreateRawSink(JStringRef{env, name}.str(), &status); + auto val = cs::CreateRawSink(JStringRef{env, name}.str(), isCv, &status); CheckStatus(env, status); return val; } @@ -1673,120 +1612,47 @@ Java_edu_wpi_first_cscore_CameraServerJNI_setSinkDescription CheckStatus(env, status); } -/* - * Class: edu_wpi_first_cscore_CameraServerCvJNI - * Method: grabSinkFrame - * Signature: (IJ)J - */ -JNIEXPORT jlong JNICALL -Java_edu_wpi_first_cscore_CameraServerCvJNI_grabSinkFrame - (JNIEnv* env, jclass, jint sink, jlong imageNativeObj) -{ - try { - cv::Mat& image = *((cv::Mat*)imageNativeObj); - CS_Status status = 0; - auto rv = cs::GrabSinkFrame(sink, image, &status); - CheckStatus(env, status); - return rv; - } catch (const std::exception& e) { - ThrowJavaException(env, &e); - return 0; - } catch (...) { - ThrowJavaException(env, nullptr); - return 0; - } -} - -/* - * Class: edu_wpi_first_cscore_CameraServerCvJNI - * Method: grabSinkFrameTimeout - * Signature: (IJD)J - */ -JNIEXPORT jlong JNICALL -Java_edu_wpi_first_cscore_CameraServerCvJNI_grabSinkFrameTimeout - (JNIEnv* env, jclass, jint sink, jlong imageNativeObj, jdouble timeout) -{ - try { - cv::Mat& image = *((cv::Mat*)imageNativeObj); - CS_Status status = 0; - auto rv = cs::GrabSinkFrameTimeout(sink, image, timeout, &status); - CheckStatus(env, status); - return rv; - } catch (const std::exception& e) { - ThrowJavaException(env, &e); - return 0; - } catch (...) { - ThrowJavaException(env, nullptr); - return 0; - } -} - -static void SetRawFrameData(JNIEnv* env, jobject rawFrameObj, - jobject byteBuffer, bool didChangeDataPtr, - const CS_RawFrame& frame) { - static jmethodID setMethod = - env->GetMethodID(rawFrameCls, "setData", "(Ljava/nio/ByteBuffer;JIIII)V"); - jlong framePtr = static_cast(reinterpret_cast(frame.data)); - - if (didChangeDataPtr) { - byteBuffer = env->NewDirectByteBuffer(frame.data, frame.dataLength); - } - - env->CallVoidMethod( - rawFrameObj, setMethod, byteBuffer, framePtr, - static_cast(frame.totalData), static_cast(frame.width), - static_cast(frame.height), static_cast(frame.pixelFormat)); -} - /* * Class: edu_wpi_first_cscore_CameraServerJNI - * Method: grabRawSinkFrameImpl - * Signature: (ILjava/lang/Object;JLjava/lang/Object;III)J + * Method: grabRawSinkFrame + * Signature: (ILjava/lang/Object;J)J */ JNIEXPORT jlong JNICALL -Java_edu_wpi_first_cscore_CameraServerJNI_grabRawSinkFrameImpl - (JNIEnv* env, jclass, jint sink, jobject rawFrameObj, jlong rawFramePtr, - jobject byteBuffer, jint width, jint height, jint pixelFormat) -{ - CS_RawFrame* ptr = - reinterpret_cast(static_cast(rawFramePtr)); - auto origDataPtr = ptr->data; - ptr->width = width; - ptr->height = height; - ptr->pixelFormat = pixelFormat; - CS_Status status = 0; - auto rv = cs::GrabSinkFrame(static_cast(sink), *ptr, &status); +Java_edu_wpi_first_cscore_CameraServerJNI_grabRawSinkFrame + (JNIEnv* env, jclass, jint sink, jobject frameObj, jlong framePtr) +{ + auto* frame = reinterpret_cast(framePtr); + auto origData = frame->data; + CS_Status status = 0; + auto rv = cs::GrabSinkFrame(static_cast(sink), *frame, &status); if (!CheckStatus(env, status)) { return 0; } - SetRawFrameData(env, rawFrameObj, byteBuffer, origDataPtr != ptr->data, *ptr); + wpi::SetFrameData(env, rawFrameCls, frameObj, *frame, + origData != frame->data); return rv; } /* * Class: edu_wpi_first_cscore_CameraServerJNI - * Method: grabRawSinkFrameTimeoutImpl - * Signature: (ILjava/lang/Object;JLjava/lang/Object;IIID)J + * Method: grabRawSinkFrameTimeout + * Signature: (ILjava/lang/Object;JD)J */ JNIEXPORT jlong JNICALL -Java_edu_wpi_first_cscore_CameraServerJNI_grabRawSinkFrameTimeoutImpl - (JNIEnv* env, jclass, jint sink, jobject rawFrameObj, jlong rawFramePtr, - jobject byteBuffer, jint width, jint height, jint pixelFormat, +Java_edu_wpi_first_cscore_CameraServerJNI_grabRawSinkFrameTimeout + (JNIEnv* env, jclass, jint sink, jobject frameObj, jlong framePtr, jdouble timeout) { - CS_RawFrame* ptr = - reinterpret_cast(static_cast(rawFramePtr)); - auto origDataPtr = ptr->data; - ptr->width = width; - ptr->height = height; - ptr->pixelFormat = pixelFormat; + auto* frame = reinterpret_cast(framePtr); + auto origData = frame->data; CS_Status status = 0; - auto rv = cs::GrabSinkFrameTimeout(static_cast(sink), *ptr, timeout, - &status); + auto rv = cs::GrabSinkFrameTimeout(static_cast(sink), *frame, + timeout, &status); if (!CheckStatus(env, status)) { return 0; } - SetRawFrameData(env, rawFrameObj, byteBuffer, origDataPtr != ptr->data, *ptr); + wpi::SetFrameData(env, rawFrameCls, frameObj, *frame, + origData != frame->data); return rv; } @@ -2199,34 +2065,6 @@ Java_edu_wpi_first_cscore_CameraServerJNI_setLogger minLevel); } -/* - * Class: edu_wpi_first_cscore_CameraServerJNI - * Method: allocateRawFrame - * Signature: ()J - */ -JNIEXPORT jlong JNICALL -Java_edu_wpi_first_cscore_CameraServerJNI_allocateRawFrame - (JNIEnv*, jclass) -{ - cs::RawFrame* rawFrame = new cs::RawFrame{}; - intptr_t rawFrameIntPtr = reinterpret_cast(rawFrame); - return static_cast(rawFrameIntPtr); -} - -/* - * Class: edu_wpi_first_cscore_CameraServerJNI - * Method: freeRawFrame - * Signature: (J)V - */ -JNIEXPORT void JNICALL -Java_edu_wpi_first_cscore_CameraServerJNI_freeRawFrame - (JNIEnv*, jclass, jlong rawFrame) -{ - cs::RawFrame* ptr = - reinterpret_cast(static_cast(rawFrame)); - delete ptr; -} - /* * Class: edu_wpi_first_cscore_CameraServerJNI * Method: runMainRunLoop diff --git a/cscore/src/main/native/include/cscore_c.h b/cscore/src/main/native/include/cscore_c.h index 3d30a0e7ec7..60e66bf209c 100644 --- a/cscore/src/main/native/include/cscore_c.h +++ b/cscore/src/main/native/include/cscore_c.h @@ -7,6 +7,9 @@ #include +#include +#include + #ifdef __cplusplus #include #else @@ -84,20 +87,6 @@ enum CS_LogLevel { CS_LOG_DEBUG4 = 6 }; -/** - * Pixel formats - */ -enum CS_PixelFormat { - CS_PIXFMT_UNKNOWN = 0, - CS_PIXFMT_MJPEG, - CS_PIXFMT_YUYV, - CS_PIXFMT_RGB565, - CS_PIXFMT_BGR, - CS_PIXFMT_GRAY, - CS_PIXFMT_Y16, - CS_PIXFMT_UYVY -}; - /** * Video mode */ @@ -216,7 +205,7 @@ struct CS_Event { CS_Sink sink; // Source/sink/property name - const char* name; + struct WPI_String name; // Fields for CS_SOURCE_VIDEOMODE_CHANGED event CS_VideoMode mode; @@ -225,7 +214,7 @@ struct CS_Event { CS_Property property; enum CS_PropertyKind propertyKind; int value; - const char* valueStr; + struct WPI_String valueStr; // Listener that was triggered CS_Listener listener; @@ -236,10 +225,10 @@ struct CS_Event { */ typedef struct CS_UsbCameraInfo { int dev; - char* path; - char* name; + struct WPI_String path; + struct WPI_String name; int otherPathsCount; - char** otherPaths; + struct WPI_String* otherPaths; int vendorId; int productId; } CS_UsbCameraInfo; @@ -250,34 +239,40 @@ typedef struct CS_UsbCameraInfo { */ enum CS_PropertyKind CS_GetPropertyKind(CS_Property property, CS_Status* status); -char* CS_GetPropertyName(CS_Property property, CS_Status* status); +void CS_GetPropertyName(CS_Property property, struct WPI_String* name, + CS_Status* status); int CS_GetProperty(CS_Property property, CS_Status* status); void CS_SetProperty(CS_Property property, int value, CS_Status* status); int CS_GetPropertyMin(CS_Property property, CS_Status* status); int CS_GetPropertyMax(CS_Property property, CS_Status* status); int CS_GetPropertyStep(CS_Property property, CS_Status* status); int CS_GetPropertyDefault(CS_Property property, CS_Status* status); -char* CS_GetStringProperty(CS_Property property, CS_Status* status); -void CS_SetStringProperty(CS_Property property, const char* value, +void CS_GetStringProperty(CS_Property property, struct WPI_String* value, CS_Status* status); -char** CS_GetEnumPropertyChoices(CS_Property property, int* count, - CS_Status* status); +void CS_SetStringProperty(CS_Property property, const struct WPI_String* value, + CS_Status* status); +struct WPI_String* CS_GetEnumPropertyChoices(CS_Property property, int* count, + CS_Status* status); /** @} */ /** * @defgroup cscore_source_create_cfunc Source Creation Functions * @{ */ -CS_Source CS_CreateUsbCameraDev(const char* name, int dev, CS_Status* status); -CS_Source CS_CreateUsbCameraPath(const char* name, const char* path, +CS_Source CS_CreateUsbCameraDev(const struct WPI_String* name, int dev, + CS_Status* status); +CS_Source CS_CreateUsbCameraPath(const struct WPI_String* name, + const struct WPI_String* path, CS_Status* status); -CS_Source CS_CreateHttpCamera(const char* name, const char* url, +CS_Source CS_CreateHttpCamera(const struct WPI_String* name, + const struct WPI_String* url, enum CS_HttpCameraKind kind, CS_Status* status); -CS_Source CS_CreateHttpCameraMulti(const char* name, const char** urls, - int count, enum CS_HttpCameraKind kind, +CS_Source CS_CreateHttpCameraMulti(const struct WPI_String* name, + const struct WPI_String* urls, int count, + enum CS_HttpCameraKind kind, CS_Status* status); -CS_Source CS_CreateCvSource(const char* name, const CS_VideoMode* mode, - CS_Status* status); +CS_Source CS_CreateCvSource(const struct WPI_String* name, + const CS_VideoMode* mode, CS_Status* status); /** @} */ /** @@ -285,15 +280,18 @@ CS_Source CS_CreateCvSource(const char* name, const CS_VideoMode* mode, * @{ */ enum CS_SourceKind CS_GetSourceKind(CS_Source source, CS_Status* status); -char* CS_GetSourceName(CS_Source source, CS_Status* status); -char* CS_GetSourceDescription(CS_Source source, CS_Status* status); +void CS_GetSourceName(CS_Source source, struct WPI_String* name, + CS_Status* status); +void CS_GetSourceDescription(CS_Source source, struct WPI_String* description, + CS_Status* status); uint64_t CS_GetSourceLastFrameTime(CS_Source source, CS_Status* status); void CS_SetSourceConnectionStrategy(CS_Source source, enum CS_ConnectionStrategy strategy, CS_Status* status); CS_Bool CS_IsSourceConnected(CS_Source source, CS_Status* status); CS_Bool CS_IsSourceEnabled(CS_Source source, CS_Status* status); -CS_Property CS_GetSourceProperty(CS_Source source, const char* name, +CS_Property CS_GetSourceProperty(CS_Source source, + const struct WPI_String* name, CS_Status* status); CS_Property* CS_EnumerateSourceProperties(CS_Source source, int* count, CS_Status* status); @@ -302,18 +300,20 @@ void CS_GetSourceVideoMode(CS_Source source, CS_VideoMode* mode, CS_Bool CS_SetSourceVideoMode(CS_Source source, const CS_VideoMode* mode, CS_Status* status); CS_Bool CS_SetSourceVideoModeDiscrete(CS_Source source, - enum CS_PixelFormat pixelFormat, + enum WPI_PixelFormat pixelFormat, int width, int height, int fps, CS_Status* status); CS_Bool CS_SetSourcePixelFormat(CS_Source source, - enum CS_PixelFormat pixelFormat, + enum WPI_PixelFormat pixelFormat, CS_Status* status); CS_Bool CS_SetSourceResolution(CS_Source source, int width, int height, CS_Status* status); CS_Bool CS_SetSourceFPS(CS_Source source, int fps, CS_Status* status); -CS_Bool CS_SetSourceConfigJson(CS_Source source, const char* config, +CS_Bool CS_SetSourceConfigJson(CS_Source source, + const struct WPI_String* config, CS_Status* status); -char* CS_GetSourceConfigJson(CS_Source source, CS_Status* status); +void CS_GetSourceConfigJson(CS_Source source, struct WPI_String* config, + CS_Status* status); CS_VideoMode* CS_EnumerateSourceVideoModes(CS_Source source, int* count, CS_Status* status); CS_Sink* CS_EnumerateSourceSinks(CS_Source source, int* count, @@ -342,9 +342,12 @@ void CS_SetCameraExposureManual(CS_Source source, int value, CS_Status* status); * @defgroup cscore_usbcamera_cfunc UsbCamera Source Functions * @{ */ -void CS_SetUsbCameraPath(CS_Source source, const char* path, CS_Status* status); -char* CS_GetUsbCameraPath(CS_Source source, CS_Status* status); -CS_UsbCameraInfo* CS_GetUsbCameraInfo(CS_Source source, CS_Status* status); +void CS_SetUsbCameraPath(CS_Source source, const struct WPI_String* path, + CS_Status* status); +void CS_GetUsbCameraPath(CS_Source source, struct WPI_String* path, + CS_Status* status); +void CS_GetUsbCameraInfo(CS_Source source, CS_UsbCameraInfo* info, + CS_Status* status); /** @} */ /** @@ -353,37 +356,44 @@ CS_UsbCameraInfo* CS_GetUsbCameraInfo(CS_Source source, CS_Status* status); */ enum CS_HttpCameraKind CS_GetHttpCameraKind(CS_Source source, CS_Status* status); -void CS_SetHttpCameraUrls(CS_Source source, const char** urls, int count, - CS_Status* status); -char** CS_GetHttpCameraUrls(CS_Source source, int* count, CS_Status* status); +void CS_SetHttpCameraUrls(CS_Source source, const struct WPI_String* urls, + int count, CS_Status* status); +struct WPI_String* CS_GetHttpCameraUrls(CS_Source source, int* count, + CS_Status* status); /** @} */ /** - * @defgroup cscore_opencv_source_cfunc OpenCV Source Functions + * @defgroup cscore_frame_source_cfunc Frame Source Functions * @{ */ -void CS_NotifySourceError(CS_Source source, const char* msg, CS_Status* status); +void CS_NotifySourceError(CS_Source source, const struct WPI_String* msg, + CS_Status* status); void CS_SetSourceConnected(CS_Source source, CS_Bool connected, CS_Status* status); -void CS_SetSourceDescription(CS_Source source, const char* description, +void CS_SetSourceDescription(CS_Source source, + const struct WPI_String* description, CS_Status* status); -CS_Property CS_CreateSourceProperty(CS_Source source, const char* name, +CS_Property CS_CreateSourceProperty(CS_Source source, + const struct WPI_String* name, enum CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value, CS_Status* status); void CS_SetSourceEnumPropertyChoices(CS_Source source, CS_Property property, - const char** choices, int count, - CS_Status* status); + const struct WPI_String* choices, + int count, CS_Status* status); /** @} */ /** * @defgroup cscore_sink_create_cfunc Sink Creation Functions * @{ */ -CS_Sink CS_CreateMjpegServer(const char* name, const char* listenAddress, - int port, CS_Status* status); -CS_Sink CS_CreateCvSink(const char* name, CS_Status* status); -CS_Sink CS_CreateCvSinkCallback(const char* name, void* data, +CS_Sink CS_CreateMjpegServer(const struct WPI_String* name, + const struct WPI_String* listenAddress, int port, + CS_Status* status); +CS_Sink CS_CreateCvSink(const struct WPI_String* name, + enum WPI_PixelFormat pixelFormat, CS_Status* status); +CS_Sink CS_CreateCvSinkCallback(const struct WPI_String* name, + enum WPI_PixelFormat pixelFormat, void* data, void (*processFrame)(void* data, uint64_t time), CS_Status* status); /** @} */ @@ -393,18 +403,21 @@ CS_Sink CS_CreateCvSinkCallback(const char* name, void* data, * @{ */ enum CS_SinkKind CS_GetSinkKind(CS_Sink sink, CS_Status* status); -char* CS_GetSinkName(CS_Sink sink, CS_Status* status); -char* CS_GetSinkDescription(CS_Sink sink, CS_Status* status); -CS_Property CS_GetSinkProperty(CS_Sink sink, const char* name, +void CS_GetSinkName(CS_Sink sink, struct WPI_String* name, CS_Status* status); +void CS_GetSinkDescription(CS_Sink sink, struct WPI_String* description, + CS_Status* status); +CS_Property CS_GetSinkProperty(CS_Sink sink, const struct WPI_String* name, CS_Status* status); CS_Property* CS_EnumerateSinkProperties(CS_Sink sink, int* count, CS_Status* status); void CS_SetSinkSource(CS_Sink sink, CS_Source source, CS_Status* status); -CS_Property CS_GetSinkSourceProperty(CS_Sink sink, const char* name, +CS_Property CS_GetSinkSourceProperty(CS_Sink sink, + const struct WPI_String* name, CS_Status* status); -CS_Bool CS_SetSinkConfigJson(CS_Sink sink, const char* config, +CS_Bool CS_SetSinkConfigJson(CS_Sink sink, const struct WPI_String* config, CS_Status* status); -char* CS_GetSinkConfigJson(CS_Sink sink, CS_Status* status); +void CS_GetSinkConfigJson(CS_Sink sink, struct WPI_String* config, + CS_Status* status); CS_Source CS_GetSinkSource(CS_Sink sink, CS_Status* status); CS_Sink CS_CopySink(CS_Sink sink, CS_Status* status); void CS_ReleaseSink(CS_Sink sink, CS_Status* status); @@ -414,17 +427,19 @@ void CS_ReleaseSink(CS_Sink sink, CS_Status* status); * @defgroup cscore_mjpegserver_cfunc MjpegServer Sink Functions * @{ */ -char* CS_GetMjpegServerListenAddress(CS_Sink sink, CS_Status* status); +void CS_GetMjpegServerListenAddress(CS_Sink sink, + struct WPI_String* listenAddress, + CS_Status* status); int CS_GetMjpegServerPort(CS_Sink sink, CS_Status* status); /** @} */ /** - * @defgroup cscore_opencv_sink_cfunc OpenCV Sink Functions + * @defgroup cscore_frame_sink_cfunc Frame Sink Functions * @{ */ -void CS_SetSinkDescription(CS_Sink sink, const char* description, +void CS_SetSinkDescription(CS_Sink sink, const struct WPI_String* description, CS_Status* status); -char* CS_GetSinkError(CS_Sink sink, CS_Status* status); +void CS_GetSinkError(CS_Sink sink, struct WPI_String* error, CS_Status* status); void CS_SetSinkEnabled(CS_Sink sink, CS_Bool enabled, CS_Status* status); /** @} */ @@ -469,9 +484,10 @@ double CS_GetTelemetryAverageValue(CS_Handle handle, enum CS_TelemetryKind kind, * @defgroup cscore_logging_cfunc Logging Functions * @{ */ -typedef void (*CS_LogFunc)(unsigned int level, const char* file, - unsigned int line, const char* msg); -void CS_SetLogger(CS_LogFunc func, unsigned int min_level); +typedef void (*CS_LogFunc)(void* data, unsigned int level, + const struct WPI_String* file, unsigned int line, + const struct WPI_String* msg); +void CS_SetLogger(CS_LogFunc func, void* data, unsigned int min_level); void CS_SetDefaultLogger(unsigned int min_level); /** @} */ @@ -496,18 +512,14 @@ void CS_ReleaseEnumeratedSources(CS_Source* sources, int count); CS_Sink* CS_EnumerateSinks(int* count, CS_Status* status); void CS_ReleaseEnumeratedSinks(CS_Sink* sinks, int count); -void CS_FreeString(char* str); -void CS_FreeEnumPropertyChoices(char** choices, int count); void CS_FreeUsbCameraInfo(CS_UsbCameraInfo* info); -void CS_FreeHttpCameraUrls(char** urls, int count); void CS_FreeEnumeratedProperties(CS_Property* properties, int count); void CS_FreeEnumeratedVideoModes(CS_VideoMode* modes, int count); -char* CS_GetHostname(void); +void CS_GetHostname(struct WPI_String* hostName); -char** CS_GetNetworkInterfaces(int* count); -void CS_FreeNetworkInterfaces(char** interfaces, int count); +struct WPI_String* CS_GetNetworkInterfaces(int* count); /** @} */ /** @} */ diff --git a/cscore/src/main/native/include/cscore_cpp.h b/cscore/src/main/native/include/cscore_cpp.h index 72c37f8b070..b57faee0ffe 100644 --- a/cscore/src/main/native/include/cscore_cpp.h +++ b/cscore/src/main/native/include/cscore_cpp.h @@ -13,6 +13,7 @@ #include #include +#include #include #include @@ -60,14 +61,15 @@ struct UsbCameraInfo { */ struct VideoMode : public CS_VideoMode { enum PixelFormat { - kUnknown = CS_PIXFMT_UNKNOWN, - kMJPEG = CS_PIXFMT_MJPEG, - kYUYV = CS_PIXFMT_YUYV, - kRGB565 = CS_PIXFMT_RGB565, - kBGR = CS_PIXFMT_BGR, - kGray = CS_PIXFMT_GRAY, - kY16 = CS_PIXFMT_Y16, - kUYVY = CS_PIXFMT_UYVY + kUnknown = WPI_PIXFMT_UNKNOWN, + kMJPEG = WPI_PIXFMT_MJPEG, + kYUYV = WPI_PIXFMT_YUYV, + kRGB565 = WPI_PIXFMT_RGB565, + kBGR = WPI_PIXFMT_BGR, + kGray = WPI_PIXFMT_GRAY, + kY16 = WPI_PIXFMT_Y16, + kUYVY = WPI_PIXFMT_UYVY, + kBGRA = WPI_PIXFMT_BGRA, }; VideoMode() { pixelFormat = 0; @@ -293,7 +295,7 @@ std::vector GetHttpCameraUrls(CS_Source source, CS_Status* status); /** @} */ /** - * @defgroup cscore_opencv_source_func OpenCV Source Functions + * @defgroup cscore_frame_source_func Frame Source Functions * @{ */ void NotifySourceError(CS_Source source, std::string_view msg, @@ -316,8 +318,10 @@ void SetSourceEnumPropertyChoices(CS_Source source, CS_Property property, */ CS_Sink CreateMjpegServer(std::string_view name, std::string_view listenAddress, int port, CS_Status* status); -CS_Sink CreateCvSink(std::string_view name, CS_Status* status); +CS_Sink CreateCvSink(std::string_view name, VideoMode::PixelFormat pixelFormat, + CS_Status* status); CS_Sink CreateCvSinkCallback(std::string_view name, + VideoMode::PixelFormat pixelFormat, std::function processFrame, CS_Status* status); @@ -362,7 +366,7 @@ int GetMjpegServerPort(CS_Sink sink, CS_Status* status); /** @} */ /** - * @defgroup cscore_opencv_sink_func OpenCV Sink Functions + * @defgroup cscore_frame_sink_func Frame Sink Functions * @{ */ void SetSinkDescription(CS_Sink sink, std::string_view description, diff --git a/cscore/src/main/native/include/cscore_cv.h b/cscore/src/main/native/include/cscore_cv.h index 66cb23e3858..aec10d4a55c 100644 --- a/cscore/src/main/native/include/cscore_cv.h +++ b/cscore/src/main/native/include/cscore_cv.h @@ -7,72 +7,17 @@ #include -#include "cscore_c.h" - -#ifdef CSCORE_CSCORE_RAW_CV_H_ -#error "Cannot include both cscore_cv.h and cscore_raw_cv.h in the same file" -#endif - -#ifdef __cplusplus -#include "cscore_oo.h" // NOLINT(build/include_order) - -#endif - -#if CV_VERSION_MAJOR < 4 - -#ifdef __cplusplus -extern "C" { // NOLINT(build/include_order) -#endif - -struct CvMat; - -void CS_PutSourceFrame(CS_Source source, struct CvMat* image, - CS_Status* status); - -uint64_t CS_GrabSinkFrame(CS_Sink sink, struct CvMat* image, CS_Status* status); -uint64_t CS_GrabSinkFrameTimeout(CS_Sink sink, struct CvMat* image, - double timeout, CS_Status* status); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // CV_VERSION_MAJOR < 4 - -#ifdef __cplusplus +#include #include "cscore_oo.h" - -namespace cv { -class Mat; -} // namespace cv +#include "cscore_raw.h" namespace cs { - -/** - * @defgroup cscore_cpp_opencv_special cscore C functions taking a cv::Mat* - * - * These are needed for specific interop implementations. - * @{ - */ -extern "C" { -uint64_t CS_GrabSinkFrameCpp(CS_Sink sink, cv::Mat* image, CS_Status* status); -uint64_t CS_GrabSinkFrameTimeoutCpp(CS_Sink sink, cv::Mat* image, - double timeout, CS_Status* status); -void CS_PutSourceFrameCpp(CS_Source source, cv::Mat* image, CS_Status* status); -} // extern "C" -/** @} */ - -void PutSourceFrame(CS_Source source, cv::Mat& image, CS_Status* status); -uint64_t GrabSinkFrame(CS_Sink sink, cv::Mat& image, CS_Status* status); -uint64_t GrabSinkFrameTimeout(CS_Sink sink, cv::Mat& image, double timeout, - CS_Status* status); - /** * A source for user code to provide OpenCV images as video frames. - * These sources require the WPILib OpenCV builds. - * For an alternate OpenCV, include "cscore_raw_cv.h" instead, and - * include your Mat header before that header. + * + * This is not dependent on any opencv binary ABI, and can be used + * with versions of most versions of OpenCV. */ class CvSource : public ImageSource { public: @@ -87,7 +32,7 @@ class CvSource : public ImageSource { CvSource(std::string_view name, const VideoMode& mode); /** - * Create an OpenCV source. + * Create an OpenCV source. * * @param name Source name (arbitrary unique identifier) * @param pixelFormat Pixel format @@ -99,26 +44,48 @@ class CvSource : public ImageSource { int height, int fps); /** - * Put an OpenCV image and notify sinks. + * Put an OpenCV image and notify sinks * - *

Only 8-bit single-channel or 3-channel (with BGR channel order) images - * are supported. If the format, depth or channel order is different, use - * cv::Mat::convertTo() and/or cv::cvtColor() to convert it first. + *

+ * The image format is guessed from the number of channels. The channel + * mapping is as follows. 1: kGray 2: kYUYV 3: BGR 4: BGRA Any other channel + * numbers will throw an error. If your image is an in alternate format, use + * the overload that takes a PixelFormat. * - * @param image OpenCV image + * @param image OpenCV Image */ void PutFrame(cv::Mat& image); + + /** + * Put an OpenCV image and notify sinks. + * + *

+ * The format of the Mat must match the PixelFormat. You will corrupt memory + * if they dont. With skipVerification false, we will verify the number of + * channels matches the pixel format. If skipVerification is true, this step + * is skipped and is passed straight through. + * + * @param image OpenCV image + * @param pixelFormat The pixel format of the image + * @param skipVerification skip verifying pixel format + */ + void PutFrame(cv::Mat& image, VideoMode::PixelFormat pixelFormat, + bool skipVerification); + + private: + static bool VerifyFormat(cv::Mat& image, VideoMode::PixelFormat pixelFormat); }; /** - * A sink for user code to accept video frames as OpenCV images. - * These sinks require the WPILib OpenCV builds. - * For an alternate OpenCV, include "cscore_raw_cv.h" instead, and - * include your Mat header before that header. + * A source for user code to accept video frames as OpenCV images. + * + * This is not dependent on any opencv binary ABI, and can be used + * with versions of most versions of OpenCV. */ class CvSink : public ImageSink { public: CvSink() = default; + CvSink(const CvSink& sink); /** * Create a sink for accepting OpenCV images. @@ -127,84 +94,277 @@ class CvSink : public ImageSink { * image. * * @param name Source name (arbitrary unique identifier) + * @param pixelFormat The pixel format to read */ - explicit CvSink(std::string_view name); + explicit CvSink(std::string_view name, VideoMode::PixelFormat pixelFormat = + VideoMode::PixelFormat::kBGR); /** - * Create a sink for accepting OpenCV images in a separate thread. + * Wait for the next frame and get the image. + * Times out (returning 0) after timeout seconds. + * The provided image will have the pixelFormat this class was constructed + * with. * - *

A thread will be created that calls WaitForFrame() and calls the - * processFrame() callback each time a new frame arrives. + * @return Frame time, or 0 on error (call GetError() to obtain the error + * message); the frame time is in the same time base as wpi::Now(), + * and is in 1 us increments. + */ + [[nodiscard]] + uint64_t GrabFrame(cv::Mat& image, double timeout = 0.225); + + /** + * Wait for the next frame and get the image. May block forever. + * The provided image will have the pixelFormat this class was constructed + * with. * - * @param name Source name (arbitrary unique identifier) - * @param processFrame Frame processing function; will be called with a - * time=0 if an error occurred. processFrame should call GetImage() - * or GetError() as needed, but should not call (except in very - * unusual circumstances) WaitForImage(). + * @return Frame time, or 0 on error (call GetError() to obtain the error + * message); the frame time is in the same time base as wpi::Now(), + * and is in 1 us increments. */ - CvSink(std::string_view name, - std::function processFrame); + [[nodiscard]] + uint64_t GrabFrameNoTimeout(cv::Mat& image); /** * Wait for the next frame and get the image. * Times out (returning 0) after timeout seconds. - * The provided image will have three 8-bit channels stored in BGR order. + * The provided image will have the pixelFormat this class was constructed + * with. The data is backed by data in the CvSink. It will be invalidated by + * any grabFrame*() call on the sink. * * @return Frame time, or 0 on error (call GetError() to obtain the error * message); the frame time is in the same time base as wpi::Now(), * and is in 1 us increments. */ [[nodiscard]] - uint64_t GrabFrame(cv::Mat& image, double timeout = 0.225) const; + uint64_t GrabFrameDirect(cv::Mat& image, double timeout = 0.225); /** * Wait for the next frame and get the image. May block forever. - * The provided image will have three 8-bit channels stored in BGR order. + * The provided image will have the pixelFormat this class was constructed + * with. The data is backed by data in the CvSink. It will be invalidated by + * any grabFrame*() call on the sink. * * @return Frame time, or 0 on error (call GetError() to obtain the error * message); the frame time is in the same time base as wpi::Now(), * and is in 1 us increments. */ [[nodiscard]] - uint64_t GrabFrameNoTimeout(cv::Mat& image) const; + uint64_t GrabFrameNoTimeoutDirect(cv::Mat& image); + + private: + constexpr int GetCvFormat(WPI_PixelFormat pixelFormat); + + wpi::RawFrame rawFrame; + VideoMode::PixelFormat pixelFormat; }; inline CvSource::CvSource(std::string_view name, const VideoMode& mode) { - m_handle = CreateCvSource(name, mode, &m_status); + m_handle = CreateRawSource(name, true, mode, &m_status); } inline CvSource::CvSource(std::string_view name, VideoMode::PixelFormat format, int width, int height, int fps) { - m_handle = - CreateCvSource(name, VideoMode{format, width, height, fps}, &m_status); + m_handle = CreateRawSource(name, true, VideoMode{format, width, height, fps}, + &m_status); +} + +inline bool CvSource::VerifyFormat(cv::Mat& image, + VideoMode::PixelFormat pixelFormat) { + int channels = image.channels(); + switch (pixelFormat) { + case VideoMode::PixelFormat::kBGR: + if (channels == 3) { + return true; + } + break; + case VideoMode::PixelFormat::kBGRA: + if (channels == 4) { + return true; + } + break; + case VideoMode::PixelFormat::kGray: + if (channels == 1) { + return true; + } + break; + case VideoMode::PixelFormat::kRGB565: + if (channels == 2) { + return true; + } + break; + case VideoMode::PixelFormat::kUYVY: + if (channels == 2) { + return true; + } + break; + case VideoMode::PixelFormat::kY16: + if (channels == 2) { + return true; + } + break; + case VideoMode::PixelFormat::kYUYV: + if (channels == 2) { + return true; + } + break; + case VideoMode::PixelFormat::kMJPEG: + if (channels == 1) { + return true; + } + break; + default: + break; + } + return false; } inline void CvSource::PutFrame(cv::Mat& image) { - m_status = 0; - PutSourceFrame(m_handle, image, &m_status); + // We only support 8-bit images; convert if necessary. + cv::Mat finalImage; + if (image.depth() == CV_8U) { + finalImage = image; + } else { + image.convertTo(finalImage, CV_8U); + } + + int channels = finalImage.channels(); + VideoMode::PixelFormat format; + if (channels == 1) { + // 1 channel is assumed Graysacle + format = VideoMode::PixelFormat::kGray; + } else if (channels == 2) { + // 2 channels is assumed YUYV + format = VideoMode::PixelFormat::kYUYV; + } else if (channels == 3) { + // 3 channels is assumed BGR + format = VideoMode::PixelFormat::kBGR; + } else if (channels == 4) { + // 4 channels is assumed BGRA + format = VideoMode::PixelFormat::kBGRA; + } else { + // TODO Error + return; + } + + PutFrame(finalImage, format, true); } -inline CvSink::CvSink(std::string_view name) { - m_handle = CreateCvSink(name, &m_status); +inline void CvSource::PutFrame(cv::Mat& image, + VideoMode::PixelFormat pixelFormat, + bool skipVerification) { + // We only support 8-bit images; convert if necessary. + cv::Mat finalImage; + if (image.depth() == CV_8U) { + finalImage = image; + } else { + image.convertTo(finalImage, CV_8U); + } + + if (!skipVerification) { + if (!VerifyFormat(finalImage, pixelFormat)) { + // TODO Error + return; + } + } + + WPI_RawFrame frame; // use WPI_Frame because we don't want the destructor + frame.data = finalImage.data; + frame.freeFunc = nullptr; + frame.freeCbData = nullptr; + frame.size = finalImage.total() * finalImage.channels(); + frame.width = finalImage.cols; + frame.height = finalImage.rows; + frame.stride = finalImage.step; + frame.pixelFormat = pixelFormat; + m_status = 0; + PutSourceFrame(m_handle, frame, &m_status); } inline CvSink::CvSink(std::string_view name, - std::function processFrame) { - m_handle = CreateCvSinkCallback(name, processFrame, &m_status); + VideoMode::PixelFormat pixelFormat) { + m_handle = CreateRawSink(name, true, &m_status); + this->pixelFormat = pixelFormat; } -inline uint64_t CvSink::GrabFrame(cv::Mat& image, double timeout) const { - m_status = 0; - return GrabSinkFrameTimeout(m_handle, image, timeout, &m_status); +inline CvSink::CvSink(const CvSink& sink) + : ImageSink{sink}, pixelFormat{sink.pixelFormat} {} + +inline uint64_t CvSink::GrabFrame(cv::Mat& image, double timeout) { + cv::Mat tmpnam; + auto retVal = GrabFrameDirect(tmpnam); + if (retVal <= 0) { + return retVal; + } + tmpnam.copyTo(image); + return retVal; } -inline uint64_t CvSink::GrabFrameNoTimeout(cv::Mat& image) const { - m_status = 0; - return GrabSinkFrame(m_handle, image, &m_status); +inline uint64_t CvSink::GrabFrameNoTimeout(cv::Mat& image) { + cv::Mat tmpnam; + auto retVal = GrabFrameNoTimeoutDirect(tmpnam); + if (retVal <= 0) { + return retVal; + } + tmpnam.copyTo(image); + return retVal; } -} // namespace cs +inline constexpr int CvSink::GetCvFormat(WPI_PixelFormat pixelFormat) { + int type = 0; + switch (pixelFormat) { + case WPI_PIXFMT_YUYV: + case WPI_PIXFMT_RGB565: + case WPI_PIXFMT_Y16: + case WPI_PIXFMT_UYVY: + type = CV_8UC2; + break; + case WPI_PIXFMT_BGR: + type = CV_8UC3; + break; + case WPI_PIXFMT_BGRA: + type = CV_8UC4; + break; + case WPI_PIXFMT_GRAY: + case WPI_PIXFMT_MJPEG: + default: + type = CV_8UC1; + break; + } + return type; +} + +inline uint64_t CvSink::GrabFrameDirect(cv::Mat& image, double timeout) { + rawFrame.height = 0; + rawFrame.width = 0; + rawFrame.stride = 0; + rawFrame.pixelFormat = pixelFormat; + auto timestamp = GrabSinkFrameTimeout(m_handle, rawFrame, timeout, &m_status); + if (m_status != CS_OK) { + return 0; + } + image = + cv::Mat{rawFrame.height, rawFrame.width, + GetCvFormat(static_cast(rawFrame.pixelFormat)), + rawFrame.data, static_cast(rawFrame.stride)}; + return timestamp; +} -#endif +inline uint64_t CvSink::GrabFrameNoTimeoutDirect(cv::Mat& image) { + rawFrame.height = 0; + rawFrame.width = 0; + rawFrame.stride = 0; + rawFrame.pixelFormat = pixelFormat; + auto timestamp = GrabSinkFrame(m_handle, rawFrame, &m_status); + if (m_status != CS_OK) { + return 0; + } + image = + cv::Mat{rawFrame.height, rawFrame.width, + GetCvFormat(static_cast(rawFrame.pixelFormat)), + rawFrame.data, static_cast(rawFrame.stride)}; + return timestamp; +} + +} // namespace cs #endif // CSCORE_CSCORE_CV_H_ diff --git a/cscore/src/main/native/include/cscore_oo.h b/cscore/src/main/native/include/cscore_oo.h index f13a6fd9772..950fa688eee 100644 --- a/cscore/src/main/native/include/cscore_oo.h +++ b/cscore/src/main/native/include/cscore_oo.h @@ -44,42 +44,153 @@ class VideoProperty { public: enum Kind { + /// No specific property. kNone = CS_PROP_NONE, + /// Boolean property. kBoolean = CS_PROP_BOOLEAN, + /// Integer property. kInteger = CS_PROP_INTEGER, + /// String property. kString = CS_PROP_STRING, + /// Enum property. kEnum = CS_PROP_ENUM }; VideoProperty() = default; + /** + * Returns property name. + * + * @return Property name. + */ std::string GetName() const; + /** + * Returns property kind. + * + * @return Property kind. + */ Kind GetKind() const { return m_kind; } + /** + * Returns true if property is valid. + * + * @return True if property is valid. + */ explicit operator bool() const { return m_kind != kNone; } - // Kind checkers + /** + * Returns true if property is a boolean. + * + * @return True if property is a boolean. + */ bool IsBoolean() const { return m_kind == kBoolean; } + + /** + * Returns true if property is an integer. + * + * @return True if property is an integer. + */ bool IsInteger() const { return m_kind == kInteger; } + + /** + * Returns true if property is a string. + * + * @return True if property is a string. + */ bool IsString() const { return m_kind == kString; } + + /** + * Returns true if property is an enum. + * + * @return True if property is an enum. + */ bool IsEnum() const { return m_kind == kEnum; } + /** + * Returns property value. + * + * @return Property value. + */ int Get() const; + + /** + * Sets property value. + * + * @param value Property value. + */ void Set(int value); + + /** + * Returns property minimum value. + * + * @return Property minimum value. + */ int GetMin() const; + + /** + * Returns property maximum value. + * + * @return Property maximum value. + */ int GetMax() const; + + /** + * Returns property step size. + * + * @return Property step size. + */ int GetStep() const; + + /** + * Returns property default value. + * + * @return Property default value. + */ int GetDefault() const; - // String-specific functions + /** + * Returns the string property value. + * + *

This function is string-specific. + * + * @return The string property value. + */ std::string GetString() const; + + /** + * Returns the string property value as a reference to the given buffer. + * + * This function is string-specific. + * + * @param buf The backing storage to which to write the property value. + * @return The string property value as a reference to the given buffer. + */ std::string_view GetString(wpi::SmallVectorImpl& buf) const; + + /** + * Sets the string property value. + * + * This function is string-specific. + * + * @param value String property value. + */ void SetString(std::string_view value); - // Enum-specific functions + /** + * Returns the possible values for the enum property value. + * + * This function is enum-specific. + * + * @return The possible values for the enum property value. + */ std::vector GetChoices() const; + /** + * Returns the last status. + * + * @return The last status. + */ CS_Status GetLastStatus() const { return m_status; } private: @@ -99,11 +210,20 @@ class VideoSource { friend class VideoSink; public: + /** + * Video source kind. + */ enum Kind { + /// Unknown video source. kUnknown = CS_SOURCE_UNKNOWN, + /// USB video source. kUsb = CS_SOURCE_USB, + /// HTTP video source. kHttp = CS_SOURCE_HTTP, - kCv = CS_SOURCE_CV + /// CV video source. + kCv = CS_SOURCE_CV, + /// Raw video source. + kRaw = CS_SOURCE_RAW, }; /** Connection strategy. Used for SetConnectionStrategy(). */ @@ -350,6 +470,8 @@ class VideoSource { explicit VideoSource(CS_Source handle) : m_handle(handle) {} mutable CS_Status m_status = 0; + + /// Video source handle. CS_Source m_handle{0}; }; @@ -358,11 +480,19 @@ class VideoSource { */ class VideoCamera : public VideoSource { public: + /** + * White balance. + */ enum WhiteBalance { + /// Fixed indoor white balance. kFixedIndoor = 3000, + /// Fixed outdoor white balance 1. kFixedOutdoor1 = 4000, + /// Fixed outdoor white balance 2. kFixedOutdoor2 = 5000, + /// Fixed fluorescent white balance 1. kFixedFluorescent1 = 5100, + /// Fixed fluorescent white balance 2. kFixedFlourescent2 = 5200 }; @@ -470,10 +600,17 @@ class UsbCamera : public VideoCamera { */ class HttpCamera : public VideoCamera { public: + /** + * HTTP camera kind. + */ enum HttpCameraKind { + /// Unknown camera kind. kUnknown = CS_HTTP_UNKNOWN, + /// MJPG Streamer camera. kMJPGStreamer = CS_HTTP_MJPGSTREAMER, + /// CS Core camera. kCSCore = CS_HTTP_CSCORE, + /// Axis camera. kAxis = CS_HTTP_AXIS }; @@ -555,8 +692,10 @@ class HttpCamera : public VideoCamera { /** * A source that represents an Axis IP camera. + * + * @deprecated Use HttpCamera instead. */ -class AxisCamera : public HttpCamera { +class [[deprecated("Use HttpCamera instead.")]] AxisCamera : public HttpCamera { static std::string HostToUrl(std::string_view host); static std::vector HostToUrl(std::span hosts); template @@ -716,9 +855,14 @@ class VideoSink { public: enum Kind { + /// Unknown sink type. kUnknown = CS_SINK_UNKNOWN, + /// MJPEG video sink. kMjpeg = CS_SINK_MJPEG, - kCv = CS_SINK_CV + /// CV video sink. + kCv = CS_SINK_CV, + /// Raw video sink. + kRaw = CS_SINK_RAW, }; VideoSink() noexcept = default; @@ -727,8 +871,18 @@ class VideoSink { VideoSink& operator=(VideoSink other) noexcept; ~VideoSink(); + /** + * Returns true if the VideoSink is valid. + * + * @return True if the VideoSink is valid. + */ explicit operator bool() const { return m_handle != 0; } + /** + * Returns the VideoSink handle. + * + * @return The VideoSink handle. + */ int GetHandle() const { return m_handle; } bool operator==(const VideoSink& other) const { @@ -972,17 +1126,23 @@ class ImageSink : public VideoSink { class VideoEvent : public RawEvent { public: /** - * Get the source associated with the event (if any). + * Returns the source associated with the event (if any). + * + * @return The source associated with the event (if any). */ VideoSource GetSource() const; /** - * Get the sink associated with the event (if any). + * Returns the sink associated with the event (if any). + * + * @return The sink associated with the event (if any). */ VideoSink GetSink() const; /** - * Get the property associated with the event (if any). + * Returns the property associated with the event (if any). + * + * @return The property associated with the event (if any). */ VideoProperty GetProperty() const; }; diff --git a/cscore/src/main/native/include/cscore_oo.inc b/cscore/src/main/native/include/cscore_oo.inc index 18a1df263df..20960f20e65 100644 --- a/cscore/src/main/native/include/cscore_oo.inc +++ b/cscore/src/main/native/include/cscore_oo.inc @@ -11,6 +11,8 @@ #include #include +#include + #include "cscore_oo.h" namespace cs { @@ -350,7 +352,7 @@ inline std::vector HttpCamera::GetUrls() const { m_status = 0; return ::cs::GetHttpCameraUrls(m_handle, &m_status); } - +WPI_IGNORE_DEPRECATED inline std::vector AxisCamera::HostToUrl( std::span hosts) { std::vector rv; @@ -389,6 +391,7 @@ template inline AxisCamera::AxisCamera(std::string_view name, std::initializer_list hosts) : HttpCamera(name, HostToUrl(hosts), kAxis) {} +WPI_UNIGNORE_DEPRECATED inline void ImageSource::NotifyError(std::string_view msg) { m_status = 0; diff --git a/cscore/src/main/native/include/cscore_raw.h b/cscore/src/main/native/include/cscore_raw.h index 21f4009ae01..e6106835633 100644 --- a/cscore/src/main/native/include/cscore_raw.h +++ b/cscore/src/main/native/include/cscore_raw.h @@ -9,50 +9,37 @@ #include "cscore_c.h" +// NOLINTBEGIN #ifdef __cplusplus #include "cscore_oo.h" #endif -/** - * Raw Frame - */ -typedef struct CS_RawFrame { // NOLINT - char* data; - int dataLength; - int pixelFormat; - int width; - int height; - int totalData; -} CS_RawFrame; - #ifdef __cplusplus extern "C" { #endif +// NOLINTEND /** * @defgroup cscore_raw_cfunc Raw Image Functions * @{ */ -void CS_AllocateRawFrameData(CS_RawFrame* frame, int requestedSize); -void CS_FreeRawFrameData(CS_RawFrame* frame); - -uint64_t CS_GrabRawSinkFrame(CS_Sink sink, struct CS_RawFrame* rawImage, +uint64_t CS_GrabRawSinkFrame(CS_Sink sink, struct WPI_RawFrame* rawImage, CS_Status* status); -uint64_t CS_GrabRawSinkFrameTimeout(CS_Sink sink, struct CS_RawFrame* rawImage, +uint64_t CS_GrabRawSinkFrameTimeout(CS_Sink sink, struct WPI_RawFrame* rawImage, double timeout, CS_Status* status); -CS_Sink CS_CreateRawSink(const char* name, CS_Status* status); +CS_Sink CS_CreateRawSink(const struct WPI_String* name, CS_Bool isCv, + CS_Status* status); -CS_Sink CS_CreateRawSinkCallback(const char* name, void* data, - void (*processFrame)(void* data, - uint64_t time), - CS_Status* status); +CS_Sink CS_CreateRawSinkCallback( + const struct WPI_String* name, CS_Bool isCv, void* data, + void (*processFrame)(void* data, uint64_t time), CS_Status* status); -void CS_PutRawSourceFrame(CS_Source source, const struct CS_RawFrame* image, +void CS_PutRawSourceFrame(CS_Source source, const struct WPI_RawFrame* image, CS_Status* status); -CS_Source CS_CreateRawSource(const char* name, const CS_VideoMode* mode, - CS_Status* status); +CS_Source CS_CreateRawSource(const struct WPI_String* name, CS_Bool isCv, + const CS_VideoMode* mode, CS_Status* status); /** @} */ #ifdef __cplusplus @@ -62,36 +49,23 @@ CS_Source CS_CreateRawSource(const char* name, const CS_VideoMode* mode, #ifdef __cplusplus namespace cs { -struct RawFrame : public CS_RawFrame { - RawFrame() { - data = nullptr; - dataLength = 0; - pixelFormat = CS_PIXFMT_UNKNOWN; - width = 0; - height = 0; - totalData = 0; - } - - ~RawFrame() { CS_FreeRawFrameData(this); } -}; - /** * @defgroup cscore_raw_func Raw Image Functions * @{ */ -CS_Source CreateRawSource(std::string_view name, const VideoMode& mode, - CS_Status* status); +CS_Source CreateRawSource(std::string_view name, bool isCv, + const VideoMode& mode, CS_Status* status); -CS_Sink CreateRawSink(std::string_view name, CS_Status* status); -CS_Sink CreateRawSinkCallback(std::string_view name, +CS_Sink CreateRawSink(std::string_view name, bool isCv, CS_Status* status); +CS_Sink CreateRawSinkCallback(std::string_view name, bool isCv, std::function processFrame, CS_Status* status); -void PutSourceFrame(CS_Source source, const CS_RawFrame& image, +void PutSourceFrame(CS_Source source, const WPI_RawFrame& image, CS_Status* status); -uint64_t GrabSinkFrame(CS_Sink sink, CS_RawFrame& image, CS_Status* status); -uint64_t GrabSinkFrameTimeout(CS_Sink sink, CS_RawFrame& image, double timeout, +uint64_t GrabSinkFrame(CS_Sink sink, WPI_RawFrame& image, CS_Status* status); +uint64_t GrabSinkFrameTimeout(CS_Sink sink, WPI_RawFrame& image, double timeout, CS_Status* status); /** @@ -129,7 +103,7 @@ class RawSource : public ImageSource { * * @param image raw frame image */ - void PutFrame(RawFrame& image); + void PutFrame(wpi::RawFrame& image); }; /** @@ -177,7 +151,7 @@ class RawSink : public ImageSink { * and is in 1 us increments. */ [[nodiscard]] - uint64_t GrabFrame(RawFrame& image, double timeout = 0.225) const; + uint64_t GrabFrame(wpi::RawFrame& image, double timeout = 0.225) const; /** * Wait for the next frame and get the image. May block forever. @@ -188,40 +162,40 @@ class RawSink : public ImageSink { * and is in 1 us increments. */ [[nodiscard]] - uint64_t GrabFrameNoTimeout(RawFrame& image) const; + uint64_t GrabFrameNoTimeout(wpi::RawFrame& image) const; }; inline RawSource::RawSource(std::string_view name, const VideoMode& mode) { - m_handle = CreateRawSource(name, mode, &m_status); + m_handle = CreateRawSource(name, false, mode, &m_status); } inline RawSource::RawSource(std::string_view name, VideoMode::PixelFormat format, int width, int height, int fps) { - m_handle = - CreateRawSource(name, VideoMode{format, width, height, fps}, &m_status); + m_handle = CreateRawSource(name, false, VideoMode{format, width, height, fps}, + &m_status); } -inline void RawSource::PutFrame(RawFrame& image) { +inline void RawSource::PutFrame(wpi::RawFrame& image) { m_status = 0; PutSourceFrame(m_handle, image, &m_status); } inline RawSink::RawSink(std::string_view name) { - m_handle = CreateRawSink(name, &m_status); + m_handle = CreateRawSink(name, false, &m_status); } inline RawSink::RawSink(std::string_view name, std::function processFrame) { - m_handle = CreateRawSinkCallback(name, processFrame, &m_status); + m_handle = CreateRawSinkCallback(name, false, processFrame, &m_status); } -inline uint64_t RawSink::GrabFrame(RawFrame& image, double timeout) const { +inline uint64_t RawSink::GrabFrame(wpi::RawFrame& image, double timeout) const { m_status = 0; return GrabSinkFrameTimeout(m_handle, image, timeout, &m_status); } -inline uint64_t RawSink::GrabFrameNoTimeout(RawFrame& image) const { +inline uint64_t RawSink::GrabFrameNoTimeout(wpi::RawFrame& image) const { m_status = 0; return GrabSinkFrame(m_handle, image, &m_status); } diff --git a/cscore/src/main/native/include/cscore_raw_cv.h b/cscore/src/main/native/include/cscore_raw_cv.h deleted file mode 100644 index 11f42d6c627..00000000000 --- a/cscore/src/main/native/include/cscore_raw_cv.h +++ /dev/null @@ -1,227 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#ifndef CSCORE_CSCORE_RAW_CV_H_ -#define CSCORE_CSCORE_RAW_CV_H_ - -#ifdef CSCORE_CSCORE_CV_H_ -#error "Cannot include both cscore_cv.h and cscore_raw_cv.h in the same file" -#endif - -#include - -#include - -#include "cscore_raw.h" - -namespace cs { -/** - * A source for using the raw frame API to provide opencv images. - * - * If you are using the WPILib OpenCV builds, do not use this, and - * instead include "cscore_cv.h" to get a more performant version. - * - * This is not dependent on any opencv binary ABI, and can be used - * with versions of OpenCV that are not 3. If using OpenCV 3, use - * CvSource. - */ -class RawCvSource : public RawSource { - public: - RawCvSource() = default; - - /** - * Create a Raw OpenCV source. - * - * @param name Source name (arbitrary unique identifier) - * @param mode Video mode being generated - */ - RawCvSource(std::string_view name, const VideoMode& mode); - - /** - * Create a Raw OpenCV source. - * - * @param name Source name (arbitrary unique identifier) - * @param pixelFormat Pixel format - * @param width width - * @param height height - * @param fps fps - */ - RawCvSource(std::string_view name, VideoMode::PixelFormat pixelFormat, - int width, int height, int fps); - - /** - * Put an OpenCV image and notify sinks. - * - *

Only 8-bit single-channel or 3-channel (with BGR channel order) images - * are supported. If the format, depth or channel order is different, use - * cv::Mat::convertTo() and/or cv::cvtColor() to convert it first. - * - * @param image OpenCV image - */ - void PutFrame(cv::Mat& image); - - private: - RawFrame rawFrame; -}; - -/** - * A sink for user code to accept raw video frames as OpenCV images. - * - * If you are using the WPILib OpenCV builds, do not use this, and - * instead include "cscore_cv.h" to get a more performant version. - * - * This is not dependent on any opencv binary ABI, and can be used - * with versions of OpenCV that are not 3. If using OpenCV 3, use - * CvSink. - */ -class RawCvSink : public RawSink { - public: - RawCvSink() = default; - - /** - * Create a sink for accepting OpenCV images. - * - *

WaitForFrame() must be called on the created sink to get each new - * image. - * - * @param name Source name (arbitrary unique identifier) - */ - explicit RawCvSink(std::string_view name); - - /** - * Create a sink for accepting OpenCV images in a separate thread. - * - *

A thread will be created that calls WaitForFrame() and calls the - * processFrame() callback each time a new frame arrives. - * - * @param name Source name (arbitrary unique identifier) - * @param processFrame Frame processing function; will be called with a - * time=0 if an error occurred. processFrame should call GetImage() - * or GetError() as needed, but should not call (except in very - * unusual circumstances) WaitForImage(). - */ - RawCvSink(std::string_view name, - std::function processFrame); - - /** - * Wait for the next frame and get the image. - * Times out (returning 0) after timeout seconds. - * The provided image will have three 8-bit channels stored in BGR order. - * - * @return Frame time, or 0 on error (call GetError() to obtain the error - * message); the frame time is in the same time base as wpi::Now(), - * and is in 1 us increments. - */ - [[nodiscard]] - uint64_t GrabFrame(cv::Mat& image, double timeout = 0.225); - - /** - * Wait for the next frame and get the image. May block forever. - * The provided image will have three 8-bit channels stored in BGR order. - * - * @return Frame time, or 0 on error (call GetError() to obtain the error - * message); the frame time is in the same time base as wpi::Now(), - * and is in 1 us increments. - */ - [[nodiscard]] - uint64_t GrabFrameNoTimeout(cv::Mat& image); - - /** - * Wait for the next frame and get the image. - * Times out (returning 0) after timeout seconds. - * The provided image will have three 8-bit channels stored in BGR order. - * - * @return Frame time, or 0 on error (call GetError() to obtain the error - * message); the frame time is in the same time base as wpi::Now(), - * and is in 1 us increments. - */ - [[nodiscard]] - uint64_t GrabFrameDirect(cv::Mat& image, double timeout = 0.225); - - /** - * Wait for the next frame and get the image. May block forever. - * The provided image will have three 8-bit channels stored in BGR order. - * - * @return Frame time, or 0 on error (call GetError() to obtain the error - * message); the frame time is in the same time base as wpi::Now(), - * and is in 1 us increments. - */ - [[nodiscard]] - uint64_t GrabFrameNoTimeoutDirect(cv::Mat& image); - - private: - RawFrame rawFrame; -}; - -inline RawCvSource::RawCvSource(std::string_view name, const VideoMode& mode) - : RawSource{name, mode} {} - -inline RawCvSource::RawCvSource(std::string_view name, - VideoMode::PixelFormat format, int width, - int height, int fps) - : RawSource{name, format, width, height, fps} {} - -inline void RawCvSource::PutFrame(cv::Mat& image) { - m_status = 0; - rawFrame.data = reinterpret_cast(image.data); - rawFrame.width = image.cols; - rawFrame.height = image.rows; - rawFrame.totalData = image.total() * image.channels(); - rawFrame.pixelFormat = image.channels() == 3 ? CS_PIXFMT_BGR : CS_PIXFMT_GRAY; - PutSourceFrame(m_handle, rawFrame, &m_status); -} - -inline RawCvSink::RawCvSink(std::string_view name) : RawSink{name} {} - -inline RawCvSink::RawCvSink(std::string_view name, - std::function processFrame) - : RawSink{name, processFrame} {} - -inline uint64_t RawCvSink::GrabFrame(cv::Mat& image, double timeout) { - cv::Mat tmpnam; - auto retVal = GrabFrameDirect(tmpnam); - if (retVal <= 0) { - return retVal; - } - tmpnam.copyTo(image); - return retVal; -} - -inline uint64_t RawCvSink::GrabFrameNoTimeout(cv::Mat& image) { - cv::Mat tmpnam; - auto retVal = GrabFrameNoTimeoutDirect(tmpnam); - if (retVal <= 0) { - return retVal; - } - tmpnam.copyTo(image); - return retVal; -} - -inline uint64_t RawCvSink::GrabFrameDirect(cv::Mat& image, double timeout) { - rawFrame.height = 0; - rawFrame.width = 0; - rawFrame.pixelFormat = CS_PixelFormat::CS_PIXFMT_BGR; - m_status = RawSink::GrabFrame(rawFrame, timeout); - if (m_status <= 0) { - return m_status; - } - image = cv::Mat{rawFrame.height, rawFrame.width, CV_8UC3, rawFrame.data}; - return m_status; -} - -inline uint64_t RawCvSink::GrabFrameNoTimeoutDirect(cv::Mat& image) { - rawFrame.height = 0; - rawFrame.width = 0; - rawFrame.pixelFormat = CS_PixelFormat::CS_PIXFMT_BGR; - m_status = RawSink::GrabFrameNoTimeout(rawFrame); - if (m_status <= 0) { - return m_status; - } - image = cv::Mat{rawFrame.height, rawFrame.width, CV_8UC3, rawFrame.data}; - return m_status; -} - -} // namespace cs - -#endif // CSCORE_CSCORE_RAW_CV_H_ diff --git a/cscore/src/main/native/linux/NetworkListener.cpp b/cscore/src/main/native/linux/NetworkListener.cpp index 1a0ac8b595a..9771cfa20f8 100644 --- a/cscore/src/main/native/linux/NetworkListener.cpp +++ b/cscore/src/main/native/linux/NetworkListener.cpp @@ -89,6 +89,7 @@ void NetworkListener::Impl::Thread::Main() { std::memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; addr.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR; + // NOLINTNEXTLINE(modernize-avoid-bind) if (bind(sd, reinterpret_cast(&addr), sizeof(addr)) < 0) { ERROR("NetworkListener: could not create socket: {}", std::strerror(errno)); ::close(sd); diff --git a/cscore/src/main/native/linux/UsbCameraImpl.cpp b/cscore/src/main/native/linux/UsbCameraImpl.cpp index b50b6d934b9..eca6ab77975 100644 --- a/cscore/src/main/native/linux/UsbCameraImpl.cpp +++ b/cscore/src/main/native/linux/UsbCameraImpl.cpp @@ -80,6 +80,8 @@ static VideoMode::PixelFormat ToPixelFormat(__u32 pixelFormat) { return VideoMode::kRGB565; case V4L2_PIX_FMT_BGR24: return VideoMode::kBGR; + case V4L2_PIX_FMT_ABGR32: + return VideoMode::kBGRA; case V4L2_PIX_FMT_GREY: return VideoMode::kGray; case V4L2_PIX_FMT_Y16: @@ -102,6 +104,8 @@ static __u32 FromPixelFormat(VideoMode::PixelFormat pixelFormat) { return V4L2_PIX_FMT_RGB565; case VideoMode::kBGR: return V4L2_PIX_FMT_BGR24; + case VideoMode::kBGRA: + return V4L2_PIX_FMT_ABGR32; case VideoMode::kGray: return V4L2_PIX_FMT_GREY; case VideoMode::kY16: diff --git a/cscore/src/main/native/objcpp/UsbCameraDelegate.mm b/cscore/src/main/native/objcpp/UsbCameraDelegate.mm index efa0fbf6020..e3a2bfdf601 100644 --- a/cscore/src/main/native/objcpp/UsbCameraDelegate.mm +++ b/cscore/src/main/native/objcpp/UsbCameraDelegate.mm @@ -7,9 +7,6 @@ #include -#include -#include - @implementation UsbCameraDelegate - (id)init { @@ -24,6 +21,8 @@ - (void)captureOutput:(AVCaptureOutput*)captureOutput (void)sampleBuffer; (void)connection; + auto currentTime = wpi::Now(); + auto sharedThis = self.cppImpl.lock(); if (!sharedThis) { return; @@ -52,16 +51,12 @@ - (void)captureOutput:(AVCaptureOutput*)captureOutput return; } - size_t currSize = width * 3 * height; - - auto tmpMat = cv::Mat(height, width, CV_8UC4, baseaddress, rowBytes); - auto image = sharedThis->AllocImage(cs::VideoMode::PixelFormat::kBGR, width, - height, currSize); - cv::cvtColor(tmpMat, image->AsMat(), cv::COLOR_BGRA2BGR); + std::unique_ptr image = cs::CreateImageFromBGRA( + sharedThis.get(), width, height, rowBytes, reinterpret_cast(baseaddress)); CVPixelBufferUnlockBaseAddress(imageBuffer, 0); - sharedThis->objcPutFrame(std::move(image), wpi::Now()); + sharedThis->objcPutFrame(std::move(image), currentTime); } @end diff --git a/cscore/src/main/native/objcpp/UsbCameraImpl.mm b/cscore/src/main/native/objcpp/UsbCameraImpl.mm index 5607fbf30ff..b0dfc330a00 100644 --- a/cscore/src/main/native/objcpp/UsbCameraImpl.mm +++ b/cscore/src/main/native/objcpp/UsbCameraImpl.mm @@ -18,7 +18,6 @@ #include "Instance.h" #include "c_util.h" #include "cscore_cpp.h" -#include "opencv2/imgproc.hpp" #include "UsbCameraImpl.h" namespace cs { @@ -135,7 +134,11 @@ CS_Source CreateUsbCameraPath(std::string_view name, std::string_view path, std::vector retval; NSArray* deviceTypes = @[ AVCaptureDeviceTypeBuiltInWideAngleCamera, +#if MAC_OS_X_VERSION_MIN_REQUIRED >= 140000 + AVCaptureDeviceTypeExternal +#else AVCaptureDeviceTypeExternalUnknown +#endif ]; AVCaptureDeviceDiscoverySession* session = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:deviceTypes diff --git a/cscore/src/main/native/objcpp/UsbCameraListener.mm b/cscore/src/main/native/objcpp/UsbCameraListener.mm index b6b59d37df3..049c781ac9d 100644 --- a/cscore/src/main/native/objcpp/UsbCameraListener.mm +++ b/cscore/src/main/native/objcpp/UsbCameraListener.mm @@ -76,7 +76,11 @@ - (void)camerasChanged:(NSNotification*)notification { if ([device.deviceType isEqualToString:AVCaptureDeviceTypeBuiltInWideAngleCamera] || [device.deviceType +#if MAC_OS_X_VERSION_MIN_REQUIRED >= 140000 + isEqualToString:AVCaptureDeviceTypeExternal]) { +#else isEqualToString:AVCaptureDeviceTypeExternalUnknown]) { +#endif self.notifier->NotifyUsbCamerasChanged(); } }); diff --git a/cscore/src/main/native/windows/UsbCameraImpl.cpp b/cscore/src/main/native/windows/UsbCameraImpl.cpp index cde8c2556b8..606ceb2145d 100644 --- a/cscore/src/main/native/windows/UsbCameraImpl.cpp +++ b/cscore/src/main/native/windows/UsbCameraImpl.cpp @@ -21,9 +21,6 @@ #include #include #include -#include -#include -#include #include #include #include @@ -284,6 +281,8 @@ void UsbCameraImpl::ProcessFrame(IMFSample* videoSample, return; } + auto currentTime = wpi::Now(); + ComPtr buf; if (!SUCCEEDED(videoSample->ConvertToContiguousBuffer(buf.GetAddressOf()))) { @@ -339,56 +338,9 @@ void UsbCameraImpl::ProcessFrame(IMFSample* videoSample, } } - cv::Mat tmpMat; - std::unique_ptr dest; - bool doFinalSet = true; - - switch (mode.pixelFormat) { - case cs::VideoMode::PixelFormat::kMJPEG: { - // Special case - PutFrame(VideoMode::kMJPEG, mode.width, mode.height, - {reinterpret_cast(ptr), length}, wpi::Now()); - doFinalSet = false; - break; - } - case cs::VideoMode::PixelFormat::kGray: - tmpMat = cv::Mat(mode.height, mode.width, CV_8UC1, ptr, pitch); - dest = AllocImage(VideoMode::kGray, tmpMat.cols, tmpMat.rows, - tmpMat.total()); - tmpMat.copyTo(dest->AsMat()); - break; - case cs::VideoMode::PixelFormat::kY16: - tmpMat = cv::Mat(mode.height, mode.width, CV_8UC2, ptr, pitch); - dest = - AllocImage(VideoMode::kY16, tmpMat.cols, tmpMat.rows, tmpMat.total()); - tmpMat.copyTo(dest->AsMat()); - break; - case cs::VideoMode::PixelFormat::kBGR: - tmpMat = cv::Mat(mode.height, mode.width, CV_8UC3, ptr, pitch); - dest = AllocImage(VideoMode::kBGR, tmpMat.cols, tmpMat.rows, - tmpMat.total() * 3); - tmpMat.copyTo(dest->AsMat()); - break; - case cs::VideoMode::PixelFormat::kYUYV: - tmpMat = cv::Mat(mode.height, mode.width, CV_8UC2, ptr, pitch); - dest = AllocImage(VideoMode::kYUYV, tmpMat.cols, tmpMat.rows, - tmpMat.total() * 2); - tmpMat.copyTo(dest->AsMat()); - break; - case cs::VideoMode::PixelFormat::kUYVY: - tmpMat = cv::Mat(mode.height, mode.width, CV_8UC2, ptr, pitch); - dest = AllocImage(VideoMode::kUYVY, tmpMat.cols, tmpMat.rows, - tmpMat.total() * 2); - tmpMat.copyTo(dest->AsMat()); - break; - default: - doFinalSet = false; - break; - } - - if (doFinalSet) { - PutFrame(std::move(dest), wpi::Now()); - } + std::string_view data_view{reinterpret_cast(ptr), length}; + SourceImpl::PutFrame(static_cast(mode.pixelFormat), + mode.width, mode.height, data_view, currentTime); if (buffer2d) { buffer2d->Unlock2D(); @@ -480,8 +432,6 @@ static cs::VideoMode::PixelFormat GetFromGUID(const GUID& guid) { return cs::VideoMode::PixelFormat::kY16; } else if (IsEqualGUID(guid, MFVideoFormat_YUY2)) { return cs::VideoMode::PixelFormat::kYUYV; - } else if (IsEqualGUID(guid, MFVideoFormat_RGB24)) { - return cs::VideoMode::PixelFormat::kBGR; } else if (IsEqualGUID(guid, MFVideoFormat_MJPG)) { return cs::VideoMode::PixelFormat::kMJPEG; } else if (IsEqualGUID(guid, MFVideoFormat_RGB565)) { diff --git a/cscore/src/main/native/windows/WindowsMessagePump.cpp b/cscore/src/main/native/windows/WindowsMessagePump.cpp index 716edd91dc7..35634faa071 100644 --- a/cscore/src/main/native/windows/WindowsMessagePump.cpp +++ b/cscore/src/main/native/windows/WindowsMessagePump.cpp @@ -99,8 +99,9 @@ WindowsMessagePump::WindowsMessagePump( WindowsMessagePump::~WindowsMessagePump() { auto res = SendMessageA(hwnd, WM_CLOSE, NULL, NULL); - if (m_mainThread.joinable()) + if (m_mainThread.joinable()) { m_mainThread.join(); + } } void WindowsMessagePump::ThreadMain(HANDLE eventHandle) { diff --git a/cscore/src/test/java/edu/wpi/first/cscore/VideoModeTest.java b/cscore/src/test/java/edu/wpi/first/cscore/VideoModeTest.java index 738888d7fe8..6108c5ca1cb 100644 --- a/cscore/src/test/java/edu/wpi/first/cscore/VideoModeTest.java +++ b/cscore/src/test/java/edu/wpi/first/cscore/VideoModeTest.java @@ -7,13 +7,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import edu.wpi.first.util.PixelFormat; import org.junit.jupiter.api.Test; class VideoModeTest { @Test void equalityTest() { - VideoMode a = new VideoMode(VideoMode.PixelFormat.kMJPEG, 1920, 1080, 30); - VideoMode b = new VideoMode(VideoMode.PixelFormat.kMJPEG, 1920, 1080, 30); + VideoMode a = new VideoMode(PixelFormat.kMJPEG, 1920, 1080, 30); + VideoMode b = new VideoMode(PixelFormat.kMJPEG, 1920, 1080, 30); assertEquals(a, b); assertNotEquals(a, null); diff --git a/datalogtool/CMakeLists.txt b/datalogtool/CMakeLists.txt index 72a05c6d82a..00b760e14a9 100644 --- a/datalogtool/CMakeLists.txt +++ b/datalogtool/CMakeLists.txt @@ -9,7 +9,7 @@ generate_resources(src/main/native/resources generated/main/cpp DLT dlt datalogt file(GLOB datalogtool_src src/main/native/cpp/*.cpp ${CMAKE_CURRENT_BINARY_DIR}/WPILibVersion.cpp) -if (WIN32) +if(WIN32) set(datalogtool_rc src/main/native/win/datalogtool.rc) elseif(APPLE) set(MACOSX_BUNDLE_ICON_FILE datalogtool.icns) @@ -17,12 +17,18 @@ elseif(APPLE) set_source_files_properties(${APP_ICON_MACOSX} PROPERTIES MACOSX_PACKAGE_LOCATION "Resources") endif() -add_executable(datalogtool ${datalogtool_src} ${datalogtool_resources_src} ${datalogtool_rc} ${APP_ICON_MACOSX}) +add_executable( + datalogtool + ${datalogtool_src} + ${datalogtool_resources_src} + ${datalogtool_rc} + ${APP_ICON_MACOSX} +) wpilib_link_macos_gui(datalogtool) target_link_libraries(datalogtool libglass ${LIBSSH_LIBRARIES}) target_include_directories(datalogtool SYSTEM PRIVATE ${LIBSSH_INCLUDE_DIRS}) -if (WIN32) +if(WIN32) set_target_properties(datalogtool PROPERTIES WIN32_EXECUTABLE YES) elseif(APPLE) set_target_properties(datalogtool PROPERTIES MACOSX_BUNDLE YES OUTPUT_NAME "datalogTool") diff --git a/datalogtool/publish.gradle b/datalogtool/publish.gradle index f24f51aa482..ae75905e7ee 100644 --- a/datalogtool/publish.gradle +++ b/datalogtool/publish.gradle @@ -29,51 +29,8 @@ model { def applicationPath = binary.executable.file def icon = file("$project.projectDir/src/main/native/mac/datalogtool.icns") - // Create the macOS bundle. - def bundleTask = project.tasks.create("bundleDataLogToolOsxApp" + binary.targetPlatform.architecture.name, Copy) { - description("Creates a macOS application bundle for DataLogTool") - from(file("$project.projectDir/Info.plist")) - into(file("$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name/DataLogTool.app/Contents")) - into("MacOS") { - with copySpec { - from binary.executable.file - } - } - into("Resources") { - with copySpec { - from icon - } - } - - inputs.property "HasDeveloperId", project.hasProperty("developerID") - - doLast { - if (project.hasProperty("developerID")) { - // Get path to binary. - exec { - workingDir rootDir - def args = [ - "sh", - "-c", - "codesign --force --strict --deep " + - "--timestamp --options=runtime " + - "--verbose -s ${project.findProperty("developerID")} " + - "$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name/DataLogTool.app/" - ] - commandLine args - } - } - } - } - - // Reset the application path if we are creating a bundle. - if (binary.targetPlatform.operatingSystem.isMacOsX()) { - applicationPath = file("$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name") - project.build.dependsOn bundleTask - } - // Create the ZIP. - def task = project.tasks.create("copyDataLogToolExecutable" + binary.targetPlatform.architecture.name, Zip) { + def task = project.tasks.create("copyDataLogToolExecutable" + binary.targetPlatform.operatingSystem.name + binary.targetPlatform.architecture.name, Zip) { description("Copies the DataLogTool executable to the outputs directory.") destinationDirectory = outputsFolder @@ -85,13 +42,63 @@ model { into '/' } - from(applicationPath) + if (binary.targetPlatform.operatingSystem.isWindows()) { + def exePath = binary.executable.file.absolutePath + exePath = exePath.substring(0, exePath.length() - 4) + def pdbPath = new File(exePath + '.pdb') + from(pdbPath) + } + into(nativeUtils.getPlatformPath(binary)) } if (binary.targetPlatform.operatingSystem.isMacOsX()) { + // Create the macOS bundle. + def bundleTask = project.tasks.create("bundleDataLogToolOsxApp" + binary.targetPlatform.architecture.name, Copy) { + description("Creates a macOS application bundle for DataLogTool") + from(file("$project.projectDir/Info.plist")) + into(file("$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name/DataLogTool.app/Contents")) + into("MacOS") { + with copySpec { + from binary.executable.file + } + } + into("Resources") { + with copySpec { + from icon + } + } + + inputs.property "HasDeveloperId", project.hasProperty("developerID") + + doLast { + if (project.hasProperty("developerID")) { + // Get path to binary. + exec { + workingDir rootDir + def args = [ + "sh", + "-c", + "codesign --force --strict --deep " + + "--timestamp --options=runtime " + + "--verbose -s ${project.findProperty("developerID")} " + + "$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name/DataLogTool.app/" + ] + commandLine args + } + } + } + } + + // Reset the application path if we are creating a bundle. + applicationPath = file("$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name") + task.from(applicationPath) + project.build.dependsOn bundleTask + bundleTask.dependsOn binary.tasks.link task.dependsOn(bundleTask) + } else { + task.from(applicationPath) } task.dependsOn binary.tasks.link diff --git a/datalogtool/src/main/generate/WPILibVersion.cpp.in b/datalogtool/src/main/generate/WPILibVersion.cpp.in index b0a44905207..cfe24411588 100644 --- a/datalogtool/src/main/generate/WPILibVersion.cpp.in +++ b/datalogtool/src/main/generate/WPILibVersion.cpp.in @@ -1,4 +1,4 @@ -/* +/** * Autogenerated file! Do not manually edit this file. This version is regenerated * any time the publish task is run, or when this file is deleted. */ diff --git a/datalogtool/src/main/native/cpp/DataLogThread.cpp b/datalogtool/src/main/native/cpp/DataLogThread.cpp deleted file mode 100644 index 90c8b196c62..00000000000 --- a/datalogtool/src/main/native/cpp/DataLogThread.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "DataLogThread.h" - -#include - -DataLogThread::~DataLogThread() { - if (m_thread.joinable()) { - m_active = false; - m_thread.join(); - } -} - -void DataLogThread::ReadMain() { - for (auto record : m_reader) { - if (!m_active) { - break; - } - ++m_numRecords; - if (record.IsStart()) { - wpi::log::StartRecordData data; - if (record.GetStartData(&data)) { - std::scoped_lock lock{m_mutex}; - if (m_entries.find(data.entry) != m_entries.end()) { - fmt::print("...DUPLICATE entry ID, overriding\n"); - } - m_entries[data.entry] = data; - m_entryNames.emplace(data.name, data); - sigEntryAdded(data); - } else { - fmt::print("Start(INVALID)\n"); - } - } else if (record.IsFinish()) { - int entry; - if (record.GetFinishEntry(&entry)) { - std::scoped_lock lock{m_mutex}; - auto it = m_entries.find(entry); - if (it == m_entries.end()) { - fmt::print("...ID not found\n"); - } else { - m_entries.erase(it); - } - } else { - fmt::print("Finish(INVALID)\n"); - } - } else if (record.IsSetMetadata()) { - wpi::log::MetadataRecordData data; - if (record.GetSetMetadataData(&data)) { - std::scoped_lock lock{m_mutex}; - auto it = m_entries.find(data.entry); - if (it == m_entries.end()) { - fmt::print("...ID not found\n"); - } else { - it->second.metadata = data.metadata; - auto nameIt = m_entryNames.find(it->second.name); - if (nameIt != m_entryNames.end()) { - nameIt->second.metadata = data.metadata; - } - } - } else { - fmt::print("SetMetadata(INVALID)\n"); - } - } else if (record.IsControl()) { - fmt::print("Unrecognized control record\n"); - } - } - - sigDone(); - m_done = true; -} diff --git a/datalogtool/src/main/native/cpp/DataLogThread.h b/datalogtool/src/main/native/cpp/DataLogThread.h deleted file mode 100644 index 267aa1fef8b..00000000000 --- a/datalogtool/src/main/native/cpp/DataLogThread.h +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -class DataLogThread { - public: - explicit DataLogThread(wpi::log::DataLogReader reader) - : m_reader{std::move(reader)}, m_thread{[=, this] { ReadMain(); }} {} - ~DataLogThread(); - - bool IsDone() const { return m_done; } - std::string_view GetBufferIdentifier() const { - return m_reader.GetBufferIdentifier(); - } - unsigned int GetNumRecords() const { return m_numRecords; } - unsigned int GetNumEntries() const { - std::scoped_lock lock{m_mutex}; - return m_entryNames.size(); - } - - // Passes wpi::log::StartRecordData to func - template - void ForEachEntryName(T&& func) { - std::scoped_lock lock{m_mutex}; - for (auto&& kv : m_entryNames) { - func(kv.second); - } - } - - wpi::log::StartRecordData GetEntry(std::string_view name) const { - std::scoped_lock lock{m_mutex}; - auto it = m_entryNames.find(name); - if (it == m_entryNames.end()) { - return {}; - } - return it->second; - } - - const wpi::log::DataLogReader& GetReader() const { return m_reader; } - - // note: these are called on separate thread - wpi::sig::Signal_mt sigEntryAdded; - wpi::sig::Signal_mt<> sigDone; - - private: - void ReadMain(); - - wpi::log::DataLogReader m_reader; - mutable wpi::mutex m_mutex; - std::atomic_bool m_active{true}; - std::atomic_bool m_done{false}; - std::atomic m_numRecords{0}; - std::map> m_entryNames; - wpi::DenseMap m_entries; - std::thread m_thread; -}; diff --git a/datalogtool/src/main/native/cpp/Downloader.cpp b/datalogtool/src/main/native/cpp/Downloader.cpp index 9629e3b0ffe..0a8b90dceeb 100644 --- a/datalogtool/src/main/native/cpp/Downloader.cpp +++ b/datalogtool/src/main/native/cpp/Downloader.cpp @@ -27,7 +27,7 @@ Downloader::Downloader(glass::Storage& storage) : m_serverTeam{storage.GetString("serverTeam")}, - m_remoteDir{storage.GetString("remoteDir", "/home/lvuser")}, + m_remoteDir{storage.GetString("remoteDir", "/home/lvuser/logs")}, m_username{storage.GetString("username", "lvuser")}, m_localDir{storage.GetString("localDir")}, m_deleteAfter{storage.GetBool("deleteAfter", true)}, diff --git a/datalogtool/src/main/native/cpp/Exporter.cpp b/datalogtool/src/main/native/cpp/Exporter.cpp index 9201c8f7a1d..f9448c9aeea 100644 --- a/datalogtool/src/main/native/cpp/Exporter.cpp +++ b/datalogtool/src/main/native/cpp/Exporter.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -29,14 +30,14 @@ #include #include #include +#include #include #include "App.h" -#include "DataLogThread.h" namespace { struct InputFile { - explicit InputFile(std::unique_ptr datalog); + explicit InputFile(std::unique_ptr datalog); InputFile(std::string_view filename, std::string_view status) : filename{filename}, @@ -47,7 +48,7 @@ struct InputFile { std::string filename; std::string stem; - std::unique_ptr datalog; + std::unique_ptr datalog; std::string status; bool highlight = false; }; @@ -135,7 +136,7 @@ static void RebuildEntryTree() { } } -InputFile::InputFile(std::unique_ptr datalog_) +InputFile::InputFile(std::unique_ptr datalog_) : filename{datalog_->GetBufferIdentifier()}, stem{fs::path{filename}.stem().string()}, datalog{std::move(datalog_)} { @@ -192,7 +193,7 @@ static std::unique_ptr LoadDataLog(std::string_view filename) { } return std::make_unique( - std::make_unique(std::move(reader))); + std::make_unique(std::move(reader))); } void DisplayInputFiles() { @@ -284,9 +285,10 @@ static bool EmitEntry(const std::string& name, Entry& entry) { if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); for (auto inputFile : entry.inputFiles) { - ImGui::Text( - "%s: %s", inputFile->stem.c_str(), - std::string{inputFile->datalog->GetEntry(entry.name).type}.c_str()); + if (auto info = inputFile->datalog->GetEntry(entry.name)) { + ImGui::Text("%s: %s", inputFile->stem.c_str(), + std::string{info->type}.c_str()); + } } ImGui::EndTooltip(); } @@ -300,10 +302,10 @@ static bool EmitEntry(const std::string& name, Entry& entry) { if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); for (auto inputFile : entry.inputFiles) { - ImGui::Text( - "%s: %s", inputFile->stem.c_str(), - std::string{inputFile->datalog->GetEntry(entry.name).metadata} - .c_str()); + if (auto info = inputFile->datalog->GetEntry(entry.name)) { + ImGui::Text("%s: %s", inputFile->stem.c_str(), + std::string{info->metadata}.c_str()); + } } ImGui::EndTooltip(); } @@ -456,21 +458,21 @@ static void ValueToCsv(wpi::raw_ostream& os, const Entry& entry, int64_t val; if (record.GetInteger(&val)) { std::time_t timeval = val / 1000000; - fmt::print(os, "{:%Y-%m-%d %H:%M:%S}.{:06}", *std::localtime(&timeval), + wpi::print(os, "{:%Y-%m-%d %H:%M:%S}.{:06}", *std::localtime(&timeval), val % 1000000); return; } } else if (entry.type == "double") { double val; if (record.GetDouble(&val)) { - fmt::print(os, "{}", val); + wpi::print(os, "{}", val); return; } } else if (entry.type == "int64" || entry.type == "int") { // support "int" for compatibility with old NT4 datalogs int64_t val; if (record.GetInteger(&val)) { - fmt::print(os, "{}", val); + wpi::print(os, "{}", val); return; } } else if (entry.type == "string" || entry.type == "json") { @@ -483,31 +485,31 @@ static void ValueToCsv(wpi::raw_ostream& os, const Entry& entry, } else if (entry.type == "boolean") { bool val; if (record.GetBoolean(&val)) { - fmt::print(os, "{}", val); + wpi::print(os, "{}", val); return; } } else if (entry.type == "boolean[]") { std::vector val; if (record.GetBooleanArray(&val)) { - fmt::print(os, "{}", fmt::join(val, ";")); + wpi::print(os, "{}", fmt::join(val, ";")); return; } } else if (entry.type == "double[]") { std::vector val; if (record.GetDoubleArray(&val)) { - fmt::print(os, "{}", fmt::join(val, ";")); + wpi::print(os, "{}", fmt::join(val, ";")); return; } } else if (entry.type == "float[]") { std::vector val; if (record.GetFloatArray(&val)) { - fmt::print(os, "{}", fmt::join(val, ";")); + wpi::print(os, "{}", fmt::join(val, ";")); return; } } else if (entry.type == "int64[]") { std::vector val; if (record.GetIntegerArray(&val)) { - fmt::print(os, "{}", fmt::join(val, ";")); + wpi::print(os, "{}", fmt::join(val, ";")); return; } } else if (entry.type == "string[]") { @@ -526,7 +528,7 @@ static void ValueToCsv(wpi::raw_ostream& os, const Entry& entry, return; } } - fmt::print(os, ""); + wpi::print(os, ""); } static void ExportCsvFile(InputFile& f, wpi::raw_ostream& os, int style) { @@ -574,13 +576,13 @@ static void ExportCsvFile(InputFile& f, wpi::raw_ostream& os, int style) { Entry* entry = entryIt->second; if (style == 0) { - fmt::print(os, "{},\"", record.GetTimestamp() / 1000000.0); + wpi::print(os, "{},\"", record.GetTimestamp() / 1000000.0); PrintEscapedCsvString(os, entry->name); os << '"' << ','; ValueToCsv(os, *entry, record); os << '\n'; } else if (style == 1 && entry->column != -1) { - fmt::print(os, "{},", record.GetTimestamp() / 1000000.0); + wpi::print(os, "{},", record.GetTimestamp() / 1000000.0); for (int i = 0; i < entry->column; ++i) { os << ','; } diff --git a/datalogtool/src/main/native/cpp/main.cpp b/datalogtool/src/main/native/cpp/main.cpp index 5f1261b00f4..3d1a1965f29 100644 --- a/datalogtool/src/main/native/cpp/main.cpp +++ b/datalogtool/src/main/native/cpp/main.cpp @@ -1,25 +1,25 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include - -void Application(std::string_view saveDir); - -#ifdef _WIN32 -int __stdcall WinMain(void* hInstance, void* hPrevInstance, char* pCmdLine, - int nCmdShow) { - int argc = __argc; - char** argv = __argv; -#else -int main(int argc, char** argv) { -#endif - std::string_view saveDir; - if (argc == 2) { - saveDir = argv[1]; - } - - Application(saveDir); - - return 0; -} +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include + +void Application(std::string_view saveDir); + +#ifdef _WIN32 +int __stdcall WinMain(void* hInstance, void* hPrevInstance, char* pCmdLine, + int nCmdShow) { + int argc = __argc; + char** argv = __argv; +#else +int main(int argc, char** argv) { +#endif + std::string_view saveDir; + if (argc == 2) { + saveDir = argv[1]; + } + + Application(saveDir); + + return 0; +} diff --git a/docs/build.gradle b/docs/build.gradle index d17057242d1..fa07e96b06d 100644 --- a/docs/build.gradle +++ b/docs/build.gradle @@ -180,12 +180,10 @@ doxygen { warn_if_undocumented false warn_no_paramdoc true - //enable doxygen preprocessor expansion of WPI_DEPRECATED to fix MotorController docs enable_preprocessing true macro_expansion true expand_only_predef true - predefined "WPI_DEPRECATED(x)=[[deprecated(x)]]\"\\\n" + - "\"__cplusplus\"\\\n" + + predefined "__cplusplus\"\\\n" + "\"HAL_ENUM(name)=enum name : int32_t" if (project.hasProperty('docWarningsAsErrors')) { @@ -208,28 +206,31 @@ configurations { } } -ext { - sharedCvConfigs = [:] - staticCvConfigs = [:] - useJava = true - useCpp = false - skipDev = true - useDocumentation = true -} - -apply from: "${rootDir}/shared/opencv.gradle" - task generateJavaDocs(type: Javadoc) { - classpath += project(":wpimath").sourceSets.main.compileClasspath + classpath += project(":wpilibj").sourceSets.main.compileClasspath options.links("https://docs.oracle.com/en/java/javase/17/docs/api/") + options.links("https://docs.opencv.org/4.x/javadoc/") options.addStringOption("tag", "pre:a:Pre-Condition") + options.addBooleanOption("Xdoclint/package:" + + // TODO: v Document these, then remove them from the list + "-edu.wpi.first.hal," + + "-edu.wpi.first.hal.can," + + "-edu.wpi.first.hal.simulation," + + // TODO: ^ Document these, then remove them from the list + "-edu.wpi.first.math.proto," + + "-edu.wpi.first.math.controller.proto," + + "-edu.wpi.first.math.controller.struct," + + "-edu.wpi.first.math.geometry.proto," + + "-edu.wpi.first.math.geometry.struct," + + "-edu.wpi.first.math.kinematics.proto," + + "-edu.wpi.first.math.kinematics.struct," + + "-edu.wpi.first.math.system.plant.proto," + + "-edu.wpi.first.math.system.plant.struct," + + "-edu.wpi.first.math.trajectory.proto", true) options.addBooleanOption("Xdoclint:html,missing,reference,syntax", true) options.addBooleanOption('html5', true) options.linkSource(true) - dependsOn project(':hal').generateUsageReporting - dependsOn project(':ntcore').ntcoreGenerateJavaTypes dependsOn project(':wpilibj').generateJavaVersion - dependsOn project(':wpimath').generateNat source project(':apriltag').sourceSets.main.java source project(':cameraserver').sourceSets.main.java source project(':cscore').sourceSets.main.java @@ -254,23 +255,7 @@ task generateJavaDocs(type: Javadoc) { // The second argument '-quiet' is a hack. The one parameter // addStringOption() doesn't work, so we add '-quiet', which is added // anyway by gradle. See https://github.com/gradle/gradle/issues/2354. - // - // See JDK-8200363 (https://bugs.openjdk.java.net/browse/JDK-8200363) - // for information about the nonstandard -Xwerror option. JDK 15+ has - // -Werror. - options.addStringOption('Xwerror', '-quiet') - } - - if (JavaVersion.current().isJava11Compatible()) { - if (!JavaVersion.current().isJava12Compatible()) { - options.addBooleanOption('-no-module-directories', true) - } - doLast { - // This is a work-around for https://bugs.openjdk.java.net/browse/JDK-8211194. Can be removed once that issue is fixed on JDK's side - // Since JDK 11, package-list is missing from javadoc output files and superseded by element-list file, but a lot of external tools still need it - // Here we generate this file manually - new File(destinationDir, 'package-list').text = new File(destinationDir, 'element-list').text - } + options.addStringOption('Werror', '-quiet') } } diff --git a/fieldImages/CMakeLists.txt b/fieldImages/CMakeLists.txt index 35327907963..9f634ec32eb 100644 --- a/fieldImages/CMakeLists.txt +++ b/fieldImages/CMakeLists.txt @@ -3,7 +3,7 @@ project(fieldImages) include(CompileWarnings) include(GenResources) -if (WITH_JAVA) +if(WITH_JAVA) find_package(Java REQUIRED) include(UseJava) @@ -11,30 +11,45 @@ if (WITH_JAVA) set(CMAKE_JAVA_INCLUDE_PATH fieldImages.jar ${JACKSON_JARS}) file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java) - file(GLOB_RECURSE JAVA_RESOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} src/main/native/resources/*.json src/main/native/resources/*.png src/main/native/resources/*.jpg) - add_jar(field_images_jar SOURCES ${JAVA_SOURCES} RESOURCES NAMESPACE "edu/wpi/first/fields" ${JAVA_RESOURCES} OUTPUT_NAME fieldImages) + file( + GLOB_RECURSE JAVA_RESOURCES + RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} + src/main/native/resources/*.json + src/main/native/resources/*.png + src/main/native/resources/*.jpg + ) + add_jar( + field_images_jar + SOURCES ${JAVA_SOURCES} + RESOURCES + NAMESPACE "edu/wpi/first/fields" ${JAVA_RESOURCES} + OUTPUT_NAME fieldImages + ) get_property(FIELD_IMAGES_JAR_FILE TARGET field_images_jar PROPERTY JAR_FILE) install(FILES ${FIELD_IMAGES_JAR_FILE} DESTINATION "${java_lib_dest}") set_property(TARGET field_images_jar PROPERTY FOLDER "java") - endif() - generate_resources(src/main/native/resources/edu/wpi/first/fields generated/main/cpp FIELDS fields field_images_resources_src) - add_library(fieldImages src/main/native/cpp/fields.cpp ${field_images_resources_src}) set_target_properties(fieldImages PROPERTIES DEBUG_POSTFIX "d") set_property(TARGET fieldImages PROPERTY FOLDER "libraries") target_compile_features(fieldImages PUBLIC cxx_std_20) -if (MSVC) +if(MSVC) target_compile_options(fieldImages PUBLIC /bigobj) endif() wpilib_target_warnings(fieldImages) -target_include_directories(fieldImages PUBLIC - $ - $) +target_include_directories( + fieldImages + PUBLIC + $ + $ +) + +install(TARGETS fieldImages EXPORT fieldimages) +export(TARGETS fieldImages FILE fieldimages.cmake NAMESPACE fieldimages::) diff --git a/fieldImages/src/main/java/edu/wpi/fields/FieldConfig.java b/fieldImages/src/main/java/edu/wpi/fields/FieldConfig.java index f33ddca6dc7..d8752c64b98 100644 --- a/fieldImages/src/main/java/edu/wpi/fields/FieldConfig.java +++ b/fieldImages/src/main/java/edu/wpi/fields/FieldConfig.java @@ -40,12 +40,10 @@ public static class Corners { public FieldConfig() {} - @SuppressWarnings("deprecation") public URL getImageUrl() { return getClass().getResource(Fields.kBaseResourceDir + m_fieldImage); } - @SuppressWarnings("deprecation") public InputStream getImageAsStream() { return getClass().getResourceAsStream(Fields.kBaseResourceDir + m_fieldImage); } diff --git a/fieldImages/src/main/java/edu/wpi/fields/Fields.java b/fieldImages/src/main/java/edu/wpi/fields/Fields.java index 119415edefc..a92cfb0f5c3 100644 --- a/fieldImages/src/main/java/edu/wpi/fields/Fields.java +++ b/fieldImages/src/main/java/edu/wpi/fields/Fields.java @@ -15,12 +15,13 @@ public enum Fields { k2021GalacticSearchB("2021-galacticsearchb.json"), k2021Slalom("2021-slalompath.json"), k2022RapidReact("2022-rapidreact.json"), - k2023ChargedUp("2023-chargedup.json"); + k2023ChargedUp("2023-chargedup.json"), + k2024Crescendo("2024-crescendo.json"); public static final String kBaseResourceDir = "/edu/wpi/first/fields/"; /** Alias to the current game. */ - public static final Fields kDefaultField = k2023ChargedUp; + public static final Fields kDefaultField = k2024Crescendo; public final String m_resourceFile; diff --git a/fieldImages/src/main/native/cpp/fields.cpp b/fieldImages/src/main/native/cpp/fields.cpp index 4f79e6bf775..6fd6af09366 100644 --- a/fieldImages/src/main/native/cpp/fields.cpp +++ b/fieldImages/src/main/native/cpp/fields.cpp @@ -15,10 +15,13 @@ #include "fields/2021-slalom.h" #include "fields/2022-rapidreact.h" #include "fields/2023-chargedup.h" +#include "fields/2024-crescendo.h" using namespace fields; static const Field kFields[] = { + {"2024 Crescendo", GetResource_2024_crescendo_json, + GetResource_2024_field_png}, {"2023 Charged Up", GetResource_2023_chargedup_json, GetResource_2023_field_png}, {"2022 Rapid React", GetResource_2022_rapidreact_json, diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandBase.cpp b/fieldImages/src/main/native/include/fields/2024-crescendo.h similarity index 52% rename from wpilibNewCommands/src/main/native/cpp/frc2/command/CommandBase.cpp rename to fieldImages/src/main/native/include/fields/2024-crescendo.h index 7e2fad1a9fd..11947efa5e2 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandBase.cpp +++ b/fieldImages/src/main/native/include/fields/2024-crescendo.h @@ -2,4 +2,11 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -#include "frc2/command/CommandBase.h" +#pragma once + +#include + +namespace fields { +std::string_view GetResource_2024_crescendo_json(); +std::string_view GetResource_2024_field_png(); +} // namespace fields diff --git a/fieldImages/src/main/native/resources/edu/wpi/first/fields/2024-crescendo.json b/fieldImages/src/main/native/resources/edu/wpi/first/fields/2024-crescendo.json new file mode 100644 index 00000000000..8a601a2acdd --- /dev/null +++ b/fieldImages/src/main/native/resources/edu/wpi/first/fields/2024-crescendo.json @@ -0,0 +1,19 @@ +{ + "game": "Crescendo", + "field-image": "2024-field.png", + "field-corners": { + "top-left": [ + 150, + 79 + ], + "bottom-right": [ + 2961, + 1476 + ] + }, + "field-size": [ + 54.27083, + 26.9375 + ], + "field-unit": "foot" +} diff --git a/fieldImages/src/main/native/resources/edu/wpi/first/fields/2024-field.png b/fieldImages/src/main/native/resources/edu/wpi/first/fields/2024-field.png new file mode 100644 index 00000000000..a2a7665f728 Binary files /dev/null and b/fieldImages/src/main/native/resources/edu/wpi/first/fields/2024-field.png differ diff --git a/glass/CMakeLists.txt b/glass/CMakeLists.txt index b949fc00fe5..1786361b96e 100644 --- a/glass/CMakeLists.txt +++ b/glass/CMakeLists.txt @@ -18,11 +18,15 @@ set_property(TARGET libglass PROPERTY FOLDER "libraries") wpilib_target_warnings(libglass) target_link_libraries(libglass PUBLIC wpigui wpimath wpiutil fieldImages) -target_include_directories(libglass PUBLIC - $ - $) +target_include_directories( + libglass + PUBLIC + $ + $ +) install(TARGETS libglass EXPORT libglass) +export(TARGETS libglass FILE libglass.cmake NAMESPACE libglass::) install(DIRECTORY src/lib/native/include/ DESTINATION "${include_dest}/glass") # @@ -39,11 +43,15 @@ set_property(TARGET libglassnt PROPERTY FOLDER "libraries") wpilib_target_warnings(libglassnt) target_link_libraries(libglassnt PUBLIC ntcore libglass) -target_include_directories(libglassnt PUBLIC - $ - $) +target_include_directories( + libglassnt + PUBLIC + $ + $ +) install(TARGETS libglassnt EXPORT libglassnt) +export(TARGETS libglassnt FILE libglassnt.cmake NAMESPACE libglassnt::) install(DIRECTORY src/libnt/native/include/ DESTINATION "${include_dest}/glass") # @@ -55,7 +63,7 @@ generate_resources(src/app/native/resources generated/app/cpp GLASS glass glass_ file(GLOB glass_src src/app/native/cpp/*.cpp ${CMAKE_CURRENT_BINARY_DIR}/WPILibVersion.cpp) -if (WIN32) +if(WIN32) set(glass_rc src/app/native/win/glass.rc) elseif(APPLE) set(MACOSX_BUNDLE_ICON_FILE glass.icns) @@ -68,18 +76,8 @@ wpilib_link_macos_gui(glass) wpilib_target_warnings(glass) target_link_libraries(glass libglassnt libglass) -if (WIN32) +if(WIN32) set_target_properties(glass PROPERTIES WIN32_EXECUTABLE YES) elseif(APPLE) set_target_properties(glass PROPERTIES MACOSX_BUNDLE YES OUTPUT_NAME "Glass") endif() - -#if (MSVC OR FLAT_INSTALL_WPILIB) -# set (wpigui_config_dir ${wpilib_dest}) -#else() -# set (wpigui_config_dir share/wpigui) -#endif() - -#configure_file(wpigui-config.cmake.in ${CMAKE_BINARY_DIR}/wpigui-config.cmake ) -#install(FILES ${CMAKE_BINARY_DIR}/wpigui-config.cmake DESTINATION ${wpigui_config_dir}) -#install(EXPORT wpigui DESTINATION ${wpigui_config_dir}) diff --git a/glass/publish.gradle b/glass/publish.gradle index 0797fa15ef6..f7c59716d65 100644 --- a/glass/publish.gradle +++ b/glass/publish.gradle @@ -97,8 +97,6 @@ model { into '/' } - from(applicationPath) - if (binary.targetPlatform.operatingSystem.isWindows()) { def exePath = binary.executable.file.absolutePath exePath = exePath.substring(0, exePath.length() - 4) @@ -149,10 +147,13 @@ model { // Reset the application path if we are creating a bundle. applicationPath = file("$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name") + task.from(applicationPath) project.build.dependsOn bundleTask bundleTask.dependsOn binary.tasks.link task.dependsOn(bundleTask) + } else { + task.from(applicationPath) } task.dependsOn binary.tasks.link diff --git a/glass/src/app/generate/WPILibVersion.cpp.in b/glass/src/app/generate/WPILibVersion.cpp.in index b0a44905207..cfe24411588 100644 --- a/glass/src/app/generate/WPILibVersion.cpp.in +++ b/glass/src/app/generate/WPILibVersion.cpp.in @@ -1,4 +1,4 @@ -/* +/** * Autogenerated file! Do not manually edit this file. This version is regenerated * any time the publish task is run, or when this file is deleted. */ diff --git a/glass/src/app/native/cpp/main.cpp b/glass/src/app/native/cpp/main.cpp index 0b3473c15cd..ec0c2c0ddd6 100644 --- a/glass/src/app/native/cpp/main.cpp +++ b/glass/src/app/native/cpp/main.cpp @@ -96,7 +96,7 @@ static void NtInitialize() { auto inst = nt::GetDefaultInstance(); auto poller = nt::CreateListenerPoller(inst); nt::AddPolledListener(poller, inst, NT_EVENT_CONNECTION | NT_EVENT_IMMEDIATE); - nt::AddPolledLogger(poller, 0, 100); + nt::AddPolledLogger(poller, NT_LOG_INFO, 100); gui::AddEarlyExecute([inst, poller] { auto win = gui::GetSystemWindow(); if (!win) { diff --git a/glass/src/lib/native/cpp/Context.cpp b/glass/src/lib/native/cpp/Context.cpp index 1213bf438ff..5adcd943bb1 100644 --- a/glass/src/lib/native/cpp/Context.cpp +++ b/glass/src/lib/native/cpp/Context.cpp @@ -178,8 +178,6 @@ static bool LoadStorageRootImpl(Context* ctx, const std::string& filename, static bool LoadStorageImpl(Context* ctx, std::string_view dir, std::string_view name) { - WorkspaceResetImpl(); - bool rv = true; for (auto&& root : ctx->storageRoots) { std::string filename; @@ -421,6 +419,7 @@ std::string glass::GetStorageDir() { bool glass::LoadStorage(std::string_view dir) { SaveStorage(); SetStorageDir(dir); + WorkspaceResetImpl(); LoadWindowStorageImpl((fs::path{gContext->storageLoadDir} / fmt::format("{}-window.json", gContext->storageName)) .string()); diff --git a/glass/src/lib/native/cpp/Window.cpp b/glass/src/lib/native/cpp/Window.cpp index 32c7a2104da..64b043ffb1e 100644 --- a/glass/src/lib/native/cpp/Window.cpp +++ b/glass/src/lib/native/cpp/Window.cpp @@ -4,9 +4,11 @@ #include "glass/Window.h" +#include + +#include #include #include -#include #include "glass/Context.h" #include "glass/Storage.h" @@ -55,15 +57,14 @@ void Window::Display() { ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, m_padding); } - char label[128]; + std::string label; if (m_name.empty()) { - wpi::format_to_n_c_str(label, sizeof(label), "{}###{}", m_defaultName, - m_id); + label = fmt::format("{}###{}", m_defaultName, m_id); } else { - wpi::format_to_n_c_str(label, sizeof(label), "{}###{}", m_name, m_id); + label = fmt::format("{}###{}", m_name, m_id); } - if (Begin(label, &m_visible, m_flags)) { + if (Begin(label.c_str(), &m_visible, m_flags)) { if (m_renamePopupEnabled || m_view->HasSettings()) { bool isClicked = (ImGui::IsMouseReleased(ImGuiMouseButton_Right) && ImGui::IsItemHovered()); diff --git a/glass/src/lib/native/cpp/WindowManager.cpp b/glass/src/lib/native/cpp/WindowManager.cpp index 333dad4bc51..8e76b5f87a4 100644 --- a/glass/src/lib/native/cpp/WindowManager.cpp +++ b/glass/src/lib/native/cpp/WindowManager.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include "glass/Context.h" @@ -31,7 +32,7 @@ Window* WindowManager::AddWindow(std::string_view id, return nullptr; } if (win->HasView()) { - fmt::print(stderr, "GUI: ignoring duplicate window '{}'\n", id); + wpi::print(stderr, "GUI: ignoring duplicate window '{}'\n", id); return nullptr; } win->SetView(MakeFunctionView(std::move(display))); @@ -46,7 +47,7 @@ Window* WindowManager::AddWindow(std::string_view id, return nullptr; } if (win->HasView()) { - fmt::print(stderr, "GUI: ignoring duplicate window '{}'\n", id); + wpi::print(stderr, "GUI: ignoring duplicate window '{}'\n", id); return nullptr; } win->SetView(std::move(view)); @@ -61,7 +62,7 @@ Window* WindowManager::GetOrAddWindow(std::string_view id, bool duplicateOk, [](const auto& elem, std::string_view s) { return elem->GetId() < s; }); if (it != m_windows.end() && (*it)->GetId() == id) { if (!duplicateOk) { - fmt::print(stderr, "GUI: ignoring duplicate window '{}'\n", id); + wpi::print(stderr, "GUI: ignoring duplicate window '{}'\n", id); return nullptr; } return it->get(); diff --git a/glass/src/lib/native/cpp/other/FMS.cpp b/glass/src/lib/native/cpp/other/FMS.cpp index 67c3f8c904e..4e702e5b481 100644 --- a/glass/src/lib/native/cpp/other/FMS.cpp +++ b/glass/src/lib/native/cpp/other/FMS.cpp @@ -5,6 +5,7 @@ #include "glass/other/FMS.h" #include +#include #include #include "glass/DataSource.h" @@ -14,7 +15,7 @@ using namespace glass; static const char* stations[] = {"Invalid", "Red 1", "Red 2", "Red 3", "Blue 1", "Blue 2", "Blue 3"}; -void glass::DisplayFMS(FMSModel* model) { +void glass::DisplayFMS(FMSModel* model, bool editableDsAttached) { if (!model->Exists() || model->IsReadOnly()) { return DisplayFMSReadOnly(model); } @@ -31,10 +32,17 @@ void glass::DisplayFMS(FMSModel* model) { // DS Attached if (auto data = model->GetDsAttachedData()) { bool val = data->GetValue(); - if (ImGui::Checkbox("DS Attached", &val)) { - model->SetDsAttached(val); + if (editableDsAttached) { + if (ImGui::Checkbox("DS Attached", &val)) { + model->SetDsAttached(val); + } + data->EmitDrag(); + } else { + ImGui::Selectable("DS Attached: "); + data->EmitDrag(); + ImGui::SameLine(); + ImGui::TextUnformatted(val ? "Yes" : "No"); } - data->EmitDrag(); } // Alliance Station @@ -51,8 +59,7 @@ void glass::DisplayFMS(FMSModel* model) { if (auto data = model->GetMatchTimeData()) { double val = data->GetValue(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); - if (ImGui::InputDouble("Match Time", &val, 0, 0, "%.1f", - ImGuiInputTextFlags_EnterReturnsTrue)) { + if (ImGui::InputDouble("Match Time", &val, 0, 0, "%.1f")) { model->SetMatchTime(val); } data->EmitDrag(); @@ -71,16 +78,12 @@ void glass::DisplayFMS(FMSModel* model) { } // Game Specific Message - // make buffer full 64 width, null terminated, for editability - wpi::SmallString<64> gameSpecificMessage; - model->GetGameSpecificMessage(gameSpecificMessage); - gameSpecificMessage.resize(63); - gameSpecificMessage.push_back('\0'); + wpi::SmallString<64> gameSpecificMessageBuf; + std::string gameSpecificMessage{ + model->GetGameSpecificMessage(gameSpecificMessageBuf)}; ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); - if (ImGui::InputText("Game Specific", gameSpecificMessage.data(), - gameSpecificMessage.size(), - ImGuiInputTextFlags_EnterReturnsTrue)) { - model->SetGameSpecificMessage(gameSpecificMessage.data()); + if (ImGui::InputText("Game Specific", &gameSpecificMessage)) { + model->SetGameSpecificMessage(gameSpecificMessage); } } @@ -144,9 +147,10 @@ void glass::DisplayFMSReadOnly(FMSModel* model) { } } - wpi::SmallString<64> gameSpecificMessage; - model->GetGameSpecificMessage(gameSpecificMessage); - ImGui::Text("Game Specific: %s", exists ? gameSpecificMessage.c_str() : "?"); + wpi::SmallString<64> gameSpecificMessageBuf; + std::string_view gameSpecificMessage = + model->GetGameSpecificMessage(gameSpecificMessageBuf); + ImGui::Text("Game Specific: %s", exists ? gameSpecificMessage.data() : "?"); if (!exists) { ImGui::PopStyleColor(); diff --git a/glass/src/lib/native/cpp/other/Field2D.cpp b/glass/src/lib/native/cpp/other/Field2D.cpp index a99da09f226..be6cca6485f 100644 --- a/glass/src/lib/native/cpp/other/Field2D.cpp +++ b/glass/src/lib/native/cpp/other/Field2D.cpp @@ -12,7 +12,6 @@ #include #include -#include #include #include #include @@ -30,6 +29,7 @@ #include #include #include +#include #include #include "glass/Context.h" @@ -222,8 +222,8 @@ class ObjectInfo { class FieldInfo { public: - static constexpr auto kDefaultWidth = 15.98_m; - static constexpr auto kDefaultHeight = 8.21_m; + static constexpr auto kDefaultWidth = 16.541052_m; + static constexpr auto kDefaultHeight = 8.211_m; explicit FieldInfo(Storage& storage); @@ -343,7 +343,7 @@ static bool InputPose(frc::Pose2d* pose) { } FieldInfo::FieldInfo(Storage& storage) - : m_builtin{storage.GetString("builtin")}, + : m_builtin{storage.GetString("builtin", "2024 Crescendo")}, m_filename{storage.GetString("image")}, m_width{storage.GetFloat("width", kDefaultWidth.to())}, m_height{storage.GetFloat("height", kDefaultHeight.to())}, @@ -450,7 +450,7 @@ bool FieldInfo::LoadJson(std::span is, std::string_view filename) { try { j = wpi::json::parse(is); } catch (const wpi::json::parse_error& e) { - fmt::print(stderr, "GUI: JSON: could not parse: {}\n", e.what()); + wpi::print(stderr, "GUI: JSON: could not parse: {}\n", e.what()); return false; } @@ -465,7 +465,7 @@ bool FieldInfo::LoadJson(std::span is, std::string_view filename) { try { image = j.at("field-image").get(); } catch (const wpi::json::exception& e) { - fmt::print(stderr, "GUI: JSON: could not read field-image: {}\n", e.what()); + wpi::print(stderr, "GUI: JSON: could not read field-image: {}\n", e.what()); return false; } @@ -477,7 +477,7 @@ bool FieldInfo::LoadJson(std::span is, std::string_view filename) { bottom = j.at("field-corners").at("bottom-right").at(1).get(); right = j.at("field-corners").at("bottom-right").at(0).get(); } catch (const wpi::json::exception& e) { - fmt::print(stderr, "GUI: JSON: could not read field-corners: {}\n", + wpi::print(stderr, "GUI: JSON: could not read field-corners: {}\n", e.what()); return false; } @@ -489,7 +489,7 @@ bool FieldInfo::LoadJson(std::span is, std::string_view filename) { width = j.at("field-size").at(0).get(); height = j.at("field-size").at(1).get(); } catch (const wpi::json::exception& e) { - fmt::print(stderr, "GUI: JSON: could not read field-size: {}\n", e.what()); + wpi::print(stderr, "GUI: JSON: could not read field-size: {}\n", e.what()); return false; } @@ -498,7 +498,7 @@ bool FieldInfo::LoadJson(std::span is, std::string_view filename) { try { unit = j.at("field-unit").get(); } catch (const wpi::json::exception& e) { - fmt::print(stderr, "GUI: JSON: could not read field-unit: {}\n", e.what()); + wpi::print(stderr, "GUI: JSON: could not read field-unit: {}\n", e.what()); return false; } @@ -508,6 +508,16 @@ bool FieldInfo::LoadJson(std::span is, std::string_view filename) { height = units::convert(height); } + // check scaling + int fieldWidth = m_right - m_left; + int fieldHeight = m_bottom - m_top; + if (std::abs((fieldWidth / width) - (fieldHeight / height)) > 0.3) { + wpi::print(stderr, + "GUI: Field X and Y scaling substantially different: " + "xscale={} yscale={}\n", + (fieldWidth / width), (fieldHeight / height)); + } + if (!filename.empty()) { // the image filename is relative to the json file auto pathname = fs::path{filename}.replace_filename(image).string(); @@ -543,7 +553,7 @@ void FieldInfo::LoadJsonFile(std::string_view jsonfile) { } bool FieldInfo::LoadImageImpl(const std::string& fn) { - fmt::print("GUI: loading field image '{}'\n", fn); + wpi::print("GUI: loading field image '{}'\n", fn); auto texture = gui::Texture::CreateFromFile(fn.c_str()); if (!texture) { std::puts("GUI: could not read field image"); @@ -560,23 +570,29 @@ FieldFrameData FieldInfo::GetFrameData(ImVec2 min, ImVec2 max) const { // fit the image into the window if (m_texture && m_imageHeight != 0 && m_imageWidth != 0) { gui::MaxFit(&min, &max, m_imageWidth, m_imageHeight); + } else { + gui::MaxFit(&min, &max, m_width, m_height); } FieldFrameData ffd; ffd.imageMin = min; ffd.imageMax = max; - // size down the box by the image corners (if any) - if (m_bottom > 0 && m_right > 0) { - min.x += m_left * (max.x - min.x) / m_imageWidth; - min.y += m_top * (max.y - min.y) / m_imageHeight; - max.x -= (m_imageWidth - m_right) * (max.x - min.x) / m_imageWidth; - max.y -= (m_imageHeight - m_bottom) * (max.y - min.y) / m_imageHeight; + if (m_bottom > 0 && m_right > 0 && m_imageWidth != 0) { + // size down the box by the image corners + float scale = (max.x - min.x) / m_imageWidth; + min.x += m_left * scale; + min.y += m_top * scale; + max.x -= (m_imageWidth - m_right) * scale; + max.y -= (m_imageHeight - m_bottom) * scale; + } else if ((max.x - min.x) > 40 && (max.y - min.y > 40)) { + // ensure there's some padding + min.x += 20; + max.x -= 20; + min.y += 20; + max.y -= 20; } - // draw the field "active area" as a yellow boundary box - gui::MaxFit(&min, &max, m_width, m_height); - ffd.min = min; ffd.max = max; ffd.scale = (max.x - min.x) / m_width; @@ -729,7 +745,7 @@ void ObjectInfo::LoadImage() { } bool ObjectInfo::LoadImageImpl(const std::string& fn) { - fmt::print("GUI: loading object image '{}'\n", fn); + wpi::print("GUI: loading object image '{}'\n", fn); auto texture = gui::Texture::CreateFromFile(fn.c_str()); if (!texture) { std::fputs("GUI: could not read object image\n", stderr); diff --git a/glass/src/lib/native/cpp/other/Mechanism2D.cpp b/glass/src/lib/native/cpp/other/Mechanism2D.cpp index 722585b2e4d..0592910d049 100644 --- a/glass/src/lib/native/cpp/other/Mechanism2D.cpp +++ b/glass/src/lib/native/cpp/other/Mechanism2D.cpp @@ -11,7 +11,6 @@ #include #include -#include #include #include #include @@ -24,6 +23,7 @@ #include #include #include +#include #include #include "glass/Context.h" @@ -126,7 +126,7 @@ void BackgroundInfo::LoadImage() { } bool BackgroundInfo::LoadImageImpl(const std::string& fn) { - fmt::print("GUI: loading background image '{}'\n", fn); + wpi::print("GUI: loading background image '{}'\n", fn); auto texture = gui::Texture::CreateFromFile(fn.c_str()); if (!texture) { std::puts("GUI: could not read background image"); diff --git a/glass/src/lib/native/cpp/other/PIDController.cpp b/glass/src/lib/native/cpp/other/PIDController.cpp index 3c83b115306..8aa5e1f99d1 100644 --- a/glass/src/lib/native/cpp/other/PIDController.cpp +++ b/glass/src/lib/native/cpp/other/PIDController.cpp @@ -29,6 +29,16 @@ void glass::DisplayPIDController(PIDControllerModel* m) { callback(*v); } }; + // Workaround to allow for the input of inf, -inf, and nan + auto createTuningParameterNoFilter = + [flag](const char* name, double* v, + std::function callback) { + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 4); + if (ImGui::InputScalar(name, ImGuiDataType_Double, v, NULL, NULL, + "%.3f", flag)) { + callback(*v); + } + }; if (auto p = m->GetPData()) { double value = p->GetValue(); @@ -47,6 +57,11 @@ void glass::DisplayPIDController(PIDControllerModel* m) { createTuningParameter("Setpoint", &value, [=](auto v) { m->SetSetpoint(v); }); } + if (auto s = m->GetIZoneData()) { + double value = s->GetValue(); + createTuningParameterNoFilter("IZone", &value, + [=](auto v) { m->SetIZone(v); }); + } } else { ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(96, 96, 96, 255)); ImGui::Text("Unknown PID Controller"); diff --git a/glass/src/lib/native/cpp/other/ProfiledPIDController.cpp b/glass/src/lib/native/cpp/other/ProfiledPIDController.cpp new file mode 100644 index 00000000000..8113c8cf1fa --- /dev/null +++ b/glass/src/lib/native/cpp/other/ProfiledPIDController.cpp @@ -0,0 +1,69 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "glass/other/ProfiledPIDController.h" + +#include + +#include + +#include "glass/Context.h" +#include "glass/DataSource.h" + +using namespace glass; + +void glass::DisplayProfiledPIDController(ProfiledPIDControllerModel* m) { + if (auto name = m->GetName()) { + ImGui::Text("%s", name); + ImGui::Separator(); + } + + if (m->Exists()) { + auto flag = m->IsReadOnly() ? ImGuiInputTextFlags_ReadOnly + : ImGuiInputTextFlags_None; + auto createTuningParameter = [flag](const char* name, double* v, + std::function callback) { + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 4); + if (ImGui::InputDouble(name, v, 0.0, 0.0, "%.3f", flag)) { + callback(*v); + } + }; + // Workaround to allow for the input of inf, -inf, and nan + auto createTuningParameterNoFilter = + [flag](const char* name, double* v, + std::function callback) { + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 4); + if (ImGui::InputScalar(name, ImGuiDataType_Double, v, NULL, NULL, + "%.3f", flag)) { + callback(*v); + } + }; + + if (auto p = m->GetPData()) { + double value = p->GetValue(); + createTuningParameter("P", &value, [=](auto v) { m->SetP(v); }); + } + if (auto i = m->GetIData()) { + double value = i->GetValue(); + createTuningParameter("I", &value, [=](auto v) { m->SetI(v); }); + } + if (auto d = m->GetDData()) { + double value = d->GetValue(); + createTuningParameter("D", &value, [=](auto v) { m->SetD(v); }); + } + if (auto s = m->GetGoalData()) { + double value = s->GetValue(); + createTuningParameter("Goal", &value, [=](auto v) { m->SetGoal(v); }); + } + if (auto s = m->GetIZoneData()) { + double value = s->GetValue(); + createTuningParameterNoFilter("IZone", &value, + [=](auto v) { m->SetIZone(v); }); + } + } else { + ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(96, 96, 96, 255)); + ImGui::Text("Unknown PID Controller"); + ImGui::PopStyleColor(); + } +} diff --git a/glass/src/lib/native/cpp/support/DataLogReaderThread.cpp b/glass/src/lib/native/cpp/support/DataLogReaderThread.cpp new file mode 100644 index 00000000000..dc68b8968ba --- /dev/null +++ b/glass/src/lib/native/cpp/support/DataLogReaderThread.cpp @@ -0,0 +1,124 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "glass/support/DataLogReaderThread.h" + +#include + +#include +#include + +using namespace glass; + +DataLogReaderThread::~DataLogReaderThread() { + if (m_thread.joinable()) { + m_active = false; + m_thread.join(); + } +} + +void DataLogReaderThread::ReadMain() { + wpi::SmallDenseMap< + int, std::pair>, 8> + schemaEntries; + + for (auto recordIt = m_reader.begin(), recordEnd = m_reader.end(); + recordIt != recordEnd; ++recordIt) { + auto& record = *recordIt; + if (!m_active) { + break; + } + ++m_numRecords; + if (record.IsStart()) { + DataLogReaderEntry data; + if (record.GetStartData(&data)) { + std::scoped_lock lock{m_mutex}; + auto& entryPtr = m_entriesById[data.entry]; + if (entryPtr) { + wpi::print("...DUPLICATE entry ID, overriding\n"); + } + auto [it, isNew] = m_entriesByName.emplace(data.name, data); + if (isNew) { + it->second.ranges.emplace_back(recordIt, recordEnd); + } + entryPtr = &it->second; + if (data.type == "structschema" || + data.type == "proto:FileDescriptorProto") { + schemaEntries.try_emplace(data.entry, entryPtr, + std::span{}); + } + sigEntryAdded(data); + } else { + wpi::print("Start(INVALID)\n"); + } + } else if (record.IsFinish()) { + int entry; + if (record.GetFinishEntry(&entry)) { + std::scoped_lock lock{m_mutex}; + auto it = m_entriesById.find(entry); + if (it == m_entriesById.end()) { + wpi::print("...ID not found\n"); + } else { + it->second->ranges.back().m_end = recordIt; + m_entriesById.erase(it); + } + } else { + wpi::print("Finish(INVALID)\n"); + } + } else if (record.IsSetMetadata()) { + wpi::log::MetadataRecordData data; + if (record.GetSetMetadataData(&data)) { + std::scoped_lock lock{m_mutex}; + auto it = m_entriesById.find(data.entry); + if (it == m_entriesById.end()) { + wpi::print("...ID not found\n"); + } else { + it->second->metadata = data.metadata; + } + } else { + wpi::print("SetMetadata(INVALID)\n"); + } + } else if (record.IsControl()) { + wpi::print("Unrecognized control record\n"); + } else { + auto it = schemaEntries.find(record.GetEntry()); + if (it != schemaEntries.end()) { + it->second.second = record.GetRaw(); + } + } + } + + // build schema databases + for (auto&& schemaPair : schemaEntries) { + auto name = schemaPair.second.first->name; + auto data = schemaPair.second.second; + if (data.empty()) { + continue; + } + if (wpi::starts_with(name, "NT:")) { + name = wpi::drop_front(name, 3); + } + if (wpi::starts_with(name, "/.schema/struct:")) { + auto typeStr = wpi::drop_front(name, 16); + std::string_view schema{reinterpret_cast(data.data()), + data.size()}; + std::string err; + auto desc = m_structDb.Add(typeStr, schema, &err); + if (!desc) { + wpi::print("could not decode struct '{}' schema '{}': {}\n", name, + schema, err); + } + } else if (wpi::starts_with(name, "/.schema/proto:")) { + // protobuf descriptor handling + auto filename = wpi::drop_front(name, 15); + if (!m_protoDb.Add(filename, data)) { + wpi::print("could not decode protobuf '{}' filename '{}'\n", name, + filename); + } + } + } + + sigDone(); + m_done = true; +} diff --git a/glass/src/lib/native/cpp/support/ExpressionParser.cpp b/glass/src/lib/native/cpp/support/ExpressionParser.cpp new file mode 100644 index 00000000000..6522b3cf8be --- /dev/null +++ b/glass/src/lib/native/cpp/support/ExpressionParser.cpp @@ -0,0 +1,374 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "glass/support/ExpressionParser.h" + +#include +#include +#include + +#include +#include + +namespace glass::expression { + +enum class TokenType { + Number, + Add, + Subtract, + Multiply, + Divide, + Exponent, + OpenParen, + CloseParen, + + End, // Hit end of input + Error, // Invalid character found +}; + +struct Token { + TokenType type; + const char* str; + int strLen; + + explicit Token(TokenType type) : type(type), str(nullptr), strLen(0) {} + + Token(TokenType type, const char* str, int strLen) + : type(type), str(str), strLen(strLen) {} +}; + +class Lexer { + public: + explicit Lexer(const char* input, bool isInteger) + : input(input), isInteger(isInteger) {} + + Token NextToken() { + // Skip leading whitespace + startIdx = currentIdx; + while (std::isspace(input[startIdx])) { + startIdx++; + } + if (input[startIdx] == 0) { + return Token(TokenType::End); + } + currentIdx = startIdx; + + char c = input[currentIdx]; + currentIdx++; + switch (c) { + case '+': + return Token(TokenType::Add); + case '-': + return Token(TokenType::Subtract); + case '*': + return Token(TokenType::Multiply); + case '/': + return Token(TokenType::Divide); + case '^': + return Token(TokenType::Exponent); + case '(': + return Token(TokenType::OpenParen); + case ')': + return Token(TokenType::CloseParen); + default: + currentIdx--; + if (wpi::isDigit(c) || c == '.') { + return nextNumber(); + } + return Token(TokenType::Error, &input[currentIdx], 1); + } + } + + // Makes NextToken() return the same token as previously + void Repeat() { currentIdx = startIdx; } + + private: + const char* input; + bool isInteger; + int startIdx = 0, currentIdx = 0; + + Token nextNumber() { + // Read whole part + bool hasDigitsBeforeDecimal = false; + while (wpi::isDigit(input[currentIdx])) { + currentIdx++; + hasDigitsBeforeDecimal = true; + } + + // Read decimal part if it exists + if (input[currentIdx] == '.') { + // Integers can't have fractional part + if (isInteger) { + return Token(TokenType::Error, &input[currentIdx], 1); + } + + currentIdx++; + // Report a single '.' with no digits as an error + if (!hasDigitsBeforeDecimal && !wpi::isDigit(input[currentIdx])) { + // Report the decimal as the unexpected char + return Token(TokenType::Error, &input[currentIdx - 1], 1); + } + + while (wpi::isDigit(input[currentIdx])) { + currentIdx++; + } + + // Make sure the number has at most one decimal point + if (input[currentIdx] == '.') { + return Token(TokenType::Error, &input[currentIdx], 1); + } + } + + return Token(TokenType::Number, input + startIdx, currentIdx - startIdx); + } +}; + +enum class Operator { Add, Subtract, Multiply, Divide, Exponent, Negate, None }; + +Operator GetOperator(TokenType type) { + switch (type) { + case TokenType::Add: + return Operator::Add; + case TokenType::Subtract: + return Operator::Subtract; + case TokenType::Multiply: + return Operator::Multiply; + case TokenType::Divide: + return Operator::Divide; + case TokenType::Exponent: + return Operator::Exponent; + default: + return Operator::None; + } +} + +int OperatorPrecedence(Operator op) { + switch (op) { + case Operator::Add: + case Operator::Subtract: + return 1; + case Operator::Multiply: + case Operator::Divide: + return 2; + case Operator::Exponent: + return 3; + case Operator::Negate: + return 4; + case Operator::None: + return 0; + } + return 0; +} + +bool IsOperatorRightAssociative(Operator op) { + return op == Operator::Exponent || op == Operator::Negate; +} + +template +void ApplyOperator(std::stack& valStack, Operator op) { + V right = valStack.top(); + valStack.pop(); + V left = valStack.top(); + valStack.pop(); + + V val = 0; + switch (op) { + case Operator::Add: + val = left + right; + break; + case Operator::Subtract: + val = left - right; + break; + case Operator::Multiply: + val = left * right; + break; + case Operator::Divide: + val = left / right; + break; + case Operator::Exponent: + val = std::pow(left, right); + break; + case Operator::Negate: + val = -right; + break; + case Operator::None: + break; + } + + valStack.push(val); +} + +template +std::optional ValueFromString(std::string_view str); + +template <> +std::optional ValueFromString(std::string_view str) { + return wpi::parse_integer(str, 10); +} + +template <> +std::optional ValueFromString(std::string_view str) { + return wpi::parse_float(str); +} + +template <> +std::optional ValueFromString(std::string_view str) { + return wpi::parse_float(str); +} + +template +wpi::expected EvalAll(std::stack& operStack, + std::stack& valStack) { + while (!operStack.empty()) { + if (valStack.size() < 2) { + return wpi::unexpected("Missing operand"); + } + ApplyOperator(valStack, operStack.top()); + operStack.pop(); + } + if (valStack.empty()) { + return wpi::unexpected("No value"); + } + + // Intentionally leaves the result value on top of valStack so unmatched + // closing parentheses work + return valStack.top(); +} + +template +wpi::expected ParseExpr(Lexer& lexer, bool insideParen) { + std::stack operStack; + std::stack valStack; + + bool prevWasOp = true; + TokenType prevType = TokenType::Add; + + while (true) { + Token token = lexer.NextToken(); + + bool wasOp = false; + switch (token.type) { + case TokenType::End: + goto end; + case TokenType::Number: { + // Check for two numbers in a row (ex: "2 4"). Implicit multiplication + // is probably not what the user intended in this case, so give them an + // error. + if (prevType == TokenType::Number) { + return wpi::unexpected("Missing operator"); + } + + // Implicit multiplication. Ex: "2(4 + 5)" + if (!prevWasOp) { + operStack.push(Operator::Multiply); + } + + auto value = + ValueFromString(std::string_view(token.str, token.strLen)); + if (value) { + valStack.push(value.value()); + } else { + return wpi::unexpected("Invalid number"); + } + + break; + } + + case TokenType::OpenParen: { + // Implicit multiplication + if (!prevWasOp) { + operStack.push(Operator::Multiply); + } + + wpi::expected result = ParseExpr(lexer, true); + if (!result) { + return result; + } + valStack.push(result.value()); + + TokenType nextType = lexer.NextToken().type; + if (nextType != TokenType::CloseParen) { + if (nextType == TokenType::End) { + goto end; // Act as if closed at end of expression + } + return wpi::unexpected("Expected )"); + } + break; + } + + case TokenType::CloseParen: { + if (insideParen) { + lexer.Repeat(); + goto end; + } + + // Acts as if there was open paren at start of expression. EvalAll will + // clear both stacks, and leave the result value on top of valStack. + // This makes sure everything inside the parentheses is evaluated first + wpi::expected result = EvalAll(operStack, valStack); + if (!result) { + return result; + } + break; + } + + case TokenType::Error: + return wpi::unexpected(std::string("Unexpected character: ") + .append(token.str, token.strLen)); + + default: + Operator op = GetOperator(token.type); + if (op == Operator::None) { + lexer.Repeat(); + goto end; + } + if (op == Operator::Subtract && prevWasOp) { + op = Operator::Negate; + // Dummy left-hand side for negation + valStack.push(0.0); + } + wasOp = true; + + while (!operStack.empty()) { + Operator prevOp = operStack.top(); + + bool rightAssoc = IsOperatorRightAssociative(op); + int precedence = OperatorPrecedence(op); + int prevPrecedence = OperatorPrecedence(prevOp); + + if ((!rightAssoc && precedence == prevPrecedence) || + precedence < prevPrecedence) { + operStack.pop(); + if (valStack.size() < 2) { + return wpi::unexpected("Missing operand"); + } + ApplyOperator(valStack, prevOp); + } else { + break; + } + } + operStack.push(op); + break; + } + prevType = token.type; + prevWasOp = wasOp; + } + +// Reached the end of the expression +end: + return EvalAll(operStack, valStack); +} + +// expr is null-terminated string, as ImGui::inputText() uses +template +wpi::expected TryParseExpr(const char* expr) { + Lexer lexer(expr, std::is_integral_v); + return ParseExpr(lexer, false); +} + +template wpi::expected TryParseExpr(const char*); +template wpi::expected TryParseExpr(const char*); +template wpi::expected TryParseExpr(const char*); + +} // namespace glass::expression diff --git a/glass/src/lib/native/cpp/support/ExtraGuiWidgets.cpp b/glass/src/lib/native/cpp/support/ExtraGuiWidgets.cpp index dede4a0b7d4..9e09fc1b8ee 100644 --- a/glass/src/lib/native/cpp/support/ExtraGuiWidgets.cpp +++ b/glass/src/lib/native/cpp/support/ExtraGuiWidgets.cpp @@ -8,7 +8,14 @@ #include #include +#include +#include +#include + +#include + #include "glass/DataSource.h" +#include "glass/support/ExpressionParser.h" namespace glass { @@ -217,4 +224,70 @@ bool HamburgerButton(const ImGuiID id, const ImVec2 position) { return pressed; } +static const int kBufferSize = 256; + +struct InputExprState { + char inputBuffer[kBufferSize]; +}; + +static wpi::DenseMap exprStates; +// Shared string buffer for inactive inputs +static char previewBuffer[kBufferSize]; + +template +bool InputExpr(const char* label, V* v, const char* format, + ImGuiInputTextFlags flags) { + int id = ImGui::GetID(label); + + char* inputBuffer; + bool hasState = exprStates.contains(id); + if (hasState) { + InputExprState& state = exprStates[id]; + inputBuffer = state.inputBuffer; + } else { + inputBuffer = previewBuffer; +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-nonliteral" +#endif + // Preview stored value + std::snprintf(inputBuffer, kBufferSize, format, *v); +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + } + + bool changed = ImGui::InputText(label, inputBuffer, kBufferSize, flags); + bool active = ImGui::IsItemActive(); + + if (active || changed) { + InputExprState& state = exprStates[id]; + if (!hasState) { + // State was just created, copy in contents of preview buffer + std::strncpy(state.inputBuffer, previewBuffer, kBufferSize); + } + + // Attempt to parse current value + auto result = glass::expression::TryParseExpr(state.inputBuffer); + if (result) { + *v = result.value(); + } else if (active) { + ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "%s", + result.error().c_str()); + } + } + + // Don't need the state anymore if not editing + if (!active) { + exprStates.erase(id); + } + + return changed; +} + +template bool InputExpr(const char*, int64_t*, const char*, + ImGuiInputTextFlags); +template bool InputExpr(const char*, float*, const char*, ImGuiInputTextFlags); +template bool InputExpr(const char*, double*, const char*, ImGuiInputTextFlags); + } // namespace glass diff --git a/glass/src/lib/native/include/glass/other/FMS.h b/glass/src/lib/native/include/glass/other/FMS.h index 5970e93e229..f039c15a702 100644 --- a/glass/src/lib/native/include/glass/other/FMS.h +++ b/glass/src/lib/native/include/glass/other/FMS.h @@ -46,8 +46,9 @@ class FMSModel : public Model { * * @param matchTimeEnabled If not null, a checkbox is displayed for * "enable match time" linked to this value + * @param editableDsAttached If true, DS attached should be editable */ -void DisplayFMS(FMSModel* model); +void DisplayFMS(FMSModel* model, bool editableDsAttached); void DisplayFMSReadOnly(FMSModel* model); } // namespace glass diff --git a/glass/src/lib/native/include/glass/other/PIDController.h b/glass/src/lib/native/include/glass/other/PIDController.h index ab0dcb3ff6f..8c11c5914db 100644 --- a/glass/src/lib/native/include/glass/other/PIDController.h +++ b/glass/src/lib/native/include/glass/other/PIDController.h @@ -16,11 +16,13 @@ class PIDControllerModel : public Model { virtual DataSource* GetIData() = 0; virtual DataSource* GetDData() = 0; virtual DataSource* GetSetpointData() = 0; + virtual DataSource* GetIZoneData() = 0; virtual void SetP(double value) = 0; virtual void SetI(double value) = 0; virtual void SetD(double value) = 0; virtual void SetSetpoint(double value) = 0; + virtual void SetIZone(double value) = 0; }; void DisplayPIDController(PIDControllerModel* m); } // namespace glass diff --git a/glass/src/lib/native/include/glass/other/ProfiledPIDController.h b/glass/src/lib/native/include/glass/other/ProfiledPIDController.h new file mode 100644 index 00000000000..bebf3abb063 --- /dev/null +++ b/glass/src/lib/native/include/glass/other/ProfiledPIDController.h @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include "glass/Model.h" + +namespace glass { +class DataSource; +class ProfiledPIDControllerModel : public Model { + public: + virtual const char* GetName() const = 0; + + virtual DataSource* GetPData() = 0; + virtual DataSource* GetIData() = 0; + virtual DataSource* GetDData() = 0; + virtual DataSource* GetGoalData() = 0; + virtual DataSource* GetIZoneData() = 0; + + virtual void SetP(double value) = 0; + virtual void SetI(double value) = 0; + virtual void SetD(double value) = 0; + virtual void SetGoal(double value) = 0; + virtual void SetIZone(double value) = 0; +}; +void DisplayProfiledPIDController(ProfiledPIDControllerModel* m); +} // namespace glass diff --git a/glass/src/lib/native/include/glass/support/DataLogReaderThread.h b/glass/src/lib/native/include/glass/support/DataLogReaderThread.h new file mode 100644 index 00000000000..bcbc9623ef8 --- /dev/null +++ b/glass/src/lib/native/include/glass/support/DataLogReaderThread.h @@ -0,0 +1,101 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace glass { + +class DataLogReaderRange { + public: + DataLogReaderRange(wpi::log::DataLogReader::iterator begin, + wpi::log::DataLogReader::iterator end) + : m_begin{begin}, m_end{end} {} + + wpi::log::DataLogReader::iterator begin() const { return m_begin; } + wpi::log::DataLogReader::iterator end() const { return m_end; } + + wpi::log::DataLogReader::iterator m_begin; + wpi::log::DataLogReader::iterator m_end; +}; + +class DataLogReaderEntry : public wpi::log::StartRecordData { + public: + std::vector ranges; // ranges where this entry is valid +}; + +class DataLogReaderThread { + public: + explicit DataLogReaderThread(wpi::log::DataLogReader reader) + : m_reader{std::move(reader)}, m_thread{[this] { ReadMain(); }} {} + ~DataLogReaderThread(); + + bool IsDone() const { return m_done; } + std::string_view GetBufferIdentifier() const { + return m_reader.GetBufferIdentifier(); + } + unsigned int GetNumRecords() const { return m_numRecords; } + unsigned int GetNumEntries() const { + std::scoped_lock lock{m_mutex}; + return m_entriesByName.size(); + } + + // Passes Entry& to func + template + void ForEachEntryName(T&& func) { + std::scoped_lock lock{m_mutex}; + for (auto&& kv : m_entriesByName) { + func(kv.second); + } + } + + const DataLogReaderEntry* GetEntry(std::string_view name) const { + std::scoped_lock lock{m_mutex}; + auto it = m_entriesByName.find(name); + if (it == m_entriesByName.end()) { + return nullptr; + } + return &it->second; + } + + wpi::StructDescriptorDatabase& GetStructDatabase() { return m_structDb; } + wpi::ProtobufMessageDatabase& GetProtobufDatabase() { return m_protoDb; } + + const wpi::log::DataLogReader& GetReader() const { return m_reader; } + + // note: these are called on separate thread + wpi::sig::Signal_mt sigEntryAdded; + wpi::sig::Signal_mt<> sigDone; + + private: + void ReadMain(); + + wpi::log::DataLogReader m_reader; + mutable wpi::mutex m_mutex; + std::atomic_bool m_active{true}; + std::atomic_bool m_done{false}; + std::atomic m_numRecords{0}; + std::map> m_entriesByName; + wpi::DenseMap m_entriesById; + wpi::StructDescriptorDatabase m_structDb; + wpi::ProtobufMessageDatabase m_protoDb; + std::thread m_thread; +}; + +} // namespace glass diff --git a/glass/src/lib/native/include/glass/support/ExpressionParser.h b/glass/src/lib/native/include/glass/support/ExpressionParser.h new file mode 100644 index 00000000000..ec03a93fb0f --- /dev/null +++ b/glass/src/lib/native/include/glass/support/ExpressionParser.h @@ -0,0 +1,22 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include + +#include + +#include + +namespace glass::expression { + +template +wpi::expected TryParseExpr(const char* expr); + +extern template wpi::expected TryParseExpr(const char*); +extern template wpi::expected TryParseExpr(const char*); +extern template wpi::expected TryParseExpr(const char*); + +} // namespace glass::expression diff --git a/glass/src/lib/native/include/glass/support/ExtraGuiWidgets.h b/glass/src/lib/native/include/glass/support/ExtraGuiWidgets.h index d56f3426f75..ec4f20ab925 100644 --- a/glass/src/lib/native/include/glass/support/ExtraGuiWidgets.h +++ b/glass/src/lib/native/include/glass/support/ExtraGuiWidgets.h @@ -4,6 +4,8 @@ #pragma once +#include + #define IMGUI_DEFINE_MATH_OPERATORS #include @@ -99,4 +101,17 @@ bool HeaderDeleteButton(const char* label); */ bool HamburgerButton(const ImGuiID id, const ImVec2 position); +/** + * Edit a value with expression input. Similar to ImGui::InputScalar() + */ +template +bool InputExpr(const char* label, V* v, const char* format, + ImGuiInputTextFlags flags = 0); +extern template bool InputExpr(const char*, int64_t*, const char*, + ImGuiInputTextFlags); +extern template bool InputExpr(const char*, float*, const char*, + ImGuiInputTextFlags); +extern template bool InputExpr(const char*, double*, const char*, + ImGuiInputTextFlags); + } // namespace glass diff --git a/glass/src/libnt/native/cpp/NTPIDController.cpp b/glass/src/libnt/native/cpp/NTPIDController.cpp index 1dde27d6fdc..9796f6d4471 100644 --- a/glass/src/libnt/native/cpp/NTPIDController.cpp +++ b/glass/src/libnt/native/cpp/NTPIDController.cpp @@ -23,10 +23,12 @@ NTPIDControllerModel::NTPIDControllerModel(nt::NetworkTableInstance inst, m_d{inst.GetDoubleTopic(fmt::format("{}/d", path)).GetEntry(0)}, m_setpoint{ inst.GetDoubleTopic(fmt::format("{}/setpoint", path)).GetEntry(0)}, + m_iZone{inst.GetDoubleTopic(fmt::format("{}/izone", path)).GetEntry(0)}, m_pData{fmt::format("NTPIDCtrlP:{}", path)}, m_iData{fmt::format("NTPIDCtrlI:{}", path)}, m_dData{fmt::format("NTPIDCtrlD:{}", path)}, m_setpointData{fmt::format("NTPIDCtrlStpt:{}", path)}, + m_iZoneData{fmt::format("NTPIDCtrlIZone:{}", path)}, m_nameValue{wpi::rsplit(path, '/').second} {} void NTPIDControllerModel::SetP(double value) { @@ -44,6 +46,9 @@ void NTPIDControllerModel::SetD(double value) { void NTPIDControllerModel::SetSetpoint(double value) { m_setpoint.Set(value); } +void NTPIDControllerModel::SetIZone(double value) { + m_iZone.Set(value); +} void NTPIDControllerModel::Update() { for (auto&& v : m_name.ReadQueue()) { @@ -61,6 +66,9 @@ void NTPIDControllerModel::Update() { for (auto&& v : m_setpoint.ReadQueue()) { m_setpointData.SetValue(v.value, v.time); } + for (auto&& v : m_iZone.ReadQueue()) { + m_iZoneData.SetValue(v.value, v.time); + } for (auto&& v : m_controllable.ReadQueue()) { m_controllableValue = v.value; } diff --git a/glass/src/libnt/native/cpp/NTProfiledPIDController.cpp b/glass/src/libnt/native/cpp/NTProfiledPIDController.cpp new file mode 100644 index 00000000000..bae069b74ff --- /dev/null +++ b/glass/src/libnt/native/cpp/NTProfiledPIDController.cpp @@ -0,0 +1,80 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "glass/networktables/NTProfiledPIDController.h" + +#include +#include + +using namespace glass; + +NTProfiledPIDControllerModel::NTProfiledPIDControllerModel( + std::string_view path) + : NTProfiledPIDControllerModel(nt::NetworkTableInstance::GetDefault(), + path) {} + +NTProfiledPIDControllerModel::NTProfiledPIDControllerModel( + nt::NetworkTableInstance inst, std::string_view path) + : m_inst{inst}, + m_name{inst.GetStringTopic(fmt::format("{}/.name", path)).Subscribe("")}, + m_controllable{inst.GetBooleanTopic(fmt::format("{}/.controllable", path)) + .Subscribe(false)}, + m_p{inst.GetDoubleTopic(fmt::format("{}/p", path)).GetEntry(0)}, + m_i{inst.GetDoubleTopic(fmt::format("{}/i", path)).GetEntry(0)}, + m_d{inst.GetDoubleTopic(fmt::format("{}/d", path)).GetEntry(0)}, + m_goal{inst.GetDoubleTopic(fmt::format("{}/goal", path)).GetEntry(0)}, + m_iZone{inst.GetDoubleTopic(fmt::format("{}/izone", path)).GetEntry(0)}, + m_pData{fmt::format("NTPIDCtrlP:{}", path)}, + m_iData{fmt::format("NTPIDCtrlI:{}", path)}, + m_dData{fmt::format("NTPIDCtrlD:{}", path)}, + m_goalData{fmt::format("NTPIDCtrlGoal:{}", path)}, + m_iZoneData{fmt::format("NTPIDCtrlIZone:{}", path)}, + m_nameValue{wpi::rsplit(path, '/').second} {} + +void NTProfiledPIDControllerModel::SetP(double value) { + m_p.Set(value); +} + +void NTProfiledPIDControllerModel::SetI(double value) { + m_i.Set(value); +} + +void NTProfiledPIDControllerModel::SetD(double value) { + m_d.Set(value); +} + +void NTProfiledPIDControllerModel::SetGoal(double value) { + m_goal.Set(value); +} +void NTProfiledPIDControllerModel::SetIZone(double value) { + m_iZone.Set(value); +} + +void NTProfiledPIDControllerModel::Update() { + for (auto&& v : m_name.ReadQueue()) { + m_nameValue = std::move(v.value); + } + for (auto&& v : m_p.ReadQueue()) { + m_pData.SetValue(v.value, v.time); + } + for (auto&& v : m_i.ReadQueue()) { + m_iData.SetValue(v.value, v.time); + } + for (auto&& v : m_d.ReadQueue()) { + m_dData.SetValue(v.value, v.time); + } + for (auto&& v : m_goal.ReadQueue()) { + m_goalData.SetValue(v.value, v.time); + } + for (auto&& v : m_iZone.ReadQueue()) { + m_iZoneData.SetValue(v.value, v.time); + } + for (auto&& v : m_controllable.ReadQueue()) { + m_controllableValue = v.value; + } +} + +bool NTProfiledPIDControllerModel::Exists() { + return m_goal.Exists(); +} diff --git a/glass/src/libnt/native/cpp/NTStringChooser.cpp b/glass/src/libnt/native/cpp/NTStringChooser.cpp index b892a2c789e..26074fc4814 100644 --- a/glass/src/libnt/native/cpp/NTStringChooser.cpp +++ b/glass/src/libnt/native/cpp/NTStringChooser.cpp @@ -5,6 +5,7 @@ #include "glass/networktables/NTStringChooser.h" #include +#include using namespace glass; @@ -16,17 +17,17 @@ NTStringChooserModel::NTStringChooserModel(nt::NetworkTableInstance inst, : m_inst{inst}, m_default{ m_inst.GetStringTopic(fmt::format("{}/default", path)).Subscribe("")}, - m_selected{ - m_inst.GetStringTopic(fmt::format("{}/selected", path)).GetEntry("")}, + m_selected{m_inst.GetStringTopic(fmt::format("{}/selected", path)) + .Subscribe("")}, + m_selectedPub{m_inst.GetStringTopic(fmt::format("{}/selected", path)) + .PublishEx("string", {{"retained", true}})}, m_active{ m_inst.GetStringTopic(fmt::format("{}/active", path)).Subscribe("")}, m_options{m_inst.GetStringArrayTopic(fmt::format("{}/options", path)) - .Subscribe({})} { - m_selected.GetTopic().SetRetained(true); -} + .Subscribe({})} {} void NTStringChooserModel::SetSelected(std::string_view val) { - m_selected.Set(val); + m_selectedPub.Set(val); } void NTStringChooserModel::Update() { diff --git a/glass/src/libnt/native/cpp/NetworkTables.cpp b/glass/src/libnt/native/cpp/NetworkTables.cpp index 57469a20bdc..6d43c049244 100644 --- a/glass/src/libnt/native/cpp/NetworkTables.cpp +++ b/glass/src/libnt/native/cpp/NetworkTables.cpp @@ -28,11 +28,13 @@ #include #include #include +#include #include #include "glass/Context.h" #include "glass/DataSource.h" #include "glass/Storage.h" +#include "glass/support/ExtraGuiWidgets.h" using namespace glass; using namespace mpack; @@ -874,12 +876,15 @@ void NetworkTablesModel::Update() { std::string err; auto desc = m_structDb.Add(typeStr, schema, &err); if (!desc) { - fmt::print("could not decode struct '{}' schema '{}': {}\n", + wpi::print("could not decode struct '{}' schema '{}': {}\n", entry->info.name, schema, err); } else if (desc->IsValid()) { // loop over all entries with this type and update for (auto&& entryPair : m_entries) { - auto ts = entryPair.second->info.type_str; + if (!entryPair.second) { + continue; + } + std::string_view ts = entryPair.second->info.type_str; if (!wpi::starts_with(ts, "struct:")) { continue; } @@ -896,12 +901,15 @@ void NetworkTablesModel::Update() { // protobuf descriptor handling auto filename = wpi::drop_front(entry->info.name, 15); if (!m_protoDb.Add(filename, entry->value.GetRaw())) { - fmt::print("could not decode protobuf '{}' filename '{}'\n", + wpi::print("could not decode protobuf '{}' filename '{}'\n", entry->info.name, filename); } else { // loop over all protobuf entries and update (conservatively) for (auto&& entryPair : m_entries) { - auto& ts = entryPair.second->info.type_str; + if (!entryPair.second) { + continue; + } + std::string_view ts = entryPair.second->info.type_str; if (wpi::starts_with(ts, "proto:")) { entryPair.second->UpdateFromValue(*this); } @@ -1019,7 +1027,7 @@ void NetworkTablesModel::Client::UpdatePublishers( if (auto pubs = nt::meta::DecodeClientPublishers(data)) { publishers = std::move(*pubs); } else { - fmt::print(stderr, "Failed to update publishers\n"); + wpi::print(stderr, "Failed to update publishers\n"); } } @@ -1032,7 +1040,7 @@ void NetworkTablesModel::Client::UpdateSubscribers( subscribers.emplace_back(std::move(sub)); } } else { - fmt::print(stderr, "Failed to update subscribers\n"); + wpi::print(stderr, "Failed to update subscribers\n"); } } @@ -1377,8 +1385,8 @@ static void EmitEntryValueEditable(NetworkTablesModel* model, } case NT_INTEGER: { int64_t v = val.GetInteger(); - if (ImGui::InputScalar(typeStr, ImGuiDataType_S64, &v, nullptr, nullptr, - nullptr, ImGuiInputTextFlags_EnterReturnsTrue)) { + if (InputExpr(typeStr, &v, "%d", + ImGuiInputTextFlags_EnterReturnsTrue)) { if (entry.publisher == 0) { entry.publisher = nt::Publish(entry.info.topic, NT_INTEGER, "int"); } @@ -1388,8 +1396,8 @@ static void EmitEntryValueEditable(NetworkTablesModel* model, } case NT_FLOAT: { float v = val.GetFloat(); - if (ImGui::InputFloat(typeStr, &v, 0, 0, "%.6f", - ImGuiInputTextFlags_EnterReturnsTrue)) { + if (InputExpr(typeStr, &v, "%.6f", + ImGuiInputTextFlags_EnterReturnsTrue)) { if (entry.publisher == 0) { entry.publisher = nt::Publish(entry.info.topic, NT_FLOAT, "float"); } @@ -1405,9 +1413,9 @@ static void EmitEntryValueEditable(NetworkTablesModel* model, #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" #endif - if (ImGui::InputDouble(typeStr, &v, 0, 0, - fmt::format("%.{}f", precision).c_str(), - ImGuiInputTextFlags_EnterReturnsTrue)) { + if (InputExpr(typeStr, &v, + fmt::format("%.{}f", precision).c_str(), + ImGuiInputTextFlags_EnterReturnsTrue)) { if (entry.publisher == 0) { entry.publisher = nt::Publish(entry.info.topic, NT_DOUBLE, "double"); } diff --git a/glass/src/libnt/native/cpp/NetworkTablesProvider.cpp b/glass/src/libnt/native/cpp/NetworkTablesProvider.cpp index 413899ee4d9..61bac02789f 100644 --- a/glass/src/libnt/native/cpp/NetworkTablesProvider.cpp +++ b/glass/src/libnt/native/cpp/NetworkTablesProvider.cpp @@ -83,6 +83,18 @@ void NetworkTablesProvider::DisplayMenu() { // FIXME: enabled? // data is the last item, so is guaranteed to be null-terminated ImGui::MenuItem(path.back().data(), nullptr, &visible, true); + // Add type label to smartdashboard sendables + if (wpi::starts_with(entry->name, "/SmartDashboard/")) { + auto typeEntry = m_typeCache.FindValue(entry->name); + if (typeEntry) { + ImGui::SameLine(); + ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(96, 96, 96, 255)); + ImGui::Text("%s", typeEntry->stringVal.c_str()); + ImGui::PopStyleColor(); + ImGui::SameLine(); + ImGui::Dummy(ImVec2(10.0f, 0.0f)); + } + } if (!wasVisible && visible) { Show(entry.get(), entry->window); } else if (wasVisible && !visible && entry->window) { diff --git a/glass/src/libnt/native/cpp/StandardNetworkTables.cpp b/glass/src/libnt/native/cpp/StandardNetworkTables.cpp index ef610253e47..4cc21212690 100644 --- a/glass/src/libnt/native/cpp/StandardNetworkTables.cpp +++ b/glass/src/libnt/native/cpp/StandardNetworkTables.cpp @@ -14,6 +14,7 @@ #include "glass/networktables/NTMechanism2D.h" #include "glass/networktables/NTMotorController.h" #include "glass/networktables/NTPIDController.h" +#include "glass/networktables/NTProfiledPIDController.h" #include "glass/networktables/NTStringChooser.h" #include "glass/networktables/NTSubsystem.h" #include "glass/networktables/NetworkTablesProvider.h" @@ -62,7 +63,7 @@ void glass::AddStandardNetworkTablesViews(NetworkTablesProvider& provider) { [](Window* win, Model* model, const char*) { win->SetFlags(ImGuiWindowFlags_AlwaysAutoResize); return MakeFunctionView( - [=] { DisplayFMS(static_cast(model)); }); + [=] { DisplayFMS(static_cast(model), true); }); }); provider.Register( NTDigitalInputModel::kType, @@ -141,6 +142,18 @@ void glass::AddStandardNetworkTablesViews(NetworkTablesProvider& provider) { DisplayPIDController(static_cast(model)); }); }); + provider.Register( + NTProfiledPIDControllerModel::kType, + [](nt::NetworkTableInstance inst, const char* path) { + return std::make_unique(inst, path); + }, + [](Window* win, Model* model, const char* path) { + win->SetFlags(ImGuiWindowFlags_AlwaysAutoResize); + return MakeFunctionView([=] { + DisplayProfiledPIDController( + static_cast(model)); + }); + }); provider.Register( NTMotorControllerModel::kType, [](nt::NetworkTableInstance inst, const char* path) { diff --git a/glass/src/libnt/native/include/glass/networktables/NTPIDController.h b/glass/src/libnt/native/include/glass/networktables/NTPIDController.h index f901f72caa2..d19dcea2de6 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTPIDController.h +++ b/glass/src/libnt/native/include/glass/networktables/NTPIDController.h @@ -29,11 +29,13 @@ class NTPIDControllerModel : public PIDControllerModel { DataSource* GetIData() override { return &m_iData; } DataSource* GetDData() override { return &m_dData; } DataSource* GetSetpointData() override { return &m_setpointData; } + DataSource* GetIZoneData() override { return &m_iZoneData; } void SetP(double value) override; void SetI(double value) override; void SetD(double value) override; void SetSetpoint(double value) override; + void SetIZone(double value) override; void Update() override; bool Exists() override; @@ -47,11 +49,13 @@ class NTPIDControllerModel : public PIDControllerModel { nt::DoubleEntry m_i; nt::DoubleEntry m_d; nt::DoubleEntry m_setpoint; + nt::DoubleEntry m_iZone; DataSource m_pData; DataSource m_iData; DataSource m_dData; DataSource m_setpointData; + DataSource m_iZoneData; std::string m_nameValue; bool m_controllableValue = false; diff --git a/glass/src/libnt/native/include/glass/networktables/NTProfiledPIDController.h b/glass/src/libnt/native/include/glass/networktables/NTProfiledPIDController.h new file mode 100644 index 00000000000..e968f79eb5f --- /dev/null +++ b/glass/src/libnt/native/include/glass/networktables/NTProfiledPIDController.h @@ -0,0 +1,64 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include +#include +#include +#include + +#include "glass/DataSource.h" +#include "glass/other/ProfiledPIDController.h" + +namespace glass { +class NTProfiledPIDControllerModel : public ProfiledPIDControllerModel { + public: + static constexpr const char* kType = "ProfiledPIDController"; + + explicit NTProfiledPIDControllerModel(std::string_view path); + NTProfiledPIDControllerModel(nt::NetworkTableInstance inst, + std::string_view path); + + const char* GetName() const override { return m_nameValue.c_str(); } + + DataSource* GetPData() override { return &m_pData; } + DataSource* GetIData() override { return &m_iData; } + DataSource* GetDData() override { return &m_dData; } + DataSource* GetGoalData() override { return &m_goalData; } + DataSource* GetIZoneData() override { return &m_iZoneData; } + + void SetP(double value) override; + void SetI(double value) override; + void SetD(double value) override; + void SetGoal(double value) override; + void SetIZone(double value) override; + + void Update() override; + bool Exists() override; + bool IsReadOnly() override { return !m_controllableValue; } + + private: + nt::NetworkTableInstance m_inst; + nt::StringSubscriber m_name; + nt::BooleanSubscriber m_controllable; + nt::DoubleEntry m_p; + nt::DoubleEntry m_i; + nt::DoubleEntry m_d; + nt::DoubleEntry m_goal; + nt::DoubleEntry m_iZone; + + DataSource m_pData; + DataSource m_iData; + DataSource m_dData; + DataSource m_goalData; + DataSource m_iZoneData; + + std::string m_nameValue; + bool m_controllableValue = false; +}; +} // namespace glass diff --git a/glass/src/libnt/native/include/glass/networktables/NTStringChooser.h b/glass/src/libnt/native/include/glass/networktables/NTStringChooser.h index d770a749e3f..49c4802ede3 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTStringChooser.h +++ b/glass/src/libnt/native/include/glass/networktables/NTStringChooser.h @@ -39,7 +39,8 @@ class NTStringChooserModel : public StringChooserModel { private: nt::NetworkTableInstance m_inst; nt::StringSubscriber m_default; - nt::StringEntry m_selected; + nt::StringSubscriber m_selected; + nt::StringPublisher m_selectedPub; nt::StringSubscriber m_active; nt::StringArraySubscriber m_options; diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index e53fca1b21a..9c092596b75 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -1,14 +1,15 @@ include(FetchContent) -FetchContent_Declare( +fetchcontent_declare( googletest - GIT_REPOSITORY https://github.com/google/googletest.git - GIT_TAG 58d77fa8070e8cec2dc1ed015d66b454c8d78850 # 1.12.1 + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG + 58d77fa8070e8cec2dc1ed015d66b454c8d78850 # 1.12.1 ) -FetchContent_GetProperties(googletest) +fetchcontent_getproperties(googletest) if(NOT googletest_POPULATED) - FetchContent_Populate(googletest) + fetchcontent_populate(googletest) # Prevent overriding the parent project's compiler/linker # settings on Windows diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 7f93135c49b..d64cd491770 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 3fa8f862f75..1af9e0930b8 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/hal/.styleguide b/hal/.styleguide index bdd9bc47c30..c04d378d074 100644 --- a/hal/.styleguide +++ b/hal/.styleguide @@ -20,7 +20,6 @@ generatedFileExclude { modifiableFileExclude { \.patch$ \.png$ - \.py$ \.so$ } diff --git a/hal/CMakeLists.txt b/hal/CMakeLists.txt index 603190b2421..bfa54f37f1b 100644 --- a/hal/CMakeLists.txt +++ b/hal/CMakeLists.txt @@ -3,33 +3,18 @@ project(hal) include(CompileWarnings) include(AddTest) -file(STRINGS src/generate/Instances.txt RAW_INSTANCES) -file(STRINGS src/generate/ResourceType.txt RAW_RESOURCE_TYPES) - -SET(usage_reporting_types_cpp "") -SET(usage_reporting_instances_cpp "") -SET(usage_reporting_types "") -SET(usage_reporting_instances "") - -foreach(ITEM ${RAW_INSTANCES}) - list(APPEND usage_reporting_instances_cpp " ${ITEM},") - list(APPEND usage_reporting_instances "\n public static final int ${ITEM};") -endforeach() - -foreach(ITEM ${RAW_RESOURCE_TYPES}) - list(APPEND usage_reporting_types_cpp " ${ITEM},") - list(APPEND usage_reporting_types "\n public static final int ${ITEM};") -endforeach() - -string(REPLACE ";" "\n" usage_reporting_types_cpp "${usage_reporting_types_cpp}") -string(REPLACE ";" "\n" usage_reporting_instances_cpp "${usage_reporting_instances_cpp}") - -file(GLOB - hal_shared_native_src src/main/native/cpp/*.cpp - hal_shared_native_src src/main/native/cpp/cpp/*.cpp - hal_shared_native_src src/main/native/cpp/handles/*.cpp - hal_sim_native_src src/main/native/sim/*.cpp - hal_sim_native_src src/main/native/sim/mockdata/*.cpp) +file( + GLOB hal_shared_native_src + src/main/native/cpp/*.cpp + hal_shared_native_src + src/main/native/cpp/cpp/*.cpp + hal_shared_native_src + src/main/native/cpp/handles/*.cpp + hal_sim_native_src + src/main/native/sim/*.cpp + hal_sim_native_src + src/main/native/sim/mockdata/*.cpp +) add_library(hal ${hal_shared_native_src}) wpilib_target_warnings(hal) set_target_properties(hal PROPERTIES DEBUG_POSTFIX "d") @@ -40,37 +25,36 @@ else() target_sources(hal PRIVATE ${hal_sim_native_src}) endif() -configure_file(src/generate/FRCUsageReporting.h.in gen/hal/FRCUsageReporting.h) - set_target_properties(hal PROPERTIES OUTPUT_NAME "wpiHal") -target_include_directories(hal PUBLIC - $ - $) - -target_include_directories(hal PUBLIC - $ - $) +target_include_directories( + hal + PUBLIC + $ + $ +) + +target_include_directories( + hal + PUBLIC + $ + $ +) target_link_libraries(hal PUBLIC wpiutil) set_property(TARGET hal PROPERTY FOLDER "libraries") install(TARGETS hal EXPORT hal) +export(TARGETS hal FILE hal.cmake NAMESPACE hal::) install(DIRECTORY src/main/native/include/ DESTINATION "${include_dest}/hal") -install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/gen/ DESTINATION "${include_dest}/hal") +install(DIRECTORY src/generated/main/native/include/ DESTINATION "${include_dest}/hal") -if (WITH_FLAT_INSTALL) - set (hal_config_dir ${wpilib_dest}) -else() - set (hal_config_dir share/hal) -endif() - -configure_file(hal-config.cmake.in ${WPILIB_BINARY_DIR}/hal-config.cmake ) -install(FILES ${WPILIB_BINARY_DIR}/hal-config.cmake DESTINATION ${hal_config_dir}) -install(EXPORT hal DESTINATION ${hal_config_dir}) +configure_file(hal-config.cmake.in ${WPILIB_BINARY_DIR}/hal-config.cmake) +install(FILES ${WPILIB_BINARY_DIR}/hal-config.cmake DESTINATION share/hal) +install(EXPORT hal DESTINATION share/hal) # Java bindings -if (WITH_JAVA) +if(WITH_JAVA) find_package(Java REQUIRED) find_package(JNI REQUIRED) include(UseJava) @@ -80,15 +64,19 @@ if (WITH_JAVA) file(GLOB_RECURSE hal_shared_jni_src src/main/native/cpp/jni/*.cpp) - file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java) + file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java src/generated/main/java/*.java) set(CMAKE_JNI_TARGET true) - add_jar(hal_jar ${JAVA_SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/FRCNetComm.java INCLUDE_JARS wpiutil_jar OUTPUT_NAME wpiHal GENERATE_NATIVE_HEADERS hal_jni_headers) - - get_property(HAL_JAR_FILE TARGET hal_jar PROPERTY JAR_FILE) - install(FILES ${HAL_JAR_FILE} DESTINATION "${java_lib_dest}") + add_jar( + hal_jar + ${JAVA_SOURCES} + INCLUDE_JARS wpiutil_jar + OUTPUT_NAME wpiHal + GENERATE_NATIVE_HEADERS hal_jni_headers + ) - set_property(TARGET hal_jar PROPERTY FOLDER "java") + install_jar(hal_jar DESTINATION ${java_lib_dest}) + install_jar_exports(TARGETS hal_jar FILE hal_jar.cmake DESTINATION share/hal) add_library(haljni ${hal_shared_jni_src}) @@ -107,23 +95,28 @@ if (WITH_JAVA) add_dependencies(haljni hal_jar) install(TARGETS haljni EXPORT haljni) - + export(TARGETS haljni FILE haljni.cmake NAMESPACE haljni::) endif() -if (WITH_JAVA_SOURCE) +if(WITH_JAVA_SOURCE) find_package(Java REQUIRED) include(UseJava) - file(GLOB HAL_SOURCES src/main/java/edu/wpi/first/hal/*.java ${CMAKE_CURRENT_BINARY_DIR}/FRCNetComm.java) + file(GLOB HAL_SOURCES src/main/java/edu/wpi/first/hal/*.java src/generated/main/java/*.java) file(GLOB HAL_CAN_SOURCES src/main/java/edu/wpi/first/hal/can/*.java) file(GLOB HAL_SIMULATION_SOURCES src/main/java/edu/wpi/first/hal/simulation/*.java) file(GLOB HAL_UTIL_SOURCES src/main/java/edu/wpi/first/hal/util/*.java) - add_jar(hal_src_jar - RESOURCES NAMESPACE "edu/wpi/first/hal" ${HAL_SOURCES} - NAMESPACE "edu/wpi/first/hal/can" ${HAL_CAN_SOURCES} - NAMESPACE "edu/wpi/first/hal/communication" src/main/java/edu/wpi/first/hal/communication/NIRioStatus.java - NAMESPACE "edu/wpi/first/hal/simulation" ${HAL_SIMULATION_SOURCES} - NAMESPACE "edu/wpi/first/hal/util" ${HAL_UTIL_SOURCES} - OUTPUT_NAME wpiHal-sources) + add_jar( + hal_src_jar + RESOURCES + NAMESPACE "edu/wpi/first/hal" ${HAL_SOURCES} + NAMESPACE "edu/wpi/first/hal/can" ${HAL_CAN_SOURCES} + NAMESPACE + "edu/wpi/first/hal/communication" + src/main/java/edu/wpi/first/hal/communication/NIRioStatus.java + NAMESPACE "edu/wpi/first/hal/simulation" ${HAL_SIMULATION_SOURCES} + NAMESPACE "edu/wpi/first/hal/util" ${HAL_UTIL_SOURCES} + OUTPUT_NAME wpiHal-sources + ) get_property(HAL_SRC_JAR_FILE TARGET hal_src_jar PROPERTY JAR_FILE) install(FILES ${HAL_SRC_JAR_FILE} DESTINATION "${java_lib_dest}") @@ -131,7 +124,7 @@ if (WITH_JAVA_SOURCE) set_property(TARGET hal_src_jar PROPERTY FOLDER "java") endif() -if (WITH_TESTS) +if(WITH_TESTS) wpilib_add_test(hal src/test/native/cpp) target_link_libraries(hal_test hal gtest) endif() diff --git a/hal/build.gradle b/hal/build.gradle index 03d07a01802..8abdfdcebfe 100644 --- a/hal/build.gradle +++ b/hal/build.gradle @@ -1,60 +1,9 @@ -def javaResourceFile = file("$buildDir/generated/java/edu/wpi/first/hal/FRCNetComm.java") -def cppResourceFile = file("$buildDir/generated/headers/hal/FRCUsageReporting.h") - -def generateUsageReporting = tasks.register('generateUsageReporting') { - def javaBase = file('src/generate/FRCNetComm.java.in') - def cppBase = file('src/generate/FRCUsageReporting.h.in') - - def instances = file('src/generate/Instances.txt') - def resourceType = file('src/generate/ResourceType.txt') - - inputs.file(javaBase) - inputs.file(cppBase) - inputs.file(instances) - inputs.file(resourceType) - - outputs.file(javaResourceFile) - outputs.file(cppResourceFile) - - doLast { - def instanceTextJava = instances as String[] - def instanceTextCpp = instances as String[] - def resourceTextJava = resourceType as String[] - def resourceTextCpp = resourceType as String[] - - instanceTextJava = instanceTextJava.collect { - " public static final int ${it};" - }.join('\n') - - instanceTextCpp = instanceTextCpp.collect { - " ${it}," - }.join('\n') - - resourceTextJava = resourceTextJava.collect { - " public static final int ${it};" - }.join('\n') - - resourceTextCpp = resourceTextCpp.collect { - " ${it}," - }.join('\n') - - javaResourceFile.text = javaBase.text.replace('${usage_reporting_types}', resourceTextJava).replace('${usage_reporting_instances}', instanceTextJava) - cppResourceFile.text = cppBase.text.replace('${usage_reporting_types_cpp}', resourceTextCpp).replace('${usage_reporting_instances_cpp}', instanceTextCpp) - } -} - ext { addHalDependency = { binary, shared-> - binary.tasks.withType(AbstractNativeSourceCompileTask) { - it.dependsOn generateUsageReporting - } binary.lib project: ':hal', library: 'hal', linkage: shared } addHalJniDependency = { binary-> - binary.tasks.withType(AbstractNativeSourceCompileTask) { - it.dependsOn generateUsageReporting - } binary.lib project: ':hal', library: 'halJNIShared', linkage: 'shared' } @@ -62,16 +11,8 @@ ext { setBaseName = 'wpiHal' devMain = 'edu.wpi.first.hal.DevMain' niLibraries = true - generatedHeaders = "$buildDir/generated/headers" - jniSplitSetup = { - it.tasks.withType(AbstractNativeSourceCompileTask) { - it.dependsOn generateUsageReporting - } - } + generatedHeaders = "src/generated/main/native/include" splitSetup = { - it.tasks.withType(AbstractNativeSourceCompileTask) { - it.dependsOn generateUsageReporting - } if (it.targetPlatform.name == nativeUtils.wpi.platforms.roborio) { it.sources { athenaCpp(CppSourceSet) { @@ -109,11 +50,7 @@ ext { apply from: "${rootDir}/shared/jni/setupBuild.gradle" -sourceSets.main.java.srcDir "${buildDir}/generated/java/" - -compileJava { - dependsOn generateUsageReporting -} +sourceSets.main.java.srcDir "${projectDir}/src/generated/main/java" cppSourcesZip { from('src/main/native/athena') { @@ -126,7 +63,6 @@ cppSourcesZip { } cppHeadersZip { - dependsOn generateUsageReporting from(generatedHeaders) { into '/' } @@ -160,9 +96,6 @@ nativeUtils.exportsConfigs { model { binaries { all { - it.tasks.withType(AbstractNativeSourceCompileTask) { - it.dependsOn generateUsageReporting - } if (!(it instanceof NativeBinarySpec)) return if (it.component.name != 'hal' && it.component.name != 'halBase') return if (it.targetPlatform.name != nativeUtils.wpi.platforms.roborio) return diff --git a/hal/generate_usage_reporting.py b/hal/generate_usage_reporting.py new file mode 100755 index 00000000000..08536a86e2c --- /dev/null +++ b/hal/generate_usage_reporting.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 + +# Copyright (c) FIRST and other WPILib contributors. +# Open Source Software; you can modify and/or share it under the terms of +# the WPILib BSD license file in the root directory of this project. +import pathlib + + +def main(): + # Gets the folder this script is in (the hal/ directory) + HAL_ROOT = pathlib.Path(__file__).parent + java_package = "edu/wpi/first/hal" + # fmt: off + (HAL_ROOT / "src/generated/main/native/include/hal").mkdir(parents=True, exist_ok=True) + (HAL_ROOT / f"src/generated/main/java/{java_package}").mkdir(parents=True, exist_ok=True) + # fmt: on + usage_reporting_types_cpp = [] + usage_reporting_instances_cpp = [] + usage_reporting_types = [] + usage_reporting_instances = [] + with open(HAL_ROOT / "src/generate/Instances.txt") as instances: + for instance in instances: + usage_reporting_instances_cpp.append(f" {instance.strip()},") + usage_reporting_instances.append( + f" /** {instance.strip()}. */\n" + f" public static final int {instance.strip()};" + ) + + with open(HAL_ROOT / "src/generate/ResourceType.txt") as resource_types: + for resource_type in resource_types: + usage_reporting_types_cpp.append(f" {resource_type.strip()},") + usage_reporting_types.append( + f" /** {resource_type.strip()}. */\n" + f" public static final int {resource_type.strip()};" + ) + + with open(HAL_ROOT / "src/generate/FRCNetComm.java.in") as java_usage_reporting: + contents = ( + # fmt: off + java_usage_reporting.read() + .replace(r"${usage_reporting_types}", "\n".join(usage_reporting_types)) + .replace(r"${usage_reporting_instances}", "\n".join(usage_reporting_instances)) + # fmt: on + ) + + with open( + HAL_ROOT / f"src/generated/main/java/{java_package}/FRCNetComm.java", "w" + ) as java_out: + java_out.write(contents) + + with open(HAL_ROOT / "src/generate/FRCUsageReporting.h.in") as cpp_usage_reporting: + contents = ( + # fmt: off + cpp_usage_reporting.read() + .replace(r"${usage_reporting_types_cpp}", "\n".join(usage_reporting_types_cpp)) + .replace(r"${usage_reporting_instances_cpp}", "\n".join(usage_reporting_instances_cpp)) + # fmt: on + ) + + with open( + HAL_ROOT / "src/generated/main/native/include/hal/FRCUsageReporting.h", "w" + ) as cpp_out: + cpp_out.write(contents) + + +if __name__ == "__main__": + main() diff --git a/hal/hal-config.cmake.in b/hal/hal-config.cmake.in index 49eac3d40d3..7429597b0e7 100644 --- a/hal/hal-config.cmake.in +++ b/hal/hal-config.cmake.in @@ -4,3 +4,6 @@ include(CMakeFindDependencyMacro) @FILENAME_DEP_REPLACE@ include(${SELF_DIR}/hal.cmake) +if(@WITH_JAVA@) + include(${SELF_DIR}/hal_jar.cmake) +endif() diff --git a/hal/src/dev/native/cpp/main.cpp b/hal/src/dev/native/cpp/main.cpp index 8614aba7830..69481ee1607 100644 --- a/hal/src/dev/native/cpp/main.cpp +++ b/hal/src/dev/native/cpp/main.cpp @@ -3,10 +3,11 @@ // the WPILib BSD license file in the root directory of this project. #include +#include #include "hal/HAL.h" int main() { - fmt::print("Hello World\n"); - fmt::print("{}\n", static_cast(HAL_GetRuntimeType())); + wpi::print("Hello World\n"); + wpi::print("{}\n", static_cast(HAL_GetRuntimeType())); } diff --git a/hal/src/generate/FRCNetComm.java.in b/hal/src/generate/FRCNetComm.java.in index 703e0349e54..e58a578e816 100644 --- a/hal/src/generate/FRCNetComm.java.in +++ b/hal/src/generate/FRCNetComm.java.in @@ -1,13 +1,15 @@ -/* - * Autogenerated file! Do not manually edit this file. - */ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./hal/generate_usage_reporting.py. DO NOT MODIFY package edu.wpi.first.hal; /** * JNI wrapper for library FRC_NetworkCommunication
. */ -public class FRCNetComm { +public final class FRCNetComm { /** * Resource type from UsageReporting. */ @@ -29,4 +31,7 @@ ${usage_reporting_types} ${usage_reporting_instances} } + + /** Utility class. */ + private FRCNetComm() {} } diff --git a/hal/src/generate/FRCUsageReporting.h.in b/hal/src/generate/FRCUsageReporting.h.in index 34330c8c99a..03a78f0cbc3 100644 --- a/hal/src/generate/FRCUsageReporting.h.in +++ b/hal/src/generate/FRCUsageReporting.h.in @@ -1,3 +1,9 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./hal/generate_usage_reporting.py. DO NOT MODIFY + #pragma once #include diff --git a/hal/src/generate/Instances.txt b/hal/src/generate/Instances.txt index bc30057d199..fc27682eea7 100644 --- a/hal/src/generate/Instances.txt +++ b/hal/src/generate/Instances.txt @@ -12,6 +12,7 @@ kFramework_CommandControl = 3 kFramework_Timed = 4 kFramework_ROS = 5 kFramework_RobotBuilder = 6 +kFramework_AdvantageKit = 7 kRobotDrive_ArcadeStandard = 1 kRobotDrive_ArcadeButtonSpin = 2 kRobotDrive_ArcadeRatioCurve = 3 @@ -44,6 +45,7 @@ kADXL345_I2C = 2 kCommand_Scheduler = 1 kCommand2_Scheduler = 2 kSmartDashboard_Instance = 1 +kSmartDashboard_LiveWindow = 2 kKinematics_DifferentialDrive = 1 kKinematics_MecanumDrive = 2 kKinematics_SwerveDrive = 3 diff --git a/hal/src/generate/ResourceType.txt b/hal/src/generate/ResourceType.txt index 943d8b00bec..13c42c0f71c 100644 --- a/hal/src/generate/ResourceType.txt +++ b/hal/src/generate/ResourceType.txt @@ -100,3 +100,17 @@ kResourceType_CTRE_future11 = 98 kResourceType_CTRE_future12 = 99 kResourceType_CTRE_future13 = 100 kResourceType_CTRE_future14 = 101 +kResourceType_ExponentialProfile = 102 +kResourceType_PS4Controller = 103 +kResourceType_PhotonCamera = 104 +kResourceType_PhotonPoseEstimator = 105 +kResourceType_PathPlannerPath = 106 +kResourceType_PathPlannerAuto = 107 +kResourceType_PathFindingCommand = 108 +kResourceType_Redux_future1 = 109 +kResourceType_Redux_future2 = 110 +kResourceType_Redux_future3 = 111 +kResourceType_Redux_future4 = 112 +kResourceType_Redux_future5 = 113 +kResourceType_RevSparkFlexCAN = 114 +kResourceType_RevSparkFlexPWM = 115 diff --git a/hal/src/generated/main/java/edu/wpi/first/hal/FRCNetComm.java b/hal/src/generated/main/java/edu/wpi/first/hal/FRCNetComm.java new file mode 100644 index 00000000000..0814a3d0fc3 --- /dev/null +++ b/hal/src/generated/main/java/edu/wpi/first/hal/FRCNetComm.java @@ -0,0 +1,375 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./hal/generate_usage_reporting.py. DO NOT MODIFY + +package edu.wpi.first.hal; + +/** + * JNI wrapper for library FRC_NetworkCommunication
. + */ +public final class FRCNetComm { + /** + * Resource type from UsageReporting. + */ + @SuppressWarnings("TypeName") + public static final class tResourceType { + private tResourceType() { + } + + /** kResourceType_Controller = 0. */ + public static final int kResourceType_Controller = 0; + /** kResourceType_Module = 1. */ + public static final int kResourceType_Module = 1; + /** kResourceType_Language = 2. */ + public static final int kResourceType_Language = 2; + /** kResourceType_CANPlugin = 3. */ + public static final int kResourceType_CANPlugin = 3; + /** kResourceType_Accelerometer = 4. */ + public static final int kResourceType_Accelerometer = 4; + /** kResourceType_ADXL345 = 5. */ + public static final int kResourceType_ADXL345 = 5; + /** kResourceType_AnalogChannel = 6. */ + public static final int kResourceType_AnalogChannel = 6; + /** kResourceType_AnalogTrigger = 7. */ + public static final int kResourceType_AnalogTrigger = 7; + /** kResourceType_AnalogTriggerOutput = 8. */ + public static final int kResourceType_AnalogTriggerOutput = 8; + /** kResourceType_CANJaguar = 9. */ + public static final int kResourceType_CANJaguar = 9; + /** kResourceType_Compressor = 10. */ + public static final int kResourceType_Compressor = 10; + /** kResourceType_Counter = 11. */ + public static final int kResourceType_Counter = 11; + /** kResourceType_Dashboard = 12. */ + public static final int kResourceType_Dashboard = 12; + /** kResourceType_DigitalInput = 13. */ + public static final int kResourceType_DigitalInput = 13; + /** kResourceType_DigitalOutput = 14. */ + public static final int kResourceType_DigitalOutput = 14; + /** kResourceType_DriverStationCIO = 15. */ + public static final int kResourceType_DriverStationCIO = 15; + /** kResourceType_DriverStationEIO = 16. */ + public static final int kResourceType_DriverStationEIO = 16; + /** kResourceType_DriverStationLCD = 17. */ + public static final int kResourceType_DriverStationLCD = 17; + /** kResourceType_Encoder = 18. */ + public static final int kResourceType_Encoder = 18; + /** kResourceType_GearTooth = 19. */ + public static final int kResourceType_GearTooth = 19; + /** kResourceType_Gyro = 20. */ + public static final int kResourceType_Gyro = 20; + /** kResourceType_I2C = 21. */ + public static final int kResourceType_I2C = 21; + /** kResourceType_Framework = 22. */ + public static final int kResourceType_Framework = 22; + /** kResourceType_Jaguar = 23. */ + public static final int kResourceType_Jaguar = 23; + /** kResourceType_Joystick = 24. */ + public static final int kResourceType_Joystick = 24; + /** kResourceType_Kinect = 25. */ + public static final int kResourceType_Kinect = 25; + /** kResourceType_KinectStick = 26. */ + public static final int kResourceType_KinectStick = 26; + /** kResourceType_PIDController = 27. */ + public static final int kResourceType_PIDController = 27; + /** kResourceType_Preferences = 28. */ + public static final int kResourceType_Preferences = 28; + /** kResourceType_PWM = 29. */ + public static final int kResourceType_PWM = 29; + /** kResourceType_Relay = 30. */ + public static final int kResourceType_Relay = 30; + /** kResourceType_RobotDrive = 31. */ + public static final int kResourceType_RobotDrive = 31; + /** kResourceType_SerialPort = 32. */ + public static final int kResourceType_SerialPort = 32; + /** kResourceType_Servo = 33. */ + public static final int kResourceType_Servo = 33; + /** kResourceType_Solenoid = 34. */ + public static final int kResourceType_Solenoid = 34; + /** kResourceType_SPI = 35. */ + public static final int kResourceType_SPI = 35; + /** kResourceType_Task = 36. */ + public static final int kResourceType_Task = 36; + /** kResourceType_Ultrasonic = 37. */ + public static final int kResourceType_Ultrasonic = 37; + /** kResourceType_Victor = 38. */ + public static final int kResourceType_Victor = 38; + /** kResourceType_Button = 39. */ + public static final int kResourceType_Button = 39; + /** kResourceType_Command = 40. */ + public static final int kResourceType_Command = 40; + /** kResourceType_AxisCamera = 41. */ + public static final int kResourceType_AxisCamera = 41; + /** kResourceType_PCVideoServer = 42. */ + public static final int kResourceType_PCVideoServer = 42; + /** kResourceType_SmartDashboard = 43. */ + public static final int kResourceType_SmartDashboard = 43; + /** kResourceType_Talon = 44. */ + public static final int kResourceType_Talon = 44; + /** kResourceType_HiTechnicColorSensor = 45. */ + public static final int kResourceType_HiTechnicColorSensor = 45; + /** kResourceType_HiTechnicAccel = 46. */ + public static final int kResourceType_HiTechnicAccel = 46; + /** kResourceType_HiTechnicCompass = 47. */ + public static final int kResourceType_HiTechnicCompass = 47; + /** kResourceType_SRF08 = 48. */ + public static final int kResourceType_SRF08 = 48; + /** kResourceType_AnalogOutput = 49. */ + public static final int kResourceType_AnalogOutput = 49; + /** kResourceType_VictorSP = 50. */ + public static final int kResourceType_VictorSP = 50; + /** kResourceType_PWMTalonSRX = 51. */ + public static final int kResourceType_PWMTalonSRX = 51; + /** kResourceType_CANTalonSRX = 52. */ + public static final int kResourceType_CANTalonSRX = 52; + /** kResourceType_ADXL362 = 53. */ + public static final int kResourceType_ADXL362 = 53; + /** kResourceType_ADXRS450 = 54. */ + public static final int kResourceType_ADXRS450 = 54; + /** kResourceType_RevSPARK = 55. */ + public static final int kResourceType_RevSPARK = 55; + /** kResourceType_MindsensorsSD540 = 56. */ + public static final int kResourceType_MindsensorsSD540 = 56; + /** kResourceType_DigitalGlitchFilter = 57. */ + public static final int kResourceType_DigitalGlitchFilter = 57; + /** kResourceType_ADIS16448 = 58. */ + public static final int kResourceType_ADIS16448 = 58; + /** kResourceType_PDP = 59. */ + public static final int kResourceType_PDP = 59; + /** kResourceType_PCM = 60. */ + public static final int kResourceType_PCM = 60; + /** kResourceType_PigeonIMU = 61. */ + public static final int kResourceType_PigeonIMU = 61; + /** kResourceType_NidecBrushless = 62. */ + public static final int kResourceType_NidecBrushless = 62; + /** kResourceType_CANifier = 63. */ + public static final int kResourceType_CANifier = 63; + /** kResourceType_TalonFX = 64. */ + public static final int kResourceType_TalonFX = 64; + /** kResourceType_CTRE_future1 = 65. */ + public static final int kResourceType_CTRE_future1 = 65; + /** kResourceType_CTRE_future2 = 66. */ + public static final int kResourceType_CTRE_future2 = 66; + /** kResourceType_CTRE_future3 = 67. */ + public static final int kResourceType_CTRE_future3 = 67; + /** kResourceType_CTRE_future4 = 68. */ + public static final int kResourceType_CTRE_future4 = 68; + /** kResourceType_CTRE_future5 = 69. */ + public static final int kResourceType_CTRE_future5 = 69; + /** kResourceType_CTRE_future6 = 70. */ + public static final int kResourceType_CTRE_future6 = 70; + /** kResourceType_LinearFilter = 71. */ + public static final int kResourceType_LinearFilter = 71; + /** kResourceType_XboxController = 72. */ + public static final int kResourceType_XboxController = 72; + /** kResourceType_UsbCamera = 73. */ + public static final int kResourceType_UsbCamera = 73; + /** kResourceType_NavX = 74. */ + public static final int kResourceType_NavX = 74; + /** kResourceType_Pixy = 75. */ + public static final int kResourceType_Pixy = 75; + /** kResourceType_Pixy2 = 76. */ + public static final int kResourceType_Pixy2 = 76; + /** kResourceType_ScanseSweep = 77. */ + public static final int kResourceType_ScanseSweep = 77; + /** kResourceType_Shuffleboard = 78. */ + public static final int kResourceType_Shuffleboard = 78; + /** kResourceType_CAN = 79. */ + public static final int kResourceType_CAN = 79; + /** kResourceType_DigilentDMC60 = 80. */ + public static final int kResourceType_DigilentDMC60 = 80; + /** kResourceType_PWMVictorSPX = 81. */ + public static final int kResourceType_PWMVictorSPX = 81; + /** kResourceType_RevSparkMaxPWM = 82. */ + public static final int kResourceType_RevSparkMaxPWM = 82; + /** kResourceType_RevSparkMaxCAN = 83. */ + public static final int kResourceType_RevSparkMaxCAN = 83; + /** kResourceType_ADIS16470 = 84. */ + public static final int kResourceType_ADIS16470 = 84; + /** kResourceType_PIDController2 = 85. */ + public static final int kResourceType_PIDController2 = 85; + /** kResourceType_ProfiledPIDController = 86. */ + public static final int kResourceType_ProfiledPIDController = 86; + /** kResourceType_Kinematics = 87. */ + public static final int kResourceType_Kinematics = 87; + /** kResourceType_Odometry = 88. */ + public static final int kResourceType_Odometry = 88; + /** kResourceType_Units = 89. */ + public static final int kResourceType_Units = 89; + /** kResourceType_TrapezoidProfile = 90. */ + public static final int kResourceType_TrapezoidProfile = 90; + /** kResourceType_DutyCycle = 91. */ + public static final int kResourceType_DutyCycle = 91; + /** kResourceType_AddressableLEDs = 92. */ + public static final int kResourceType_AddressableLEDs = 92; + /** kResourceType_FusionVenom = 93. */ + public static final int kResourceType_FusionVenom = 93; + /** kResourceType_CTRE_future7 = 94. */ + public static final int kResourceType_CTRE_future7 = 94; + /** kResourceType_CTRE_future8 = 95. */ + public static final int kResourceType_CTRE_future8 = 95; + /** kResourceType_CTRE_future9 = 96. */ + public static final int kResourceType_CTRE_future9 = 96; + /** kResourceType_CTRE_future10 = 97. */ + public static final int kResourceType_CTRE_future10 = 97; + /** kResourceType_CTRE_future11 = 98. */ + public static final int kResourceType_CTRE_future11 = 98; + /** kResourceType_CTRE_future12 = 99. */ + public static final int kResourceType_CTRE_future12 = 99; + /** kResourceType_CTRE_future13 = 100. */ + public static final int kResourceType_CTRE_future13 = 100; + /** kResourceType_CTRE_future14 = 101. */ + public static final int kResourceType_CTRE_future14 = 101; + /** kResourceType_ExponentialProfile = 102. */ + public static final int kResourceType_ExponentialProfile = 102; + /** kResourceType_PS4Controller = 103. */ + public static final int kResourceType_PS4Controller = 103; + /** kResourceType_PhotonCamera = 104. */ + public static final int kResourceType_PhotonCamera = 104; + /** kResourceType_PhotonPoseEstimator = 105. */ + public static final int kResourceType_PhotonPoseEstimator = 105; + /** kResourceType_PathPlannerPath = 106. */ + public static final int kResourceType_PathPlannerPath = 106; + /** kResourceType_PathPlannerAuto = 107. */ + public static final int kResourceType_PathPlannerAuto = 107; + /** kResourceType_PathFindingCommand = 108. */ + public static final int kResourceType_PathFindingCommand = 108; + /** kResourceType_Redux_future1 = 109. */ + public static final int kResourceType_Redux_future1 = 109; + /** kResourceType_Redux_future2 = 110. */ + public static final int kResourceType_Redux_future2 = 110; + /** kResourceType_Redux_future3 = 111. */ + public static final int kResourceType_Redux_future3 = 111; + /** kResourceType_Redux_future4 = 112. */ + public static final int kResourceType_Redux_future4 = 112; + /** kResourceType_Redux_future5 = 113. */ + public static final int kResourceType_Redux_future5 = 113; + /** kResourceType_RevSparkFlexCAN = 114. */ + public static final int kResourceType_RevSparkFlexCAN = 114; + /** kResourceType_RevSparkFlexPWM = 115. */ + public static final int kResourceType_RevSparkFlexPWM = 115; + } + + /** + * Instances from UsageReporting. + */ + @SuppressWarnings("TypeName") + public static final class tInstances { + private tInstances() { + } + + /** kLanguage_LabVIEW = 1. */ + public static final int kLanguage_LabVIEW = 1; + /** kLanguage_CPlusPlus = 2. */ + public static final int kLanguage_CPlusPlus = 2; + /** kLanguage_Java = 3. */ + public static final int kLanguage_Java = 3; + /** kLanguage_Python = 4. */ + public static final int kLanguage_Python = 4; + /** kLanguage_DotNet = 5. */ + public static final int kLanguage_DotNet = 5; + /** kLanguage_Kotlin = 6. */ + public static final int kLanguage_Kotlin = 6; + /** kCANPlugin_BlackJagBridge = 1. */ + public static final int kCANPlugin_BlackJagBridge = 1; + /** kCANPlugin_2CAN = 2. */ + public static final int kCANPlugin_2CAN = 2; + /** kFramework_Iterative = 1. */ + public static final int kFramework_Iterative = 1; + /** kFramework_Simple = 2. */ + public static final int kFramework_Simple = 2; + /** kFramework_CommandControl = 3. */ + public static final int kFramework_CommandControl = 3; + /** kFramework_Timed = 4. */ + public static final int kFramework_Timed = 4; + /** kFramework_ROS = 5. */ + public static final int kFramework_ROS = 5; + /** kFramework_RobotBuilder = 6. */ + public static final int kFramework_RobotBuilder = 6; + /** kFramework_AdvantageKit = 7. */ + public static final int kFramework_AdvantageKit = 7; + /** kRobotDrive_ArcadeStandard = 1. */ + public static final int kRobotDrive_ArcadeStandard = 1; + /** kRobotDrive_ArcadeButtonSpin = 2. */ + public static final int kRobotDrive_ArcadeButtonSpin = 2; + /** kRobotDrive_ArcadeRatioCurve = 3. */ + public static final int kRobotDrive_ArcadeRatioCurve = 3; + /** kRobotDrive_Tank = 4. */ + public static final int kRobotDrive_Tank = 4; + /** kRobotDrive_MecanumPolar = 5. */ + public static final int kRobotDrive_MecanumPolar = 5; + /** kRobotDrive_MecanumCartesian = 6. */ + public static final int kRobotDrive_MecanumCartesian = 6; + /** kRobotDrive2_DifferentialArcade = 7. */ + public static final int kRobotDrive2_DifferentialArcade = 7; + /** kRobotDrive2_DifferentialTank = 8. */ + public static final int kRobotDrive2_DifferentialTank = 8; + /** kRobotDrive2_DifferentialCurvature = 9. */ + public static final int kRobotDrive2_DifferentialCurvature = 9; + /** kRobotDrive2_MecanumCartesian = 10. */ + public static final int kRobotDrive2_MecanumCartesian = 10; + /** kRobotDrive2_MecanumPolar = 11. */ + public static final int kRobotDrive2_MecanumPolar = 11; + /** kRobotDrive2_KilloughCartesian = 12. */ + public static final int kRobotDrive2_KilloughCartesian = 12; + /** kRobotDrive2_KilloughPolar = 13. */ + public static final int kRobotDrive2_KilloughPolar = 13; + /** kDriverStationCIO_Analog = 1. */ + public static final int kDriverStationCIO_Analog = 1; + /** kDriverStationCIO_DigitalIn = 2. */ + public static final int kDriverStationCIO_DigitalIn = 2; + /** kDriverStationCIO_DigitalOut = 3. */ + public static final int kDriverStationCIO_DigitalOut = 3; + /** kDriverStationEIO_Acceleration = 1. */ + public static final int kDriverStationEIO_Acceleration = 1; + /** kDriverStationEIO_AnalogIn = 2. */ + public static final int kDriverStationEIO_AnalogIn = 2; + /** kDriverStationEIO_AnalogOut = 3. */ + public static final int kDriverStationEIO_AnalogOut = 3; + /** kDriverStationEIO_Button = 4. */ + public static final int kDriverStationEIO_Button = 4; + /** kDriverStationEIO_LED = 5. */ + public static final int kDriverStationEIO_LED = 5; + /** kDriverStationEIO_DigitalIn = 6. */ + public static final int kDriverStationEIO_DigitalIn = 6; + /** kDriverStationEIO_DigitalOut = 7. */ + public static final int kDriverStationEIO_DigitalOut = 7; + /** kDriverStationEIO_FixedDigitalOut = 8. */ + public static final int kDriverStationEIO_FixedDigitalOut = 8; + /** kDriverStationEIO_PWM = 9. */ + public static final int kDriverStationEIO_PWM = 9; + /** kDriverStationEIO_Encoder = 10. */ + public static final int kDriverStationEIO_Encoder = 10; + /** kDriverStationEIO_TouchSlider = 11. */ + public static final int kDriverStationEIO_TouchSlider = 11; + /** kADXL345_SPI = 1. */ + public static final int kADXL345_SPI = 1; + /** kADXL345_I2C = 2. */ + public static final int kADXL345_I2C = 2; + /** kCommand_Scheduler = 1. */ + public static final int kCommand_Scheduler = 1; + /** kCommand2_Scheduler = 2. */ + public static final int kCommand2_Scheduler = 2; + /** kSmartDashboard_Instance = 1. */ + public static final int kSmartDashboard_Instance = 1; + /** kSmartDashboard_LiveWindow = 2. */ + public static final int kSmartDashboard_LiveWindow = 2; + /** kKinematics_DifferentialDrive = 1. */ + public static final int kKinematics_DifferentialDrive = 1; + /** kKinematics_MecanumDrive = 2. */ + public static final int kKinematics_MecanumDrive = 2; + /** kKinematics_SwerveDrive = 3. */ + public static final int kKinematics_SwerveDrive = 3; + /** kOdometry_DifferentialDrive = 1. */ + public static final int kOdometry_DifferentialDrive = 1; + /** kOdometry_MecanumDrive = 2. */ + public static final int kOdometry_MecanumDrive = 2; + /** kOdometry_SwerveDrive = 3. */ + public static final int kOdometry_SwerveDrive = 3; + } + + /** Utility class. */ + private FRCNetComm() {} +} diff --git a/hal/src/generated/main/native/include/hal/FRCUsageReporting.h b/hal/src/generated/main/native/include/hal/FRCUsageReporting.h new file mode 100644 index 00000000000..024ff13eb4f --- /dev/null +++ b/hal/src/generated/main/native/include/hal/FRCUsageReporting.h @@ -0,0 +1,228 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./hal/generate_usage_reporting.py. DO NOT MODIFY + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// ifdef's definition is to allow for default parameters in C++. +#ifdef __cplusplus +/** + * Reports a hardware usage to the HAL. + * + * @param resource the used resource + * @param instanceNumber the instance of the resource + * @param context a user specified context index + * @param feature a user specified feature string + * @return the index of the added value in NetComm + */ +int64_t HAL_Report(int32_t resource, int32_t instanceNumber, + int32_t context = 0, const char* feature = nullptr); +#else + +/** + * Reports a hardware usage to the HAL. + * + * @param resource the used resource + * @param instanceNumber the instance of the resource + * @param context a user specified context index + * @param feature a user specified feature string + * @return the index of the added value in NetComm + */ +int64_t HAL_Report(int32_t resource, int32_t instanceNumber, int32_t context, + const char* feature); +#endif + +#ifdef __cplusplus +} +#endif + +/* + * Autogenerated file! Do not manually edit this file. + */ + +#ifdef __cplusplus +namespace HALUsageReporting { + enum tResourceType : int32_t { + kResourceType_Controller = 0, + kResourceType_Module = 1, + kResourceType_Language = 2, + kResourceType_CANPlugin = 3, + kResourceType_Accelerometer = 4, + kResourceType_ADXL345 = 5, + kResourceType_AnalogChannel = 6, + kResourceType_AnalogTrigger = 7, + kResourceType_AnalogTriggerOutput = 8, + kResourceType_CANJaguar = 9, + kResourceType_Compressor = 10, + kResourceType_Counter = 11, + kResourceType_Dashboard = 12, + kResourceType_DigitalInput = 13, + kResourceType_DigitalOutput = 14, + kResourceType_DriverStationCIO = 15, + kResourceType_DriverStationEIO = 16, + kResourceType_DriverStationLCD = 17, + kResourceType_Encoder = 18, + kResourceType_GearTooth = 19, + kResourceType_Gyro = 20, + kResourceType_I2C = 21, + kResourceType_Framework = 22, + kResourceType_Jaguar = 23, + kResourceType_Joystick = 24, + kResourceType_Kinect = 25, + kResourceType_KinectStick = 26, + kResourceType_PIDController = 27, + kResourceType_Preferences = 28, + kResourceType_PWM = 29, + kResourceType_Relay = 30, + kResourceType_RobotDrive = 31, + kResourceType_SerialPort = 32, + kResourceType_Servo = 33, + kResourceType_Solenoid = 34, + kResourceType_SPI = 35, + kResourceType_Task = 36, + kResourceType_Ultrasonic = 37, + kResourceType_Victor = 38, + kResourceType_Button = 39, + kResourceType_Command = 40, + kResourceType_AxisCamera = 41, + kResourceType_PCVideoServer = 42, + kResourceType_SmartDashboard = 43, + kResourceType_Talon = 44, + kResourceType_HiTechnicColorSensor = 45, + kResourceType_HiTechnicAccel = 46, + kResourceType_HiTechnicCompass = 47, + kResourceType_SRF08 = 48, + kResourceType_AnalogOutput = 49, + kResourceType_VictorSP = 50, + kResourceType_PWMTalonSRX = 51, + kResourceType_CANTalonSRX = 52, + kResourceType_ADXL362 = 53, + kResourceType_ADXRS450 = 54, + kResourceType_RevSPARK = 55, + kResourceType_MindsensorsSD540 = 56, + kResourceType_DigitalGlitchFilter = 57, + kResourceType_ADIS16448 = 58, + kResourceType_PDP = 59, + kResourceType_PCM = 60, + kResourceType_PigeonIMU = 61, + kResourceType_NidecBrushless = 62, + kResourceType_CANifier = 63, + kResourceType_TalonFX = 64, + kResourceType_CTRE_future1 = 65, + kResourceType_CTRE_future2 = 66, + kResourceType_CTRE_future3 = 67, + kResourceType_CTRE_future4 = 68, + kResourceType_CTRE_future5 = 69, + kResourceType_CTRE_future6 = 70, + kResourceType_LinearFilter = 71, + kResourceType_XboxController = 72, + kResourceType_UsbCamera = 73, + kResourceType_NavX = 74, + kResourceType_Pixy = 75, + kResourceType_Pixy2 = 76, + kResourceType_ScanseSweep = 77, + kResourceType_Shuffleboard = 78, + kResourceType_CAN = 79, + kResourceType_DigilentDMC60 = 80, + kResourceType_PWMVictorSPX = 81, + kResourceType_RevSparkMaxPWM = 82, + kResourceType_RevSparkMaxCAN = 83, + kResourceType_ADIS16470 = 84, + kResourceType_PIDController2 = 85, + kResourceType_ProfiledPIDController = 86, + kResourceType_Kinematics = 87, + kResourceType_Odometry = 88, + kResourceType_Units = 89, + kResourceType_TrapezoidProfile = 90, + kResourceType_DutyCycle = 91, + kResourceType_AddressableLEDs = 92, + kResourceType_FusionVenom = 93, + kResourceType_CTRE_future7 = 94, + kResourceType_CTRE_future8 = 95, + kResourceType_CTRE_future9 = 96, + kResourceType_CTRE_future10 = 97, + kResourceType_CTRE_future11 = 98, + kResourceType_CTRE_future12 = 99, + kResourceType_CTRE_future13 = 100, + kResourceType_CTRE_future14 = 101, + kResourceType_ExponentialProfile = 102, + kResourceType_PS4Controller = 103, + kResourceType_PhotonCamera = 104, + kResourceType_PhotonPoseEstimator = 105, + kResourceType_PathPlannerPath = 106, + kResourceType_PathPlannerAuto = 107, + kResourceType_PathFindingCommand = 108, + kResourceType_Redux_future1 = 109, + kResourceType_Redux_future2 = 110, + kResourceType_Redux_future3 = 111, + kResourceType_Redux_future4 = 112, + kResourceType_Redux_future5 = 113, + kResourceType_RevSparkFlexCAN = 114, + kResourceType_RevSparkFlexPWM = 115, + }; + enum tInstances : int32_t { + kLanguage_LabVIEW = 1, + kLanguage_CPlusPlus = 2, + kLanguage_Java = 3, + kLanguage_Python = 4, + kLanguage_DotNet = 5, + kLanguage_Kotlin = 6, + kCANPlugin_BlackJagBridge = 1, + kCANPlugin_2CAN = 2, + kFramework_Iterative = 1, + kFramework_Simple = 2, + kFramework_CommandControl = 3, + kFramework_Timed = 4, + kFramework_ROS = 5, + kFramework_RobotBuilder = 6, + kFramework_AdvantageKit = 7, + kRobotDrive_ArcadeStandard = 1, + kRobotDrive_ArcadeButtonSpin = 2, + kRobotDrive_ArcadeRatioCurve = 3, + kRobotDrive_Tank = 4, + kRobotDrive_MecanumPolar = 5, + kRobotDrive_MecanumCartesian = 6, + kRobotDrive2_DifferentialArcade = 7, + kRobotDrive2_DifferentialTank = 8, + kRobotDrive2_DifferentialCurvature = 9, + kRobotDrive2_MecanumCartesian = 10, + kRobotDrive2_MecanumPolar = 11, + kRobotDrive2_KilloughCartesian = 12, + kRobotDrive2_KilloughPolar = 13, + kDriverStationCIO_Analog = 1, + kDriverStationCIO_DigitalIn = 2, + kDriverStationCIO_DigitalOut = 3, + kDriverStationEIO_Acceleration = 1, + kDriverStationEIO_AnalogIn = 2, + kDriverStationEIO_AnalogOut = 3, + kDriverStationEIO_Button = 4, + kDriverStationEIO_LED = 5, + kDriverStationEIO_DigitalIn = 6, + kDriverStationEIO_DigitalOut = 7, + kDriverStationEIO_FixedDigitalOut = 8, + kDriverStationEIO_PWM = 9, + kDriverStationEIO_Encoder = 10, + kDriverStationEIO_TouchSlider = 11, + kADXL345_SPI = 1, + kADXL345_I2C = 2, + kCommand_Scheduler = 1, + kCommand2_Scheduler = 2, + kSmartDashboard_Instance = 1, + kSmartDashboard_LiveWindow = 2, + kKinematics_DifferentialDrive = 1, + kKinematics_MecanumDrive = 2, + kKinematics_SwerveDrive = 3, + kOdometry_DifferentialDrive = 1, + kOdometry_MecanumDrive = 2, + kOdometry_SwerveDrive = 3, + }; +} +#endif diff --git a/hal/src/main/java/edu/wpi/first/hal/AccelerometerJNI.java b/hal/src/main/java/edu/wpi/first/hal/AccelerometerJNI.java index 5f34924eb54..fc1bbb588f8 100644 --- a/hal/src/main/java/edu/wpi/first/hal/AccelerometerJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/AccelerometerJNI.java @@ -59,4 +59,7 @@ public class AccelerometerJNI extends JNIWrapper { * @return the Z acceleration */ public static native double getAccelerometerZ(); + + /** Utility class. */ + private AccelerometerJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/AccumulatorResult.java b/hal/src/main/java/edu/wpi/first/hal/AccumulatorResult.java index f416ff8192d..569c94b00ae 100644 --- a/hal/src/main/java/edu/wpi/first/hal/AccumulatorResult.java +++ b/hal/src/main/java/edu/wpi/first/hal/AccumulatorResult.java @@ -13,6 +13,9 @@ public class AccumulatorResult { /** The number of sample value was accumulated over. */ public long count; + /** Constructs an AccumulatorResult. */ + public AccumulatorResult() {} + /** * Set the value and count. * diff --git a/hal/src/main/java/edu/wpi/first/hal/AddressableLEDJNI.java b/hal/src/main/java/edu/wpi/first/hal/AddressableLEDJNI.java index b2695a38274..a7a355237b0 100644 --- a/hal/src/main/java/edu/wpi/first/hal/AddressableLEDJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/AddressableLEDJNI.java @@ -97,4 +97,7 @@ public static native void setBitTiming( * @see "HAL_StopAddressableLEDOutput" */ public static native void stop(int handle); + + /** Utility class. */ + private AddressableLEDJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/AllianceStationID.java b/hal/src/main/java/edu/wpi/first/hal/AllianceStationID.java index 56c2143c818..6b1fd84ced6 100644 --- a/hal/src/main/java/edu/wpi/first/hal/AllianceStationID.java +++ b/hal/src/main/java/edu/wpi/first/hal/AllianceStationID.java @@ -4,12 +4,20 @@ package edu.wpi.first.hal; +/** Alliance station ID. */ public enum AllianceStationID { + /** Unknown. */ Unknown, + /** Red 1. */ Red1, + /** Red 2. */ Red2, + /** Red 3. */ Red3, + /** Blue 1. */ Blue1, + /** Blue 2. */ Blue2, + /** Blue 3. */ Blue3 } diff --git a/hal/src/main/java/edu/wpi/first/hal/AnalogGyroJNI.java b/hal/src/main/java/edu/wpi/first/hal/AnalogGyroJNI.java index cbc3d4f8e57..5d483f9c8a9 100644 --- a/hal/src/main/java/edu/wpi/first/hal/AnalogGyroJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/AnalogGyroJNI.java @@ -126,4 +126,7 @@ public static native void setAnalogGyroVoltsPerDegreePerSecond( * @see "HAL_GetAnalogGyroCenter" */ public static native int getAnalogGyroCenter(int handle); + + /** Utility class. */ + private AnalogGyroJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/AnalogJNI.java b/hal/src/main/java/edu/wpi/first/hal/AnalogJNI.java index bf8b27f4927..2884b8c95f0 100644 --- a/hal/src/main/java/edu/wpi/first/hal/AnalogJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/AnalogJNI.java @@ -84,6 +84,16 @@ public interface AnalogTriggerType { */ public static native boolean checkAnalogInputChannel(int channel); + /** + * Checks that the analog output channel number is valid. + * + *

Verifies that the analog channel number is one of the legal channel numbers. Channel numbers + * are 0-based. + * + * @param channel The analog output channel number. + * @return Analog channel is valid + * @see "HAL_CheckAnalogOutputChannel" + */ public static native boolean checkAnalogOutputChannel(int channel); /** @@ -95,8 +105,22 @@ public interface AnalogTriggerType { */ public static native void setAnalogInputSimDevice(int handle, int device); + /** + * Sets an analog output value. + * + * @param portHandle the analog output handle + * @param voltage the voltage (0-5v) to output + * @see "HAL_SetAnalogOutput" + */ public static native void setAnalogOutput(int portHandle, double voltage); + /** + * Gets the current analog output value. + * + * @param portHandle the analog output handle + * @return the current output voltage (0-5v) + * @see "HAL_GetAnalogOutput" + */ public static native double getAnalogOutput(int portHandle); /** @@ -497,4 +521,7 @@ public static native void setAnalogTriggerFiltered( * @see "HAL_GetAnalogTriggerFPGAIndex" */ public static native int getAnalogTriggerFPGAIndex(int analogTriggerHandle); + + /** Utility class. */ + private AnalogJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/CANAPIJNI.java b/hal/src/main/java/edu/wpi/first/hal/CANAPIJNI.java index b42def47ea9..90b16889054 100644 --- a/hal/src/main/java/edu/wpi/first/hal/CANAPIJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/CANAPIJNI.java @@ -177,4 +177,7 @@ public static native int writeCANPacketRepeatingNoThrow( */ public static native boolean readCANPacketTimeout( int handle, int apiId, int timeoutMs, CANData data); + + /** Utility class. */ + private CANAPIJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/CANAPITypes.java b/hal/src/main/java/edu/wpi/first/hal/CANAPITypes.java new file mode 100644 index 00000000000..5a8a3e6f86e --- /dev/null +++ b/hal/src/main/java/edu/wpi/first/hal/CANAPITypes.java @@ -0,0 +1,117 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.hal; + +/** + * CAN API Types. + * + *

This class defines enums for CAN device types and manufacturer IDs as specified in the WPILib + * documentation: https://docs.wpilib.org/en/stable/docs/software/can-devices/can-addressing.html + */ +@SuppressWarnings("PMD.MissingStaticMethodInNonInstantiatableClass") +public final class CANAPITypes { + /** + * FRC CAN device type. + * + *

This enum represents different types of CAN devices. Teams are encouraged to use the + * kMiscellaneous for custom or miscellaneous devices. + * + * @see CAN + * Device Types + */ + public enum CANDeviceType { + /** Broadcast. */ + kBroadcast(0), + /** Robot controller. */ + kRobotController(1), + /** Motor controller. */ + kMotorController(2), + /** Relay controller. */ + kRelayController(3), + /** Gyro sensor. */ + kGyroSensor(4), + /** Accelerometer. */ + kAccelerometer(5), + /** Ultrasonic sensor. */ + kUltrasonicSensor(6), + /** Gear tooth sensor. */ + kGearToothSensor(7), + /** Power distribution. */ + kPowerDistribution(8), + /** Pneumatics. */ + kPneumatics(9), + /** Miscellaneous. */ + kMiscellaneous(10), + /** IO breakout. */ + kIOBreakout(11), + /** Firmware update. */ + kFirmwareUpdate(31); + + @SuppressWarnings("PMD.MemberName") + public final int id; + + CANDeviceType(int id) { + this.id = id; + } + } + + /** + * FRC CAN manufacturer ID. + * + *

This enum represents different manufacturer IDs for CAN devices. Teams are encouraged to use + * the kTeamUse manufacturer ID for custom or team-specific devices. + * + * @see CAN + * Manufacturer IDs + */ + public enum CANManufacturer { + /** Broadcast. */ + kBroadcast(0), + /** National Instruments. */ + kNI(1), + /** Luminary Micro. */ + kLM(2), + /** DEKA Research and Development Corp. */ + kDEKA(3), + /** Cross the Road Electronics. */ + kCTRE(4), + /** REV Robotics. */ + kREV(5), + /** Grapple. */ + kGrapple(6), + /** MindSensors. */ + kMS(7), + /** Team use. */ + kTeamUse(8), + /** Kauai Labs. */ + kKauaiLabs(9), + /** Copperforge. */ + kCopperforge(10), + /** Playing With Fusion. */ + kPWF(11), + /** Studica. */ + kStudica(12), + /** TheThriftyBot. */ + kTheThriftyBot(13), + /** Redux Robotics. */ + kReduxRobotics(14), + /** AndyMark. */ + kAndyMark(15), + /** Vivid-Hosting. */ + kVividHosting(16); + + @SuppressWarnings("PMD.MemberName") + public final int id; + + CANManufacturer(int id) { + this.id = id; + } + } + + /** Utility class. */ + private CANAPITypes() {} +} diff --git a/hal/src/main/java/edu/wpi/first/hal/CANData.java b/hal/src/main/java/edu/wpi/first/hal/CANData.java index 0e2956888cb..ffd2f3919f5 100644 --- a/hal/src/main/java/edu/wpi/first/hal/CANData.java +++ b/hal/src/main/java/edu/wpi/first/hal/CANData.java @@ -15,6 +15,9 @@ public class CANData { /** CAN frame timestamp in milliseconds. */ public long timestamp; + /** Default constructor. */ + public CANData() {} + /** * API used from JNI to set the data. * diff --git a/hal/src/main/java/edu/wpi/first/hal/CANStreamMessage.java b/hal/src/main/java/edu/wpi/first/hal/CANStreamMessage.java index bdb21128544..5706aa080b8 100644 --- a/hal/src/main/java/edu/wpi/first/hal/CANStreamMessage.java +++ b/hal/src/main/java/edu/wpi/first/hal/CANStreamMessage.java @@ -17,6 +17,9 @@ public class CANStreamMessage { @SuppressWarnings("MemberName") public int messageID; + /** Default constructor. */ + public CANStreamMessage() {} + /** * API used from JNI to set the data. * diff --git a/hal/src/main/java/edu/wpi/first/hal/CTREPCMJNI.java b/hal/src/main/java/edu/wpi/first/hal/CTREPCMJNI.java index b657da592e2..0abe084dd94 100644 --- a/hal/src/main/java/edu/wpi/first/hal/CTREPCMJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/CTREPCMJNI.java @@ -221,4 +221,7 @@ public class CTREPCMJNI extends JNIWrapper { * @see "HAL_SetCTREPCMOneShotDuration" */ public static native void setOneShotDuration(int handle, int index, int durMs); + + /** Utility class. */ + private CTREPCMJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/ConstantsJNI.java b/hal/src/main/java/edu/wpi/first/hal/ConstantsJNI.java index 48434499ffe..2ccef74db35 100644 --- a/hal/src/main/java/edu/wpi/first/hal/ConstantsJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/ConstantsJNI.java @@ -17,4 +17,7 @@ public class ConstantsJNI extends JNIWrapper { * @see "HAL_GetSystemClockTicksPerMicrosecond" */ public static native int getSystemClockTicksPerMicrosecond(); + + /** Utility class. */ + private ConstantsJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/ControlWord.java b/hal/src/main/java/edu/wpi/first/hal/ControlWord.java index 7dff0f46359..31f8a7d0067 100644 --- a/hal/src/main/java/edu/wpi/first/hal/ControlWord.java +++ b/hal/src/main/java/edu/wpi/first/hal/ControlWord.java @@ -13,6 +13,9 @@ public class ControlWord { private boolean m_fmsAttached; private boolean m_dsAttached; + /** Default constructor. */ + public ControlWord() {} + void update( boolean enabled, boolean autonomous, diff --git a/hal/src/main/java/edu/wpi/first/hal/CounterJNI.java b/hal/src/main/java/edu/wpi/first/hal/CounterJNI.java index ebc4cffe265..6823185137c 100644 --- a/hal/src/main/java/edu/wpi/first/hal/CounterJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/CounterJNI.java @@ -279,4 +279,7 @@ public static native void setCounterDownSourceEdge( * @see "HAL_SetCounterReverseDirection" */ public static native void setCounterReverseDirection(int counterHandle, boolean reverseDirection); + + /** Utility class. */ + private CounterJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/DIOJNI.java b/hal/src/main/java/edu/wpi/first/hal/DIOJNI.java index 3330f4ad3c5..4d597cccddc 100644 --- a/hal/src/main/java/edu/wpi/first/hal/DIOJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/DIOJNI.java @@ -178,4 +178,7 @@ public class DIOJNI extends JNIWrapper { * @see "HAL_SetDigitalPWMOutputChannel" */ public static native void setDigitalPWMOutputChannel(int pwmGenerator, int channel); + + /** Utility class. */ + DIOJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/DMAJNI.java b/hal/src/main/java/edu/wpi/first/hal/DMAJNI.java index 00000d2f2b9..77eebf014ff 100644 --- a/hal/src/main/java/edu/wpi/first/hal/DMAJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/DMAJNI.java @@ -245,4 +245,7 @@ public static native long readDMA( * @return The DMA sample */ public static native DMAJNISample.BaseStore getSensorReadData(int handle); + + /** Utility class. */ + private DMAJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/DMAJNISample.java b/hal/src/main/java/edu/wpi/first/hal/DMAJNISample.java index 22f21c8c6b6..df66c558b0c 100644 --- a/hal/src/main/java/edu/wpi/first/hal/DMAJNISample.java +++ b/hal/src/main/java/edu/wpi/first/hal/DMAJNISample.java @@ -26,6 +26,9 @@ static class BaseStore { private long m_timeStamp; private Map m_propertyMap = new HashMap<>(); + /** Default constructor. */ + public DMAJNISample() {} + public int update(int dmaHandle, double timeoutSeconds) { m_timeStamp = DMAJNI.readDMA(dmaHandle, timeoutSeconds, m_dataBuffer, m_storage); return m_storage[25]; @@ -131,8 +134,7 @@ public int getAnalogInputAveraged(int analogInputHandle) { } // + 2 Hack, but needed to not have to call into JNI - int value = readValue(data.m_valueType + 2, data.m_index); - return value; + return readValue(data.m_valueType + 2, data.m_index); } public void getAnalogAccumulator(int analogInputHandle, AccumulatorResult result) { diff --git a/hal/src/main/java/edu/wpi/first/hal/DigitalGlitchFilterJNI.java b/hal/src/main/java/edu/wpi/first/hal/DigitalGlitchFilterJNI.java index 9a16984d89b..ececa130c55 100644 --- a/hal/src/main/java/edu/wpi/first/hal/DigitalGlitchFilterJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/DigitalGlitchFilterJNI.java @@ -59,4 +59,7 @@ public class DigitalGlitchFilterJNI extends JNIWrapper { * @see "HAL_GetFilterPeriod" */ public static native int getFilterPeriod(int filterIndex); + + /** Utility class. */ + private DigitalGlitchFilterJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/DriverStationJNI.java b/hal/src/main/java/edu/wpi/first/hal/DriverStationJNI.java index 4a46b525e16..26334e901a5 100644 --- a/hal/src/main/java/edu/wpi/first/hal/DriverStationJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/DriverStationJNI.java @@ -250,7 +250,7 @@ public static native void getAllJoystickData( * @see "HAL_SetJoystickOutputs" */ public static native int setJoystickOutputs( - byte joystickNum, int outputs, short leftRumble, short rightRumble); + byte joystickNum, int outputs, int leftRumble, int rightRumble); /** * Gets whether a specific joystick is considered to be an XBox controller. @@ -372,5 +372,6 @@ public static native int sendError( */ public static native boolean getOutputsActive(); + /** Utility class. */ private DriverStationJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/DutyCycleJNI.java b/hal/src/main/java/edu/wpi/first/hal/DutyCycleJNI.java index 1e7dfa0ccc6..6920b2970fb 100644 --- a/hal/src/main/java/edu/wpi/first/hal/DutyCycleJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/DutyCycleJNI.java @@ -78,4 +78,7 @@ public class DutyCycleJNI extends JNIWrapper { * @see "HAL_GetDutyCycleFPGAIndex" */ public static native int getFPGAIndex(int handle); + + /** Utility class. */ + private DutyCycleJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/EncoderJNI.java b/hal/src/main/java/edu/wpi/first/hal/EncoderJNI.java index d219db056bd..59503f8c43e 100644 --- a/hal/src/main/java/edu/wpi/first/hal/EncoderJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/EncoderJNI.java @@ -275,4 +275,7 @@ public static native void setEncoderIndexSource( * @see "HAL_GetEncoderEncodingType" */ public static native int getEncoderEncodingType(int encoderHandle); + + /** Utility class. */ + private EncoderJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/HAL.java b/hal/src/main/java/edu/wpi/first/hal/HAL.java index d9eb8d599db..68cf0e8deed 100644 --- a/hal/src/main/java/edu/wpi/first/hal/HAL.java +++ b/hal/src/main/java/edu/wpi/first/hal/HAL.java @@ -75,6 +75,9 @@ public final class HAL extends JNIWrapper { */ public static native void exitMain(); + /** Terminates the executable (at the native level). Does nothing in simulation. */ + public static native void terminate(); + private static native void simPeriodicBeforeNative(); private static final List s_simPeriodicBefore = new ArrayList<>(); diff --git a/hal/src/main/java/edu/wpi/first/hal/HALUtil.java b/hal/src/main/java/edu/wpi/first/hal/HALUtil.java index 11d9b4d74a8..0cadf3914cc 100644 --- a/hal/src/main/java/edu/wpi/first/hal/HALUtil.java +++ b/hal/src/main/java/edu/wpi/first/hal/HALUtil.java @@ -90,6 +90,10 @@ public final class HALUtil extends JNIWrapper { /** * Gets the state of the "USER" button on the roboRIO. * + *

Warning: the User Button is used to stop user programs from automatically loading if it is + * held for more then 5 seconds. Because of this, it's not recommended to be used by teams for any + * other purpose. + * * @return true if the button is currently pressed down * @see "HAL_GetFPGAButton" */ diff --git a/hal/src/main/java/edu/wpi/first/hal/I2CJNI.java b/hal/src/main/java/edu/wpi/first/hal/I2CJNI.java index 90e8ddb4d8f..1b729af805c 100644 --- a/hal/src/main/java/edu/wpi/first/hal/I2CJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/I2CJNI.java @@ -135,4 +135,7 @@ public static native int i2CRead( * @see "HAL_CloseI2C" */ public static native void i2CClose(int port); + + /** Utility class. */ + private I2CJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/InterruptJNI.java b/hal/src/main/java/edu/wpi/first/hal/InterruptJNI.java index c60543566bd..ec60b839236 100644 --- a/hal/src/main/java/edu/wpi/first/hal/InterruptJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/InterruptJNI.java @@ -113,4 +113,7 @@ public static native void setInterruptUpSourceEdge( * @see "HAL_ReleaseWaitingInterrupt" */ public static native void releaseWaitingInterrupt(int interruptHandle); + + /** Utility class. */ + private InterruptJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/JNIWrapper.java b/hal/src/main/java/edu/wpi/first/hal/JNIWrapper.java index 6826cd80743..49bcb4a5ec8 100644 --- a/hal/src/main/java/edu/wpi/first/hal/JNIWrapper.java +++ b/hal/src/main/java/edu/wpi/first/hal/JNIWrapper.java @@ -13,16 +13,30 @@ public class JNIWrapper { static boolean libraryLoaded = false; static RuntimeLoader loader = null; + /** Sets whether JNI should be loaded in the static block. */ public static class Helper { private static AtomicBoolean extractOnStaticLoad = new AtomicBoolean(true); + /** + * Returns true if the JNI should be loaded in the static block. + * + * @return True if the JNI should be loaded in the static block. + */ public static boolean getExtractOnStaticLoad() { return extractOnStaticLoad.get(); } + /** + * Sets whether the JNI should be loaded in the static block. + * + * @param load Whether the JNI should be loaded in the static block. + */ public static void setExtractOnStaticLoad(boolean load) { extractOnStaticLoad.set(load); } + + /** Utility class. */ + private Helper() {} } static { @@ -57,4 +71,7 @@ public static synchronized void forceLoad() throws IOException { } public static void suppressUnused(Object object) {} + + /** Utility class. */ + public JNIWrapper() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/LEDJNI.java b/hal/src/main/java/edu/wpi/first/hal/LEDJNI.java new file mode 100644 index 00000000000..397328eac47 --- /dev/null +++ b/hal/src/main/java/edu/wpi/first/hal/LEDJNI.java @@ -0,0 +1,31 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.hal; + +public class LEDJNI extends JNIWrapper { + public static final int RADIO_LED_STATE_OFF = 0; + public static final int RADIO_LED_STATE_GREEN = 1; + public static final int RADIO_LED_STATE_RED = 2; + public static final int RADIO_LED_STATE_ORANGE = 3; + + /** + * Set the state of the "Radio" LED. + * + * @param state The state to set the LED to. + * @see "HAL_SetRadioLEDState" + */ + public static native void setRadioLEDState(int state); + + /** + * Get the state of the "Radio" LED. + * + * @return The state of the LED. + * @see "HAL_GetRadioLEDState" + */ + public static native int getRadioLEDState(); + + /** Utility class. */ + private LEDJNI() {} +} diff --git a/hal/src/main/java/edu/wpi/first/hal/MatchInfoData.java b/hal/src/main/java/edu/wpi/first/hal/MatchInfoData.java index 699ecc59fd3..d9e9796a343 100644 --- a/hal/src/main/java/edu/wpi/first/hal/MatchInfoData.java +++ b/hal/src/main/java/edu/wpi/first/hal/MatchInfoData.java @@ -22,6 +22,9 @@ public class MatchInfoData { /** Stores the match type. */ public int matchType; + /** Default constructor. */ + public MatchInfoData() {} + /** * Called from JNI to set the structure data. * diff --git a/hal/src/main/java/edu/wpi/first/hal/NotifierJNI.java b/hal/src/main/java/edu/wpi/first/hal/NotifierJNI.java index 5620f032dee..04784bcf4d5 100644 --- a/hal/src/main/java/edu/wpi/first/hal/NotifierJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/NotifierJNI.java @@ -101,4 +101,7 @@ public class NotifierJNI extends JNIWrapper { * @return the FPGA time the notifier returned */ public static native long waitForNotifierAlarm(int notifierHandle); + + /** Utility class. */ + private NotifierJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/PWMJNI.java b/hal/src/main/java/edu/wpi/first/hal/PWMJNI.java index dc2abc10768..3f0e3d4be68 100644 --- a/hal/src/main/java/edu/wpi/first/hal/PWMJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/PWMJNI.java @@ -5,12 +5,41 @@ package edu.wpi.first.hal; public class PWMJNI extends DIOJNI { + /** + * Initializes a PWM port. + * + * @param halPortHandle the port to initialize + * @return the created pwm handle + */ public static native int initializePWMPort(int halPortHandle); + /** + * Checks if a pwm channel is valid. + * + * @param channel the channel to check + * @return true if the channel is valid, otherwise false + */ public static native boolean checkPWMChannel(int channel); + /** + * Frees a PWM port. + * + * @param pwmPortHandle the pwm handle + */ public static native void freePWMPort(int pwmPortHandle); + /** + * Sets the configuration settings for the PWM channel. + * + *

All values are in microseconds. + * + * @param pwmPortHandle the PWM handle + * @param maxPwm the maximum PWM value + * @param deadbandMaxPwm the high range of the center deadband + * @param centerPwm the center PWM value + * @param deadbandMinPwm the low range of the center deadband + * @param minPwm the minimum PWM value + */ public static native void setPWMConfigMicroseconds( int pwmPortHandle, int maxPwm, @@ -19,29 +48,122 @@ public static native void setPWMConfigMicroseconds( int deadbandMinPwm, int minPwm); + /** + * Gets the pwm configuration settings for the PWM channel. + * + *

Values are in microseconds. + * + * @param pwmPortHandle the PWM handle + * @return the pwm configuration settings + */ public static native PWMConfigDataResult getPWMConfigMicroseconds(int pwmPortHandle); + /** + * Sets if the FPGA should output the center value if the input value is within the deadband. + * + * @param pwmPortHandle the PWM handle + * @param eliminateDeadband true to eliminate deadband, otherwise false + */ public static native void setPWMEliminateDeadband(int pwmPortHandle, boolean eliminateDeadband); + /** + * Gets the current eliminate deadband value. + * + * @param pwmPortHandle the PWM handle + * @return true if set, otherwise false + */ public static native boolean getPWMEliminateDeadband(int pwmPortHandle); + /** + * Sets a PWM channel to the desired pulse width in microseconds. + * + * @param pwmPortHandle the PWM handle + * @param microsecondPulseTime the PWM value to set + */ public static native void setPulseTimeMicroseconds(int pwmPortHandle, int microsecondPulseTime); + /** + * Sets a PWM channel to the desired scaled value. + * + *

The values range from -1 to 1 and the period is controlled by the PWM Period and MinHigh + * registers. + * + * @param pwmPortHandle the PWM handle + * @param speed the scaled PWM value to set + */ public static native void setPWMSpeed(int pwmPortHandle, double speed); + /** + * Sets a PWM channel to the desired position value. + * + *

The values range from 0 to 1 and the period is controlled by the PWM Period and MinHigh + * registers. + * + * @param pwmPortHandle the PWM handle + * @param position the positional PWM value to set + */ public static native void setPWMPosition(int pwmPortHandle, double position); + /** + * Gets the current microsecond pulse time from a PWM channel. + * + * @param pwmPortHandle the PWM handle + * @return the current PWM microsecond pulse time + */ public static native int getPulseTimeMicroseconds(int pwmPortHandle); + /** + * Gets a scaled value from a PWM channel. + * + *

The values range from -1 to 1. + * + * @param pwmPortHandle the PWM handle + * @return the current speed PWM value + */ public static native double getPWMSpeed(int pwmPortHandle); + /** + * Gets a position value from a PWM channel. + * + *

The values range from 0 to 1. + * + * @param pwmPortHandle the PWM handle + * @return the current positional PWM value + */ public static native double getPWMPosition(int pwmPortHandle); + /** + * Sets a PWM channel to be disabled. + * + *

The channel is disabled until the next time it is set. Note this is different from just + * setting a 0 speed, as this will actively stop all signaling on the channel. + * + * @param pwmPortHandle the PWM handle. + */ public static native void setPWMDisabled(int pwmPortHandle); + /** + * Forces a PWM signal to go to 0 temporarily. + * + * @param pwmPortHandle the PWM handle. + */ public static native void latchPWMZero(int pwmPortHandle); + /** + * Sets the PWM output to be a continuous high signal while enabled. + * + * @param pwmPortHandle the PWM handle. + */ public static native void setAlwaysHighMode(int pwmPortHandle); + /** + * Sets how how often the PWM signal is squelched, thus scaling the period. + * + * @param pwmPortHandle the PWM handle. + * @param squelchMask the 2-bit mask of outputs to squelch + */ public static native void setPWMPeriodScale(int pwmPortHandle, int squelchMask); + + /** Utility class. */ + private PWMJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/PortsJNI.java b/hal/src/main/java/edu/wpi/first/hal/PortsJNI.java index 20f9b42110d..b47697b0e62 100644 --- a/hal/src/main/java/edu/wpi/first/hal/PortsJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/PortsJNI.java @@ -185,4 +185,7 @@ public class PortsJNI extends JNIWrapper { * @see "HAL_GetNumREVPHChannels" */ public static native int getNumREVPHChannels(); + + /** Utility class. */ + private PortsJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/PowerDistributionFaults.java b/hal/src/main/java/edu/wpi/first/hal/PowerDistributionFaults.java index aa2cac5b6b5..ffc27930f2e 100644 --- a/hal/src/main/java/edu/wpi/first/hal/PowerDistributionFaults.java +++ b/hal/src/main/java/edu/wpi/first/hal/PowerDistributionFaults.java @@ -60,6 +60,69 @@ public class PowerDistributionFaults { public final boolean HardwareFault; + /** + * Gets whether there is a breaker fault at the specified channel. + * + * @param channel Channel to check for faults. + * @return True if there is a breaker fault at the channel, otherwise false. + * @throws IndexOutOfBoundsException if the provided channel is outside of the range supported by + * the hardware. + */ + public final boolean getBreakerFault(int channel) { + switch (channel) { + case 0: + return Channel0BreakerFault; + case 1: + return Channel1BreakerFault; + case 2: + return Channel2BreakerFault; + case 3: + return Channel3BreakerFault; + case 4: + return Channel4BreakerFault; + case 5: + return Channel5BreakerFault; + case 6: + return Channel6BreakerFault; + case 7: + return Channel7BreakerFault; + case 8: + return Channel8BreakerFault; + case 9: + return Channel9BreakerFault; + case 10: + return Channel10BreakerFault; + case 11: + return Channel11BreakerFault; + case 12: + return Channel12BreakerFault; + case 13: + return Channel13BreakerFault; + case 14: + return Channel14BreakerFault; + case 15: + return Channel15BreakerFault; + case 16: + return Channel16BreakerFault; + case 17: + return Channel17BreakerFault; + case 18: + return Channel18BreakerFault; + case 19: + return Channel19BreakerFault; + case 20: + return Channel20BreakerFault; + case 21: + return Channel21BreakerFault; + case 22: + return Channel22BreakerFault; + case 23: + return Channel23BreakerFault; + default: + throw new IndexOutOfBoundsException("Power distribution fault channel out of bounds!"); + } + } + /** * Constructs from a bitfield. * diff --git a/hal/src/main/java/edu/wpi/first/hal/PowerDistributionJNI.java b/hal/src/main/java/edu/wpi/first/hal/PowerDistributionJNI.java index bc7060d2b4b..f2b096ccf72 100644 --- a/hal/src/main/java/edu/wpi/first/hal/PowerDistributionJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/PowerDistributionJNI.java @@ -83,6 +83,8 @@ public class PowerDistributionJNI extends JNIWrapper { /** * Gets the temperature of the PowerDistribution. * + *

Not supported on the Rev PDH and returns 0. + * * @param handle the module handle * @return the module temperature (celsius) * @see "HAL_GetPowerDistributionTemperature" @@ -129,7 +131,9 @@ public class PowerDistributionJNI extends JNIWrapper { public static native double getTotalCurrent(int handle); /** - * Gets the total power of the PowerDistribution. + * Gets the total power of the Power Distribution Panel. + * + *

Not supported on the Rev PDH and returns 0. * * @param handle the module handle * @return the total power (watts) @@ -138,7 +142,9 @@ public class PowerDistributionJNI extends JNIWrapper { public static native double getTotalPower(int handle); /** - * Gets the total energy of the PowerDistribution. + * Gets the total energy of the Power Distribution Panel. + * + *

Not supported on the Rev PDH and does nothing. * * @param handle the module handle * @return the total energy (joules) @@ -147,7 +153,9 @@ public class PowerDistributionJNI extends JNIWrapper { public static native double getTotalEnergy(int handle); /** - * Resets the PowerDistribution accumulated energy. + * Resets the Power Distribution Panel accumulated energy. + * + *

Not supported on the Rev PDH and returns 0. * * @param handle the module handle * @see "HAL_ClearPowerDistributionStickyFaults" @@ -282,4 +290,7 @@ public static PowerDistributionStickyFaults getStickyFaults(int handle) { * @see "HAL_GetPowerDistributionVersion" */ public static native PowerDistributionVersion getVersion(int handle); + + /** Utility class. */ + private PowerDistributionJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/PowerDistributionStickyFaults.java b/hal/src/main/java/edu/wpi/first/hal/PowerDistributionStickyFaults.java index f60f8df9108..060fbf5a537 100644 --- a/hal/src/main/java/edu/wpi/first/hal/PowerDistributionStickyFaults.java +++ b/hal/src/main/java/edu/wpi/first/hal/PowerDistributionStickyFaults.java @@ -62,6 +62,69 @@ public class PowerDistributionStickyFaults { public final boolean HasReset; + /** + * Gets whether there is a sticky breaker fault at the specified channel. + * + * @param channel Channel to check for sticky faults. + * @return True if there is a sticky breaker fault at the channel, otherwise false. + * @throws IndexOutOfBoundsException if the provided channel is outside of the range supported by + * the hardware. + */ + public final boolean getBreakerFault(int channel) { + switch (channel) { + case 0: + return Channel0BreakerFault; + case 1: + return Channel1BreakerFault; + case 2: + return Channel2BreakerFault; + case 3: + return Channel3BreakerFault; + case 4: + return Channel4BreakerFault; + case 5: + return Channel5BreakerFault; + case 6: + return Channel6BreakerFault; + case 7: + return Channel7BreakerFault; + case 8: + return Channel8BreakerFault; + case 9: + return Channel9BreakerFault; + case 10: + return Channel10BreakerFault; + case 11: + return Channel11BreakerFault; + case 12: + return Channel12BreakerFault; + case 13: + return Channel13BreakerFault; + case 14: + return Channel14BreakerFault; + case 15: + return Channel15BreakerFault; + case 16: + return Channel16BreakerFault; + case 17: + return Channel17BreakerFault; + case 18: + return Channel18BreakerFault; + case 19: + return Channel19BreakerFault; + case 20: + return Channel20BreakerFault; + case 21: + return Channel21BreakerFault; + case 22: + return Channel22BreakerFault; + case 23: + return Channel23BreakerFault; + default: + throw new IndexOutOfBoundsException("Power distribution fault channel out of bounds!"); + } + } + /** * Constructs from a bitfield. * diff --git a/hal/src/main/java/edu/wpi/first/hal/PowerDistributionVersion.java b/hal/src/main/java/edu/wpi/first/hal/PowerDistributionVersion.java index fdd1233b25a..bfb5ff2d0e3 100644 --- a/hal/src/main/java/edu/wpi/first/hal/PowerDistributionVersion.java +++ b/hal/src/main/java/edu/wpi/first/hal/PowerDistributionVersion.java @@ -4,18 +4,25 @@ package edu.wpi.first.hal; +/** Power distribution version. */ @SuppressWarnings("MemberName") public class PowerDistributionVersion { + /** Firmware major version number. */ public final int firmwareMajor; + /** Firmware minor version number. */ public final int firmwareMinor; + /** Firmware fix version number. */ public final int firmwareFix; + /** Hardware minor version number. */ public final int hardwareMinor; + /** Hardware major version number. */ public final int hardwareMajor; + /** Unique ID. */ public final int uniqueId; /** diff --git a/hal/src/main/java/edu/wpi/first/hal/PowerJNI.java b/hal/src/main/java/edu/wpi/first/hal/PowerJNI.java index 8dd9548cca5..900b423f344 100644 --- a/hal/src/main/java/edu/wpi/first/hal/PowerJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/PowerJNI.java @@ -167,4 +167,7 @@ public class PowerJNI extends JNIWrapper { * @return current CPU temperature in degrees Celsius */ public static native double getCPUTemp(); + + /** Utility class. */ + private PowerJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/REVPHFaults.java b/hal/src/main/java/edu/wpi/first/hal/REVPHFaults.java index 23f0882c84b..931f8b78db3 100644 --- a/hal/src/main/java/edu/wpi/first/hal/REVPHFaults.java +++ b/hal/src/main/java/edu/wpi/first/hal/REVPHFaults.java @@ -50,6 +50,53 @@ public class REVPHFaults { public final boolean HardwareFault; + /** + * Gets whether there is a fault at the specified channel. + * + * @param channel Channel to check for faults. + * @return True if a a fault exists at the channel, otherwise false. + * @throws IndexOutOfBoundsException if the provided channel is outside of the range supported by + * the hardware. + */ + public final boolean getChannelFault(int channel) { + switch (channel) { + case 0: + return Channel0Fault; + case 1: + return Channel1Fault; + case 2: + return Channel2Fault; + case 3: + return Channel3Fault; + case 4: + return Channel4Fault; + case 5: + return Channel5Fault; + case 6: + return Channel6Fault; + case 7: + return Channel7Fault; + case 8: + return Channel8Fault; + case 9: + return Channel9Fault; + case 10: + return Channel10Fault; + case 11: + return Channel11Fault; + case 12: + return Channel12Fault; + case 13: + return Channel13Fault; + case 14: + return Channel14Fault; + case 15: + return Channel15Fault; + default: + throw new IndexOutOfBoundsException("Pneumatics fault channel out of bounds!"); + } + } + /** * Called from HAL to construct. * diff --git a/hal/src/main/java/edu/wpi/first/hal/REVPHJNI.java b/hal/src/main/java/edu/wpi/first/hal/REVPHJNI.java index b1935b2f983..1180b9b107c 100644 --- a/hal/src/main/java/edu/wpi/first/hal/REVPHJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/REVPHJNI.java @@ -286,4 +286,7 @@ public static REVPHFaults getFaults(int handle) { * @see "HAL_GetREVPHVersion" */ public static native REVPHVersion getVersion(int handle); + + /** Utility class. */ + private REVPHJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/RelayJNI.java b/hal/src/main/java/edu/wpi/first/hal/RelayJNI.java index 10a39b4884e..abe146e1a6c 100644 --- a/hal/src/main/java/edu/wpi/first/hal/RelayJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/RelayJNI.java @@ -57,4 +57,7 @@ public class RelayJNI extends DIOJNI { * @see "HAL_GetRelay" */ public static native boolean getRelay(int relayPortHandle); + + /** Utility class. */ + private RelayJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/SPIJNI.java b/hal/src/main/java/edu/wpi/first/hal/SPIJNI.java index 82b9fed1602..18a0a8e7672 100644 --- a/hal/src/main/java/edu/wpi/first/hal/SPIJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/SPIJNI.java @@ -302,4 +302,7 @@ public static native int spiReadAutoReceivedData( */ public static native void spiConfigureAutoStall( int port, int csToSclkTicks, int stallTicks, int pow2BytesPerRead); + + /** Utility class. */ + private SPIJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/SerialPortJNI.java b/hal/src/main/java/edu/wpi/first/hal/SerialPortJNI.java index e156f3a0a67..052218fbe79 100644 --- a/hal/src/main/java/edu/wpi/first/hal/SerialPortJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/SerialPortJNI.java @@ -205,4 +205,7 @@ public class SerialPortJNI extends JNIWrapper { * @see "HAL_CloseSerial" */ public static native void serialClose(int handle); + + /** Utility class. */ + private SerialPortJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/SimDevice.java b/hal/src/main/java/edu/wpi/first/hal/SimDevice.java index 21ac69aaaaf..4c57d05595e 100644 --- a/hal/src/main/java/edu/wpi/first/hal/SimDevice.java +++ b/hal/src/main/java/edu/wpi/first/hal/SimDevice.java @@ -16,9 +16,13 @@ * edu.wpi.first.wpilibj.ADXRS450_Gyro} for an example implementation. */ public class SimDevice implements AutoCloseable { + /** Sim device direction. */ public enum Direction { + /** Input direction for simulation devices. */ kInput(SimDeviceJNI.kInput), + /** Output direction for simulation devices. */ kOutput(SimDeviceJNI.kOutput), + /** Bidirectional direction for simulation devices. */ kBidir(SimDeviceJNI.kBidir); public final int m_value; diff --git a/hal/src/main/java/edu/wpi/first/hal/SimDeviceJNI.java b/hal/src/main/java/edu/wpi/first/hal/SimDeviceJNI.java index 4352a2df481..fdf09b4435b 100644 --- a/hal/src/main/java/edu/wpi/first/hal/SimDeviceJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/SimDeviceJNI.java @@ -286,4 +286,7 @@ public static void setSimValueBoolean(int handle, boolean value) { * @param handle simulated value handle */ public static native void resetSimValue(int handle); + + /** Utility class. */ + private SimDeviceJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/ThreadsJNI.java b/hal/src/main/java/edu/wpi/first/hal/ThreadsJNI.java index 2ccc8085603..2183ae3d557 100644 --- a/hal/src/main/java/edu/wpi/first/hal/ThreadsJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/ThreadsJNI.java @@ -37,4 +37,7 @@ public class ThreadsJNI extends JNIWrapper { * @see "HAL_SetCurrentThreadPriority" */ public static native boolean setCurrentThreadPriority(boolean realTime, int priority); + + /** Utility class. */ + private ThreadsJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/can/CANExceptionFactory.java b/hal/src/main/java/edu/wpi/first/hal/can/CANExceptionFactory.java index d8fe36e230c..a4ad1e2af0f 100644 --- a/hal/src/main/java/edu/wpi/first/hal/can/CANExceptionFactory.java +++ b/hal/src/main/java/edu/wpi/first/hal/can/CANExceptionFactory.java @@ -7,6 +7,9 @@ import edu.wpi.first.hal.communication.NIRioStatus; import edu.wpi.first.hal.util.UncleanStatusException; +/** + * Checks the status of a CAN message and throws an exception of the appropriate type if necessary. + */ public final class CANExceptionFactory { // FRC Error codes static final int ERR_CANSessionMux_InvalidBuffer = -44086; diff --git a/hal/src/main/java/edu/wpi/first/hal/can/CANJNI.java b/hal/src/main/java/edu/wpi/first/hal/can/CANJNI.java index e0734dd369e..ba9ac791ed7 100644 --- a/hal/src/main/java/edu/wpi/first/hal/can/CANJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/can/CANJNI.java @@ -9,27 +9,91 @@ import java.nio.ByteBuffer; import java.nio.IntBuffer; +/** + * CAN API HAL JNI Functions. + * + * @see "hal/CAN.h" + */ @SuppressWarnings("MethodName") public class CANJNI extends JNIWrapper { + /** Flag for sending a CAN message once. */ public static final int CAN_SEND_PERIOD_NO_REPEAT = 0; + + /** Flag for stopping periodic CAN message sends. */ public static final int CAN_SEND_PERIOD_STOP_REPEATING = -1; - /* Flags in the upper bits of the messageID */ + /** Mask for "is frame remote" in message ID. */ public static final int CAN_IS_FRAME_REMOTE = 0x80000000; + + /** Mask for "is frame 11 bits" in message ID. */ public static final int CAN_IS_FRAME_11BIT = 0x40000000; + /** Default constructor. */ + public CANJNI() {} + + /** + * Sends a CAN message. + * + * @param messageID The ID of the CAN message. + * @param data The data bytes to be sent. + * @param periodMs The period in milliseconds at which to send the message, use {@link + * #CAN_SEND_PERIOD_NO_REPEAT} for a single send. + */ public static native void FRCNetCommCANSessionMuxSendMessage( int messageID, byte[] data, int periodMs); + /** + * Receives a CAN message. + * + * @param messageID store for the received message ID (output parameter). + * @param messageIDMask the message ID mask to look for + * @param timeStamp the packet received timestamp (based off of CLOCK_MONOTONIC) (output + * parameter). + * @return The data bytes of the received message. + */ public static native byte[] FRCNetCommCANSessionMuxReceiveMessage( IntBuffer messageID, int messageIDMask, ByteBuffer timeStamp); + /** + * Retrieves the current status of the CAN bus. + * + * @param status The CANStatus object to hold the retrieved status. + */ public static native void getCANStatus(CANStatus status); + /** + * Opens a new CAN stream session for receiving CAN messages with specified filters. + * + * @param messageID The CAN messageID to match against. The bits of the messageID are bitwise + * ANDed with the messageIDMask. + * @param messageIDMask The CAN messageIDMask is a bit-wise mask of bits in the messageID to match + * against. This allows matching against multiple frames. For example, providing an messageID + * of 0x2050001 and a mask of 0x1FFF003F would match all REV motor controller frames for a + * device with CAN ID 1. Providing a mask of 0x1FFFFFFF means that only the exact messageID + * will be matched. Providing a mask of 0 would match any frame of any type. + * @param maxMessages The maximum number of messages that can be buffered in the session. + * @return The handle to the opened CAN stream session. + */ public static native int openCANStreamSession(int messageID, int messageIDMask, int maxMessages); + /** + * Closes a CAN stream session. + * + * @param sessionHandle The handle of the CAN stream session to be closed. + */ public static native void closeCANStreamSession(int sessionHandle); + /** + * Reads messages from a CAN stream session. + * + * @param sessionHandle The handle of the CAN stream session. + * @param messages An array to hold the CANStreamMessage objects (output parameter). + * @param messagesToRead The number of messages to read from the session. + * @return The number of messages read into the buffer + * @throws CANStreamOverflowException If the number of messages to read exceeds the capacity of + * the provided messages array. + */ public static native int readCANStreamSession( - int sessionHandle, CANStreamMessage[] messages, int messagesToRead); + int sessionHandle, CANStreamMessage[] messages, int messagesToRead) + throws CANStreamOverflowException; } diff --git a/hal/src/main/java/edu/wpi/first/hal/can/CANStatus.java b/hal/src/main/java/edu/wpi/first/hal/can/CANStatus.java index 8ec89f74a2a..1966a17c83a 100644 --- a/hal/src/main/java/edu/wpi/first/hal/can/CANStatus.java +++ b/hal/src/main/java/edu/wpi/first/hal/can/CANStatus.java @@ -22,6 +22,9 @@ public class CANStatus { /** The CAN Bus transmit error count. */ public int transmitErrorCount; + /** Default constructor. */ + public CANStatus() {} + /** * Set CAN bus status. * diff --git a/hal/src/main/java/edu/wpi/first/hal/can/CANStreamOverflowException.java b/hal/src/main/java/edu/wpi/first/hal/can/CANStreamOverflowException.java new file mode 100644 index 00000000000..f5e2f21358c --- /dev/null +++ b/hal/src/main/java/edu/wpi/first/hal/can/CANStreamOverflowException.java @@ -0,0 +1,38 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.hal.can; + +import edu.wpi.first.hal.CANStreamMessage; +import java.io.IOException; + +public class CANStreamOverflowException extends IOException { + /** The messages. */ + private final CANStreamMessage[] m_messages; + + /** The length of messages read. */ + private final int m_messagesRead; + + /** + * Constructs a new CANStreamOverflowException. + * + * @param messages The messages + * @param messagesRead The length of messages read + */ + @SuppressWarnings("PMD.ArrayIsStoredDirectly") + public CANStreamOverflowException(CANStreamMessage[] messages, int messagesRead) { + super("A CAN Stream has overflowed. Data will be missed"); + this.m_messages = messages; + this.m_messagesRead = messagesRead; + } + + @SuppressWarnings("PMD.MethodReturnsInternalArray") + public CANStreamMessage[] getMessages() { + return m_messages; + } + + public int getMessagesRead() { + return m_messagesRead; + } +} diff --git a/hal/src/main/java/edu/wpi/first/hal/communication/NIRioStatus.java b/hal/src/main/java/edu/wpi/first/hal/communication/NIRioStatus.java index ad17a3e911c..f689b600c45 100644 --- a/hal/src/main/java/edu/wpi/first/hal/communication/NIRioStatus.java +++ b/hal/src/main/java/edu/wpi/first/hal/communication/NIRioStatus.java @@ -4,12 +4,26 @@ package edu.wpi.first.hal.communication; +/** NI RIO status. */ public class NIRioStatus { + /** RIO status offset. */ public static final int kRioStatusOffset = -63000; + /** Success. */ public static final int kRioStatusSuccess = 0; + + /** Buffer invalid size. */ public static final int kRIOStatusBufferInvalidSize = kRioStatusOffset - 80; + + /** Operation timed out. */ public static final int kRIOStatusOperationTimedOut = -52007; + + /** Feature not supported. */ public static final int kRIOStatusFeatureNotSupported = kRioStatusOffset - 193; + + /** Resource not initialized. */ public static final int kRIOStatusResourceNotInitialized = -52010; + + /** Default constructor. */ + public NIRioStatus() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/AccelerometerDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/AccelerometerDataJNI.java index 5ea3726eb75..26975c08404 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/AccelerometerDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/AccelerometerDataJNI.java @@ -6,7 +6,16 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for accelerometer data. */ public class AccelerometerDataJNI extends JNIWrapper { + /** + * Register a callback to be run when this accelerometer activates. + * + * @param index the index + * @param callback the callback + * @param initialNotify whether to run the callback with the initial state + * @return the CallbackStore object associated with this callback + */ public static native int registerActiveCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -53,4 +62,7 @@ public static native int registerZCallback( public static native void setZ(int index, double z); public static native void resetData(int index); + + /** Utility class. */ + private AccelerometerDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/AddressableLEDDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/AddressableLEDDataJNI.java index 8ba0e94c7b5..b1465352cb8 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/AddressableLEDDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/AddressableLEDDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for addressable LED data. */ public class AddressableLEDDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -54,4 +55,7 @@ public static native int registerRunningCallback( public static native void resetData(int index); public static native int findForChannel(int channel); + + /** Utility class. */ + private AddressableLEDDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogGyroDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogGyroDataJNI.java index a6acc9aa0da..b369dcda15a 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogGyroDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogGyroDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for analog gyro data. */ public class AnalogGyroDataJNI extends JNIWrapper { public static native int registerAngleCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -35,4 +36,7 @@ public static native int registerInitializedCallback( public static native void setInitialized(int index, boolean initialized); public static native void resetData(int index); + + /** Utility class. */ + private AnalogGyroDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogInDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogInDataJNI.java index 4229c09574d..b3dde0e176a 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogInDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogInDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for analog input data. */ public class AnalogInDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -89,4 +90,7 @@ public static native int registerAccumulatorDeadbandCallback( public static native void setAccumulatorDeadband(int index, int AccumulatorDeadband); public static native void resetData(int index); + + /** Utility class. */ + private AnalogInDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogOutDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogOutDataJNI.java index 6af16a0957c..f8e4eeccd1e 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogOutDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogOutDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for analog output data. */ public class AnalogOutDataJNI extends JNIWrapper { public static native int registerVoltageCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -26,4 +27,7 @@ public static native int registerInitializedCallback( public static native void setInitialized(int index, boolean initialized); public static native void resetData(int index); + + /** Utility class. */ + private AnalogOutDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogTriggerDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogTriggerDataJNI.java index 67b65b50c93..681e5bd8c7a 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogTriggerDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/AnalogTriggerDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for analog trigger data. */ public class AnalogTriggerDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -37,4 +38,7 @@ public static native int registerTriggerUpperBoundCallback( public static native void resetData(int index); public static native int findForChannel(int channel); + + /** Utility class. */ + private AnalogTriggerDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/BufferCallback.java b/hal/src/main/java/edu/wpi/first/hal/simulation/BufferCallback.java index e93a92127da..7c66563a323 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/BufferCallback.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/BufferCallback.java @@ -4,6 +4,14 @@ package edu.wpi.first.hal.simulation; +/** Interface for simulation buffer callbacks. */ public interface BufferCallback { + /** + * Simulation buffer callback function. + * + * @param name Buffer name. + * @param buffer Buffer. + * @param count Buffer size. + */ void callback(String name, byte[] buffer, int count); } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/CTREPCMDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/CTREPCMDataJNI.java index 6d94438d999..265edd036bd 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/CTREPCMDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/CTREPCMDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for CTRE PCM data. */ public class CTREPCMDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -68,4 +69,7 @@ public static native void registerAllSolenoidCallbacks( int index, int channel, NotifyCallback callback, boolean initialNotify); public static native void resetData(int index); + + /** Utility class. */ + private CTREPCMDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/DIODataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/DIODataJNI.java index 0c59415ee1e..dbbab99a510 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/DIODataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/DIODataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for DIO data. */ public class DIODataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -53,4 +54,7 @@ public static native int registerFilterIndexCallback( public static native void setFilterIndex(int index, int filterIndex); public static native void resetData(int index); + + /** Utility class. */ + private DIODataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/DigitalPWMDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/DigitalPWMDataJNI.java index addcffcd126..e72a2337b9d 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/DigitalPWMDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/DigitalPWMDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for digital PWM data. */ public class DigitalPWMDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -37,4 +38,7 @@ public static native int registerPinCallback( public static native void resetData(int index); public static native int findForChannel(int channel); + + /** Utility class. */ + private DigitalPWMDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/DriverStationDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/DriverStationDataJNI.java index 196f0174aea..e310b14d797 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/DriverStationDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/DriverStationDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for Driver Station data. */ public class DriverStationDataJNI extends JNIWrapper { public static native int registerEnabledCallback(NotifyCallback callback, boolean initialNotify); @@ -134,4 +135,7 @@ public static native void setMatchInfo( public static native void setReplayNumber(int replayNumber); public static native void resetData(); + + /** Utility class. */ + private DriverStationDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/DutyCycleDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/DutyCycleDataJNI.java index 8f244cac455..e2ed8735827 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/DutyCycleDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/DutyCycleDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for duty cycle data. */ public class DutyCycleDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -37,4 +38,7 @@ public static native int registerOutputCallback( public static native void resetData(int index); public static native int findForChannel(int channel); + + /** Utility class. */ + private DutyCycleDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/EncoderDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/EncoderDataJNI.java index e48607a8c15..d853d00508a 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/EncoderDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/EncoderDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for encoder data. */ public class EncoderDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -99,4 +100,7 @@ public static native int registerDistancePerPulseCallback( public static native void resetData(int index); public static native int findForChannel(int channel); + + /** Utility class. */ + private EncoderDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/I2CDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/I2CDataJNI.java index ebe15ebb8e2..f74d63e074c 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/I2CDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/I2CDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for I2C data. */ public class I2CDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -25,4 +26,7 @@ public static native int registerInitializedCallback( public static native void cancelWriteCallback(int index, int uid); public static native void resetData(int index); + + /** Utility class. */ + private I2CDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/NotifierDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/NotifierDataJNI.java index 9c7b0a271e7..9323d1afa01 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/NotifierDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/NotifierDataJNI.java @@ -6,8 +6,12 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for notifier data. */ public class NotifierDataJNI extends JNIWrapper { public static native long getNextTimeout(); public static native int getNumNotifiers(); + + /** Utility class. */ + private NotifierDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/PWMDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/PWMDataJNI.java index d66256bbc8e..10f8b6669a7 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/PWMDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/PWMDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for PWM data. */ public class PWMDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -62,4 +63,7 @@ public static native int registerZeroLatchCallback( public static native void setZeroLatch(int index, boolean zeroLatch); public static native void resetData(int index); + + /** Utility class. */ + private PWMDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/PowerDistributionDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/PowerDistributionDataJNI.java index c17da137a19..80a7e46b1e9 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/PowerDistributionDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/PowerDistributionDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for power distribution data. */ public class PowerDistributionDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -44,4 +45,7 @@ public static native int registerCurrentCallback( public static native void setCurrent(int index, int channel, double current); public static native void resetData(int index); + + /** Utility class. */ + private PowerDistributionDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/REVPHDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/REVPHDataJNI.java index 96b9701c272..9609f3dc22f 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/REVPHDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/REVPHDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for REV PH data. */ public class REVPHDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -68,4 +69,7 @@ public static native void registerAllSolenoidCallbacks( int index, int channel, NotifyCallback callback, boolean initialNotify); public static native void resetData(int index); + + /** Utility class. */ + private REVPHDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/RelayDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/RelayDataJNI.java index 3b165e2754d..734371522b6 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/RelayDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/RelayDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for relay data. */ public class RelayDataJNI extends JNIWrapper { public static native int registerInitializedForwardCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -44,4 +45,7 @@ public static native int registerReverseCallback( public static native void setReverse(int index, boolean reverse); public static native void resetData(int index); + + /** Utility class. */ + private RelayDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/RoboRioDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/RoboRioDataJNI.java index 7f51331a799..83d599db2f1 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/RoboRioDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/RoboRioDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for roboRIO data. */ public class RoboRioDataJNI extends JNIWrapper { public static native int registerFPGAButtonCallback( NotifyCallback callback, boolean initialNotify); @@ -176,5 +177,17 @@ public static native int registerTeamNumberCallback( public static native void setComments(String comments); + public static native int registerRadioLEDStateCallback( + NotifyCallback callback, boolean initialNotify); + + public static native void cancelRadioLEDStateCallback(int uid); + + public static native int getRadioLEDState(); + + public static native void setRadioLEDState(int state); + public static native void resetData(); + + /** Utility class. */ + private RoboRioDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/SPIAccelerometerDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/SPIAccelerometerDataJNI.java index 9ceaad8c403..b38fb553314 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/SPIAccelerometerDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/SPIAccelerometerDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for SPI accelerometer data. */ public class SPIAccelerometerDataJNI extends JNIWrapper { public static native int registerActiveCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -53,4 +54,7 @@ public static native int registerZCallback( public static native void setZ(int index, double z); public static native void resetData(int index); + + /** Utility class. */ + private SPIAccelerometerDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/SPIDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/SPIDataJNI.java index 11b777e2621..fa8df895df2 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/SPIDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/SPIDataJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for SPI data. */ public class SPIDataJNI extends JNIWrapper { public static native int registerInitializedCallback( int index, NotifyCallback callback, boolean initialNotify); @@ -30,4 +31,7 @@ public static native int registerReadAutoReceiveBufferCallback( public static native void cancelReadAutoReceiveBufferCallback(int index, int uid); public static native void resetData(int index); + + /** Utility class. */ + private SPIDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/SimDeviceDataJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/SimDeviceDataJNI.java index 092b955dc68..b4abb3306e8 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/SimDeviceDataJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/SimDeviceDataJNI.java @@ -7,6 +7,7 @@ import edu.wpi.first.hal.HALValue; import edu.wpi.first.hal.JNIWrapper; +/** JNI for sim device data. */ public class SimDeviceDataJNI extends JNIWrapper { public static native void setSimDeviceEnabled(String prefix, boolean enabled); @@ -106,4 +107,7 @@ public SimValueInfo( public static native double[] getSimValueEnumDoubleValues(int handle); public static native void resetSimDeviceData(); + + /** Utility class. */ + private SimDeviceDataJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/simulation/SimulatorJNI.java b/hal/src/main/java/edu/wpi/first/hal/simulation/SimulatorJNI.java index 3dfeb068a98..298929c06f8 100644 --- a/hal/src/main/java/edu/wpi/first/hal/simulation/SimulatorJNI.java +++ b/hal/src/main/java/edu/wpi/first/hal/simulation/SimulatorJNI.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.JNIWrapper; +/** JNI for simulator. */ public class SimulatorJNI extends JNIWrapper { public static native void setRuntimeType(int type); @@ -28,4 +29,7 @@ public class SimulatorJNI extends JNIWrapper { public static native void stepTimingAsync(long delta); public static native void resetHandles(); + + /** Utility class. */ + private SimulatorJNI() {} } diff --git a/hal/src/main/java/edu/wpi/first/hal/util/UncleanStatusException.java b/hal/src/main/java/edu/wpi/first/hal/util/UncleanStatusException.java index 7be73b4f1bb..6c188d3752b 100644 --- a/hal/src/main/java/edu/wpi/first/hal/util/UncleanStatusException.java +++ b/hal/src/main/java/edu/wpi/first/hal/util/UncleanStatusException.java @@ -6,6 +6,7 @@ /** Exception for bad status codes from the chip object. */ public final class UncleanStatusException extends IllegalStateException { + /** The status code from the chip object. */ private final int m_statusCode; /** diff --git a/hal/src/main/native/athena/AddressableLED.cpp b/hal/src/main/native/athena/AddressableLED.cpp index 57f37cbf75e..05fe5def2b4 100644 --- a/hal/src/main/native/athena/AddressableLED.cpp +++ b/hal/src/main/native/athena/AddressableLED.cpp @@ -198,6 +198,10 @@ void HAL_WriteAddressableLEDData(HAL_AddressableLEDHandle handle, return; } + if (length == 0) { + return; + } + std::memcpy(led->ledBuffer, data, length * sizeof(HAL_AddressableLEDData)); asm("dmb"); diff --git a/hal/src/main/native/athena/AnalogGyro.cpp b/hal/src/main/native/athena/AnalogGyro.cpp index 1751ac03253..b847237b95e 100644 --- a/hal/src/main/native/athena/AnalogGyro.cpp +++ b/hal/src/main/native/athena/AnalogGyro.cpp @@ -8,7 +8,7 @@ #include #include -#include +#include #include "AnalogInternal.h" #include "HALInitializer.h" @@ -194,7 +194,7 @@ void HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status) { if (*status != 0) { return; } - fmt::print("Calibrating analog gyro for {} seconds.\n", + wpi::print("Calibrating analog gyro for {} seconds.\n", kCalibrationSampleTime); Wait(kCalibrationSampleTime); diff --git a/hal/src/main/native/athena/CANAPI.cpp b/hal/src/main/native/athena/CANAPI.cpp index 70f09e06f31..40332ef1695 100644 --- a/hal/src/main/native/athena/CANAPI.cpp +++ b/hal/src/main/native/athena/CANAPI.cpp @@ -281,4 +281,19 @@ void HAL_ReadCANPacketTimeout(HAL_CANHandle handle, int32_t apiId, } } } + +uint32_t HAL_StartCANStream(HAL_CANHandle handle, int32_t apiId, int32_t depth, + int32_t* status) { + auto can = canHandles->Get(handle); + if (!can) { + *status = HAL_HANDLE_ERROR; + return 0; + } + + uint32_t messageId = CreateCANId(can.get(), apiId); + + uint32_t session = 0; + HAL_CAN_OpenStreamSession(&session, messageId, 0x1FFFFFFF, depth, status); + return session; +} } // extern "C" diff --git a/hal/src/main/native/athena/CTREPDP.cpp b/hal/src/main/native/athena/CTREPDP.cpp index 1a25a6427fd..21896ec7785 100644 --- a/hal/src/main/native/athena/CTREPDP.cpp +++ b/hal/src/main/native/athena/CTREPDP.cpp @@ -10,6 +10,7 @@ #include "HALInitializer.h" #include "HALInternal.h" #include "PortsInternal.h" +#include "hal/CAN.h" #include "hal/CANAPI.h" #include "hal/Errors.h" #include "hal/handles/IndexedHandleResource.h" @@ -107,6 +108,8 @@ namespace { struct PDP { HAL_CANHandle canHandle; std::string previousAllocation; + bool streamHandleAllocated{false}; + uint32_t streamSessionHandles[3]; }; } // namespace @@ -523,4 +526,241 @@ void HAL_ClearPDPStickyFaults(HAL_PDPHandle handle, int32_t* status) { HAL_WriteCANPacket(pdp->canHandle, pdpControl, 1, Control1, status); } +uint32_t HAL_StartCANStream(HAL_CANHandle handle, int32_t apiId, int32_t depth, + int32_t* status); + +void HAL_StartPDPStream(HAL_PDPHandle handle, int32_t* status) { + auto pdp = pdpHandles->Get(handle); + if (pdp == nullptr) { + *status = HAL_HANDLE_ERROR; + return; + } + + if (pdp->streamHandleAllocated) { + *status = RESOURCE_IS_ALLOCATED; + return; + } + + pdp->streamSessionHandles[0] = + HAL_StartCANStream(pdp->canHandle, Status1, 50, status); + if (*status != 0) { + return; + } + pdp->streamSessionHandles[1] = + HAL_StartCANStream(pdp->canHandle, Status2, 50, status); + if (*status != 0) { + HAL_CAN_CloseStreamSession(pdp->streamSessionHandles[0]); + return; + } + pdp->streamSessionHandles[2] = + HAL_StartCANStream(pdp->canHandle, Status3, 50, status); + if (*status != 0) { + HAL_CAN_CloseStreamSession(pdp->streamSessionHandles[0]); + HAL_CAN_CloseStreamSession(pdp->streamSessionHandles[1]); + return; + } + pdp->streamHandleAllocated = true; +} + +HAL_PowerDistributionChannelData* HAL_GetPDPStreamData(HAL_PDPHandle handle, + int32_t* count, + int32_t* status) { + auto pdp = pdpHandles->Get(handle); + if (pdp == nullptr) { + *status = HAL_HANDLE_ERROR; + return nullptr; + } + + if (!pdp->streamHandleAllocated) { + *status = RESOURCE_OUT_OF_RANGE; + return nullptr; + } + + *count = 0; + // 3 streams, 6 channels per stream, 50 depth per stream + HAL_PowerDistributionChannelData* retData = + new HAL_PowerDistributionChannelData[3 * 6 * 50]; + + HAL_CANStreamMessage messages[50]; + uint32_t messagesRead = 0; + HAL_CAN_ReadStreamSession(pdp->streamSessionHandles[0], messages, 50, + &messagesRead, status); + if (*status < 0) { + goto Exit; + } + + for (uint32_t i = 0; i < messagesRead; i++) { + PdpStatus1 pdpStatus; + std::memcpy(pdpStatus.data, messages[i].data, sizeof(messages[i].data)); + uint32_t timestamp = messages[i].timeStamp; + + retData[*count].current = + ((static_cast(pdpStatus.bits.chan1_h8) << 2) | + pdpStatus.bits.chan1_l2) * + 0.125; + retData[*count].channel = 1; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan2_h6) << 4) | + pdpStatus.bits.chan2_l4) * + 0.125; + retData[*count].channel = 2; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan3_h4) << 6) | + pdpStatus.bits.chan3_l6) * + 0.125; + retData[*count].channel = 3; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan4_h2) << 8) | + pdpStatus.bits.chan4_l8) * + 0.125; + retData[*count].channel = 4; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan5_h8) << 2) | + pdpStatus.bits.chan5_l2) * + 0.125; + retData[*count].channel = 5; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan6_h6) << 4) | + pdpStatus.bits.chan6_l4) * + 0.125; + retData[*count].channel = 6; + retData[*count].timestamp = timestamp; + (*count)++; + } + + messagesRead = 0; + HAL_CAN_ReadStreamSession(pdp->streamSessionHandles[1], messages, 50, + &messagesRead, status); + if (*status < 0) { + goto Exit; + } + + for (uint32_t i = 0; i < messagesRead; i++) { + PdpStatus2 pdpStatus; + std::memcpy(pdpStatus.data, messages[i].data, sizeof(messages[i].data)); + uint32_t timestamp = messages[i].timeStamp; + + retData[*count].current = + ((static_cast(pdpStatus.bits.chan7_h8) << 2) | + pdpStatus.bits.chan7_l2) * + 0.125; + retData[*count].channel = 7; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan8_h6) << 4) | + pdpStatus.bits.chan8_l4) * + 0.125; + retData[*count].channel = 8; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan9_h4) << 6) | + pdpStatus.bits.chan9_l6) * + 0.125; + retData[*count].channel = 9; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan10_h2) << 8) | + pdpStatus.bits.chan10_l8) * + 0.125; + retData[*count].channel = 10; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan11_h8) << 2) | + pdpStatus.bits.chan11_l2) * + 0.125; + retData[*count].channel = 11; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan12_h6) << 4) | + pdpStatus.bits.chan12_l4) * + 0.125; + retData[*count].channel = 12; + retData[*count].timestamp = timestamp; + (*count)++; + } + + messagesRead = 0; + HAL_CAN_ReadStreamSession(pdp->streamSessionHandles[2], messages, 50, + &messagesRead, status); + if (*status < 0) { + goto Exit; + } + + for (uint32_t i = 0; i < messagesRead; i++) { + PdpStatus3 pdpStatus; + std::memcpy(pdpStatus.data, messages[i].data, sizeof(messages[i].data)); + uint32_t timestamp = messages[i].timeStamp; + + retData[*count].current = + ((static_cast(pdpStatus.bits.chan13_h8) << 2) | + pdpStatus.bits.chan13_l2) * + 0.125; + retData[*count].channel = 13; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan14_h6) << 4) | + pdpStatus.bits.chan14_l4) * + 0.125; + retData[*count].channel = 14; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan15_h4) << 6) | + pdpStatus.bits.chan15_l6) * + 0.125; + retData[*count].channel = 15; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + ((static_cast(pdpStatus.bits.chan16_h2) << 8) | + pdpStatus.bits.chan16_l8) * + 0.125; + retData[*count].channel = 16; + retData[*count].timestamp = timestamp; + (*count)++; + } + +Exit: + if (*status < 0) { + delete[] retData; + retData = nullptr; + } + return retData; +} + +void HAL_StopPDPStream(HAL_PDPHandle handle, int32_t* status) { + auto pdp = pdpHandles->Get(handle); + if (pdp == nullptr) { + *status = HAL_HANDLE_ERROR; + return; + } + + if (!pdp->streamHandleAllocated) { + *status = RESOURCE_OUT_OF_RANGE; + return; + } + + HAL_CAN_CloseStreamSession(pdp->streamSessionHandles[0]); + HAL_CAN_CloseStreamSession(pdp->streamSessionHandles[1]); + HAL_CAN_CloseStreamSession(pdp->streamSessionHandles[2]); + + pdp->streamHandleAllocated = false; +} + } // extern "C" diff --git a/hal/src/main/native/athena/CTREPDP.h b/hal/src/main/native/athena/CTREPDP.h index dd4b298d5c7..99606e05754 100644 --- a/hal/src/main/native/athena/CTREPDP.h +++ b/hal/src/main/native/athena/CTREPDP.h @@ -6,6 +6,7 @@ #include +#include "hal/PowerDistribution.h" #include "hal/Types.h" /** @@ -130,6 +131,15 @@ void HAL_ResetPDPTotalEnergy(HAL_PDPHandle handle, int32_t* status); * @param handle the module handle */ void HAL_ClearPDPStickyFaults(HAL_PDPHandle handle, int32_t* status); + +void HAL_StartPDPStream(HAL_PDPHandle handle, int32_t* status); + +HAL_PowerDistributionChannelData* HAL_GetPDPStreamData(HAL_PDPHandle handle, + int32_t* count, + int32_t* status); + +void HAL_StopPDPStream(HAL_PDPHandle handle, int32_t* status); + #ifdef __cplusplus } // extern "C" #endif diff --git a/hal/src/main/native/athena/DMA.cpp b/hal/src/main/native/athena/DMA.cpp index 23e92642484..f46969d4fb5 100644 --- a/hal/src/main/native/athena/DMA.cpp +++ b/hal/src/main/native/athena/DMA.cpp @@ -10,6 +10,8 @@ #include #include +#include + #include "AnalogInternal.h" #include "ConstantsInternal.h" #include "DigitalInternal.h" @@ -676,7 +678,7 @@ void HAL_StartDMA(HAL_DMAHandle handle, int32_t queueDepth, int32_t* status) { SET_SIZE(Enable_DutyCycle_Low); SET_SIZE(Enable_DutyCycle_High); #undef SET_SIZE - dma->captureStore.captureSize = accum_size + 1; + dma->captureStore.captureSize = accum_size + 2; } uint32_t byteDepth = queueDepth * dma->captureStore.captureSize; @@ -734,12 +736,22 @@ enum HAL_DMAReadStatus HAL_ReadDMADirect(void* dmaPointer, static_cast(timeoutSeconds * 1000), &remainingBytes, status); + if ((remainingBytes % dma->captureStore.captureSize) != 0) { + wpi::print( + "Remaining bytes {} is not a multiple of capture size {}. This is " + "likely a " + "bug in WPILib. Please report this issue with a copy of your code.\n", + remainingBytes, dma->captureStore.captureSize); + } + *remainingOut = remainingBytes / dma->captureStore.captureSize; if (*status == 0) { - uint32_t lower_sample = + uint64_t upper_sample = dmaSample->readBuffer[dma->captureStore.captureSize - 1]; - dmaSample->timeStamp = HAL_ExpandFPGATime(lower_sample, status); + uint64_t lower_sample = + dmaSample->readBuffer[dma->captureStore.captureSize - 2]; + dmaSample->timeStamp = (upper_sample << 32) + lower_sample; if (*status != 0) { return HAL_DMA_ERROR; } diff --git a/hal/src/main/native/athena/FRCDriverStation.cpp b/hal/src/main/native/athena/FRCDriverStation.cpp index c30fbb94c59..1e2565b0096 100644 --- a/hal/src/main/native/athena/FRCDriverStation.cpp +++ b/hal/src/main/native/athena/FRCDriverStation.cpp @@ -424,22 +424,15 @@ int32_t HAL_GetJoystickType(int32_t joystickNum) { } } -char* HAL_GetJoystickName(int32_t joystickNum) { +void HAL_GetJoystickName(struct WPI_String* name, int32_t joystickNum) { HAL_JoystickDescriptor joystickDesc; + const char* cName = joystickDesc.name; if (HAL_GetJoystickDescriptor(joystickNum, &joystickDesc) < 0) { - char* name = static_cast(std::malloc(1)); - name[0] = '\0'; - return name; - } else { - const size_t len = std::strlen(joystickDesc.name) + 1; - char* name = static_cast(std::malloc(len)); - std::memcpy(name, joystickDesc.name, len); - return name; + cName = ""; } -} - -void HAL_FreeJoystickName(char* name) { - std::free(name); + auto len = std::strlen(cName); + auto write = WPI_AllocateString(name, len); + std::memcpy(write, cName, len); } int32_t HAL_GetJoystickAxisType(int32_t joystickNum, int32_t axis) { @@ -539,15 +532,25 @@ HAL_Bool HAL_RefreshDSData(void) { } // If newest state shows we have a DS attached, just use the // control word out of the cache, As it will be the one in sync - // with the data. Otherwise use the state that shows disconnected. - if (controlWord.dsAttached) { - newestControlWord = currentRead->controlWord; - } else { - // Zero out the control word. When the DS has never been connected - // this returns garbage. And there is no way we can detect that. - std::memset(&controlWord, 0, sizeof(controlWord)); - newestControlWord = controlWord; + // with the data. If no data has been updated, at this point, + // and a DS wasn't attached previously, this will still return + // a zeroed out control word, with is the correct state for + // no new data. + if (!controlWord.dsAttached) { + // If the DS is not attached, we need to zero out the control word. + // This is because HAL_RefreshDSData is called asynchronously from + // the DS data. The dsAttached variable comes directly from netcomm + // and could be updated before the caches are. If that happens, + // we would end up returning the previous cached control word, + // which is out of sync with the current control word and could + // break invariants such as which alliance station is in used. + // Also, when the DS has never been connected the rest of the fields + // in control word are garbage, so we also need to zero out in that + // case too + std::memset(¤tRead->controlWord, 0, + sizeof(currentRead->controlWord)); } + newestControlWord = currentRead->controlWord; } uint32_t mask = tcpMask.exchange(0); diff --git a/hal/src/main/native/athena/HAL.cpp b/hal/src/main/native/athena/HAL.cpp index d00bf9f370a..3ada7d8170b 100644 --- a/hal/src/main/native/athena/HAL.cpp +++ b/hal/src/main/native/athena/HAL.cpp @@ -4,6 +4,7 @@ #include "hal/HAL.h" +#include #include // linux for kill #include #include @@ -23,6 +24,7 @@ #include #include #include +#include #include #include "FPGACalls.h" @@ -82,6 +84,7 @@ void InitializeHAL() { InitializeFRCDriverStation(); InitializeI2C(); InitializeInterrupts(); + InitializeLEDs(); InitializeMain(); InitializeNotifier(); InitializeCTREPDP(); @@ -283,18 +286,14 @@ int64_t HAL_GetFPGARevision(int32_t* status) { return global->readRevision(status); } -size_t HAL_GetSerialNumber(char* buffer, size_t size) { +void HAL_GetSerialNumber(struct WPI_String* serialNumber) { const char* serialNum = std::getenv("serialnum"); - if (serialNum) { - std::strncpy(buffer, serialNum, size); - buffer[size - 1] = '\0'; - return std::strlen(buffer); - } else { - if (size > 0) { - buffer[0] = '\0'; - } - return 0; + if (!serialNum) { + serialNum = ""; } + size_t len = std::strlen(serialNum); + auto write = WPI_AllocateString(serialNumber, len); + std::memcpy(write, serialNum, len); } void InitializeRoboRioComments(void) { @@ -338,21 +337,12 @@ void InitializeRoboRioComments(void) { } } -size_t HAL_GetComments(char* buffer, size_t size) { +void HAL_GetComments(struct WPI_String* comments) { if (!roboRioCommentsStringInitialized) { InitializeRoboRioComments(); } - size_t toCopy = size; - if (size > roboRioCommentsStringSize) { - toCopy = roboRioCommentsStringSize; - } - std::memcpy(buffer, roboRioCommentsString, toCopy); - if (toCopy < size) { - buffer[toCopy] = '\0'; - } else { - buffer[toCopy - 1] = '\0'; - } - return toCopy; + auto write = WPI_AllocateString(comments, roboRioCommentsStringSize); + std::memcpy(write, roboRioCommentsString, roboRioCommentsStringSize); } void InitializeTeamNumber(void) { @@ -498,14 +488,14 @@ static bool killExistingProgram(int timeout, int mode) { std::this_thread::sleep_for(std::chrono::milliseconds(timeout)); if (kill(pid, 0) == 0) { // still not successful - fmt::print( + wpi::print( "FRC pid {} did not die within {} ms. Force killing with kill -9\n", pid, timeout); // Force kill -9 auto forceKill = kill(pid, SIGKILL); if (forceKill != 0) { auto errorMsg = std::strerror(forceKill); - fmt::print("Kill -9 error: {}\n", errorMsg); + wpi::print("Kill -9 error: {}\n", errorMsg); } // Give a bit of time for the kill to take place std::this_thread::sleep_for(std::chrono::milliseconds(250)); @@ -522,6 +512,35 @@ static bool killExistingProgram(int timeout, int mode) { return true; } +static bool SetupNowRio(void) { + nFPGA::nRoboRIO_FPGANamespace::g_currentTargetClass = + nLoadOut::getTargetClass(); + + int32_t status = 0; + + Dl_info info; + status = dladdr(reinterpret_cast(tHMB::create), &info); + if (status == 0) { + wpi::print(stderr, "Failed to call dladdr on chipobject {}\n", dlerror()); + return false; + } + + void* chipObjectLibrary = dlopen(info.dli_fname, RTLD_LAZY); + if (chipObjectLibrary == nullptr) { + wpi::print(stderr, "Failed to call dlopen on chipobject {}\n", dlerror()); + return false; + } + + std::unique_ptr hmb; + hmb.reset(tHMB::create(&status)); + if (hmb == nullptr) { + wpi::print(stderr, "Failed to open HMB on chipobject {}\n", status); + dlclose(chipObjectLibrary); + return false; + } + return wpi::impl::SetupNowRio(chipObjectLibrary, std::move(hmb)); +} + HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) { static std::atomic_bool initialized{false}; static wpi::mutex initializeMutex; @@ -562,14 +581,23 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) { setNewDataSem(nullptr); }); - // Setup WPI_Now to use FPGA timestamp - // this also sets nFPGA::nRoboRIO_FPGANamespace::g_currentTargetClass - wpi::impl::SetupNowRio(); + if (!SetupNowRio()) { + fmt::print(stderr, + "Failed to run SetupNowRio(). This is a fatal error. The " + "process is being terminated.\n"); + std::fflush(stderr); + // Attempt to force a segfault to get a better java log + *reinterpret_cast(0) = 0; + // If that fails, terminate + std::terminate(); + return false; + } int32_t status = 0; HAL_InitializeHMB(&status); if (status != 0) { + wpi::print(stderr, "Failed to open HAL HMB, status code {}\n", status); return false; } hmbBuffer = HAL_GetHMBBuffer(); diff --git a/hal/src/main/native/athena/HALInitializer.h b/hal/src/main/native/athena/HALInitializer.h index 182ab5b9738..20b9a8bff08 100644 --- a/hal/src/main/native/athena/HALInitializer.h +++ b/hal/src/main/native/athena/HALInitializer.h @@ -40,6 +40,7 @@ extern void InitializeFRCDriverStation(); extern void InitializeHAL(); extern void InitializeI2C(); extern void InitializeInterrupts(); +extern void InitializeLEDs(); extern void InitializeMain(); extern void InitializeNotifier(); extern void InitializeCTREPDP(); diff --git a/hal/src/main/native/athena/I2C.cpp b/hal/src/main/native/athena/I2C.cpp index 479f6463cad..777edc47e49 100644 --- a/hal/src/main/native/athena/I2C.cpp +++ b/hal/src/main/native/athena/I2C.cpp @@ -12,7 +12,7 @@ #include -#include +#include #include "DigitalInternal.h" #include "HALInitializer.h" @@ -65,7 +65,7 @@ void HAL_InitializeI2C(HAL_I2CPort port, int32_t* status) { } int handle = open("/dev/i2c-2", O_RDWR); if (handle < 0) { - fmt::print("Failed to open onboard i2c bus: {}\n", std::strerror(errno)); + wpi::print("Failed to open onboard i2c bus: {}\n", std::strerror(errno)); return; } i2COnBoardHandle = handle; @@ -88,7 +88,7 @@ void HAL_InitializeI2C(HAL_I2CPort port, int32_t* status) { digitalSystem->readEnableMXPSpecialFunction(status) | 0xC000, status); int handle = open("/dev/i2c-1", O_RDWR); if (handle < 0) { - fmt::print("Failed to open MXP i2c bus: {}\n", std::strerror(errno)); + wpi::print("Failed to open MXP i2c bus: {}\n", std::strerror(errno)); return; } i2CMXPHandle = handle; diff --git a/hal/src/main/native/athena/LEDs.cpp b/hal/src/main/native/athena/LEDs.cpp new file mode 100644 index 00000000000..8fa603e0fa0 --- /dev/null +++ b/hal/src/main/native/athena/LEDs.cpp @@ -0,0 +1,89 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "hal/LEDs.h" + +#include + +#include + +#include + +#include "hal/Errors.h" + +namespace hal::init { + +void InitializeLEDs() { + int32_t status = 0; + HAL_SetRadioLEDState(HAL_RadioLED_kOff, &status); +} +} // namespace hal::init + +static const fs::path radioLEDGreenFilePath = + "/sys/class/leds/nilrt:wifi:primary/brightness"; +static const fs::path radioLEDRedFilePath = + "/sys/class/leds/nilrt:wifi:secondary/brightness"; + +static const char* onStr = "1"; +static const char* offStr = "0"; + +extern "C" { +void HAL_SetRadioLEDState(HAL_RadioLEDState state, int32_t* status) { + std::error_code ec; + fs::file_t greenFile = fs::OpenFileForWrite(radioLEDGreenFilePath, ec, + fs::CD_OpenExisting, fs::OF_Text); + if (ec) { + *status = INCOMPATIBLE_STATE; + return; + } + fs::file_t redFile = fs::OpenFileForWrite(radioLEDRedFilePath, ec, + fs::CD_OpenExisting, fs::OF_Text); + if (ec) { + *status = INCOMPATIBLE_STATE; + return; + } + + write(greenFile, state & HAL_RadioLED_kGreen ? onStr : offStr, 1); + write(redFile, state & HAL_RadioLED_kRed ? onStr : offStr, 1); + + fs::CloseFile(greenFile); + fs::CloseFile(redFile); +} + +bool ReadStateFromFile(fs::path path, int32_t* status) { + std::error_code ec; + fs::file_t file = fs::OpenFileForRead(path, ec, fs::OF_Text); + if (ec) { + *status = INCOMPATIBLE_STATE; + return false; + } + // We only need to read one byte because the file won't have leading zeros. + char buf[1]{}; + size_t count = read(file, buf, 1); + if (count == 0) { + *status = INCOMPATIBLE_STATE; + return false; + } + // If the brightness is not zero, the LED is on. + return buf[0] != '0'; +} + +HAL_RadioLEDState HAL_GetRadioLEDState(int32_t* status) { + bool green = ReadStateFromFile(radioLEDGreenFilePath, status); + bool red = ReadStateFromFile(radioLEDRedFilePath, status); + if (*status == 0) { + if (green && red) { + return HAL_RadioLED_kOrange; + } else if (green) { + return HAL_RadioLED_kGreen; + } else if (red) { + return HAL_RadioLED_kRed; + } else { + return HAL_RadioLED_kOff; + } + } else { + return HAL_RadioLED_kOff; + } +} +} // extern "C" diff --git a/hal/src/main/native/athena/Notifier.cpp b/hal/src/main/native/athena/Notifier.cpp index bed998d06c4..29f5806c287 100644 --- a/hal/src/main/native/athena/Notifier.cpp +++ b/hal/src/main/native/athena/Notifier.cpp @@ -9,9 +9,9 @@ #include #include -#include #include #include +#include #include "HALInitializer.h" #include "HALInternal.h" @@ -164,12 +164,12 @@ HAL_NotifierHandle HAL_InitializeNotifier(int32_t* status) { notifierThreadPriority, status); if (*status == HAL_THREAD_PRIORITY_ERROR) { *status = 0; - fmt::print("{}: HAL Notifier thread\n", + wpi::print("{}: HAL Notifier thread\n", HAL_THREAD_PRIORITY_ERROR_MESSAGE); } if (*status == HAL_THREAD_PRIORITY_RANGE_ERROR) { *status = 0; - fmt::print("{}: HAL Notifier thread\n", + wpi::print("{}: HAL Notifier thread\n", HAL_THREAD_PRIORITY_RANGE_ERROR_MESSAGE); } diff --git a/hal/src/main/native/athena/PowerDistribution.cpp b/hal/src/main/native/athena/PowerDistribution.cpp index 0d2b963432a..580aa9005a6 100644 --- a/hal/src/main/native/athena/PowerDistribution.cpp +++ b/hal/src/main/native/athena/PowerDistribution.cpp @@ -273,4 +273,36 @@ void HAL_GetPowerDistributionStickyFaults( } } +void HAL_StartPowerDistributionStream(HAL_PowerDistributionHandle handle, + int32_t* status) { + if (IsCtre(handle)) { + HAL_StartPDPStream(handle, status); + } else { + HAL_StartREVPDHStream(handle, status); + } +} + +HAL_PowerDistributionChannelData* HAL_GetPowerDistributionStreamData( + HAL_PowerDistributionHandle handle, int32_t* count, int32_t* status) { + if (IsCtre(handle)) { + return HAL_GetPDPStreamData(handle, count, status); + } else { + return HAL_GetREVPDHStreamData(handle, count, status); + } +} + +void HAL_FreePowerDistributionStreamData(HAL_PowerDistributionChannelData* data, + int32_t count) { + delete[] data; +} + +void HAL_StopPowerDistributionStream(HAL_PowerDistributionHandle handle, + int32_t* status) { + if (IsCtre(handle)) { + HAL_StopPDPStream(handle, status); + } else { + HAL_StopREVPDHStream(handle, status); + } +} + } // extern "C" diff --git a/hal/src/main/native/athena/REVPDH.cpp b/hal/src/main/native/athena/REVPDH.cpp index 10c019d59ef..339840414b9 100644 --- a/hal/src/main/native/athena/REVPDH.cpp +++ b/hal/src/main/native/athena/REVPDH.cpp @@ -4,6 +4,7 @@ #include "REVPDH.h" +#include #include #include #include @@ -37,6 +38,8 @@ struct REV_PDHObj { HAL_CANHandle hcan; std::string previousAllocation; HAL_PowerDistributionVersion versionInfo; + bool streamHandleAllocated{false}; + uint32_t streamSessionHandles[4]; }; } // namespace @@ -636,4 +639,271 @@ void HAL_ClearREVPDHStickyFaults(HAL_REVPDHHandle handle, int32_t* status) { PDH_CLEAR_FAULTS_FRAME_API, status); } +uint32_t HAL_StartCANStream(HAL_CANHandle handle, int32_t apiId, int32_t depth, + int32_t* status); + +void HAL_StartREVPDHStream(HAL_REVPDHHandle handle, int32_t* status) { + auto hpdh = REVPDHHandles->Get(handle); + if (hpdh == nullptr) { + *status = HAL_HANDLE_ERROR; + return; + } + + if (hpdh->streamHandleAllocated) { + *status = RESOURCE_IS_ALLOCATED; + return; + } + + hpdh->streamSessionHandles[0] = + HAL_StartCANStream(hpdh->hcan, PDH_STATUS_0_FRAME_API, 50, status); + if (*status != 0) { + return; + } + hpdh->streamSessionHandles[1] = + HAL_StartCANStream(hpdh->hcan, PDH_STATUS_1_FRAME_API, 50, status); + if (*status != 0) { + HAL_CAN_CloseStreamSession(hpdh->streamSessionHandles[0]); + return; + } + hpdh->streamSessionHandles[2] = + HAL_StartCANStream(hpdh->hcan, PDH_STATUS_2_FRAME_API, 50, status); + if (*status != 0) { + HAL_CAN_CloseStreamSession(hpdh->streamSessionHandles[0]); + HAL_CAN_CloseStreamSession(hpdh->streamSessionHandles[1]); + return; + } + hpdh->streamSessionHandles[3] = + HAL_StartCANStream(hpdh->hcan, PDH_STATUS_3_FRAME_API, 50, status); + if (*status != 0) { + HAL_CAN_CloseStreamSession(hpdh->streamSessionHandles[0]); + HAL_CAN_CloseStreamSession(hpdh->streamSessionHandles[1]); + HAL_CAN_CloseStreamSession(hpdh->streamSessionHandles[3]); + return; + } + hpdh->streamHandleAllocated = true; +} + +HAL_PowerDistributionChannelData* HAL_GetREVPDHStreamData( + HAL_REVPDHHandle handle, int32_t* count, int32_t* status) { + auto hpdh = REVPDHHandles->Get(handle); + if (hpdh == nullptr) { + *status = HAL_HANDLE_ERROR; + return nullptr; + } + + if (!hpdh->streamHandleAllocated) { + *status = RESOURCE_OUT_OF_RANGE; + return nullptr; + } + + *count = 0; + // 4 streams, 6 channels per stream, 50 depth per stream + HAL_PowerDistributionChannelData* retData = + new HAL_PowerDistributionChannelData[4 * 6 * 50]; + + HAL_CANStreamMessage messages[50]; + uint32_t messagesRead = 0; + HAL_CAN_ReadStreamSession(hpdh->streamSessionHandles[0], messages, 50, + &messagesRead, status); + if (*status < 0) { + goto Exit; + } + + for (uint32_t i = 0; i < messagesRead; i++) { + PDH_status_0_t statusFrame0; + PDH_status_0_unpack(&statusFrame0, messages[i].data, PDH_STATUS_0_LENGTH); + uint32_t timestamp = messages[i].timeStamp; + + retData[*count].current = + PDH_status_0_channel_0_current_decode(statusFrame0.channel_0_current); + retData[*count].channel = 1; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_0_channel_1_current_decode(statusFrame0.channel_1_current); + retData[*count].channel = 2; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_0_channel_2_current_decode(statusFrame0.channel_2_current); + retData[*count].channel = 3; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_0_channel_3_current_decode(statusFrame0.channel_3_current); + retData[*count].channel = 4; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_0_channel_4_current_decode(statusFrame0.channel_4_current); + retData[*count].channel = 5; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_0_channel_5_current_decode(statusFrame0.channel_5_current); + retData[*count].channel = 6; + retData[*count].timestamp = timestamp; + (*count)++; + } + + messagesRead = 0; + HAL_CAN_ReadStreamSession(hpdh->streamSessionHandles[1], messages, 50, + &messagesRead, status); + if (*status < 0) { + goto Exit; + } + + for (uint32_t i = 0; i < messagesRead; i++) { + PDH_status_1_t statusFrame1; + PDH_status_1_unpack(&statusFrame1, messages[i].data, PDH_STATUS_1_LENGTH); + uint32_t timestamp = messages[i].timeStamp; + + retData[*count].current = + PDH_status_1_channel_6_current_decode(statusFrame1.channel_6_current); + retData[*count].channel = 7; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_1_channel_7_current_decode(statusFrame1.channel_7_current); + retData[*count].channel = 8; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_1_channel_8_current_decode(statusFrame1.channel_8_current); + retData[*count].channel = 9; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_1_channel_9_current_decode(statusFrame1.channel_9_current); + retData[*count].channel = 10; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_1_channel_10_current_decode(statusFrame1.channel_10_current); + retData[*count].channel = 11; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_1_channel_11_current_decode(statusFrame1.channel_11_current); + retData[*count].channel = 12; + retData[*count].timestamp = timestamp; + (*count)++; + } + + messagesRead = 0; + HAL_CAN_ReadStreamSession(hpdh->streamSessionHandles[2], messages, 50, + &messagesRead, status); + if (*status < 0) { + goto Exit; + } + + for (uint32_t i = 0; i < messagesRead; i++) { + PDH_status_2_t statusFrame2; + PDH_status_2_unpack(&statusFrame2, messages[i].data, PDH_STATUS_2_LENGTH); + uint32_t timestamp = messages[i].timeStamp; + + retData[*count].current = + PDH_status_2_channel_12_current_decode(statusFrame2.channel_12_current); + retData[*count].channel = 13; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_2_channel_13_current_decode(statusFrame2.channel_13_current); + retData[*count].channel = 14; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_2_channel_14_current_decode(statusFrame2.channel_14_current); + retData[*count].channel = 15; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_2_channel_15_current_decode(statusFrame2.channel_15_current); + retData[*count].channel = 16; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_2_channel_16_current_decode(statusFrame2.channel_16_current); + retData[*count].channel = 17; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_2_channel_17_current_decode(statusFrame2.channel_17_current); + retData[*count].channel = 18; + retData[*count].timestamp = timestamp; + (*count)++; + } + + messagesRead = 0; + HAL_CAN_ReadStreamSession(hpdh->streamSessionHandles[3], messages, 50, + &messagesRead, status); + if (*status < 0) { + goto Exit; + } + + for (uint32_t i = 0; i < messagesRead; i++) { + PDH_status_3_t statusFrame3; + PDH_status_3_unpack(&statusFrame3, messages[i].data, PDH_STATUS_3_LENGTH); + uint32_t timestamp = messages[i].timeStamp; + + retData[*count].current = + PDH_status_3_channel_18_current_decode(statusFrame3.channel_18_current); + retData[*count].channel = 19; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_3_channel_19_current_decode(statusFrame3.channel_19_current); + retData[*count].channel = 20; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_3_channel_20_current_decode(statusFrame3.channel_20_current); + retData[*count].channel = 21; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_3_channel_21_current_decode(statusFrame3.channel_21_current); + retData[*count].channel = 22; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_3_channel_22_current_decode(statusFrame3.channel_22_current); + retData[*count].channel = 23; + retData[*count].timestamp = timestamp; + (*count)++; + retData[*count].current = + PDH_status_3_channel_23_current_decode(statusFrame3.channel_23_current); + retData[*count].channel = 24; + retData[*count].timestamp = timestamp; + (*count)++; + } + +Exit: + if (*status < 0) { + delete[] retData; + retData = nullptr; + } + return retData; +} + +void HAL_StopREVPDHStream(HAL_REVPDHHandle handle, int32_t* status) { + auto hpdh = REVPDHHandles->Get(handle); + if (hpdh == nullptr) { + *status = HAL_HANDLE_ERROR; + return; + } + + if (!hpdh->streamHandleAllocated) { + *status = RESOURCE_OUT_OF_RANGE; + return; + } + + HAL_CAN_CloseStreamSession(hpdh->streamSessionHandles[0]); + HAL_CAN_CloseStreamSession(hpdh->streamSessionHandles[1]); + HAL_CAN_CloseStreamSession(hpdh->streamSessionHandles[2]); + HAL_CAN_CloseStreamSession(hpdh->streamSessionHandles[3]); + + hpdh->streamHandleAllocated = false; +} + } // extern "C" diff --git a/hal/src/main/native/athena/REVPDH.h b/hal/src/main/native/athena/REVPDH.h index d0b10f27778..0046455339d 100644 --- a/hal/src/main/native/athena/REVPDH.h +++ b/hal/src/main/native/athena/REVPDH.h @@ -158,6 +158,13 @@ void HAL_GetREVPDHStickyFaults(HAL_REVPDHHandle handle, */ void HAL_ClearREVPDHStickyFaults(HAL_REVPDHHandle handle, int32_t* status); +void HAL_StartREVPDHStream(HAL_REVPDHHandle handle, int32_t* status); + +HAL_PowerDistributionChannelData* HAL_GetREVPDHStreamData( + HAL_REVPDHHandle handle, int32_t* count, int32_t* status); + +void HAL_StopREVPDHStream(HAL_REVPDHHandle handle, int32_t* status); + #ifdef __cplusplus } // extern "C" #endif diff --git a/hal/src/main/native/athena/SPI.cpp b/hal/src/main/native/athena/SPI.cpp index 309813e86be..0b8c365d23d 100644 --- a/hal/src/main/native/athena/SPI.cpp +++ b/hal/src/main/native/athena/SPI.cpp @@ -14,8 +14,8 @@ #include #include -#include #include +#include #include "DigitalInternal.h" #include "HALInitializer.h" @@ -125,7 +125,7 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { // CS0 is not a DIO port, so nothing to allocate handle = open("/dev/spidev0.0", O_RDWR); if (handle < 0) { - fmt::print("Failed to open SPI port {}: {}\n", + wpi::print("Failed to open SPI port {}: {}\n", static_cast(port), std::strerror(errno)); CommonSPIPortFree(); return; @@ -147,7 +147,7 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { } handle = open("/dev/spidev0.1", O_RDWR); if (handle < 0) { - fmt::print("Failed to open SPI port {}: {}\n", + wpi::print("Failed to open SPI port {}: {}\n", static_cast(port), std::strerror(errno)); CommonSPIPortFree(); HAL_FreeDIOPort(digitalHandles[0]); @@ -170,7 +170,7 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { } handle = open("/dev/spidev0.2", O_RDWR); if (handle < 0) { - fmt::print("Failed to open SPI port {}: {}\n", + wpi::print("Failed to open SPI port {}: {}\n", static_cast(port), std::strerror(errno)); CommonSPIPortFree(); HAL_FreeDIOPort(digitalHandles[1]); @@ -193,7 +193,7 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { } handle = open("/dev/spidev0.3", O_RDWR); if (handle < 0) { - fmt::print("Failed to open SPI port {}: {}\n", + wpi::print("Failed to open SPI port {}: {}\n", static_cast(port), std::strerror(errno)); CommonSPIPortFree(); HAL_FreeDIOPort(digitalHandles[2]); @@ -240,7 +240,7 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { digitalSystem->readEnableMXPSpecialFunction(status) | 0x00F0, status); handle = open("/dev/spidev1.0", O_RDWR); if (handle < 0) { - fmt::print("Failed to open SPI port {}: {}\n", + wpi::print("Failed to open SPI port {}: {}\n", static_cast(port), std::strerror(errno)); HAL_FreeDIOPort(digitalHandles[5]); // free the first port allocated HAL_FreeDIOPort(digitalHandles[6]); // free the second port allocated diff --git a/hal/src/main/native/athena/mockdata/DriverStationData.cpp b/hal/src/main/native/athena/mockdata/DriverStationData.cpp index 76a8e8bf1e8..90fa34fc566 100644 --- a/hal/src/main/native/athena/mockdata/DriverStationData.cpp +++ b/hal/src/main/native/athena/mockdata/DriverStationData.cpp @@ -103,13 +103,13 @@ void HALSIM_SetJoystickIsXbox(int32_t stick, HAL_Bool isXbox) {} void HALSIM_SetJoystickType(int32_t stick, int32_t type) {} -void HALSIM_SetJoystickName(int32_t stick, const char* name, size_t size) {} +void HALSIM_SetJoystickName(int32_t stick, const struct WPI_String* name) {} void HALSIM_SetJoystickAxisType(int32_t stick, int32_t axis, int32_t type) {} -void HALSIM_SetGameSpecificMessage(const char* message, size_t size) {} +void HALSIM_SetGameSpecificMessage(const struct WPI_String* message) {} -void HALSIM_SetEventName(const char* name, size_t size) {} +void HALSIM_SetEventName(const struct WPI_String* name) {} void HALSIM_SetMatchType(HAL_MatchType type) {} diff --git a/hal/src/main/native/athena/mockdata/RoboRioData.cpp b/hal/src/main/native/athena/mockdata/RoboRioData.cpp index 85593942b1e..b1ba26026da 100644 --- a/hal/src/main/native/athena/mockdata/RoboRioData.cpp +++ b/hal/src/main/native/athena/mockdata/RoboRioData.cpp @@ -30,32 +30,27 @@ DEFINE_CAPI(int32_t, UserFaults3V3, 0) DEFINE_CAPI(double, BrownoutVoltage, 6.75) DEFINE_CAPI(double, CPUTemp, 45.0) DEFINE_CAPI(int32_t, TeamNumber, 0) +DEFINE_CAPI(HAL_RadioLEDState, RadioLEDState, HAL_RadioLED_kOff); int32_t HALSIM_RegisterRoboRioSerialNumberCallback( HAL_RoboRioStringCallback callback, void* param, HAL_Bool initialNotify) { return 0; } void HALSIM_CancelRoboRioSerialNumberCallback(int32_t uid) {} -size_t HALSIM_GetRoboRioSerialNumber(char* buffer, size_t size) { - if (size > 0) { - buffer[0] = '\0'; - } - return 0; +void HALSIM_GetRoboRioSerialNumber(struct WPI_String* serialNumber) { + WPI_AllocateString(serialNumber, 0); } -void HALSIM_SetRoboRioSerialNumber(const char* buffer, size_t size) {} +void HALSIM_SetRoboRioSerialNumber(const struct WPI_String* serialNumber) {} int32_t HALSIM_RegisterRoboRioCommentsCallback( HAL_RoboRioStringCallback callback, void* param, HAL_Bool initialNotify) { return 0; } void HALSIM_CancelRoboRioCommentsCallback(int32_t uid) {} -size_t HALSIM_GetRoboRioComments(char* buffer, size_t size) { - if (size > 0) { - buffer[0] = '\0'; - } - return 0; +void HALSIM_GetRoboRioComments(struct WPI_String* comments) { + WPI_AllocateString(comments, 0); } -void HALSIM_SetRoboRioComments(const char* buffer, size_t size) {} +void HALSIM_SetRoboRioComments(const struct WPI_String* comments) {} void HALSIM_RegisterRoboRioAllCallbacks(HAL_NotifyCallback callback, void* param, HAL_Bool initialNotify) {} diff --git a/hal/src/main/native/athena/rev/PHFrames.cpp b/hal/src/main/native/athena/rev/PHFrames.cpp index d098c004fc8..0d108c25e66 100644 --- a/hal/src/main/native/athena/rev/PHFrames.cpp +++ b/hal/src/main/native/athena/rev/PHFrames.cpp @@ -1,2071 +1,2071 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2018-2019 Erik Moqvist - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -/** - * This file was generated by cantools version - */ - -#include - -#include "PHFrames.h" - -static inline uint8_t pack_left_shift_u8( - uint8_t value, - uint8_t shift, - uint8_t mask) -{ - return (uint8_t)((uint8_t)(value << shift) & mask); -} - -static inline uint8_t pack_left_shift_u16( - uint16_t value, - uint8_t shift, - uint8_t mask) -{ - return (uint8_t)((uint8_t)(value << shift) & mask); -} - -static inline uint8_t pack_left_shift_u32( - uint32_t value, - uint8_t shift, - uint8_t mask) -{ - return (uint8_t)((uint8_t)(value << shift) & mask); -} - -static inline uint8_t pack_right_shift_u16( - uint16_t value, - uint8_t shift, - uint8_t mask) -{ - return (uint8_t)((uint8_t)(value >> shift) & mask); -} - -static inline uint8_t pack_right_shift_u32( - uint32_t value, - uint8_t shift, - uint8_t mask) -{ - return (uint8_t)((uint8_t)(value >> shift) & mask); -} - -static inline uint16_t unpack_left_shift_u16( - uint8_t value, - uint8_t shift, - uint8_t mask) -{ - return (uint16_t)((uint16_t)(value & mask) << shift); -} - -static inline uint32_t unpack_left_shift_u32( - uint8_t value, - uint8_t shift, - uint8_t mask) -{ - return (uint32_t)((uint32_t)(value & mask) << shift); -} - -static inline uint8_t unpack_right_shift_u8( - uint8_t value, - uint8_t shift, - uint8_t mask) -{ - return (uint8_t)((uint8_t)(value & mask) >> shift); -} - -static inline uint16_t unpack_right_shift_u16( - uint8_t value, - uint8_t shift, - uint8_t mask) -{ - return (uint16_t)((uint16_t)(value & mask) >> shift); -} - -static inline uint32_t unpack_right_shift_u32( - uint8_t value, - uint8_t shift, - uint8_t mask) -{ - return (uint32_t)((uint32_t)(value & mask) >> shift); -} - -int PH_compressor_config_pack( - uint8_t *dst_p, - const struct PH_compressor_config_t *src_p, - size_t size) -{ - if (size < 5u) { - return (-EINVAL); - } - - memset(&dst_p[0], 0, 5); - - dst_p[0] |= pack_left_shift_u16(src_p->minimum_tank_pressure, 0u, 0xffu); - dst_p[1] |= pack_right_shift_u16(src_p->minimum_tank_pressure, 8u, 0xffu); - dst_p[2] |= pack_left_shift_u16(src_p->maximum_tank_pressure, 0u, 0xffu); - dst_p[3] |= pack_right_shift_u16(src_p->maximum_tank_pressure, 8u, 0xffu); - dst_p[4] |= pack_left_shift_u8(src_p->force_disable, 0u, 0x01u); - dst_p[4] |= pack_left_shift_u8(src_p->use_digital, 1u, 0x02u); - - return (5); -} - -int PH_compressor_config_unpack( - struct PH_compressor_config_t *dst_p, - const uint8_t *src_p, - size_t size) -{ - if (size < 5u) { - return (-EINVAL); - } - - dst_p->minimum_tank_pressure = unpack_right_shift_u16(src_p[0], 0u, 0xffu); - dst_p->minimum_tank_pressure |= unpack_left_shift_u16(src_p[1], 8u, 0xffu); - dst_p->maximum_tank_pressure = unpack_right_shift_u16(src_p[2], 0u, 0xffu); - dst_p->maximum_tank_pressure |= unpack_left_shift_u16(src_p[3], 8u, 0xffu); - dst_p->force_disable = unpack_right_shift_u8(src_p[4], 0u, 0x01u); - dst_p->use_digital = unpack_right_shift_u8(src_p[4], 1u, 0x02u); - - return (0); -} - -uint16_t PH_compressor_config_minimum_tank_pressure_encode(double value) -{ - return (uint16_t)(value / 0.001); -} - -double PH_compressor_config_minimum_tank_pressure_decode(uint16_t value) -{ - return ((double)value * 0.001); -} - -bool PH_compressor_config_minimum_tank_pressure_is_in_range(uint16_t value) -{ - return (value <= 5000u); -} - -uint16_t PH_compressor_config_maximum_tank_pressure_encode(double value) -{ - return (uint16_t)(value / 0.001); -} - -double PH_compressor_config_maximum_tank_pressure_decode(uint16_t value) -{ - return ((double)value * 0.001); -} - -bool PH_compressor_config_maximum_tank_pressure_is_in_range(uint16_t value) -{ - return (value <= 5000u); -} - -uint8_t PH_compressor_config_force_disable_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_compressor_config_force_disable_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_compressor_config_force_disable_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_compressor_config_use_digital_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_compressor_config_use_digital_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_compressor_config_use_digital_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -int PH_set_all_pack( - uint8_t *dst_p, - const struct PH_set_all_t *src_p, - size_t size) -{ - if (size < 4u) { - return (-EINVAL); - } - - memset(&dst_p[0], 0, 4); - - dst_p[0] |= pack_left_shift_u8(src_p->channel_0, 0u, 0x03u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_1, 2u, 0x0cu); - dst_p[0] |= pack_left_shift_u8(src_p->channel_2, 4u, 0x30u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_3, 6u, 0xc0u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_4, 0u, 0x03u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_5, 2u, 0x0cu); - dst_p[1] |= pack_left_shift_u8(src_p->channel_6, 4u, 0x30u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_7, 6u, 0xc0u); - dst_p[2] |= pack_left_shift_u8(src_p->channel_8, 0u, 0x03u); - dst_p[2] |= pack_left_shift_u8(src_p->channel_9, 2u, 0x0cu); - dst_p[2] |= pack_left_shift_u8(src_p->channel_10, 4u, 0x30u); - dst_p[2] |= pack_left_shift_u8(src_p->channel_11, 6u, 0xc0u); - dst_p[3] |= pack_left_shift_u8(src_p->channel_12, 0u, 0x03u); - dst_p[3] |= pack_left_shift_u8(src_p->channel_13, 2u, 0x0cu); - dst_p[3] |= pack_left_shift_u8(src_p->channel_14, 4u, 0x30u); - dst_p[3] |= pack_left_shift_u8(src_p->channel_15, 6u, 0xc0u); - - return (4); -} - -int PH_set_all_unpack( - struct PH_set_all_t *dst_p, - const uint8_t *src_p, - size_t size) -{ - if (size < 4u) { - return (-EINVAL); - } - - dst_p->channel_0 = unpack_right_shift_u8(src_p[0], 0u, 0x03u); - dst_p->channel_1 = unpack_right_shift_u8(src_p[0], 2u, 0x0cu); - dst_p->channel_2 = unpack_right_shift_u8(src_p[0], 4u, 0x30u); - dst_p->channel_3 = unpack_right_shift_u8(src_p[0], 6u, 0xc0u); - dst_p->channel_4 = unpack_right_shift_u8(src_p[1], 0u, 0x03u); - dst_p->channel_5 = unpack_right_shift_u8(src_p[1], 2u, 0x0cu); - dst_p->channel_6 = unpack_right_shift_u8(src_p[1], 4u, 0x30u); - dst_p->channel_7 = unpack_right_shift_u8(src_p[1], 6u, 0xc0u); - dst_p->channel_8 = unpack_right_shift_u8(src_p[2], 0u, 0x03u); - dst_p->channel_9 = unpack_right_shift_u8(src_p[2], 2u, 0x0cu); - dst_p->channel_10 = unpack_right_shift_u8(src_p[2], 4u, 0x30u); - dst_p->channel_11 = unpack_right_shift_u8(src_p[2], 6u, 0xc0u); - dst_p->channel_12 = unpack_right_shift_u8(src_p[3], 0u, 0x03u); - dst_p->channel_13 = unpack_right_shift_u8(src_p[3], 2u, 0x0cu); - dst_p->channel_14 = unpack_right_shift_u8(src_p[3], 4u, 0x30u); - dst_p->channel_15 = unpack_right_shift_u8(src_p[3], 6u, 0xc0u); - - return (0); -} - -uint8_t PH_set_all_channel_0_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_0_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_0_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_1_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_1_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_1_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_2_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_2_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_2_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_3_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_3_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_3_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_4_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_4_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_4_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_5_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_5_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_5_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_6_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_6_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_6_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_7_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_7_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_7_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_8_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_8_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_8_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_9_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_9_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_9_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_10_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_10_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_10_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_11_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_11_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_11_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_12_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_12_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_12_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_13_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_13_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_13_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_14_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_14_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_14_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -uint8_t PH_set_all_channel_15_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_set_all_channel_15_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_set_all_channel_15_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -int PH_pulse_once_pack( - uint8_t *dst_p, - const struct PH_pulse_once_t *src_p, - size_t size) -{ - if (size < 4u) { - return (-EINVAL); - } - - memset(&dst_p[0], 0, 4); - - dst_p[0] |= pack_left_shift_u8(src_p->channel_0, 0u, 0x01u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_1, 1u, 0x02u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_2, 2u, 0x04u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_3, 3u, 0x08u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_4, 4u, 0x10u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_5, 5u, 0x20u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_6, 6u, 0x40u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_7, 7u, 0x80u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_8, 0u, 0x01u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_9, 1u, 0x02u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_10, 2u, 0x04u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_11, 3u, 0x08u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_12, 4u, 0x10u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_13, 5u, 0x20u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_14, 6u, 0x40u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_15, 7u, 0x80u); - dst_p[2] |= pack_left_shift_u16(src_p->pulse_length_ms, 0u, 0xffu); - dst_p[3] |= pack_right_shift_u16(src_p->pulse_length_ms, 8u, 0xffu); - - return (4); -} - -int PH_pulse_once_unpack( - struct PH_pulse_once_t *dst_p, - const uint8_t *src_p, - size_t size) -{ - if (size < 4u) { - return (-EINVAL); - } - - dst_p->channel_0 = unpack_right_shift_u8(src_p[0], 0u, 0x01u); - dst_p->channel_1 = unpack_right_shift_u8(src_p[0], 1u, 0x02u); - dst_p->channel_2 = unpack_right_shift_u8(src_p[0], 2u, 0x04u); - dst_p->channel_3 = unpack_right_shift_u8(src_p[0], 3u, 0x08u); - dst_p->channel_4 = unpack_right_shift_u8(src_p[0], 4u, 0x10u); - dst_p->channel_5 = unpack_right_shift_u8(src_p[0], 5u, 0x20u); - dst_p->channel_6 = unpack_right_shift_u8(src_p[0], 6u, 0x40u); - dst_p->channel_7 = unpack_right_shift_u8(src_p[0], 7u, 0x80u); - dst_p->channel_8 = unpack_right_shift_u8(src_p[1], 0u, 0x01u); - dst_p->channel_9 = unpack_right_shift_u8(src_p[1], 1u, 0x02u); - dst_p->channel_10 = unpack_right_shift_u8(src_p[1], 2u, 0x04u); - dst_p->channel_11 = unpack_right_shift_u8(src_p[1], 3u, 0x08u); - dst_p->channel_12 = unpack_right_shift_u8(src_p[1], 4u, 0x10u); - dst_p->channel_13 = unpack_right_shift_u8(src_p[1], 5u, 0x20u); - dst_p->channel_14 = unpack_right_shift_u8(src_p[1], 6u, 0x40u); - dst_p->channel_15 = unpack_right_shift_u8(src_p[1], 7u, 0x80u); - dst_p->pulse_length_ms = unpack_right_shift_u16(src_p[2], 0u, 0xffu); - dst_p->pulse_length_ms |= unpack_left_shift_u16(src_p[3], 8u, 0xffu); - - return (0); -} - -uint8_t PH_pulse_once_channel_0_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_0_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_0_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_1_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_1_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_1_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_2_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_2_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_2_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_3_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_3_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_3_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_4_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_4_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_4_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_5_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_5_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_5_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_6_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_6_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_6_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_7_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_7_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_7_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_8_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_8_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_8_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_9_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_9_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_9_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_10_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_10_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_10_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_11_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_11_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_11_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_12_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_12_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_12_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_13_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_13_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_13_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_14_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_14_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_14_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_pulse_once_channel_15_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_pulse_once_channel_15_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_channel_15_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint16_t PH_pulse_once_pulse_length_ms_encode(double value) -{ - return (uint16_t)(value); -} - -double PH_pulse_once_pulse_length_ms_decode(uint16_t value) -{ - return ((double)value); -} - -bool PH_pulse_once_pulse_length_ms_is_in_range(uint16_t value) -{ - (void)value; - - return (true); -} - -int PH_status_0_pack( - uint8_t *dst_p, - const struct PH_status_0_t *src_p, - size_t size) -{ - if (size < 8u) { - return (-EINVAL); - } - - memset(&dst_p[0], 0, 8); - - dst_p[0] |= pack_left_shift_u8(src_p->channel_0, 0u, 0x01u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_1, 1u, 0x02u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_2, 2u, 0x04u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_3, 3u, 0x08u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_4, 4u, 0x10u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_5, 5u, 0x20u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_6, 6u, 0x40u); - dst_p[0] |= pack_left_shift_u8(src_p->channel_7, 7u, 0x80u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_8, 0u, 0x01u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_9, 1u, 0x02u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_10, 2u, 0x04u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_11, 3u, 0x08u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_12, 4u, 0x10u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_13, 5u, 0x20u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_14, 6u, 0x40u); - dst_p[1] |= pack_left_shift_u8(src_p->channel_15, 7u, 0x80u); - dst_p[2] |= pack_left_shift_u8(src_p->analog_0, 0u, 0xffu); - dst_p[3] |= pack_left_shift_u8(src_p->analog_1, 0u, 0xffu); - dst_p[4] |= pack_left_shift_u8(src_p->digital_sensor, 0u, 0x01u); - dst_p[4] |= pack_left_shift_u8(src_p->brownout_fault, 1u, 0x02u); - dst_p[4] |= pack_left_shift_u8(src_p->compressor_oc_fault, 2u, 0x04u); - dst_p[4] |= pack_left_shift_u8(src_p->compressor_open_fault, 3u, 0x08u); - dst_p[4] |= pack_left_shift_u8(src_p->solenoid_oc_fault, 4u, 0x10u); - dst_p[4] |= pack_left_shift_u8(src_p->can_warning_fault, 5u, 0x20u); - dst_p[4] |= pack_left_shift_u8(src_p->hardware_fault, 6u, 0x40u); - dst_p[5] |= pack_left_shift_u8(src_p->channel_0_fault, 0u, 0x01u); - dst_p[5] |= pack_left_shift_u8(src_p->channel_1_fault, 1u, 0x02u); - dst_p[5] |= pack_left_shift_u8(src_p->channel_2_fault, 2u, 0x04u); - dst_p[5] |= pack_left_shift_u8(src_p->channel_3_fault, 3u, 0x08u); - dst_p[5] |= pack_left_shift_u8(src_p->channel_4_fault, 4u, 0x10u); - dst_p[5] |= pack_left_shift_u8(src_p->channel_5_fault, 5u, 0x20u); - dst_p[5] |= pack_left_shift_u8(src_p->channel_6_fault, 6u, 0x40u); - dst_p[5] |= pack_left_shift_u8(src_p->channel_7_fault, 7u, 0x80u); - dst_p[6] |= pack_left_shift_u8(src_p->channel_8_fault, 0u, 0x01u); - dst_p[6] |= pack_left_shift_u8(src_p->channel_9_fault, 1u, 0x02u); - dst_p[6] |= pack_left_shift_u8(src_p->channel_10_fault, 2u, 0x04u); - dst_p[6] |= pack_left_shift_u8(src_p->channel_11_fault, 3u, 0x08u); - dst_p[6] |= pack_left_shift_u8(src_p->channel_12_fault, 4u, 0x10u); - dst_p[6] |= pack_left_shift_u8(src_p->channel_13_fault, 5u, 0x20u); - dst_p[6] |= pack_left_shift_u8(src_p->channel_14_fault, 6u, 0x40u); - dst_p[6] |= pack_left_shift_u8(src_p->channel_15_fault, 7u, 0x80u); - dst_p[7] |= pack_left_shift_u8(src_p->compressor_on, 0u, 0x01u); - dst_p[7] |= pack_left_shift_u8(src_p->system_enabled, 1u, 0x02u); - dst_p[7] |= pack_left_shift_u8(src_p->robo_rio_present, 2u, 0x04u); - dst_p[7] |= pack_left_shift_u8(src_p->compressor_config, 3u, 0x18u); - - return (8); -} - -int PH_status_0_unpack( - struct PH_status_0_t *dst_p, - const uint8_t *src_p, - size_t size) -{ - if (size < 8u) { - return (-EINVAL); - } - - dst_p->channel_0 = unpack_right_shift_u8(src_p[0], 0u, 0x01u); - dst_p->channel_1 = unpack_right_shift_u8(src_p[0], 1u, 0x02u); - dst_p->channel_2 = unpack_right_shift_u8(src_p[0], 2u, 0x04u); - dst_p->channel_3 = unpack_right_shift_u8(src_p[0], 3u, 0x08u); - dst_p->channel_4 = unpack_right_shift_u8(src_p[0], 4u, 0x10u); - dst_p->channel_5 = unpack_right_shift_u8(src_p[0], 5u, 0x20u); - dst_p->channel_6 = unpack_right_shift_u8(src_p[0], 6u, 0x40u); - dst_p->channel_7 = unpack_right_shift_u8(src_p[0], 7u, 0x80u); - dst_p->channel_8 = unpack_right_shift_u8(src_p[1], 0u, 0x01u); - dst_p->channel_9 = unpack_right_shift_u8(src_p[1], 1u, 0x02u); - dst_p->channel_10 = unpack_right_shift_u8(src_p[1], 2u, 0x04u); - dst_p->channel_11 = unpack_right_shift_u8(src_p[1], 3u, 0x08u); - dst_p->channel_12 = unpack_right_shift_u8(src_p[1], 4u, 0x10u); - dst_p->channel_13 = unpack_right_shift_u8(src_p[1], 5u, 0x20u); - dst_p->channel_14 = unpack_right_shift_u8(src_p[1], 6u, 0x40u); - dst_p->channel_15 = unpack_right_shift_u8(src_p[1], 7u, 0x80u); - dst_p->analog_0 = unpack_right_shift_u8(src_p[2], 0u, 0xffu); - dst_p->analog_1 = unpack_right_shift_u8(src_p[3], 0u, 0xffu); - dst_p->digital_sensor = unpack_right_shift_u8(src_p[4], 0u, 0x01u); - dst_p->brownout_fault = unpack_right_shift_u8(src_p[4], 1u, 0x02u); - dst_p->compressor_oc_fault = unpack_right_shift_u8(src_p[4], 2u, 0x04u); - dst_p->compressor_open_fault = unpack_right_shift_u8(src_p[4], 3u, 0x08u); - dst_p->solenoid_oc_fault = unpack_right_shift_u8(src_p[4], 4u, 0x10u); - dst_p->can_warning_fault = unpack_right_shift_u8(src_p[4], 5u, 0x20u); - dst_p->hardware_fault = unpack_right_shift_u8(src_p[4], 6u, 0x40u); - dst_p->channel_0_fault = unpack_right_shift_u8(src_p[5], 0u, 0x01u); - dst_p->channel_1_fault = unpack_right_shift_u8(src_p[5], 1u, 0x02u); - dst_p->channel_2_fault = unpack_right_shift_u8(src_p[5], 2u, 0x04u); - dst_p->channel_3_fault = unpack_right_shift_u8(src_p[5], 3u, 0x08u); - dst_p->channel_4_fault = unpack_right_shift_u8(src_p[5], 4u, 0x10u); - dst_p->channel_5_fault = unpack_right_shift_u8(src_p[5], 5u, 0x20u); - dst_p->channel_6_fault = unpack_right_shift_u8(src_p[5], 6u, 0x40u); - dst_p->channel_7_fault = unpack_right_shift_u8(src_p[5], 7u, 0x80u); - dst_p->channel_8_fault = unpack_right_shift_u8(src_p[6], 0u, 0x01u); - dst_p->channel_9_fault = unpack_right_shift_u8(src_p[6], 1u, 0x02u); - dst_p->channel_10_fault = unpack_right_shift_u8(src_p[6], 2u, 0x04u); - dst_p->channel_11_fault = unpack_right_shift_u8(src_p[6], 3u, 0x08u); - dst_p->channel_12_fault = unpack_right_shift_u8(src_p[6], 4u, 0x10u); - dst_p->channel_13_fault = unpack_right_shift_u8(src_p[6], 5u, 0x20u); - dst_p->channel_14_fault = unpack_right_shift_u8(src_p[6], 6u, 0x40u); - dst_p->channel_15_fault = unpack_right_shift_u8(src_p[6], 7u, 0x80u); - dst_p->compressor_on = unpack_right_shift_u8(src_p[7], 0u, 0x01u); - dst_p->system_enabled = unpack_right_shift_u8(src_p[7], 1u, 0x02u); - dst_p->robo_rio_present = unpack_right_shift_u8(src_p[7], 2u, 0x04u); - dst_p->compressor_config = unpack_right_shift_u8(src_p[7], 3u, 0x18u); - - return (0); -} - -uint8_t PH_status_0_channel_0_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_0_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_0_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_1_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_1_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_1_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_2_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_2_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_2_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_3_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_3_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_3_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_4_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_4_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_4_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_5_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_5_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_5_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_6_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_6_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_6_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_7_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_7_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_7_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_8_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_8_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_8_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_9_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_9_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_9_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_10_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_10_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_10_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_11_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_11_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_11_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_12_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_12_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_12_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_13_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_13_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_13_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_14_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_14_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_14_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_15_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_15_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_15_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_analog_0_encode(double value) -{ - return (uint8_t)(value / 0.01961); -} - -double PH_status_0_analog_0_decode(uint8_t value) -{ - return ((double)value * 0.01961); -} - -bool PH_status_0_analog_0_is_in_range(uint8_t value) -{ - (void)value; - - return (true); -} - -uint8_t PH_status_0_analog_1_encode(double value) -{ - return (uint8_t)(value / 0.01961); -} - -double PH_status_0_analog_1_decode(uint8_t value) -{ - return ((double)value * 0.01961); -} - -bool PH_status_0_analog_1_is_in_range(uint8_t value) -{ - (void)value; - - return (true); -} - -uint8_t PH_status_0_digital_sensor_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_digital_sensor_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_digital_sensor_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_brownout_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_brownout_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_brownout_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_compressor_oc_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_compressor_oc_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_compressor_oc_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_compressor_open_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_compressor_open_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_compressor_open_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_solenoid_oc_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_solenoid_oc_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_solenoid_oc_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_can_warning_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_can_warning_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_can_warning_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_hardware_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_hardware_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_hardware_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_0_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_0_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_0_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_1_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_1_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_1_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_2_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_2_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_2_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_3_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_3_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_3_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_4_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_4_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_4_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_5_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_5_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_5_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_6_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_6_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_6_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_7_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_7_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_7_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_8_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_8_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_8_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_9_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_9_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_9_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_10_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_10_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_10_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_11_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_11_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_11_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_12_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_12_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_12_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_13_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_13_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_13_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_14_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_14_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_14_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_channel_15_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_channel_15_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_channel_15_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_compressor_on_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_compressor_on_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_compressor_on_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_system_enabled_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_system_enabled_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_system_enabled_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_robo_rio_present_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_robo_rio_present_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_robo_rio_present_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_0_compressor_config_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_0_compressor_config_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_0_compressor_config_is_in_range(uint8_t value) -{ - return (value <= 3u); -} - -int PH_status_1_pack( - uint8_t *dst_p, - const struct PH_status_1_t *src_p, - size_t size) -{ - if (size < 8u) { - return (-EINVAL); - } - - memset(&dst_p[0], 0, 8); - - dst_p[0] |= pack_left_shift_u8(src_p->v_bus, 0u, 0xffu); - dst_p[1] |= pack_left_shift_u16(src_p->solenoid_voltage, 0u, 0xffu); - dst_p[2] |= pack_right_shift_u16(src_p->solenoid_voltage, 8u, 0x0fu); - dst_p[4] |= pack_left_shift_u8(src_p->compressor_current, 0u, 0xffu); - dst_p[5] |= pack_left_shift_u8(src_p->solenoid_current, 0u, 0xffu); - dst_p[6] |= pack_left_shift_u8(src_p->sticky_brownout_fault, 0u, 0x01u); - dst_p[6] |= pack_left_shift_u8(src_p->sticky_compressor_oc_fault, 1u, 0x02u); - dst_p[6] |= pack_left_shift_u8(src_p->sticky_compressor_open_fault, 2u, 0x04u); - dst_p[6] |= pack_left_shift_u8(src_p->sticky_solenoid_oc_fault, 3u, 0x08u); - dst_p[6] |= pack_left_shift_u8(src_p->sticky_can_warning_fault, 4u, 0x10u); - dst_p[6] |= pack_left_shift_u8(src_p->sticky_can_bus_off_fault, 5u, 0x20u); - dst_p[6] |= pack_left_shift_u8(src_p->sticky_hardware_fault, 6u, 0x40u); - dst_p[6] |= pack_left_shift_u8(src_p->sticky_firmware_fault, 7u, 0x80u); - dst_p[7] |= pack_left_shift_u8(src_p->sticky_has_reset_fault, 0u, 0x01u); - dst_p[7] |= pack_left_shift_u8(src_p->supply_voltage_5_v, 1u, 0xfeu); - - return (8); -} - -int PH_status_1_unpack( - struct PH_status_1_t *dst_p, - const uint8_t *src_p, - size_t size) -{ - if (size < 8u) { - return (-EINVAL); - } - - dst_p->v_bus = unpack_right_shift_u8(src_p[0], 0u, 0xffu); - dst_p->solenoid_voltage = unpack_right_shift_u16(src_p[1], 0u, 0xffu); - dst_p->solenoid_voltage |= unpack_left_shift_u16(src_p[2], 8u, 0x0fu); - dst_p->compressor_current = unpack_right_shift_u8(src_p[4], 0u, 0xffu); - dst_p->solenoid_current = unpack_right_shift_u8(src_p[5], 0u, 0xffu); - dst_p->sticky_brownout_fault = unpack_right_shift_u8(src_p[6], 0u, 0x01u); - dst_p->sticky_compressor_oc_fault = unpack_right_shift_u8(src_p[6], 1u, 0x02u); - dst_p->sticky_compressor_open_fault = unpack_right_shift_u8(src_p[6], 2u, 0x04u); - dst_p->sticky_solenoid_oc_fault = unpack_right_shift_u8(src_p[6], 3u, 0x08u); - dst_p->sticky_can_warning_fault = unpack_right_shift_u8(src_p[6], 4u, 0x10u); - dst_p->sticky_can_bus_off_fault = unpack_right_shift_u8(src_p[6], 5u, 0x20u); - dst_p->sticky_hardware_fault = unpack_right_shift_u8(src_p[6], 6u, 0x40u); - dst_p->sticky_firmware_fault = unpack_right_shift_u8(src_p[6], 7u, 0x80u); - dst_p->sticky_has_reset_fault = unpack_right_shift_u8(src_p[7], 0u, 0x01u); - dst_p->supply_voltage_5_v = unpack_right_shift_u8(src_p[7], 1u, 0xfeu); - - return (0); -} - -uint8_t PH_status_1_v_bus_encode(double value) -{ - return (uint8_t)((value - 4.0) / 0.0625); -} - -double PH_status_1_v_bus_decode(uint8_t value) -{ - return (((double)value * 0.0625) + 4.0); -} - -bool PH_status_1_v_bus_is_in_range(uint8_t value) -{ - return (value <= 192u); -} - -uint16_t PH_status_1_solenoid_voltage_encode(double value) -{ - return (uint16_t)(value / 0.0078125); -} - -double PH_status_1_solenoid_voltage_decode(uint16_t value) -{ - return ((double)value * 0.0078125); -} - -bool PH_status_1_solenoid_voltage_is_in_range(uint16_t value) -{ - return (value <= 4096u); -} - -uint8_t PH_status_1_compressor_current_encode(double value) -{ - return (uint8_t)(value / 0.125); -} - -double PH_status_1_compressor_current_decode(uint8_t value) -{ - return ((double)value * 0.125); -} - -bool PH_status_1_compressor_current_is_in_range(uint8_t value) -{ - (void)value; - - return (true); -} - -uint8_t PH_status_1_solenoid_current_encode(double value) -{ - return (uint8_t)(value / 0.125); -} - -double PH_status_1_solenoid_current_decode(uint8_t value) -{ - return ((double)value * 0.125); -} - -bool PH_status_1_solenoid_current_is_in_range(uint8_t value) -{ - (void)value; - - return (true); -} - -uint8_t PH_status_1_sticky_brownout_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_1_sticky_brownout_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_1_sticky_brownout_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_1_sticky_compressor_oc_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_1_sticky_compressor_oc_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_1_sticky_compressor_oc_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_1_sticky_compressor_open_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_1_sticky_compressor_open_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_1_sticky_compressor_open_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_1_sticky_solenoid_oc_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_1_sticky_solenoid_oc_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_1_sticky_solenoid_oc_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_1_sticky_can_warning_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_1_sticky_can_warning_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_1_sticky_can_warning_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_1_sticky_can_bus_off_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_1_sticky_can_bus_off_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_1_sticky_can_bus_off_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_1_sticky_hardware_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_1_sticky_hardware_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_1_sticky_hardware_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_1_sticky_firmware_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_1_sticky_firmware_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_1_sticky_firmware_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_1_sticky_has_reset_fault_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_status_1_sticky_has_reset_fault_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_status_1_sticky_has_reset_fault_is_in_range(uint8_t value) -{ - return (value <= 1u); -} - -uint8_t PH_status_1_supply_voltage_5_v_encode(double value) -{ - return (uint8_t)((value - 4.5) / 0.0078125); -} - -double PH_status_1_supply_voltage_5_v_decode(uint8_t value) -{ - return (((double)value * 0.0078125) + 4.5); -} - -bool PH_status_1_supply_voltage_5_v_is_in_range(uint8_t value) -{ - return (value <= 128u); -} - -int PH_clear_faults_pack( - uint8_t *dst_p, - const struct PH_clear_faults_t *src_p, - size_t size) -{ - (void)dst_p; - (void)src_p; - (void)size; - - return (0); -} - -int PH_clear_faults_unpack( - struct PH_clear_faults_t *dst_p, - const uint8_t *src_p, - size_t size) -{ - (void)dst_p; - (void)src_p; - (void)size; - - return (0); -} - -int PH_version_pack( - uint8_t *dst_p, - const struct PH_version_t *src_p, - size_t size) -{ - if (size < 8u) { - return (-EINVAL); - } - - memset(&dst_p[0], 0, 8); - - dst_p[0] |= pack_left_shift_u8(src_p->firmware_fix, 0u, 0xffu); - dst_p[1] |= pack_left_shift_u8(src_p->firmware_minor, 0u, 0xffu); - dst_p[2] |= pack_left_shift_u8(src_p->firmware_year, 0u, 0xffu); - dst_p[3] |= pack_left_shift_u8(src_p->hardware_minor, 0u, 0xffu); - dst_p[4] |= pack_left_shift_u8(src_p->hardware_major, 0u, 0xffu); - dst_p[5] |= pack_left_shift_u32(src_p->unique_id, 0u, 0xffu); - dst_p[6] |= pack_right_shift_u32(src_p->unique_id, 8u, 0xffu); - dst_p[7] |= pack_right_shift_u32(src_p->unique_id, 16u, 0xffu); - - return (8); -} - -int PH_version_unpack( - struct PH_version_t *dst_p, - const uint8_t *src_p, - size_t size) -{ - if (size < 8u) { - return (-EINVAL); - } - - dst_p->firmware_fix = unpack_right_shift_u8(src_p[0], 0u, 0xffu); - dst_p->firmware_minor = unpack_right_shift_u8(src_p[1], 0u, 0xffu); - dst_p->firmware_year = unpack_right_shift_u8(src_p[2], 0u, 0xffu); - dst_p->hardware_minor = unpack_right_shift_u8(src_p[3], 0u, 0xffu); - dst_p->hardware_major = unpack_right_shift_u8(src_p[4], 0u, 0xffu); - dst_p->unique_id = unpack_right_shift_u32(src_p[5], 0u, 0xffu); - dst_p->unique_id |= unpack_left_shift_u32(src_p[6], 8u, 0xffu); - dst_p->unique_id |= unpack_left_shift_u32(src_p[7], 16u, 0xffu); - - return (0); -} - -uint8_t PH_version_firmware_fix_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_version_firmware_fix_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_version_firmware_fix_is_in_range(uint8_t value) -{ - (void)value; - - return (true); -} - -uint8_t PH_version_firmware_minor_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_version_firmware_minor_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_version_firmware_minor_is_in_range(uint8_t value) -{ - (void)value; - - return (true); -} - -uint8_t PH_version_firmware_year_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_version_firmware_year_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_version_firmware_year_is_in_range(uint8_t value) -{ - (void)value; - - return (true); -} - -uint8_t PH_version_hardware_minor_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_version_hardware_minor_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_version_hardware_minor_is_in_range(uint8_t value) -{ - (void)value; - - return (true); -} - -uint8_t PH_version_hardware_major_encode(double value) -{ - return (uint8_t)(value); -} - -double PH_version_hardware_major_decode(uint8_t value) -{ - return ((double)value); -} - -bool PH_version_hardware_major_is_in_range(uint8_t value) -{ - (void)value; - - return (true); -} - -uint32_t PH_version_unique_id_encode(double value) -{ - return (uint32_t)(value); -} - -double PH_version_unique_id_decode(uint32_t value) -{ - return ((double)value); -} - -bool PH_version_unique_id_is_in_range(uint32_t value) -{ - return (value <= 16777215u); -} +/** + * The MIT License (MIT) + * + * Copyright (c) 2018-2019 Erik Moqvist + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, copy, + * modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * This file was generated by cantools version + */ + +#include + +#include "PHFrames.h" + +static inline uint8_t pack_left_shift_u8( + uint8_t value, + uint8_t shift, + uint8_t mask) +{ + return (uint8_t)((uint8_t)(value << shift) & mask); +} + +static inline uint8_t pack_left_shift_u16( + uint16_t value, + uint8_t shift, + uint8_t mask) +{ + return (uint8_t)((uint8_t)(value << shift) & mask); +} + +static inline uint8_t pack_left_shift_u32( + uint32_t value, + uint8_t shift, + uint8_t mask) +{ + return (uint8_t)((uint8_t)(value << shift) & mask); +} + +static inline uint8_t pack_right_shift_u16( + uint16_t value, + uint8_t shift, + uint8_t mask) +{ + return (uint8_t)((uint8_t)(value >> shift) & mask); +} + +static inline uint8_t pack_right_shift_u32( + uint32_t value, + uint8_t shift, + uint8_t mask) +{ + return (uint8_t)((uint8_t)(value >> shift) & mask); +} + +static inline uint16_t unpack_left_shift_u16( + uint8_t value, + uint8_t shift, + uint8_t mask) +{ + return (uint16_t)((uint16_t)(value & mask) << shift); +} + +static inline uint32_t unpack_left_shift_u32( + uint8_t value, + uint8_t shift, + uint8_t mask) +{ + return (uint32_t)((uint32_t)(value & mask) << shift); +} + +static inline uint8_t unpack_right_shift_u8( + uint8_t value, + uint8_t shift, + uint8_t mask) +{ + return (uint8_t)((uint8_t)(value & mask) >> shift); +} + +static inline uint16_t unpack_right_shift_u16( + uint8_t value, + uint8_t shift, + uint8_t mask) +{ + return (uint16_t)((uint16_t)(value & mask) >> shift); +} + +static inline uint32_t unpack_right_shift_u32( + uint8_t value, + uint8_t shift, + uint8_t mask) +{ + return (uint32_t)((uint32_t)(value & mask) >> shift); +} + +int PH_compressor_config_pack( + uint8_t *dst_p, + const struct PH_compressor_config_t *src_p, + size_t size) +{ + if (size < 5u) { + return (-EINVAL); + } + + memset(&dst_p[0], 0, 5); + + dst_p[0] |= pack_left_shift_u16(src_p->minimum_tank_pressure, 0u, 0xffu); + dst_p[1] |= pack_right_shift_u16(src_p->minimum_tank_pressure, 8u, 0xffu); + dst_p[2] |= pack_left_shift_u16(src_p->maximum_tank_pressure, 0u, 0xffu); + dst_p[3] |= pack_right_shift_u16(src_p->maximum_tank_pressure, 8u, 0xffu); + dst_p[4] |= pack_left_shift_u8(src_p->force_disable, 0u, 0x01u); + dst_p[4] |= pack_left_shift_u8(src_p->use_digital, 1u, 0x02u); + + return (5); +} + +int PH_compressor_config_unpack( + struct PH_compressor_config_t *dst_p, + const uint8_t *src_p, + size_t size) +{ + if (size < 5u) { + return (-EINVAL); + } + + dst_p->minimum_tank_pressure = unpack_right_shift_u16(src_p[0], 0u, 0xffu); + dst_p->minimum_tank_pressure |= unpack_left_shift_u16(src_p[1], 8u, 0xffu); + dst_p->maximum_tank_pressure = unpack_right_shift_u16(src_p[2], 0u, 0xffu); + dst_p->maximum_tank_pressure |= unpack_left_shift_u16(src_p[3], 8u, 0xffu); + dst_p->force_disable = unpack_right_shift_u8(src_p[4], 0u, 0x01u); + dst_p->use_digital = unpack_right_shift_u8(src_p[4], 1u, 0x02u); + + return (0); +} + +uint16_t PH_compressor_config_minimum_tank_pressure_encode(double value) +{ + return (uint16_t)(value / 0.001); +} + +double PH_compressor_config_minimum_tank_pressure_decode(uint16_t value) +{ + return ((double)value * 0.001); +} + +bool PH_compressor_config_minimum_tank_pressure_is_in_range(uint16_t value) +{ + return (value <= 5000u); +} + +uint16_t PH_compressor_config_maximum_tank_pressure_encode(double value) +{ + return (uint16_t)(value / 0.001); +} + +double PH_compressor_config_maximum_tank_pressure_decode(uint16_t value) +{ + return ((double)value * 0.001); +} + +bool PH_compressor_config_maximum_tank_pressure_is_in_range(uint16_t value) +{ + return (value <= 5000u); +} + +uint8_t PH_compressor_config_force_disable_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_compressor_config_force_disable_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_compressor_config_force_disable_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_compressor_config_use_digital_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_compressor_config_use_digital_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_compressor_config_use_digital_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +int PH_set_all_pack( + uint8_t *dst_p, + const struct PH_set_all_t *src_p, + size_t size) +{ + if (size < 4u) { + return (-EINVAL); + } + + memset(&dst_p[0], 0, 4); + + dst_p[0] |= pack_left_shift_u8(src_p->channel_0, 0u, 0x03u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_1, 2u, 0x0cu); + dst_p[0] |= pack_left_shift_u8(src_p->channel_2, 4u, 0x30u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_3, 6u, 0xc0u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_4, 0u, 0x03u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_5, 2u, 0x0cu); + dst_p[1] |= pack_left_shift_u8(src_p->channel_6, 4u, 0x30u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_7, 6u, 0xc0u); + dst_p[2] |= pack_left_shift_u8(src_p->channel_8, 0u, 0x03u); + dst_p[2] |= pack_left_shift_u8(src_p->channel_9, 2u, 0x0cu); + dst_p[2] |= pack_left_shift_u8(src_p->channel_10, 4u, 0x30u); + dst_p[2] |= pack_left_shift_u8(src_p->channel_11, 6u, 0xc0u); + dst_p[3] |= pack_left_shift_u8(src_p->channel_12, 0u, 0x03u); + dst_p[3] |= pack_left_shift_u8(src_p->channel_13, 2u, 0x0cu); + dst_p[3] |= pack_left_shift_u8(src_p->channel_14, 4u, 0x30u); + dst_p[3] |= pack_left_shift_u8(src_p->channel_15, 6u, 0xc0u); + + return (4); +} + +int PH_set_all_unpack( + struct PH_set_all_t *dst_p, + const uint8_t *src_p, + size_t size) +{ + if (size < 4u) { + return (-EINVAL); + } + + dst_p->channel_0 = unpack_right_shift_u8(src_p[0], 0u, 0x03u); + dst_p->channel_1 = unpack_right_shift_u8(src_p[0], 2u, 0x0cu); + dst_p->channel_2 = unpack_right_shift_u8(src_p[0], 4u, 0x30u); + dst_p->channel_3 = unpack_right_shift_u8(src_p[0], 6u, 0xc0u); + dst_p->channel_4 = unpack_right_shift_u8(src_p[1], 0u, 0x03u); + dst_p->channel_5 = unpack_right_shift_u8(src_p[1], 2u, 0x0cu); + dst_p->channel_6 = unpack_right_shift_u8(src_p[1], 4u, 0x30u); + dst_p->channel_7 = unpack_right_shift_u8(src_p[1], 6u, 0xc0u); + dst_p->channel_8 = unpack_right_shift_u8(src_p[2], 0u, 0x03u); + dst_p->channel_9 = unpack_right_shift_u8(src_p[2], 2u, 0x0cu); + dst_p->channel_10 = unpack_right_shift_u8(src_p[2], 4u, 0x30u); + dst_p->channel_11 = unpack_right_shift_u8(src_p[2], 6u, 0xc0u); + dst_p->channel_12 = unpack_right_shift_u8(src_p[3], 0u, 0x03u); + dst_p->channel_13 = unpack_right_shift_u8(src_p[3], 2u, 0x0cu); + dst_p->channel_14 = unpack_right_shift_u8(src_p[3], 4u, 0x30u); + dst_p->channel_15 = unpack_right_shift_u8(src_p[3], 6u, 0xc0u); + + return (0); +} + +uint8_t PH_set_all_channel_0_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_0_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_0_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_1_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_1_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_1_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_2_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_2_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_2_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_3_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_3_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_3_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_4_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_4_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_4_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_5_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_5_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_5_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_6_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_6_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_6_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_7_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_7_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_7_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_8_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_8_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_8_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_9_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_9_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_9_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_10_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_10_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_10_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_11_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_11_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_11_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_12_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_12_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_12_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_13_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_13_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_13_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_14_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_14_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_14_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +uint8_t PH_set_all_channel_15_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_set_all_channel_15_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_set_all_channel_15_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +int PH_pulse_once_pack( + uint8_t *dst_p, + const struct PH_pulse_once_t *src_p, + size_t size) +{ + if (size < 4u) { + return (-EINVAL); + } + + memset(&dst_p[0], 0, 4); + + dst_p[0] |= pack_left_shift_u8(src_p->channel_0, 0u, 0x01u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_1, 1u, 0x02u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_2, 2u, 0x04u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_3, 3u, 0x08u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_4, 4u, 0x10u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_5, 5u, 0x20u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_6, 6u, 0x40u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_7, 7u, 0x80u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_8, 0u, 0x01u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_9, 1u, 0x02u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_10, 2u, 0x04u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_11, 3u, 0x08u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_12, 4u, 0x10u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_13, 5u, 0x20u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_14, 6u, 0x40u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_15, 7u, 0x80u); + dst_p[2] |= pack_left_shift_u16(src_p->pulse_length_ms, 0u, 0xffu); + dst_p[3] |= pack_right_shift_u16(src_p->pulse_length_ms, 8u, 0xffu); + + return (4); +} + +int PH_pulse_once_unpack( + struct PH_pulse_once_t *dst_p, + const uint8_t *src_p, + size_t size) +{ + if (size < 4u) { + return (-EINVAL); + } + + dst_p->channel_0 = unpack_right_shift_u8(src_p[0], 0u, 0x01u); + dst_p->channel_1 = unpack_right_shift_u8(src_p[0], 1u, 0x02u); + dst_p->channel_2 = unpack_right_shift_u8(src_p[0], 2u, 0x04u); + dst_p->channel_3 = unpack_right_shift_u8(src_p[0], 3u, 0x08u); + dst_p->channel_4 = unpack_right_shift_u8(src_p[0], 4u, 0x10u); + dst_p->channel_5 = unpack_right_shift_u8(src_p[0], 5u, 0x20u); + dst_p->channel_6 = unpack_right_shift_u8(src_p[0], 6u, 0x40u); + dst_p->channel_7 = unpack_right_shift_u8(src_p[0], 7u, 0x80u); + dst_p->channel_8 = unpack_right_shift_u8(src_p[1], 0u, 0x01u); + dst_p->channel_9 = unpack_right_shift_u8(src_p[1], 1u, 0x02u); + dst_p->channel_10 = unpack_right_shift_u8(src_p[1], 2u, 0x04u); + dst_p->channel_11 = unpack_right_shift_u8(src_p[1], 3u, 0x08u); + dst_p->channel_12 = unpack_right_shift_u8(src_p[1], 4u, 0x10u); + dst_p->channel_13 = unpack_right_shift_u8(src_p[1], 5u, 0x20u); + dst_p->channel_14 = unpack_right_shift_u8(src_p[1], 6u, 0x40u); + dst_p->channel_15 = unpack_right_shift_u8(src_p[1], 7u, 0x80u); + dst_p->pulse_length_ms = unpack_right_shift_u16(src_p[2], 0u, 0xffu); + dst_p->pulse_length_ms |= unpack_left_shift_u16(src_p[3], 8u, 0xffu); + + return (0); +} + +uint8_t PH_pulse_once_channel_0_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_0_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_0_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_1_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_1_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_1_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_2_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_2_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_2_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_3_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_3_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_3_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_4_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_4_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_4_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_5_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_5_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_5_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_6_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_6_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_6_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_7_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_7_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_7_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_8_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_8_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_8_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_9_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_9_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_9_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_10_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_10_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_10_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_11_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_11_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_11_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_12_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_12_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_12_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_13_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_13_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_13_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_14_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_14_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_14_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_pulse_once_channel_15_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_pulse_once_channel_15_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_channel_15_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint16_t PH_pulse_once_pulse_length_ms_encode(double value) +{ + return (uint16_t)(value); +} + +double PH_pulse_once_pulse_length_ms_decode(uint16_t value) +{ + return ((double)value); +} + +bool PH_pulse_once_pulse_length_ms_is_in_range(uint16_t value) +{ + (void)value; + + return (true); +} + +int PH_status_0_pack( + uint8_t *dst_p, + const struct PH_status_0_t *src_p, + size_t size) +{ + if (size < 8u) { + return (-EINVAL); + } + + memset(&dst_p[0], 0, 8); + + dst_p[0] |= pack_left_shift_u8(src_p->channel_0, 0u, 0x01u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_1, 1u, 0x02u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_2, 2u, 0x04u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_3, 3u, 0x08u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_4, 4u, 0x10u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_5, 5u, 0x20u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_6, 6u, 0x40u); + dst_p[0] |= pack_left_shift_u8(src_p->channel_7, 7u, 0x80u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_8, 0u, 0x01u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_9, 1u, 0x02u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_10, 2u, 0x04u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_11, 3u, 0x08u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_12, 4u, 0x10u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_13, 5u, 0x20u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_14, 6u, 0x40u); + dst_p[1] |= pack_left_shift_u8(src_p->channel_15, 7u, 0x80u); + dst_p[2] |= pack_left_shift_u8(src_p->analog_0, 0u, 0xffu); + dst_p[3] |= pack_left_shift_u8(src_p->analog_1, 0u, 0xffu); + dst_p[4] |= pack_left_shift_u8(src_p->digital_sensor, 0u, 0x01u); + dst_p[4] |= pack_left_shift_u8(src_p->brownout_fault, 1u, 0x02u); + dst_p[4] |= pack_left_shift_u8(src_p->compressor_oc_fault, 2u, 0x04u); + dst_p[4] |= pack_left_shift_u8(src_p->compressor_open_fault, 3u, 0x08u); + dst_p[4] |= pack_left_shift_u8(src_p->solenoid_oc_fault, 4u, 0x10u); + dst_p[4] |= pack_left_shift_u8(src_p->can_warning_fault, 5u, 0x20u); + dst_p[4] |= pack_left_shift_u8(src_p->hardware_fault, 6u, 0x40u); + dst_p[5] |= pack_left_shift_u8(src_p->channel_0_fault, 0u, 0x01u); + dst_p[5] |= pack_left_shift_u8(src_p->channel_1_fault, 1u, 0x02u); + dst_p[5] |= pack_left_shift_u8(src_p->channel_2_fault, 2u, 0x04u); + dst_p[5] |= pack_left_shift_u8(src_p->channel_3_fault, 3u, 0x08u); + dst_p[5] |= pack_left_shift_u8(src_p->channel_4_fault, 4u, 0x10u); + dst_p[5] |= pack_left_shift_u8(src_p->channel_5_fault, 5u, 0x20u); + dst_p[5] |= pack_left_shift_u8(src_p->channel_6_fault, 6u, 0x40u); + dst_p[5] |= pack_left_shift_u8(src_p->channel_7_fault, 7u, 0x80u); + dst_p[6] |= pack_left_shift_u8(src_p->channel_8_fault, 0u, 0x01u); + dst_p[6] |= pack_left_shift_u8(src_p->channel_9_fault, 1u, 0x02u); + dst_p[6] |= pack_left_shift_u8(src_p->channel_10_fault, 2u, 0x04u); + dst_p[6] |= pack_left_shift_u8(src_p->channel_11_fault, 3u, 0x08u); + dst_p[6] |= pack_left_shift_u8(src_p->channel_12_fault, 4u, 0x10u); + dst_p[6] |= pack_left_shift_u8(src_p->channel_13_fault, 5u, 0x20u); + dst_p[6] |= pack_left_shift_u8(src_p->channel_14_fault, 6u, 0x40u); + dst_p[6] |= pack_left_shift_u8(src_p->channel_15_fault, 7u, 0x80u); + dst_p[7] |= pack_left_shift_u8(src_p->compressor_on, 0u, 0x01u); + dst_p[7] |= pack_left_shift_u8(src_p->system_enabled, 1u, 0x02u); + dst_p[7] |= pack_left_shift_u8(src_p->robo_rio_present, 2u, 0x04u); + dst_p[7] |= pack_left_shift_u8(src_p->compressor_config, 3u, 0x18u); + + return (8); +} + +int PH_status_0_unpack( + struct PH_status_0_t *dst_p, + const uint8_t *src_p, + size_t size) +{ + if (size < 8u) { + return (-EINVAL); + } + + dst_p->channel_0 = unpack_right_shift_u8(src_p[0], 0u, 0x01u); + dst_p->channel_1 = unpack_right_shift_u8(src_p[0], 1u, 0x02u); + dst_p->channel_2 = unpack_right_shift_u8(src_p[0], 2u, 0x04u); + dst_p->channel_3 = unpack_right_shift_u8(src_p[0], 3u, 0x08u); + dst_p->channel_4 = unpack_right_shift_u8(src_p[0], 4u, 0x10u); + dst_p->channel_5 = unpack_right_shift_u8(src_p[0], 5u, 0x20u); + dst_p->channel_6 = unpack_right_shift_u8(src_p[0], 6u, 0x40u); + dst_p->channel_7 = unpack_right_shift_u8(src_p[0], 7u, 0x80u); + dst_p->channel_8 = unpack_right_shift_u8(src_p[1], 0u, 0x01u); + dst_p->channel_9 = unpack_right_shift_u8(src_p[1], 1u, 0x02u); + dst_p->channel_10 = unpack_right_shift_u8(src_p[1], 2u, 0x04u); + dst_p->channel_11 = unpack_right_shift_u8(src_p[1], 3u, 0x08u); + dst_p->channel_12 = unpack_right_shift_u8(src_p[1], 4u, 0x10u); + dst_p->channel_13 = unpack_right_shift_u8(src_p[1], 5u, 0x20u); + dst_p->channel_14 = unpack_right_shift_u8(src_p[1], 6u, 0x40u); + dst_p->channel_15 = unpack_right_shift_u8(src_p[1], 7u, 0x80u); + dst_p->analog_0 = unpack_right_shift_u8(src_p[2], 0u, 0xffu); + dst_p->analog_1 = unpack_right_shift_u8(src_p[3], 0u, 0xffu); + dst_p->digital_sensor = unpack_right_shift_u8(src_p[4], 0u, 0x01u); + dst_p->brownout_fault = unpack_right_shift_u8(src_p[4], 1u, 0x02u); + dst_p->compressor_oc_fault = unpack_right_shift_u8(src_p[4], 2u, 0x04u); + dst_p->compressor_open_fault = unpack_right_shift_u8(src_p[4], 3u, 0x08u); + dst_p->solenoid_oc_fault = unpack_right_shift_u8(src_p[4], 4u, 0x10u); + dst_p->can_warning_fault = unpack_right_shift_u8(src_p[4], 5u, 0x20u); + dst_p->hardware_fault = unpack_right_shift_u8(src_p[4], 6u, 0x40u); + dst_p->channel_0_fault = unpack_right_shift_u8(src_p[5], 0u, 0x01u); + dst_p->channel_1_fault = unpack_right_shift_u8(src_p[5], 1u, 0x02u); + dst_p->channel_2_fault = unpack_right_shift_u8(src_p[5], 2u, 0x04u); + dst_p->channel_3_fault = unpack_right_shift_u8(src_p[5], 3u, 0x08u); + dst_p->channel_4_fault = unpack_right_shift_u8(src_p[5], 4u, 0x10u); + dst_p->channel_5_fault = unpack_right_shift_u8(src_p[5], 5u, 0x20u); + dst_p->channel_6_fault = unpack_right_shift_u8(src_p[5], 6u, 0x40u); + dst_p->channel_7_fault = unpack_right_shift_u8(src_p[5], 7u, 0x80u); + dst_p->channel_8_fault = unpack_right_shift_u8(src_p[6], 0u, 0x01u); + dst_p->channel_9_fault = unpack_right_shift_u8(src_p[6], 1u, 0x02u); + dst_p->channel_10_fault = unpack_right_shift_u8(src_p[6], 2u, 0x04u); + dst_p->channel_11_fault = unpack_right_shift_u8(src_p[6], 3u, 0x08u); + dst_p->channel_12_fault = unpack_right_shift_u8(src_p[6], 4u, 0x10u); + dst_p->channel_13_fault = unpack_right_shift_u8(src_p[6], 5u, 0x20u); + dst_p->channel_14_fault = unpack_right_shift_u8(src_p[6], 6u, 0x40u); + dst_p->channel_15_fault = unpack_right_shift_u8(src_p[6], 7u, 0x80u); + dst_p->compressor_on = unpack_right_shift_u8(src_p[7], 0u, 0x01u); + dst_p->system_enabled = unpack_right_shift_u8(src_p[7], 1u, 0x02u); + dst_p->robo_rio_present = unpack_right_shift_u8(src_p[7], 2u, 0x04u); + dst_p->compressor_config = unpack_right_shift_u8(src_p[7], 3u, 0x18u); + + return (0); +} + +uint8_t PH_status_0_channel_0_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_0_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_0_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_1_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_1_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_1_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_2_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_2_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_2_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_3_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_3_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_3_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_4_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_4_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_4_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_5_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_5_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_5_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_6_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_6_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_6_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_7_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_7_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_7_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_8_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_8_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_8_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_9_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_9_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_9_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_10_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_10_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_10_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_11_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_11_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_11_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_12_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_12_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_12_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_13_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_13_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_13_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_14_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_14_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_14_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_15_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_15_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_15_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_analog_0_encode(double value) +{ + return (uint8_t)(value / 0.01961); +} + +double PH_status_0_analog_0_decode(uint8_t value) +{ + return ((double)value * 0.01961); +} + +bool PH_status_0_analog_0_is_in_range(uint8_t value) +{ + (void)value; + + return (true); +} + +uint8_t PH_status_0_analog_1_encode(double value) +{ + return (uint8_t)(value / 0.01961); +} + +double PH_status_0_analog_1_decode(uint8_t value) +{ + return ((double)value * 0.01961); +} + +bool PH_status_0_analog_1_is_in_range(uint8_t value) +{ + (void)value; + + return (true); +} + +uint8_t PH_status_0_digital_sensor_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_digital_sensor_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_digital_sensor_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_brownout_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_brownout_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_brownout_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_compressor_oc_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_compressor_oc_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_compressor_oc_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_compressor_open_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_compressor_open_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_compressor_open_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_solenoid_oc_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_solenoid_oc_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_solenoid_oc_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_can_warning_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_can_warning_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_can_warning_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_hardware_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_hardware_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_hardware_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_0_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_0_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_0_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_1_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_1_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_1_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_2_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_2_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_2_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_3_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_3_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_3_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_4_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_4_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_4_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_5_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_5_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_5_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_6_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_6_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_6_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_7_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_7_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_7_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_8_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_8_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_8_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_9_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_9_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_9_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_10_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_10_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_10_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_11_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_11_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_11_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_12_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_12_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_12_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_13_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_13_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_13_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_14_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_14_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_14_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_channel_15_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_channel_15_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_channel_15_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_compressor_on_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_compressor_on_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_compressor_on_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_system_enabled_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_system_enabled_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_system_enabled_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_robo_rio_present_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_robo_rio_present_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_robo_rio_present_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_0_compressor_config_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_0_compressor_config_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_0_compressor_config_is_in_range(uint8_t value) +{ + return (value <= 3u); +} + +int PH_status_1_pack( + uint8_t *dst_p, + const struct PH_status_1_t *src_p, + size_t size) +{ + if (size < 8u) { + return (-EINVAL); + } + + memset(&dst_p[0], 0, 8); + + dst_p[0] |= pack_left_shift_u8(src_p->v_bus, 0u, 0xffu); + dst_p[1] |= pack_left_shift_u16(src_p->solenoid_voltage, 0u, 0xffu); + dst_p[2] |= pack_right_shift_u16(src_p->solenoid_voltage, 8u, 0x0fu); + dst_p[4] |= pack_left_shift_u8(src_p->compressor_current, 0u, 0xffu); + dst_p[5] |= pack_left_shift_u8(src_p->solenoid_current, 0u, 0xffu); + dst_p[6] |= pack_left_shift_u8(src_p->sticky_brownout_fault, 0u, 0x01u); + dst_p[6] |= pack_left_shift_u8(src_p->sticky_compressor_oc_fault, 1u, 0x02u); + dst_p[6] |= pack_left_shift_u8(src_p->sticky_compressor_open_fault, 2u, 0x04u); + dst_p[6] |= pack_left_shift_u8(src_p->sticky_solenoid_oc_fault, 3u, 0x08u); + dst_p[6] |= pack_left_shift_u8(src_p->sticky_can_warning_fault, 4u, 0x10u); + dst_p[6] |= pack_left_shift_u8(src_p->sticky_can_bus_off_fault, 5u, 0x20u); + dst_p[6] |= pack_left_shift_u8(src_p->sticky_hardware_fault, 6u, 0x40u); + dst_p[6] |= pack_left_shift_u8(src_p->sticky_firmware_fault, 7u, 0x80u); + dst_p[7] |= pack_left_shift_u8(src_p->sticky_has_reset_fault, 0u, 0x01u); + dst_p[7] |= pack_left_shift_u8(src_p->supply_voltage_5_v, 1u, 0xfeu); + + return (8); +} + +int PH_status_1_unpack( + struct PH_status_1_t *dst_p, + const uint8_t *src_p, + size_t size) +{ + if (size < 8u) { + return (-EINVAL); + } + + dst_p->v_bus = unpack_right_shift_u8(src_p[0], 0u, 0xffu); + dst_p->solenoid_voltage = unpack_right_shift_u16(src_p[1], 0u, 0xffu); + dst_p->solenoid_voltage |= unpack_left_shift_u16(src_p[2], 8u, 0x0fu); + dst_p->compressor_current = unpack_right_shift_u8(src_p[4], 0u, 0xffu); + dst_p->solenoid_current = unpack_right_shift_u8(src_p[5], 0u, 0xffu); + dst_p->sticky_brownout_fault = unpack_right_shift_u8(src_p[6], 0u, 0x01u); + dst_p->sticky_compressor_oc_fault = unpack_right_shift_u8(src_p[6], 1u, 0x02u); + dst_p->sticky_compressor_open_fault = unpack_right_shift_u8(src_p[6], 2u, 0x04u); + dst_p->sticky_solenoid_oc_fault = unpack_right_shift_u8(src_p[6], 3u, 0x08u); + dst_p->sticky_can_warning_fault = unpack_right_shift_u8(src_p[6], 4u, 0x10u); + dst_p->sticky_can_bus_off_fault = unpack_right_shift_u8(src_p[6], 5u, 0x20u); + dst_p->sticky_hardware_fault = unpack_right_shift_u8(src_p[6], 6u, 0x40u); + dst_p->sticky_firmware_fault = unpack_right_shift_u8(src_p[6], 7u, 0x80u); + dst_p->sticky_has_reset_fault = unpack_right_shift_u8(src_p[7], 0u, 0x01u); + dst_p->supply_voltage_5_v = unpack_right_shift_u8(src_p[7], 1u, 0xfeu); + + return (0); +} + +uint8_t PH_status_1_v_bus_encode(double value) +{ + return (uint8_t)((value - 4.0) / 0.0625); +} + +double PH_status_1_v_bus_decode(uint8_t value) +{ + return (((double)value * 0.0625) + 4.0); +} + +bool PH_status_1_v_bus_is_in_range(uint8_t value) +{ + return (value <= 192u); +} + +uint16_t PH_status_1_solenoid_voltage_encode(double value) +{ + return (uint16_t)(value / 0.0078125); +} + +double PH_status_1_solenoid_voltage_decode(uint16_t value) +{ + return ((double)value * 0.0078125); +} + +bool PH_status_1_solenoid_voltage_is_in_range(uint16_t value) +{ + return (value <= 4096u); +} + +uint8_t PH_status_1_compressor_current_encode(double value) +{ + return (uint8_t)(value / 0.125); +} + +double PH_status_1_compressor_current_decode(uint8_t value) +{ + return ((double)value * 0.125); +} + +bool PH_status_1_compressor_current_is_in_range(uint8_t value) +{ + (void)value; + + return (true); +} + +uint8_t PH_status_1_solenoid_current_encode(double value) +{ + return (uint8_t)(value / 0.125); +} + +double PH_status_1_solenoid_current_decode(uint8_t value) +{ + return ((double)value * 0.125); +} + +bool PH_status_1_solenoid_current_is_in_range(uint8_t value) +{ + (void)value; + + return (true); +} + +uint8_t PH_status_1_sticky_brownout_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_1_sticky_brownout_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_1_sticky_brownout_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_1_sticky_compressor_oc_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_1_sticky_compressor_oc_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_1_sticky_compressor_oc_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_1_sticky_compressor_open_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_1_sticky_compressor_open_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_1_sticky_compressor_open_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_1_sticky_solenoid_oc_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_1_sticky_solenoid_oc_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_1_sticky_solenoid_oc_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_1_sticky_can_warning_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_1_sticky_can_warning_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_1_sticky_can_warning_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_1_sticky_can_bus_off_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_1_sticky_can_bus_off_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_1_sticky_can_bus_off_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_1_sticky_hardware_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_1_sticky_hardware_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_1_sticky_hardware_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_1_sticky_firmware_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_1_sticky_firmware_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_1_sticky_firmware_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_1_sticky_has_reset_fault_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_status_1_sticky_has_reset_fault_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_status_1_sticky_has_reset_fault_is_in_range(uint8_t value) +{ + return (value <= 1u); +} + +uint8_t PH_status_1_supply_voltage_5_v_encode(double value) +{ + return (uint8_t)((value - 4.5) / 0.0078125); +} + +double PH_status_1_supply_voltage_5_v_decode(uint8_t value) +{ + return (((double)value * 0.0078125) + 4.5); +} + +bool PH_status_1_supply_voltage_5_v_is_in_range(uint8_t value) +{ + return (value <= 128u); +} + +int PH_clear_faults_pack( + uint8_t *dst_p, + const struct PH_clear_faults_t *src_p, + size_t size) +{ + (void)dst_p; + (void)src_p; + (void)size; + + return (0); +} + +int PH_clear_faults_unpack( + struct PH_clear_faults_t *dst_p, + const uint8_t *src_p, + size_t size) +{ + (void)dst_p; + (void)src_p; + (void)size; + + return (0); +} + +int PH_version_pack( + uint8_t *dst_p, + const struct PH_version_t *src_p, + size_t size) +{ + if (size < 8u) { + return (-EINVAL); + } + + memset(&dst_p[0], 0, 8); + + dst_p[0] |= pack_left_shift_u8(src_p->firmware_fix, 0u, 0xffu); + dst_p[1] |= pack_left_shift_u8(src_p->firmware_minor, 0u, 0xffu); + dst_p[2] |= pack_left_shift_u8(src_p->firmware_year, 0u, 0xffu); + dst_p[3] |= pack_left_shift_u8(src_p->hardware_minor, 0u, 0xffu); + dst_p[4] |= pack_left_shift_u8(src_p->hardware_major, 0u, 0xffu); + dst_p[5] |= pack_left_shift_u32(src_p->unique_id, 0u, 0xffu); + dst_p[6] |= pack_right_shift_u32(src_p->unique_id, 8u, 0xffu); + dst_p[7] |= pack_right_shift_u32(src_p->unique_id, 16u, 0xffu); + + return (8); +} + +int PH_version_unpack( + struct PH_version_t *dst_p, + const uint8_t *src_p, + size_t size) +{ + if (size < 8u) { + return (-EINVAL); + } + + dst_p->firmware_fix = unpack_right_shift_u8(src_p[0], 0u, 0xffu); + dst_p->firmware_minor = unpack_right_shift_u8(src_p[1], 0u, 0xffu); + dst_p->firmware_year = unpack_right_shift_u8(src_p[2], 0u, 0xffu); + dst_p->hardware_minor = unpack_right_shift_u8(src_p[3], 0u, 0xffu); + dst_p->hardware_major = unpack_right_shift_u8(src_p[4], 0u, 0xffu); + dst_p->unique_id = unpack_right_shift_u32(src_p[5], 0u, 0xffu); + dst_p->unique_id |= unpack_left_shift_u32(src_p[6], 8u, 0xffu); + dst_p->unique_id |= unpack_left_shift_u32(src_p[7], 16u, 0xffu); + + return (0); +} + +uint8_t PH_version_firmware_fix_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_version_firmware_fix_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_version_firmware_fix_is_in_range(uint8_t value) +{ + (void)value; + + return (true); +} + +uint8_t PH_version_firmware_minor_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_version_firmware_minor_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_version_firmware_minor_is_in_range(uint8_t value) +{ + (void)value; + + return (true); +} + +uint8_t PH_version_firmware_year_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_version_firmware_year_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_version_firmware_year_is_in_range(uint8_t value) +{ + (void)value; + + return (true); +} + +uint8_t PH_version_hardware_minor_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_version_hardware_minor_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_version_hardware_minor_is_in_range(uint8_t value) +{ + (void)value; + + return (true); +} + +uint8_t PH_version_hardware_major_encode(double value) +{ + return (uint8_t)(value); +} + +double PH_version_hardware_major_decode(uint8_t value) +{ + return ((double)value); +} + +bool PH_version_hardware_major_is_in_range(uint8_t value) +{ + (void)value; + + return (true); +} + +uint32_t PH_version_unique_id_encode(double value) +{ + return (uint32_t)(value); +} + +double PH_version_unique_id_decode(uint32_t value) +{ + return ((double)value); +} + +bool PH_version_unique_id_is_in_range(uint32_t value) +{ + return (value <= 16777215u); +} diff --git a/hal/src/main/native/athena/rev/PHFrames.h b/hal/src/main/native/athena/rev/PHFrames.h index a1849e1e6e4..cc9c23ccb3e 100644 --- a/hal/src/main/native/athena/rev/PHFrames.h +++ b/hal/src/main/native/athena/rev/PHFrames.h @@ -1,3816 +1,3816 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2018-2019 Erik Moqvist - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -/** - * This file was generated by cantools version - */ - -#ifndef PH_H -#define PH_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include - -#ifndef EINVAL -# define EINVAL 22 -#endif - -/* Frame ids. */ -#define PH_COMPRESSOR_CONFIG_FRAME_ID (0x9050840u) -#define PH_SET_ALL_FRAME_ID (0x9050c00u) -#define PH_PULSE_ONCE_FRAME_ID (0x9050c40u) -#define PH_STATUS_0_FRAME_ID (0x9051800u) -#define PH_STATUS_1_FRAME_ID (0x9051840u) -#define PH_CLEAR_FAULTS_FRAME_ID (0x9051b80u) -#define PH_VERSION_FRAME_ID (0x9052600u) - -/* Frame lengths in bytes. */ -#define PH_COMPRESSOR_CONFIG_LENGTH (5u) -#define PH_SET_ALL_LENGTH (4u) -#define PH_PULSE_ONCE_LENGTH (4u) -#define PH_STATUS_0_LENGTH (8u) -#define PH_STATUS_1_LENGTH (8u) -#define PH_CLEAR_FAULTS_LENGTH (0u) -#define PH_VERSION_LENGTH (8u) - -/* Extended or standard frame types. */ -#define PH_COMPRESSOR_CONFIG_IS_EXTENDED (1) -#define PH_SET_ALL_IS_EXTENDED (1) -#define PH_PULSE_ONCE_IS_EXTENDED (1) -#define PH_STATUS_0_IS_EXTENDED (1) -#define PH_STATUS_1_IS_EXTENDED (1) -#define PH_CLEAR_FAULTS_IS_EXTENDED (1) -#define PH_VERSION_IS_EXTENDED (1) - -/* Frame cycle times in milliseconds. */ - - -/* Signal choices. */ - - -/** - * Signals in message Compressor_Config. - * - * Configures compressor to use digital/analog sensors - * - * All signal values are as on the CAN bus. - */ -struct PH_compressor_config_t { - /** - * Range: 0..5000 (0..5 V) - * Scale: 0.001 - * Offset: 0 - */ - uint16_t minimum_tank_pressure : 16; - - /** - * Range: 0..5000 (0..5 V) - * Scale: 0.001 - * Offset: 0 - */ - uint16_t maximum_tank_pressure : 16; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t force_disable : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t use_digital : 1; -}; - -/** - * Signals in message Set_All. - * - * Set state of all channels - * - * All signal values are as on the CAN bus. - */ -struct PH_set_all_t { - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_0 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_1 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_2 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_3 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_4 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_5 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_6 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_7 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_8 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_9 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_10 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_11 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_12 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_13 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_14 : 2; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_15 : 2; -}; - -/** - * Signals in message Pulse_Once. - * - * Pulse selected channels once - * - * All signal values are as on the CAN bus. - */ -struct PH_pulse_once_t { - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_0 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_1 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_2 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_3 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_4 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_5 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_6 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_7 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_8 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_9 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_10 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_11 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_12 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_13 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_14 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_15 : 1; - - /** - * Range: 0..65535 (0..65535 -) - * Scale: 1 - * Offset: 0 - */ - uint16_t pulse_length_ms : 16; -}; - -/** - * Signals in message Status_0. - * - * Periodic status frame 0 - * - * All signal values are as on the CAN bus. - */ -struct PH_status_0_t { - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_0 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_1 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_2 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_3 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_4 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_5 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_6 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_7 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_8 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_9 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_10 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_11 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_12 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_13 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_14 : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_15 : 1; - - /** - * Range: 0..255 (0..5.00055 V) - * Scale: 0.01961 - * Offset: 0 - */ - uint8_t analog_0 : 8; - - /** - * Range: 0..255 (0..5.00055 V) - * Scale: 0.01961 - * Offset: 0 - */ - uint8_t analog_1 : 8; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t digital_sensor : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t brownout_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t compressor_oc_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t compressor_open_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t solenoid_oc_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t can_warning_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t hardware_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_0_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_1_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_2_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_3_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_4_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_5_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_6_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_7_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_8_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_9_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_10_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_11_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_12_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_13_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_14_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t channel_15_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t compressor_on : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t system_enabled : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t robo_rio_present : 1; - - /** - * Range: 0..3 (0..3 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t compressor_config : 2; -}; - -/** - * Signals in message Status_1. - * - * Periodic status frame 1 - * - * All signal values are as on the CAN bus. - */ -struct PH_status_1_t { - /** - * Range: 0..192 (4..16 V) - * Scale: 0.0625 - * Offset: 4 - */ - uint8_t v_bus : 8; - - /** - * Range: 0..4096 (0..32 V) - * Scale: 0.0078125 - * Offset: 0 - */ - uint16_t solenoid_voltage : 12; - - /** - * Range: 0..256 (0..32 A) - * Scale: 0.125 - * Offset: 0 - */ - uint8_t compressor_current : 8; - - /** - * Range: 0..256 (0..32 A) - * Scale: 0.125 - * Offset: 0 - */ - uint8_t solenoid_current : 8; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t sticky_brownout_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t sticky_compressor_oc_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t sticky_compressor_open_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t sticky_solenoid_oc_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t sticky_can_warning_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t sticky_can_bus_off_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t sticky_hardware_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t sticky_firmware_fault : 1; - - /** - * Range: 0..1 (0..1 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t sticky_has_reset_fault : 1; - - /** - * Range: 0..128 (4.5..5.5 V) - * Scale: 0.0078125 - * Offset: 4.5 - */ - uint8_t supply_voltage_5_v : 7; -}; - -/** - * Signals in message Clear_Faults. - * - * Clear sticky faults on the device - * - * All signal values are as on the CAN bus. - */ -struct PH_clear_faults_t { - /** - * Dummy signal in empty message. - */ - uint8_t dummy; -}; - -/** - * Signals in message Version. - * - * Get the version of the PH - * - * All signal values are as on the CAN bus. - */ -struct PH_version_t { - /** - * Range: 0..255 (0..255 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t firmware_fix : 8; - - /** - * Range: 0..255 (0..255 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t firmware_minor : 8; - - /** - * Range: 0..255 (0..255 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t firmware_year : 8; - - /** - * Range: 0..255 (0..255 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t hardware_minor : 8; - - /** - * Range: 0..255 (0..255 -) - * Scale: 1 - * Offset: 0 - */ - uint8_t hardware_major : 8; - - /** - * Range: 0..16777215 (0..16777215 -) - * Scale: 1 - * Offset: 0 - */ - uint32_t unique_id : 24; -}; - -/** - * Pack message Compressor_Config. - * - * @param[out] dst_p Buffer to pack the message into. - * @param[in] src_p Data to pack. - * @param[in] size Size of dst_p. - * - * @return Size of packed data, or negative error code. - */ -int PH_compressor_config_pack( - uint8_t *dst_p, - const struct PH_compressor_config_t *src_p, - size_t size); - -/** - * Unpack message Compressor_Config. - * - * @param[out] dst_p Object to unpack the message into. - * @param[in] src_p Message to unpack. - * @param[in] size Size of src_p. - * - * @return zero(0) or negative error code. - */ -int PH_compressor_config_unpack( - struct PH_compressor_config_t *dst_p, - const uint8_t *src_p, - size_t size); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint16_t PH_compressor_config_minimum_tank_pressure_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_compressor_config_minimum_tank_pressure_decode(uint16_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_compressor_config_minimum_tank_pressure_is_in_range(uint16_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint16_t PH_compressor_config_maximum_tank_pressure_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_compressor_config_maximum_tank_pressure_decode(uint16_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_compressor_config_maximum_tank_pressure_is_in_range(uint16_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_compressor_config_force_disable_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_compressor_config_force_disable_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_compressor_config_force_disable_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_compressor_config_use_digital_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_compressor_config_use_digital_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_compressor_config_use_digital_is_in_range(uint8_t value); - -/** - * Pack message Set_All. - * - * @param[out] dst_p Buffer to pack the message into. - * @param[in] src_p Data to pack. - * @param[in] size Size of dst_p. - * - * @return Size of packed data, or negative error code. - */ -int PH_set_all_pack( - uint8_t *dst_p, - const struct PH_set_all_t *src_p, - size_t size); - -/** - * Unpack message Set_All. - * - * @param[out] dst_p Object to unpack the message into. - * @param[in] src_p Message to unpack. - * @param[in] size Size of src_p. - * - * @return zero(0) or negative error code. - */ -int PH_set_all_unpack( - struct PH_set_all_t *dst_p, - const uint8_t *src_p, - size_t size); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_0_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_0_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_0_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_1_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_1_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_1_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_2_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_2_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_2_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_3_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_3_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_3_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_4_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_4_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_4_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_5_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_5_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_5_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_6_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_6_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_6_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_7_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_7_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_7_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_8_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_8_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_8_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_9_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_9_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_9_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_10_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_10_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_10_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_11_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_11_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_11_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_12_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_12_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_12_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_13_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_13_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_13_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_14_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_14_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_14_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_set_all_channel_15_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_set_all_channel_15_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_set_all_channel_15_is_in_range(uint8_t value); - -/** - * Pack message Pulse_Once. - * - * @param[out] dst_p Buffer to pack the message into. - * @param[in] src_p Data to pack. - * @param[in] size Size of dst_p. - * - * @return Size of packed data, or negative error code. - */ -int PH_pulse_once_pack( - uint8_t *dst_p, - const struct PH_pulse_once_t *src_p, - size_t size); - -/** - * Unpack message Pulse_Once. - * - * @param[out] dst_p Object to unpack the message into. - * @param[in] src_p Message to unpack. - * @param[in] size Size of src_p. - * - * @return zero(0) or negative error code. - */ -int PH_pulse_once_unpack( - struct PH_pulse_once_t *dst_p, - const uint8_t *src_p, - size_t size); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_0_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_0_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_0_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_1_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_1_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_1_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_2_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_2_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_2_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_3_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_3_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_3_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_4_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_4_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_4_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_5_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_5_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_5_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_6_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_6_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_6_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_7_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_7_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_7_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_8_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_8_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_8_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_9_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_9_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_9_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_10_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_10_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_10_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_11_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_11_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_11_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_12_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_12_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_12_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_13_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_13_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_13_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_14_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_14_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_14_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_pulse_once_channel_15_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_channel_15_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_channel_15_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint16_t PH_pulse_once_pulse_length_ms_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_pulse_once_pulse_length_ms_decode(uint16_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_pulse_once_pulse_length_ms_is_in_range(uint16_t value); - -/** - * Pack message Status_0. - * - * @param[out] dst_p Buffer to pack the message into. - * @param[in] src_p Data to pack. - * @param[in] size Size of dst_p. - * - * @return Size of packed data, or negative error code. - */ -int PH_status_0_pack( - uint8_t *dst_p, - const struct PH_status_0_t *src_p, - size_t size); - -/** - * Unpack message Status_0. - * - * @param[out] dst_p Object to unpack the message into. - * @param[in] src_p Message to unpack. - * @param[in] size Size of src_p. - * - * @return zero(0) or negative error code. - */ -int PH_status_0_unpack( - struct PH_status_0_t *dst_p, - const uint8_t *src_p, - size_t size); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_0_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_0_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_0_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_1_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_1_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_1_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_2_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_2_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_2_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_3_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_3_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_3_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_4_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_4_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_4_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_5_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_5_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_5_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_6_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_6_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_6_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_7_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_7_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_7_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_8_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_8_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_8_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_9_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_9_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_9_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_10_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_10_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_10_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_11_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_11_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_11_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_12_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_12_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_12_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_13_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_13_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_13_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_14_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_14_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_14_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_15_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_15_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_15_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_analog_0_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_analog_0_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_analog_0_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_analog_1_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_analog_1_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_analog_1_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_digital_sensor_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_digital_sensor_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_digital_sensor_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_brownout_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_brownout_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_brownout_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_compressor_oc_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_compressor_oc_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_compressor_oc_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_compressor_open_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_compressor_open_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_compressor_open_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_solenoid_oc_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_solenoid_oc_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_solenoid_oc_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_can_warning_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_can_warning_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_can_warning_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_hardware_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_hardware_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_hardware_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_0_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_0_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_0_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_1_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_1_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_1_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_2_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_2_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_2_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_3_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_3_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_3_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_4_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_4_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_4_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_5_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_5_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_5_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_6_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_6_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_6_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_7_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_7_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_7_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_8_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_8_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_8_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_9_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_9_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_9_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_10_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_10_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_10_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_11_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_11_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_11_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_12_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_12_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_12_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_13_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_13_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_13_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_14_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_14_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_14_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_channel_15_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_channel_15_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_channel_15_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_compressor_on_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_compressor_on_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_compressor_on_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_system_enabled_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_system_enabled_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_system_enabled_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_robo_rio_present_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_robo_rio_present_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_robo_rio_present_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_0_compressor_config_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_0_compressor_config_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_0_compressor_config_is_in_range(uint8_t value); - -/** - * Pack message Status_1. - * - * @param[out] dst_p Buffer to pack the message into. - * @param[in] src_p Data to pack. - * @param[in] size Size of dst_p. - * - * @return Size of packed data, or negative error code. - */ -int PH_status_1_pack( - uint8_t *dst_p, - const struct PH_status_1_t *src_p, - size_t size); - -/** - * Unpack message Status_1. - * - * @param[out] dst_p Object to unpack the message into. - * @param[in] src_p Message to unpack. - * @param[in] size Size of src_p. - * - * @return zero(0) or negative error code. - */ -int PH_status_1_unpack( - struct PH_status_1_t *dst_p, - const uint8_t *src_p, - size_t size); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_v_bus_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_v_bus_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_v_bus_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint16_t PH_status_1_solenoid_voltage_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_solenoid_voltage_decode(uint16_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_solenoid_voltage_is_in_range(uint16_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_compressor_current_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_compressor_current_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_compressor_current_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_solenoid_current_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_solenoid_current_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_solenoid_current_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_sticky_brownout_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_sticky_brownout_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_sticky_brownout_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_sticky_compressor_oc_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_sticky_compressor_oc_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_sticky_compressor_oc_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_sticky_compressor_open_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_sticky_compressor_open_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_sticky_compressor_open_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_sticky_solenoid_oc_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_sticky_solenoid_oc_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_sticky_solenoid_oc_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_sticky_can_warning_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_sticky_can_warning_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_sticky_can_warning_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_sticky_can_bus_off_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_sticky_can_bus_off_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_sticky_can_bus_off_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_sticky_hardware_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_sticky_hardware_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_sticky_hardware_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_sticky_firmware_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_sticky_firmware_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_sticky_firmware_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_sticky_has_reset_fault_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_sticky_has_reset_fault_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_sticky_has_reset_fault_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_status_1_supply_voltage_5_v_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_status_1_supply_voltage_5_v_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_status_1_supply_voltage_5_v_is_in_range(uint8_t value); - -/** - * Pack message Clear_Faults. - * - * @param[out] dst_p Buffer to pack the message into. - * @param[in] src_p Data to pack. - * @param[in] size Size of dst_p. - * - * @return Size of packed data, or negative error code. - */ -int PH_clear_faults_pack( - uint8_t *dst_p, - const struct PH_clear_faults_t *src_p, - size_t size); - -/** - * Unpack message Clear_Faults. - * - * @param[out] dst_p Object to unpack the message into. - * @param[in] src_p Message to unpack. - * @param[in] size Size of src_p. - * - * @return zero(0) or negative error code. - */ -int PH_clear_faults_unpack( - struct PH_clear_faults_t *dst_p, - const uint8_t *src_p, - size_t size); - -/** - * Pack message Version. - * - * @param[out] dst_p Buffer to pack the message into. - * @param[in] src_p Data to pack. - * @param[in] size Size of dst_p. - * - * @return Size of packed data, or negative error code. - */ -int PH_version_pack( - uint8_t *dst_p, - const struct PH_version_t *src_p, - size_t size); - -/** - * Unpack message Version. - * - * @param[out] dst_p Object to unpack the message into. - * @param[in] src_p Message to unpack. - * @param[in] size Size of src_p. - * - * @return zero(0) or negative error code. - */ -int PH_version_unpack( - struct PH_version_t *dst_p, - const uint8_t *src_p, - size_t size); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_version_firmware_fix_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_version_firmware_fix_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_version_firmware_fix_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_version_firmware_minor_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_version_firmware_minor_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_version_firmware_minor_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_version_firmware_year_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_version_firmware_year_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_version_firmware_year_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_version_hardware_minor_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_version_hardware_minor_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_version_hardware_minor_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint8_t PH_version_hardware_major_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_version_hardware_major_decode(uint8_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_version_hardware_major_is_in_range(uint8_t value); - -/** - * Encode given signal by applying scaling and offset. - * - * @param[in] value Signal to encode. - * - * @return Encoded signal. - */ -uint32_t PH_version_unique_id_encode(double value); - -/** - * Decode given signal by applying scaling and offset. - * - * @param[in] value Signal to decode. - * - * @return Decoded signal. - */ -double PH_version_unique_id_decode(uint32_t value); - -/** - * Check that given signal is in allowed range. - * - * @param[in] value Signal to check. - * - * @return true if in range, false otherwise. - */ -bool PH_version_unique_id_is_in_range(uint32_t value); - - -#ifdef __cplusplus -} -#endif - -#endif +/** + * The MIT License (MIT) + * + * Copyright (c) 2018-2019 Erik Moqvist + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, copy, + * modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * This file was generated by cantools version + */ + +#ifndef PH_H +#define PH_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#ifndef EINVAL +# define EINVAL 22 +#endif + +/* Frame ids. */ +#define PH_COMPRESSOR_CONFIG_FRAME_ID (0x9050840u) +#define PH_SET_ALL_FRAME_ID (0x9050c00u) +#define PH_PULSE_ONCE_FRAME_ID (0x9050c40u) +#define PH_STATUS_0_FRAME_ID (0x9051800u) +#define PH_STATUS_1_FRAME_ID (0x9051840u) +#define PH_CLEAR_FAULTS_FRAME_ID (0x9051b80u) +#define PH_VERSION_FRAME_ID (0x9052600u) + +/* Frame lengths in bytes. */ +#define PH_COMPRESSOR_CONFIG_LENGTH (5u) +#define PH_SET_ALL_LENGTH (4u) +#define PH_PULSE_ONCE_LENGTH (4u) +#define PH_STATUS_0_LENGTH (8u) +#define PH_STATUS_1_LENGTH (8u) +#define PH_CLEAR_FAULTS_LENGTH (0u) +#define PH_VERSION_LENGTH (8u) + +/* Extended or standard frame types. */ +#define PH_COMPRESSOR_CONFIG_IS_EXTENDED (1) +#define PH_SET_ALL_IS_EXTENDED (1) +#define PH_PULSE_ONCE_IS_EXTENDED (1) +#define PH_STATUS_0_IS_EXTENDED (1) +#define PH_STATUS_1_IS_EXTENDED (1) +#define PH_CLEAR_FAULTS_IS_EXTENDED (1) +#define PH_VERSION_IS_EXTENDED (1) + +/* Frame cycle times in milliseconds. */ + + +/* Signal choices. */ + + +/** + * Signals in message Compressor_Config. + * + * Configures compressor to use digital/analog sensors + * + * All signal values are as on the CAN bus. + */ +struct PH_compressor_config_t { + /** + * Range: 0..5000 (0..5 V) + * Scale: 0.001 + * Offset: 0 + */ + uint16_t minimum_tank_pressure : 16; + + /** + * Range: 0..5000 (0..5 V) + * Scale: 0.001 + * Offset: 0 + */ + uint16_t maximum_tank_pressure : 16; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t force_disable : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t use_digital : 1; +}; + +/** + * Signals in message Set_All. + * + * Set state of all channels + * + * All signal values are as on the CAN bus. + */ +struct PH_set_all_t { + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_0 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_1 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_2 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_3 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_4 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_5 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_6 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_7 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_8 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_9 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_10 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_11 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_12 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_13 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_14 : 2; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_15 : 2; +}; + +/** + * Signals in message Pulse_Once. + * + * Pulse selected channels once + * + * All signal values are as on the CAN bus. + */ +struct PH_pulse_once_t { + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_0 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_1 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_2 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_3 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_4 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_5 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_6 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_7 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_8 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_9 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_10 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_11 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_12 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_13 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_14 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_15 : 1; + + /** + * Range: 0..65535 (0..65535 -) + * Scale: 1 + * Offset: 0 + */ + uint16_t pulse_length_ms : 16; +}; + +/** + * Signals in message Status_0. + * + * Periodic status frame 0 + * + * All signal values are as on the CAN bus. + */ +struct PH_status_0_t { + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_0 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_1 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_2 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_3 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_4 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_5 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_6 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_7 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_8 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_9 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_10 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_11 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_12 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_13 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_14 : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_15 : 1; + + /** + * Range: 0..255 (0..5.00055 V) + * Scale: 0.01961 + * Offset: 0 + */ + uint8_t analog_0 : 8; + + /** + * Range: 0..255 (0..5.00055 V) + * Scale: 0.01961 + * Offset: 0 + */ + uint8_t analog_1 : 8; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t digital_sensor : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t brownout_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t compressor_oc_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t compressor_open_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t solenoid_oc_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t can_warning_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t hardware_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_0_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_1_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_2_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_3_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_4_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_5_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_6_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_7_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_8_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_9_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_10_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_11_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_12_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_13_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_14_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t channel_15_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t compressor_on : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t system_enabled : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t robo_rio_present : 1; + + /** + * Range: 0..3 (0..3 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t compressor_config : 2; +}; + +/** + * Signals in message Status_1. + * + * Periodic status frame 1 + * + * All signal values are as on the CAN bus. + */ +struct PH_status_1_t { + /** + * Range: 0..192 (4..16 V) + * Scale: 0.0625 + * Offset: 4 + */ + uint8_t v_bus : 8; + + /** + * Range: 0..4096 (0..32 V) + * Scale: 0.0078125 + * Offset: 0 + */ + uint16_t solenoid_voltage : 12; + + /** + * Range: 0..256 (0..32 A) + * Scale: 0.125 + * Offset: 0 + */ + uint8_t compressor_current : 8; + + /** + * Range: 0..256 (0..32 A) + * Scale: 0.125 + * Offset: 0 + */ + uint8_t solenoid_current : 8; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t sticky_brownout_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t sticky_compressor_oc_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t sticky_compressor_open_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t sticky_solenoid_oc_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t sticky_can_warning_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t sticky_can_bus_off_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t sticky_hardware_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t sticky_firmware_fault : 1; + + /** + * Range: 0..1 (0..1 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t sticky_has_reset_fault : 1; + + /** + * Range: 0..128 (4.5..5.5 V) + * Scale: 0.0078125 + * Offset: 4.5 + */ + uint8_t supply_voltage_5_v : 7; +}; + +/** + * Signals in message Clear_Faults. + * + * Clear sticky faults on the device + * + * All signal values are as on the CAN bus. + */ +struct PH_clear_faults_t { + /** + * Dummy signal in empty message. + */ + uint8_t dummy; +}; + +/** + * Signals in message Version. + * + * Get the version of the PH + * + * All signal values are as on the CAN bus. + */ +struct PH_version_t { + /** + * Range: 0..255 (0..255 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t firmware_fix : 8; + + /** + * Range: 0..255 (0..255 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t firmware_minor : 8; + + /** + * Range: 0..255 (0..255 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t firmware_year : 8; + + /** + * Range: 0..255 (0..255 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t hardware_minor : 8; + + /** + * Range: 0..255 (0..255 -) + * Scale: 1 + * Offset: 0 + */ + uint8_t hardware_major : 8; + + /** + * Range: 0..16777215 (0..16777215 -) + * Scale: 1 + * Offset: 0 + */ + uint32_t unique_id : 24; +}; + +/** + * Pack message Compressor_Config. + * + * @param[out] dst_p Buffer to pack the message into. + * @param[in] src_p Data to pack. + * @param[in] size Size of dst_p. + * + * @return Size of packed data, or negative error code. + */ +int PH_compressor_config_pack( + uint8_t *dst_p, + const struct PH_compressor_config_t *src_p, + size_t size); + +/** + * Unpack message Compressor_Config. + * + * @param[out] dst_p Object to unpack the message into. + * @param[in] src_p Message to unpack. + * @param[in] size Size of src_p. + * + * @return zero(0) or negative error code. + */ +int PH_compressor_config_unpack( + struct PH_compressor_config_t *dst_p, + const uint8_t *src_p, + size_t size); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint16_t PH_compressor_config_minimum_tank_pressure_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_compressor_config_minimum_tank_pressure_decode(uint16_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_compressor_config_minimum_tank_pressure_is_in_range(uint16_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint16_t PH_compressor_config_maximum_tank_pressure_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_compressor_config_maximum_tank_pressure_decode(uint16_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_compressor_config_maximum_tank_pressure_is_in_range(uint16_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_compressor_config_force_disable_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_compressor_config_force_disable_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_compressor_config_force_disable_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_compressor_config_use_digital_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_compressor_config_use_digital_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_compressor_config_use_digital_is_in_range(uint8_t value); + +/** + * Pack message Set_All. + * + * @param[out] dst_p Buffer to pack the message into. + * @param[in] src_p Data to pack. + * @param[in] size Size of dst_p. + * + * @return Size of packed data, or negative error code. + */ +int PH_set_all_pack( + uint8_t *dst_p, + const struct PH_set_all_t *src_p, + size_t size); + +/** + * Unpack message Set_All. + * + * @param[out] dst_p Object to unpack the message into. + * @param[in] src_p Message to unpack. + * @param[in] size Size of src_p. + * + * @return zero(0) or negative error code. + */ +int PH_set_all_unpack( + struct PH_set_all_t *dst_p, + const uint8_t *src_p, + size_t size); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_0_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_0_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_0_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_1_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_1_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_1_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_2_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_2_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_2_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_3_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_3_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_3_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_4_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_4_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_4_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_5_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_5_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_5_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_6_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_6_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_6_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_7_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_7_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_7_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_8_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_8_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_8_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_9_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_9_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_9_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_10_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_10_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_10_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_11_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_11_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_11_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_12_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_12_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_12_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_13_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_13_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_13_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_14_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_14_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_14_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_set_all_channel_15_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_set_all_channel_15_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_set_all_channel_15_is_in_range(uint8_t value); + +/** + * Pack message Pulse_Once. + * + * @param[out] dst_p Buffer to pack the message into. + * @param[in] src_p Data to pack. + * @param[in] size Size of dst_p. + * + * @return Size of packed data, or negative error code. + */ +int PH_pulse_once_pack( + uint8_t *dst_p, + const struct PH_pulse_once_t *src_p, + size_t size); + +/** + * Unpack message Pulse_Once. + * + * @param[out] dst_p Object to unpack the message into. + * @param[in] src_p Message to unpack. + * @param[in] size Size of src_p. + * + * @return zero(0) or negative error code. + */ +int PH_pulse_once_unpack( + struct PH_pulse_once_t *dst_p, + const uint8_t *src_p, + size_t size); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_0_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_0_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_0_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_1_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_1_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_1_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_2_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_2_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_2_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_3_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_3_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_3_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_4_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_4_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_4_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_5_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_5_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_5_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_6_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_6_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_6_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_7_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_7_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_7_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_8_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_8_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_8_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_9_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_9_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_9_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_10_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_10_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_10_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_11_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_11_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_11_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_12_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_12_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_12_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_13_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_13_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_13_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_14_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_14_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_14_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_pulse_once_channel_15_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_channel_15_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_channel_15_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint16_t PH_pulse_once_pulse_length_ms_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_pulse_once_pulse_length_ms_decode(uint16_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_pulse_once_pulse_length_ms_is_in_range(uint16_t value); + +/** + * Pack message Status_0. + * + * @param[out] dst_p Buffer to pack the message into. + * @param[in] src_p Data to pack. + * @param[in] size Size of dst_p. + * + * @return Size of packed data, or negative error code. + */ +int PH_status_0_pack( + uint8_t *dst_p, + const struct PH_status_0_t *src_p, + size_t size); + +/** + * Unpack message Status_0. + * + * @param[out] dst_p Object to unpack the message into. + * @param[in] src_p Message to unpack. + * @param[in] size Size of src_p. + * + * @return zero(0) or negative error code. + */ +int PH_status_0_unpack( + struct PH_status_0_t *dst_p, + const uint8_t *src_p, + size_t size); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_0_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_0_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_0_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_1_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_1_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_1_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_2_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_2_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_2_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_3_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_3_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_3_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_4_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_4_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_4_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_5_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_5_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_5_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_6_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_6_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_6_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_7_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_7_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_7_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_8_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_8_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_8_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_9_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_9_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_9_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_10_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_10_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_10_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_11_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_11_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_11_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_12_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_12_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_12_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_13_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_13_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_13_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_14_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_14_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_14_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_15_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_15_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_15_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_analog_0_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_analog_0_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_analog_0_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_analog_1_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_analog_1_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_analog_1_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_digital_sensor_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_digital_sensor_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_digital_sensor_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_brownout_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_brownout_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_brownout_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_compressor_oc_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_compressor_oc_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_compressor_oc_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_compressor_open_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_compressor_open_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_compressor_open_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_solenoid_oc_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_solenoid_oc_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_solenoid_oc_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_can_warning_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_can_warning_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_can_warning_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_hardware_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_hardware_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_hardware_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_0_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_0_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_0_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_1_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_1_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_1_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_2_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_2_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_2_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_3_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_3_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_3_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_4_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_4_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_4_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_5_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_5_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_5_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_6_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_6_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_6_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_7_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_7_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_7_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_8_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_8_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_8_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_9_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_9_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_9_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_10_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_10_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_10_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_11_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_11_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_11_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_12_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_12_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_12_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_13_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_13_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_13_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_14_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_14_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_14_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_channel_15_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_channel_15_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_channel_15_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_compressor_on_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_compressor_on_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_compressor_on_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_system_enabled_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_system_enabled_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_system_enabled_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_robo_rio_present_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_robo_rio_present_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_robo_rio_present_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_0_compressor_config_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_0_compressor_config_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_0_compressor_config_is_in_range(uint8_t value); + +/** + * Pack message Status_1. + * + * @param[out] dst_p Buffer to pack the message into. + * @param[in] src_p Data to pack. + * @param[in] size Size of dst_p. + * + * @return Size of packed data, or negative error code. + */ +int PH_status_1_pack( + uint8_t *dst_p, + const struct PH_status_1_t *src_p, + size_t size); + +/** + * Unpack message Status_1. + * + * @param[out] dst_p Object to unpack the message into. + * @param[in] src_p Message to unpack. + * @param[in] size Size of src_p. + * + * @return zero(0) or negative error code. + */ +int PH_status_1_unpack( + struct PH_status_1_t *dst_p, + const uint8_t *src_p, + size_t size); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_v_bus_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_v_bus_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_v_bus_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint16_t PH_status_1_solenoid_voltage_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_solenoid_voltage_decode(uint16_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_solenoid_voltage_is_in_range(uint16_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_compressor_current_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_compressor_current_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_compressor_current_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_solenoid_current_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_solenoid_current_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_solenoid_current_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_sticky_brownout_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_sticky_brownout_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_sticky_brownout_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_sticky_compressor_oc_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_sticky_compressor_oc_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_sticky_compressor_oc_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_sticky_compressor_open_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_sticky_compressor_open_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_sticky_compressor_open_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_sticky_solenoid_oc_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_sticky_solenoid_oc_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_sticky_solenoid_oc_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_sticky_can_warning_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_sticky_can_warning_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_sticky_can_warning_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_sticky_can_bus_off_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_sticky_can_bus_off_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_sticky_can_bus_off_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_sticky_hardware_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_sticky_hardware_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_sticky_hardware_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_sticky_firmware_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_sticky_firmware_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_sticky_firmware_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_sticky_has_reset_fault_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_sticky_has_reset_fault_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_sticky_has_reset_fault_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_status_1_supply_voltage_5_v_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_status_1_supply_voltage_5_v_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_status_1_supply_voltage_5_v_is_in_range(uint8_t value); + +/** + * Pack message Clear_Faults. + * + * @param[out] dst_p Buffer to pack the message into. + * @param[in] src_p Data to pack. + * @param[in] size Size of dst_p. + * + * @return Size of packed data, or negative error code. + */ +int PH_clear_faults_pack( + uint8_t *dst_p, + const struct PH_clear_faults_t *src_p, + size_t size); + +/** + * Unpack message Clear_Faults. + * + * @param[out] dst_p Object to unpack the message into. + * @param[in] src_p Message to unpack. + * @param[in] size Size of src_p. + * + * @return zero(0) or negative error code. + */ +int PH_clear_faults_unpack( + struct PH_clear_faults_t *dst_p, + const uint8_t *src_p, + size_t size); + +/** + * Pack message Version. + * + * @param[out] dst_p Buffer to pack the message into. + * @param[in] src_p Data to pack. + * @param[in] size Size of dst_p. + * + * @return Size of packed data, or negative error code. + */ +int PH_version_pack( + uint8_t *dst_p, + const struct PH_version_t *src_p, + size_t size); + +/** + * Unpack message Version. + * + * @param[out] dst_p Object to unpack the message into. + * @param[in] src_p Message to unpack. + * @param[in] size Size of src_p. + * + * @return zero(0) or negative error code. + */ +int PH_version_unpack( + struct PH_version_t *dst_p, + const uint8_t *src_p, + size_t size); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_version_firmware_fix_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_version_firmware_fix_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_version_firmware_fix_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_version_firmware_minor_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_version_firmware_minor_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_version_firmware_minor_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_version_firmware_year_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_version_firmware_year_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_version_firmware_year_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_version_hardware_minor_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_version_hardware_minor_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_version_hardware_minor_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint8_t PH_version_hardware_major_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_version_hardware_major_decode(uint8_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_version_hardware_major_is_in_range(uint8_t value); + +/** + * Encode given signal by applying scaling and offset. + * + * @param[in] value Signal to encode. + * + * @return Encoded signal. + */ +uint32_t PH_version_unique_id_encode(double value); + +/** + * Decode given signal by applying scaling and offset. + * + * @param[in] value Signal to decode. + * + * @return Decoded signal. + */ +double PH_version_unique_id_decode(uint32_t value); + +/** + * Check that given signal is in allowed range. + * + * @param[in] value Signal to check. + * + * @return true if in range, false otherwise. + */ +bool PH_version_unique_id_is_in_range(uint32_t value); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/hal/src/main/native/cpp/cpp/fpga_clock.cpp b/hal/src/main/native/cpp/cpp/fpga_clock.cpp index 550596a8ac8..35dff1c21b8 100644 --- a/hal/src/main/native/cpp/cpp/fpga_clock.cpp +++ b/hal/src/main/native/cpp/cpp/fpga_clock.cpp @@ -7,7 +7,7 @@ #include #include -#include +#include #include "hal/HALBase.h" @@ -20,7 +20,7 @@ fpga_clock::time_point fpga_clock::now() noexcept { int32_t status = 0; uint64_t currentTime = HAL_GetFPGATime(&status); if (status != 0) { - fmt::print( + wpi::print( stderr, "Call to HAL_GetFPGATime failed in fpga_clock::now() with status {}. " "Initialization might have failed. Time will not be correct\n", diff --git a/hal/src/main/native/cpp/jni/CANJNI.cpp b/hal/src/main/native/cpp/jni/CANJNI.cpp index 9375a06e80e..40838d3892c 100644 --- a/hal/src/main/native/cpp/jni/CANJNI.cpp +++ b/hal/src/main/native/cpp/jni/CANJNI.cpp @@ -135,6 +135,17 @@ Java_edu_wpi_first_hal_can_CANJNI_readCANStreamSession (JNIEnv* env, jclass, jint sessionHandle, jobjectArray messages, jint messagesToRead) { + if (messages == nullptr) { + ThrowNullPointerException(env, "messages cannot be null"); + return 0; + } + + jsize messagesArrayLen = env->GetArrayLength(messages); + + if (messagesArrayLen < messagesToRead) { + messagesToRead = messagesArrayLen; + } + uint32_t handle = static_cast(sessionHandle); uint32_t messagesRead = 0; @@ -151,7 +162,8 @@ Java_edu_wpi_first_hal_can_CANJNI_readCANStreamSession return 0; } - if (!CheckStatus(env, status)) { + if (status != HAL_ERR_CANSessionMux_SessionOverrun && + !CheckStatus(env, status)) { return 0; } @@ -160,8 +172,15 @@ Java_edu_wpi_first_hal_can_CANJNI_readCANStreamSession JLocal elem{ env, static_cast(env->GetObjectArrayElement(messages, i))}; if (!elem) { - // TODO decide if should throw - continue; + // If element doesn't exist, construct it in place. If that fails, we are + // OOM, just return + elem = JLocal{env, CreateCANStreamMessage(env)}; + if (elem) { + std::printf("Allocated and set object\n"); + env->SetObjectArrayElement(messages, i, elem); + } else { + return 0; + } } JLocal toSetArray{ env, SetCANStreamObject(env, elem, msg->dataSize, msg->messageID, @@ -174,6 +193,12 @@ Java_edu_wpi_first_hal_can_CANJNI_readCANStreamSession reinterpret_cast(msg->data)); } + if (status == HAL_ERR_CANSessionMux_SessionOverrun) { + ThrowCANStreamOverflowException(env, messages, + static_cast(messagesRead)); + return 0; + } + return static_cast(messagesRead); } diff --git a/hal/src/main/native/cpp/jni/DriverStationJNI.cpp b/hal/src/main/native/cpp/jni/DriverStationJNI.cpp index 5e3e97f5f8d..87c8b145058 100644 --- a/hal/src/main/native/cpp/jni/DriverStationJNI.cpp +++ b/hal/src/main/native/cpp/jni/DriverStationJNI.cpp @@ -294,12 +294,11 @@ Java_edu_wpi_first_hal_DriverStationJNI_getJoystickButtons /* * Class: edu_wpi_first_hal_DriverStationJNI * Method: setJoystickOutputs - * Signature: (BISS)I + * Signature: (BIII)I */ JNIEXPORT jint JNICALL Java_edu_wpi_first_hal_DriverStationJNI_setJoystickOutputs - (JNIEnv*, jclass, jbyte port, jint outputs, jshort leftRumble, - jshort rightRumble) + (JNIEnv*, jclass, jbyte port, jint outputs, jint leftRumble, jint rightRumble) { return HAL_SetJoystickOutputs(port, outputs, leftRumble, rightRumble); } @@ -337,9 +336,10 @@ JNIEXPORT jstring JNICALL Java_edu_wpi_first_hal_DriverStationJNI_getJoystickName (JNIEnv* env, jclass, jbyte port) { - char* joystickName = HAL_GetJoystickName(port); - jstring str = MakeJString(env, joystickName); - HAL_FreeJoystickName(joystickName); + WPI_String joystickName; + HAL_GetJoystickName(&joystickName, port); + jstring str = MakeJString(env, wpi::to_string_view(&joystickName)); + WPI_FreeString(&joystickName); return str; } diff --git a/hal/src/main/native/cpp/jni/HAL.cpp b/hal/src/main/native/cpp/jni/HAL.cpp index 6f486e5fc0f..7dcdf45edbf 100644 --- a/hal/src/main/native/cpp/jni/HAL.cpp +++ b/hal/src/main/native/cpp/jni/HAL.cpp @@ -6,6 +6,10 @@ #include +#ifdef __FRC_ROBORIO__ +#include +#endif + #include #include @@ -82,6 +86,20 @@ Java_edu_wpi_first_hal_HAL_exitMain HAL_ExitMain(); } +/* + * Class: edu_wpi_first_hal_HAL + * Method: terminate + * Signature: ()V + */ +JNIEXPORT void JNICALL +Java_edu_wpi_first_hal_HAL_terminate + (JNIEnv*, jclass) +{ +#ifdef __FRC_ROBORIO__ + ::raise(SIGKILL); +#endif +} + /* * Class: edu_wpi_first_hal_HAL * Method: simPeriodicBeforeNative diff --git a/hal/src/main/native/cpp/jni/HALUtil.cpp b/hal/src/main/native/cpp/jni/HALUtil.cpp index 6316a8c1f8e..31b40efc57b 100644 --- a/hal/src/main/native/cpp/jni/HALUtil.cpp +++ b/hal/src/main/native/cpp/jni/HALUtil.cpp @@ -46,6 +46,7 @@ static JException canMessageNotFoundExCls; static JException canMessageNotAllowedExCls; static JException canNotInitializedExCls; static JException uncleanStatusExCls; +static JException nullPointerEx; static JClass powerDistributionVersionCls; static JClass pwmConfigDataResultCls; static JClass canStatusCls; @@ -56,6 +57,7 @@ static JClass canStreamMessageCls; static JClass halValueCls; static JClass baseStoreCls; static JClass revPHVersionCls; +static JClass canStreamOverflowExCls; static const JClassInit classes[] = { {"edu/wpi/first/hal/PowerDistributionVersion", @@ -68,7 +70,9 @@ static const JClassInit classes[] = { {"edu/wpi/first/hal/CANStreamMessage", &canStreamMessageCls}, {"edu/wpi/first/hal/HALValue", &halValueCls}, {"edu/wpi/first/hal/DMAJNISample$BaseStore", &baseStoreCls}, - {"edu/wpi/first/hal/REVPHVersion", &revPHVersionCls}}; + {"edu/wpi/first/hal/REVPHVersion", &revPHVersionCls}, + {"edu/wpi/first/hal/can/CANStreamOverflowException", + &canStreamOverflowExCls}}; static const JExceptionInit exceptions[] = { {"java/lang/IllegalArgumentException", &illegalArgExCls}, @@ -82,7 +86,8 @@ static const JExceptionInit exceptions[] = { &canMessageNotAllowedExCls}, {"edu/wpi/first/hal/can/CANNotInitializedException", &canNotInitializedExCls}, - {"edu/wpi/first/hal/util/UncleanStatusException", &uncleanStatusExCls}}; + {"edu/wpi/first/hal/util/UncleanStatusException", &uncleanStatusExCls}, + {"java/lang/NullPointerException", &nullPointerEx}}; namespace hal { @@ -209,6 +214,20 @@ void ReportCANError(JNIEnv* env, int32_t status, int message_id) { } } +void ThrowNullPointerException(JNIEnv* env, std::string_view msg) { + nullPointerEx.Throw(env, msg); +} + +void ThrowCANStreamOverflowException(JNIEnv* env, jobjectArray messages, + jint length) { + static jmethodID constructor = + env->GetMethodID(canStreamOverflowExCls, "", + "([Ledu/wpi/first/hal/CANStreamMessage;I)V"); + jobject exception = + env->NewObject(canStreamOverflowExCls, constructor, messages, length); + env->Throw(static_cast(exception)); +} + void ThrowIllegalArgumentException(JNIEnv* env, std::string_view msg) { illegalArgExCls.Throw(env, msg); } @@ -365,6 +384,12 @@ jobject CreatePowerDistributionVersion(JNIEnv* env, uint32_t firmwareMajor, static_cast(hardwareMajor), static_cast(uniqueId)); } +jobject CreateCANStreamMessage(JNIEnv* env) { + static jmethodID constructor = + env->GetMethodID(canStreamMessageCls, "", "()V"); + return env->NewObject(canStreamMessageCls, constructor); +} + JavaVM* GetJVM() { return jvm; } @@ -465,9 +490,11 @@ JNIEXPORT jstring JNICALL Java_edu_wpi_first_hal_HALUtil_getSerialNumber (JNIEnv* env, jclass) { - char serialNum[9]; - size_t len = HAL_GetSerialNumber(serialNum, sizeof(serialNum)); - return MakeJString(env, std::string_view(serialNum, len)); + WPI_String serialNum; + HAL_GetSerialNumber(&serialNum); + jstring ret = MakeJString(env, wpi::to_string_view(&serialNum)); + WPI_FreeString(&serialNum); + return ret; } /* @@ -479,9 +506,11 @@ JNIEXPORT jstring JNICALL Java_edu_wpi_first_hal_HALUtil_getComments (JNIEnv* env, jclass) { - char comments[65]; - size_t len = HAL_GetComments(comments, sizeof(comments)); - return MakeJString(env, std::string_view(comments, len)); + WPI_String comments; + HAL_GetComments(&comments); + jstring ret = MakeJString(env, wpi::to_string_view(&comments)); + WPI_FreeString(&comments); + return ret; } /* diff --git a/hal/src/main/native/cpp/jni/HALUtil.h b/hal/src/main/native/cpp/jni/HALUtil.h index 9c9487cd308..b64238bf217 100644 --- a/hal/src/main/native/cpp/jni/HALUtil.h +++ b/hal/src/main/native/cpp/jni/HALUtil.h @@ -51,6 +51,9 @@ inline bool CheckCANStatus(JNIEnv* env, int32_t status, int32_t message_id) { return status == 0; } +void ThrowNullPointerException(JNIEnv* env, std::string_view msg); +void ThrowCANStreamOverflowException(JNIEnv* env, jobjectArray messages, + jint length); void ThrowIllegalArgumentException(JNIEnv* env, std::string_view msg); void ThrowBoundaryException(JNIEnv* env, double value, double lower, double upper); @@ -93,6 +96,8 @@ jobject CreatePowerDistributionVersion(JNIEnv* env, uint32_t firmwareMajor, uint32_t hardwareMajor, uint32_t uniqueId); +jobject CreateCANStreamMessage(JNIEnv* env); + JavaVM* GetJVM(); } // namespace hal diff --git a/hal/src/main/native/cpp/jni/LEDJNI.cpp b/hal/src/main/native/cpp/jni/LEDJNI.cpp new file mode 100644 index 00000000000..62aeaffbf23 --- /dev/null +++ b/hal/src/main/native/cpp/jni/LEDJNI.cpp @@ -0,0 +1,51 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include + +#include "HALUtil.h" +#include "edu_wpi_first_hal_LEDJNI.h" +#include "hal/LEDs.h" + +static_assert(edu_wpi_first_hal_LEDJNI_RADIO_LED_STATE_OFF == + HAL_RadioLEDState::HAL_RadioLED_kOff); +static_assert(edu_wpi_first_hal_LEDJNI_RADIO_LED_STATE_GREEN == + HAL_RadioLEDState::HAL_RadioLED_kGreen); +static_assert(edu_wpi_first_hal_LEDJNI_RADIO_LED_STATE_RED == + HAL_RadioLEDState::HAL_RadioLED_kRed); +static_assert(edu_wpi_first_hal_LEDJNI_RADIO_LED_STATE_ORANGE == + HAL_RadioLEDState::HAL_RadioLED_kOrange); + +using namespace hal; + +extern "C" { +/* + * Class: edu_wpi_first_hal_LEDJNI + * Method: setRadioLEDState + * Signature: (I)V + */ +JNIEXPORT void JNICALL +Java_edu_wpi_first_hal_LEDJNI_setRadioLEDState + (JNIEnv* env, jclass, jint state) +{ + int32_t status = 0; + HAL_SetRadioLEDState(static_cast(state), &status); + CheckStatus(env, status); +} + +/* + * Class: edu_wpi_first_hal_LEDJNI + * Method: getRadioLEDState + * Signature: ()I + */ +JNIEXPORT jint JNICALL +Java_edu_wpi_first_hal_LEDJNI_getRadioLEDState + (JNIEnv* env, jclass) +{ + int32_t status = 0; + auto retVal = HAL_GetRadioLEDState(&status); + CheckStatus(env, status); + return retVal; +} +} // extern "C" diff --git a/hal/src/main/native/cpp/jni/simulation/DriverStationDataJNI.cpp b/hal/src/main/native/cpp/jni/simulation/DriverStationDataJNI.cpp index 8b1ba4f68f5..63af783d41c 100644 --- a/hal/src/main/native/cpp/jni/simulation/DriverStationDataJNI.cpp +++ b/hal/src/main/native/cpp/jni/simulation/DriverStationDataJNI.cpp @@ -733,7 +733,8 @@ Java_edu_wpi_first_hal_simulation_DriverStationDataJNI_setJoystickName (JNIEnv* env, jclass, jint stick, jstring name) { JStringRef nameJString{env, name}; - HALSIM_SetJoystickName(stick, nameJString.c_str(), nameJString.size()); + auto str = wpi::make_string(nameJString); + HALSIM_SetJoystickName(stick, &str); } /* @@ -758,7 +759,8 @@ Java_edu_wpi_first_hal_simulation_DriverStationDataJNI_setGameSpecificMessage (JNIEnv* env, jclass, jstring message) { JStringRef messageJString{env, message}; - HALSIM_SetGameSpecificMessage(messageJString.c_str(), messageJString.size()); + auto str = wpi::make_string(messageJString); + HALSIM_SetGameSpecificMessage(&str); } /* @@ -771,7 +773,8 @@ Java_edu_wpi_first_hal_simulation_DriverStationDataJNI_setEventName (JNIEnv* env, jclass, jstring name) { JStringRef nameJString{env, name}; - HALSIM_SetEventName(nameJString.c_str(), nameJString.size()); + auto str = wpi::make_string(nameJString); + HALSIM_SetEventName(&str); } /* diff --git a/hal/src/main/native/cpp/jni/simulation/RoboRioDataJNI.cpp b/hal/src/main/native/cpp/jni/simulation/RoboRioDataJNI.cpp index 9555f593192..3c9d4422d4d 100644 --- a/hal/src/main/native/cpp/jni/simulation/RoboRioDataJNI.cpp +++ b/hal/src/main/native/cpp/jni/simulation/RoboRioDataJNI.cpp @@ -937,9 +937,11 @@ JNIEXPORT jstring JNICALL Java_edu_wpi_first_hal_simulation_RoboRioDataJNI_getSerialNumber (JNIEnv* env, jclass) { - char serialNum[9]; - size_t len = HALSIM_GetRoboRioSerialNumber(serialNum, sizeof(serialNum)); - return MakeJString(env, std::string_view(serialNum, len)); + WPI_String str; + HALSIM_GetRoboRioSerialNumber(&str); + auto jstr = MakeJString(env, wpi::to_string_view(&str)); + WPI_FreeString(&str); + return jstr; } /* @@ -952,8 +954,8 @@ Java_edu_wpi_first_hal_simulation_RoboRioDataJNI_setSerialNumber (JNIEnv* env, jclass, jstring serialNumber) { JStringRef serialNumberJString{env, serialNumber}; - HALSIM_SetRoboRioSerialNumber(serialNumberJString.c_str(), - serialNumberJString.size()); + auto str = wpi::make_string(serialNumberJString); + HALSIM_SetRoboRioSerialNumber(&str); } /* @@ -965,9 +967,11 @@ JNIEXPORT jstring JNICALL Java_edu_wpi_first_hal_simulation_RoboRioDataJNI_getComments (JNIEnv* env, jclass) { - char comments[65]; - size_t len = HALSIM_GetRoboRioComments(comments, sizeof(comments)); - return MakeJString(env, std::string_view(comments, len)); + WPI_String str; + HALSIM_GetRoboRioComments(&str); + auto jstr = MakeJString(env, wpi::to_string_view(&str)); + WPI_FreeString(&str); + return jstr; } /* @@ -980,7 +984,59 @@ Java_edu_wpi_first_hal_simulation_RoboRioDataJNI_setComments (JNIEnv* env, jclass, jstring comments) { JStringRef commentsJString{env, comments}; - HALSIM_SetRoboRioComments(commentsJString.c_str(), commentsJString.size()); + auto str = wpi::make_string(commentsJString); + HALSIM_SetRoboRioComments(&str); +} + +/* + * Class: edu_wpi_first_hal_simulation_RoboRioDataJNI + * Method: registerRadioLEDStateCallback + * Signature: (Ljava/lang/Object;Z)I + */ +JNIEXPORT jint JNICALL +Java_edu_wpi_first_hal_simulation_RoboRioDataJNI_registerRadioLEDStateCallback + (JNIEnv* env, jclass, jobject callback, jboolean initialNotify) +{ + return sim::AllocateCallbackNoIndex( + env, callback, initialNotify, + &HALSIM_RegisterRoboRioRadioLEDStateCallback); +} + +/* + * Class: edu_wpi_first_hal_simulation_RoboRioDataJNI + * Method: cancelRadioLEDStateCallback + * Signature: (I)V + */ +JNIEXPORT void JNICALL +Java_edu_wpi_first_hal_simulation_RoboRioDataJNI_cancelRadioLEDStateCallback + (JNIEnv* env, jclass, jint handle) +{ + return sim::FreeCallbackNoIndex(env, handle, + &HALSIM_CancelRoboRioRadioLEDStateCallback); +} + +/* + * Class: edu_wpi_first_hal_simulation_RoboRioDataJNI + * Method: getRadioLEDState + * Signature: ()I + */ +JNIEXPORT jint JNICALL +Java_edu_wpi_first_hal_simulation_RoboRioDataJNI_getRadioLEDState + (JNIEnv*, jclass) +{ + return HALSIM_GetRoboRioRadioLEDState(); +} + +/* + * Class: edu_wpi_first_hal_simulation_RoboRioDataJNI + * Method: setRadioLEDState + * Signature: (I)V + */ +JNIEXPORT void JNICALL +Java_edu_wpi_first_hal_simulation_RoboRioDataJNI_setRadioLEDState + (JNIEnv*, jclass, jint value) +{ + HALSIM_SetRoboRioRadioLEDState(static_cast(value)); } /* diff --git a/hal/src/main/native/include/hal/.clang-tidy b/hal/src/main/native/include/hal/.clang-tidy index 4f4edda0f0a..26312851e96 100644 --- a/hal/src/main/native/include/hal/.clang-tidy +++ b/hal/src/main/native/include/hal/.clang-tidy @@ -36,7 +36,6 @@ Checks: bugprone-unhandled-self-assignment, bugprone-unused-raii, bugprone-virtual-near-miss, - cert-dcl58-cpp, cert-err52-cpp, cert-err60-cpp, cert-mem57-cpp, @@ -54,7 +53,6 @@ Checks: google-readability-avoid-underscore-in-googletest-name, google-readability-casting, google-runtime-operator, - llvm-twine-local, misc-definitions-in-headers, misc-misplaced-const, misc-new-delete-overloads, diff --git a/hal/src/main/native/include/hal/Accelerometer.h b/hal/src/main/native/include/hal/Accelerometer.h index 9131e83ec44..ab48ca53fe5 100644 --- a/hal/src/main/native/include/hal/Accelerometer.h +++ b/hal/src/main/native/include/hal/Accelerometer.h @@ -12,7 +12,6 @@ * @{ */ -// clang-format off /** * The acceptable accelerometer ranges. */ @@ -21,7 +20,6 @@ HAL_ENUM(HAL_AccelerometerRange) { HAL_AccelerometerRange_k4G = 1, HAL_AccelerometerRange_k8G = 2, }; -// clang-format on #ifdef __cplusplus extern "C" { diff --git a/hal/src/main/native/include/hal/AnalogTrigger.h b/hal/src/main/native/include/hal/AnalogTrigger.h index f4622e3f479..e678b6864ef 100644 --- a/hal/src/main/native/include/hal/AnalogTrigger.h +++ b/hal/src/main/native/include/hal/AnalogTrigger.h @@ -14,7 +14,6 @@ * @{ */ -// clang-format off /** * The type of analog trigger to trigger on. */ @@ -24,7 +23,6 @@ HAL_ENUM(HAL_AnalogTriggerType) { HAL_Trigger_kRisingPulse = 2, HAL_Trigger_kFallingPulse = 3 }; -// clang-format on #ifdef __cplusplus extern "C" { diff --git a/hal/src/main/native/include/hal/CAN.h b/hal/src/main/native/include/hal/CAN.h index 77a6239d6e3..6d53cfaa942 100644 --- a/hal/src/main/native/include/hal/CAN.h +++ b/hal/src/main/native/include/hal/CAN.h @@ -14,11 +14,24 @@ // These are copies of defines located in CANSessionMux.h prepended with HAL_ +/** + * Flag for sending a CAN message once. + */ #define HAL_CAN_SEND_PERIOD_NO_REPEAT 0 + +/** + * Flag for stopping periodic CAN message sends. + */ #define HAL_CAN_SEND_PERIOD_STOP_REPEATING -1 -/* Flags in the upper bits of the messageID */ +/** + * Mask for "is frame remote" in message ID. + */ #define HAL_CAN_IS_FRAME_REMOTE 0x80000000 + +/** + * Mask for "is frame 11 bits" in message ID. + */ #define HAL_CAN_IS_FRAME_11BIT 0x40000000 #define HAL_ERR_CANSessionMux_InvalidBuffer -44086 diff --git a/hal/src/main/native/include/hal/CANAPITypes.h b/hal/src/main/native/include/hal/CANAPITypes.h index decaf867200..247732c8958 100644 --- a/hal/src/main/native/include/hal/CANAPITypes.h +++ b/hal/src/main/native/include/hal/CANAPITypes.h @@ -14,25 +14,37 @@ * @{ */ -// clang-format off /** * The CAN device type. * * Teams should use HAL_CAN_Dev_kMiscellaneous */ HAL_ENUM(HAL_CANDeviceType) { + /// Broadcast. HAL_CAN_Dev_kBroadcast = 0, + /// Robot controller. HAL_CAN_Dev_kRobotController = 1, + /// Motor controller. HAL_CAN_Dev_kMotorController = 2, + /// Relay controller. HAL_CAN_Dev_kRelayController = 3, + /// Gyro sensor. HAL_CAN_Dev_kGyroSensor = 4, + /// Accelerometer. HAL_CAN_Dev_kAccelerometer = 5, + /// Ultrasonic sensor. HAL_CAN_Dev_kUltrasonicSensor = 6, + /// Gear tooth sensor. HAL_CAN_Dev_kGearToothSensor = 7, + /// Power distribution. HAL_CAN_Dev_kPowerDistribution = 8, + /// Pneumatics. HAL_CAN_Dev_kPneumatics = 9, + /// Miscellaneous. HAL_CAN_Dev_kMiscellaneous = 10, + /// IO breakout. HAL_CAN_Dev_kIOBreakout = 11, + /// Firmware update. HAL_CAN_Dev_kFirmwareUpdate = 31 }; @@ -42,23 +54,39 @@ HAL_ENUM(HAL_CANDeviceType) { * Teams should use HAL_CAN_Man_kTeamUse. */ HAL_ENUM(HAL_CANManufacturer) { + /// Broadcast. HAL_CAN_Man_kBroadcast = 0, + /// National Instruments. HAL_CAN_Man_kNI = 1, + /// Luminary Micro. HAL_CAN_Man_kLM = 2, + /// DEKA Research and Development Corp. HAL_CAN_Man_kDEKA = 3, + /// Cross the Road Electronics. HAL_CAN_Man_kCTRE = 4, + /// REV robotics. HAL_CAN_Man_kREV = 5, + /// Grapple. HAL_CAN_Man_kGrapple = 6, + /// MindSensors. HAL_CAN_Man_kMS = 7, + /// Team use. HAL_CAN_Man_kTeamUse = 8, + /// Kauai Labs. HAL_CAN_Man_kKauaiLabs = 9, + /// Copperforge. HAL_CAN_Man_kCopperforge = 10, + /// Playing With Fusion. HAL_CAN_Man_kPWF = 11, + /// Studica. HAL_CAN_Man_kStudica = 12, + /// TheThriftyBot. HAL_CAN_Man_kTheThriftyBot = 13, + /// Redux Robotics. HAL_CAN_Man_kReduxRobotics = 14, + /// AndyMark. HAL_CAN_Man_kAndyMark = 15, + /// Vivid-Hosting. HAL_CAN_Man_kVividHosting = 16 }; -// clang-format on /** @} */ diff --git a/hal/src/main/native/include/hal/Counter.h b/hal/src/main/native/include/hal/Counter.h index 0338cdae7a5..9c9d3af401a 100644 --- a/hal/src/main/native/include/hal/Counter.h +++ b/hal/src/main/native/include/hal/Counter.h @@ -15,7 +15,6 @@ * @{ */ -// clang-format off /** * The counter mode. */ @@ -25,7 +24,6 @@ HAL_ENUM(HAL_Counter_Mode) { HAL_Counter_kPulseLength = 2, HAL_Counter_kExternalDirection = 3 }; -// clang-format on #ifdef __cplusplus extern "C" { diff --git a/hal/src/main/native/include/hal/DMA.h b/hal/src/main/native/include/hal/DMA.h index b735b6d265c..2d570a40320 100644 --- a/hal/src/main/native/include/hal/DMA.h +++ b/hal/src/main/native/include/hal/DMA.h @@ -13,7 +13,6 @@ * @{ */ -// clang-format off /** * The DMA Read Status. */ @@ -22,7 +21,6 @@ HAL_ENUM(HAL_DMAReadStatus) { HAL_DMA_TIMEOUT = 2, HAL_DMA_ERROR = 3, }; -// clang-format on /** * Buffer for containing all DMA data for a specific sample. @@ -140,6 +138,8 @@ void HAL_AddDMACounter(HAL_DMAHandle handle, HAL_CounterHandle counterHandle, /** * Adds timer data for an counter to be collected by DMA. * + * This can only be called if DMA is not started. + * * @param[in] handle the dma handle * @param[in] counterHandle the counter to add * @param[out] status Error status variable. 0 on success. diff --git a/hal/src/main/native/include/hal/DriverStation.h b/hal/src/main/native/include/hal/DriverStation.h index e0790742b02..8c5fea0c23f 100644 --- a/hal/src/main/native/include/hal/DriverStation.h +++ b/hal/src/main/native/include/hal/DriverStation.h @@ -9,6 +9,7 @@ #include //NOLINT #include +#include #include "hal/DriverStationTypes.h" #include "hal/Types.h" @@ -142,21 +143,12 @@ int32_t HAL_GetJoystickType(int32_t joystickNum); /** * Gets the name of a joystick. * - * The returned array must be freed with HAL_FreeJoystickName. - * - * Will be null terminated. + * The returned string must be freed with WPI_FreeString * + * @param name the joystick name string * @param joystickNum the joystick number - * @return the joystick name - */ -char* HAL_GetJoystickName(int32_t joystickNum); - -/** - * Frees a joystick name received with HAL_GetJoystickName - * - * @param name the name storage */ -void HAL_FreeJoystickName(char* name); +void HAL_GetJoystickName(struct WPI_String* name, int32_t joystickNum); /** * Gets the type of a specific joystick axis. diff --git a/hal/src/main/native/include/hal/DriverStationTypes.h b/hal/src/main/native/include/hal/DriverStationTypes.h index 5917c519191..8282024a2b5 100644 --- a/hal/src/main/native/include/hal/DriverStationTypes.h +++ b/hal/src/main/native/include/hal/DriverStationTypes.h @@ -40,7 +40,6 @@ struct HAL_ControlWord { }; typedef struct HAL_ControlWord HAL_ControlWord; -// clang-format off HAL_ENUM(HAL_AllianceStationID) { HAL_AllianceStationID_kUnknown = 0, HAL_AllianceStationID_kRed1, @@ -57,7 +56,6 @@ HAL_ENUM(HAL_MatchType) { HAL_kMatchType_qualification, HAL_kMatchType_elimination, }; -// clang-format on /* The maximum number of axes that will be stored in a single HALJoystickAxes * struct. This is used for allocating buffers, not bounds checking, since diff --git a/hal/src/main/native/include/hal/Encoder.h b/hal/src/main/native/include/hal/Encoder.h index c6e16a67785..451f1aafcbe 100644 --- a/hal/src/main/native/include/hal/Encoder.h +++ b/hal/src/main/native/include/hal/Encoder.h @@ -15,7 +15,6 @@ * @{ */ -// clang-format off /** * The type of index pulse for the encoder. */ @@ -34,7 +33,6 @@ HAL_ENUM(HAL_EncoderEncodingType) { HAL_Encoder_k2X, HAL_Encoder_k4X }; -// clang-format on #ifdef __cplusplus extern "C" { diff --git a/hal/src/main/native/include/hal/HAL.h b/hal/src/main/native/include/hal/HAL.h index 0d6023729bb..84bee9f75ad 100644 --- a/hal/src/main/native/include/hal/HAL.h +++ b/hal/src/main/native/include/hal/HAL.h @@ -25,6 +25,7 @@ #include "hal/HALBase.h" #include "hal/I2C.h" #include "hal/Interrupts.h" +#include "hal/LEDs.h" #include "hal/Main.h" #include "hal/Notifier.h" #include "hal/PWM.h" diff --git a/hal/src/main/native/include/hal/HALBase.h b/hal/src/main/native/include/hal/HALBase.h index fe8d1bf190e..e59b26cbae1 100644 --- a/hal/src/main/native/include/hal/HALBase.h +++ b/hal/src/main/native/include/hal/HALBase.h @@ -14,6 +14,8 @@ #endif +#include + #include "hal/Types.h" /** @@ -22,9 +24,11 @@ * @{ */ -// clang-format off -HAL_ENUM(HAL_RuntimeType) { HAL_Runtime_RoboRIO, HAL_Runtime_RoboRIO2, HAL_Runtime_Simulation }; -// clang-format on +HAL_ENUM(HAL_RuntimeType) { + HAL_Runtime_RoboRIO, + HAL_Runtime_RoboRIO2, + HAL_Runtime_Simulation +}; #ifdef __cplusplus extern "C" { @@ -77,20 +81,16 @@ int64_t HAL_GetFPGARevision(int32_t* status); /** * Returns the roboRIO serial number. * - * @param[out] buffer The roboRIO serial number. - * @param size The maximum characters to copy into buffer. - * @return Number of characters copied into buffer. + * @param[out] serialNumber The roboRIO serial number. Free with WPI_FreeString */ -size_t HAL_GetSerialNumber(char* buffer, size_t size); +void HAL_GetSerialNumber(struct WPI_String* serialNumber); /** * Returns the comments from the roboRIO web interface. * - * @param[out] buffer The comments string. - * @param size The maximum characters to copy into buffer. - * @return Number of characters copied into buffer. + * @param[out] comments The comments string. Free with WPI_FreeString */ -size_t HAL_GetComments(char* buffer, size_t size); +void HAL_GetComments(struct WPI_String* comments); /** * Returns the team number configured for the robot controller. @@ -108,6 +108,10 @@ HAL_RuntimeType HAL_GetRuntimeType(void); /** * Gets the state of the "USER" button on the roboRIO. * + * @warning the User Button is used to stop user programs from automatically + * loading if it is held for more then 5 seconds. Because of this, it's not + * recommended to be used by teams for any other purpose. + * * @param[out] status the error code, or 0 for success * @return true if the button is currently pressed down */ diff --git a/hal/src/main/native/include/hal/I2CTypes.h b/hal/src/main/native/include/hal/I2CTypes.h index 6aac0fb1065..8c658eee228 100644 --- a/hal/src/main/native/include/hal/I2CTypes.h +++ b/hal/src/main/native/include/hal/I2CTypes.h @@ -14,9 +14,11 @@ * @{ */ -// clang-format off -HAL_ENUM(HAL_I2CPort) { HAL_I2C_kInvalid = -1, HAL_I2C_kOnboard, HAL_I2C_kMXP }; -// clang-format on +HAL_ENUM(HAL_I2CPort) { + HAL_I2C_kInvalid = -1, + HAL_I2C_kOnboard, + HAL_I2C_kMXP +}; #ifdef __cplusplus namespace hal { diff --git a/hal/src/main/native/include/hal/LEDs.h b/hal/src/main/native/include/hal/LEDs.h new file mode 100644 index 00000000000..d7ee7168688 --- /dev/null +++ b/hal/src/main/native/include/hal/LEDs.h @@ -0,0 +1,34 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once +#include "hal/Types.h" + +HAL_ENUM(HAL_RadioLEDState) { + HAL_RadioLED_kOff = 0, + HAL_RadioLED_kGreen = 1, + HAL_RadioLED_kRed = 2, + HAL_RadioLED_kOrange = 3 +}; + +#ifdef __cplusplus +extern "C" { +#endif +/** + * Set the state of the "Radio" LED. + * @param state The state to set the LED to. + * @param[out] status the error code, or 0 for success + */ +void HAL_SetRadioLEDState(HAL_RadioLEDState state, int32_t* status); + +/** + * Get the state of the "Radio" LED. + * + * @param[out] status the error code, or 0 for success + * @return The state of the LED. + */ +HAL_RadioLEDState HAL_GetRadioLEDState(int32_t* status); +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/hal/src/main/native/include/hal/PowerDistribution.h b/hal/src/main/native/include/hal/PowerDistribution.h index 47543bb2bdd..835f2eaf4cf 100644 --- a/hal/src/main/native/include/hal/PowerDistribution.h +++ b/hal/src/main/native/include/hal/PowerDistribution.h @@ -15,7 +15,6 @@ * @{ */ -// clang-format off /** * The types of power distribution devices. */ @@ -24,7 +23,6 @@ HAL_ENUM(HAL_PowerDistributionType) { HAL_PowerDistributionType_kCTRE = 1, HAL_PowerDistributionType_kRev = 2, }; -// clang-format on #define HAL_DEFAULT_POWER_DISTRIBUTION_MODULE -1 @@ -103,7 +101,9 @@ int32_t HAL_GetPowerDistributionNumChannels(HAL_PowerDistributionHandle handle, int32_t* status); /** - * Gets the temperature of the PowerDistribution. + * Gets the temperature of the Power Distribution Panel. + * + * Not supported on the Rev PDH and returns 0. * * @param[in] handle the module handle * @param[out] status Error status variable. 0 on success. @@ -158,7 +158,9 @@ double HAL_GetPowerDistributionTotalCurrent(HAL_PowerDistributionHandle handle, int32_t* status); /** - * Gets the total power of the PowerDistribution. + * Gets the total power of the Power Distribution Panel. + * + * Not supported on the Rev PDH and returns 0. * * @param[in] handle the module handle * @param[out] status Error status variable. 0 on success. @@ -168,7 +170,9 @@ double HAL_GetPowerDistributionTotalPower(HAL_PowerDistributionHandle handle, int32_t* status); /** - * Gets the total energy of the PowerDistribution. + * Gets the total energy of the Power Distribution Panel. + * + * Not supported on the Rev PDH and returns 0. * * @param[in] handle the module handle * @param[out] status Error status variable. 0 on success. @@ -180,6 +184,8 @@ double HAL_GetPowerDistributionTotalEnergy(HAL_PowerDistributionHandle handle, /** * Resets the PowerDistribution accumulated energy. * + * Not supported on the Rev PDH and does nothing. + * * @param[in] handle the module handle * @param[out] status Error status variable. 0 on success. */ @@ -219,12 +225,21 @@ void HAL_SetPowerDistributionSwitchableChannel( HAL_Bool HAL_GetPowerDistributionSwitchableChannel( HAL_PowerDistributionHandle handle, int32_t* status); +/** + * Power distribution version. + */ struct HAL_PowerDistributionVersion { + /// Firmware major version number. uint32_t firmwareMajor; + /// Firmware minor version number. uint32_t firmwareMinor; + /// Firmware fix version number. uint32_t firmwareFix; + /// Hardware minor version number. uint32_t hardwareMinor; + /// Hardware major version number. uint32_t hardwareMajor; + /// Unique ID. uint32_t uniqueId; }; @@ -324,6 +339,24 @@ void HAL_GetPowerDistributionStickyFaults( HAL_PowerDistributionHandle handle, HAL_PowerDistributionStickyFaults* stickyFaults, int32_t* status); +void HAL_StartPowerDistributionStream(HAL_PowerDistributionHandle handle, + int32_t* status); + +typedef struct HAL_PowerDistributionChannelData { + float current; + int32_t channel; + uint32_t timestamp; +} HAL_PowerDistributionChannelData; + +HAL_PowerDistributionChannelData* HAL_GetPowerDistributionStreamData( + HAL_PowerDistributionHandle handle, int32_t* count, int32_t* status); + +void HAL_FreePowerDistributionStreamData(HAL_PowerDistributionChannelData* data, + int32_t count); + +void HAL_StopPowerDistributionStream(HAL_PowerDistributionHandle handle, + int32_t* status); + #ifdef __cplusplus } // extern "C" #endif diff --git a/hal/src/main/native/include/hal/REVPH.h b/hal/src/main/native/include/hal/REVPH.h index 4476675a962..754c0f23eda 100644 --- a/hal/src/main/native/include/hal/REVPH.h +++ b/hal/src/main/native/include/hal/REVPH.h @@ -17,11 +17,11 @@ /** * The compressor configuration type */ -HAL_ENUM(HAL_REVPHCompressorConfigType){ - HAL_REVPHCompressorConfigType_kDisabled = 0, - HAL_REVPHCompressorConfigType_kDigital = 1, - HAL_REVPHCompressorConfigType_kAnalog = 2, - HAL_REVPHCompressorConfigType_kHybrid = 3, +HAL_ENUM(HAL_REVPHCompressorConfigType) { + HAL_REVPHCompressorConfigType_kDisabled = 0, + HAL_REVPHCompressorConfigType_kDigital = 1, + HAL_REVPHCompressorConfigType_kAnalog = 2, + HAL_REVPHCompressorConfigType_kHybrid = 3, }; /** diff --git a/hal/src/main/native/include/hal/SPITypes.h b/hal/src/main/native/include/hal/SPITypes.h index 34b5d618d64..d521665607a 100644 --- a/hal/src/main/native/include/hal/SPITypes.h +++ b/hal/src/main/native/include/hal/SPITypes.h @@ -14,7 +14,6 @@ * @{ */ -// clang-format off HAL_ENUM(HAL_SPIPort) { HAL_SPI_kInvalid = -1, HAL_SPI_kOnboardCS0, @@ -23,16 +22,13 @@ HAL_ENUM(HAL_SPIPort) { HAL_SPI_kOnboardCS3, HAL_SPI_kMXP }; -// clang-format on -// clang-format off HAL_ENUM(HAL_SPIMode) { HAL_SPI_kMode0 = 0, HAL_SPI_kMode1 = 1, HAL_SPI_kMode2 = 2, HAL_SPI_kMode3 = 3, }; -// clang-format on #ifdef __cplusplus namespace hal { diff --git a/hal/src/main/native/include/hal/SerialPort.h b/hal/src/main/native/include/hal/SerialPort.h index f4a357eb9ea..c6b80c7b44c 100644 --- a/hal/src/main/native/include/hal/SerialPort.h +++ b/hal/src/main/native/include/hal/SerialPort.h @@ -14,14 +14,12 @@ * @{ */ -// clang-format off HAL_ENUM(HAL_SerialPort) { HAL_SerialPort_Onboard = 0, HAL_SerialPort_MXP = 1, HAL_SerialPort_USB1 = 2, HAL_SerialPort_USB2 = 3 }; -// clang-format on #ifdef __cplusplus extern "C" { diff --git a/hal/src/main/native/include/hal/SimDevice.h b/hal/src/main/native/include/hal/SimDevice.h index 0e75cea5f51..e5e3324f9d4 100644 --- a/hal/src/main/native/include/hal/SimDevice.h +++ b/hal/src/main/native/include/hal/SimDevice.h @@ -30,13 +30,11 @@ /** * Direction of a simulated value (from the perspective of user code). */ -// clang-format off HAL_ENUM(HAL_SimValueDirection) { - HAL_SimValueInput = 0, /**< input to user code from the simulator */ - HAL_SimValueOutput, /**< output from user code to the simulator */ - HAL_SimValueBidir /**< bidirectional between user code and simulator */ + HAL_SimValueInput = 0, /**< input to user code from the simulator */ + HAL_SimValueOutput, /**< output from user code to the simulator */ + HAL_SimValueBidir /**< bidirectional between user code and simulator */ }; -// clang-format on #ifdef __cplusplus extern "C" { diff --git a/hal/src/main/native/include/hal/simulation/DriverStationData.h b/hal/src/main/native/include/hal/simulation/DriverStationData.h index b10cf032622..b00fef8b515 100644 --- a/hal/src/main/native/include/hal/simulation/DriverStationData.h +++ b/hal/src/main/native/include/hal/simulation/DriverStationData.h @@ -6,6 +6,8 @@ #include +#include + #include "hal/DriverStationTypes.h" #include "hal/Types.h" #include "hal/simulation/NotifyListener.h" @@ -147,11 +149,11 @@ void HALSIM_GetJoystickCounts(int32_t stick, int32_t* axisCount, void HALSIM_SetJoystickIsXbox(int32_t stick, HAL_Bool isXbox); void HALSIM_SetJoystickType(int32_t stick, int32_t type); -void HALSIM_SetJoystickName(int32_t stick, const char* name, size_t size); +void HALSIM_SetJoystickName(int32_t stick, const struct WPI_String* name); void HALSIM_SetJoystickAxisType(int32_t stick, int32_t axis, int32_t type); -void HALSIM_SetGameSpecificMessage(const char* message, size_t size); -void HALSIM_SetEventName(const char* name, size_t size); +void HALSIM_SetGameSpecificMessage(const struct WPI_String* message); +void HALSIM_SetEventName(const struct WPI_String* name); void HALSIM_SetMatchType(HAL_MatchType type); void HALSIM_SetMatchNumber(int32_t matchNumber); void HALSIM_SetReplayNumber(int32_t replayNumber); diff --git a/hal/src/main/native/include/hal/simulation/RoboRioData.h b/hal/src/main/native/include/hal/simulation/RoboRioData.h index d191fcb41f6..0c87b07e5cb 100644 --- a/hal/src/main/native/include/hal/simulation/RoboRioData.h +++ b/hal/src/main/native/include/hal/simulation/RoboRioData.h @@ -6,6 +6,9 @@ #include +#include + +#include "hal/LEDs.h" #include "hal/Types.h" #include "hal/simulation/NotifyListener.h" @@ -136,17 +139,14 @@ void HALSIM_SetRoboRioTeamNumber(int32_t teamNumber); int32_t HALSIM_RegisterRoboRioSerialNumberCallback( HAL_RoboRioStringCallback callback, void* param, HAL_Bool initialNotify); void HALSIM_CancelRoboRioSerialNumberCallback(int32_t uid); -size_t HALSIM_GetRoboRioSerialNumber(char* buffer, size_t size); -void HALSIM_SetRoboRioSerialNumber(const char* serialNumber, size_t size); +void HALSIM_GetRoboRioSerialNumber(struct WPI_String* serialNumber); +void HALSIM_SetRoboRioSerialNumber(const struct WPI_String* serialNumber); int32_t HALSIM_RegisterRoboRioCommentsCallback( HAL_RoboRioStringCallback callback, void* param, HAL_Bool initialNotify); void HALSIM_CancelRoboRioCommentsCallback(int32_t uid); -size_t HALSIM_GetRoboRioComments(char* buffer, size_t size); -void HALSIM_SetRoboRioComments(const char* comments, size_t size); - -void HALSIM_RegisterRoboRioAllCallbacks(HAL_NotifyCallback callback, - void* param, HAL_Bool initialNotify); +void HALSIM_GetRoboRioComments(struct WPI_String* comments); +void HALSIM_SetRoboRioComments(const struct WPI_String* comments); int32_t HALSIM_RegisterRoboRioCPUTempCallback(HAL_NotifyCallback callback, void* param, @@ -155,6 +155,15 @@ void HALSIM_CancelRoboRioCPUTempCallback(int32_t uid); double HALSIM_GetRoboRioCPUTemp(void); void HALSIM_SetRoboRioCPUTemp(double cpuTemp); +int32_t HALSIM_RegisterRoboRioRadioLEDStateCallback(HAL_NotifyCallback callback, + void* param, + HAL_Bool initialNotify); +void HALSIM_CancelRoboRioRadioLEDStateCallback(int32_t uid); +HAL_RadioLEDState HALSIM_GetRoboRioRadioLEDState(void); +void HALSIM_SetRoboRioRadioLEDState(HAL_RadioLEDState state); + +void HALSIM_RegisterRoboRioAllCallbacks(HAL_NotifyCallback callback, + void* param, HAL_Bool initialNotify); #ifdef __cplusplus } // extern "C" #endif diff --git a/hal/src/main/native/sim/DriverStation.cpp b/hal/src/main/native/sim/DriverStation.cpp index 67b2eb728a4..f50deaceb51 100644 --- a/hal/src/main/native/sim/DriverStation.cpp +++ b/hal/src/main/native/sim/DriverStation.cpp @@ -44,6 +44,7 @@ struct JoystickDataCache { HAL_JoystickButtons buttons[kJoystickPorts]; HAL_AllianceStationID allianceStation; double matchTime; + HAL_ControlWord controlWord; }; static_assert(std::is_standard_layout_v); // static_assert(std::is_trivial_v); @@ -65,6 +66,16 @@ void JoystickDataCache::Update() { } allianceStation = SimDriverStationData->allianceStationId; matchTime = SimDriverStationData->matchTime; + + HAL_ControlWord tmpControlWord; + std::memset(&tmpControlWord, 0, sizeof(tmpControlWord)); + tmpControlWord.enabled = SimDriverStationData->enabled; + tmpControlWord.autonomous = SimDriverStationData->autonomous; + tmpControlWord.test = SimDriverStationData->test; + tmpControlWord.eStop = SimDriverStationData->eStop; + tmpControlWord.fmsAttached = SimDriverStationData->fmsAttached; + tmpControlWord.dsAttached = SimDriverStationData->dsAttached; + this->controlWord = tmpControlWord; } #define CHECK_JOYSTICK_NUMBER(stickNum) \ @@ -261,17 +272,12 @@ int32_t HAL_GetJoystickType(int32_t joystickNum) { return desc.type; } -char* HAL_GetJoystickName(int32_t joystickNum) { +void HAL_GetJoystickName(struct WPI_String* name, int32_t joystickNum) { HAL_JoystickDescriptor desc; SimDriverStationData->GetJoystickDescriptor(joystickNum, &desc); size_t len = std::strlen(desc.name); - char* name = static_cast(std::malloc(len + 1)); - std::memcpy(name, desc.name, len + 1); - return name; -} - -void HAL_FreeJoystickName(char* name) { - std::free(name); + auto write = WPI_AllocateString(name, len); + std::memcpy(write, desc.name, len); } int32_t HAL_GetJoystickAxisType(int32_t joystickNum, int32_t axis) { @@ -322,20 +328,32 @@ HAL_Bool HAL_RefreshDSData(void) { if (gShutdown) { return false; } - HAL_ControlWord controlWord; - std::memset(&controlWord, 0, sizeof(controlWord)); - controlWord.enabled = SimDriverStationData->enabled; - controlWord.autonomous = SimDriverStationData->autonomous; - controlWord.test = SimDriverStationData->test; - controlWord.eStop = SimDriverStationData->eStop; - controlWord.fmsAttached = SimDriverStationData->fmsAttached; - controlWord.dsAttached = SimDriverStationData->dsAttached; + bool dsAttached = SimDriverStationData->dsAttached; std::scoped_lock lock{driverStation->cacheMutex}; JoystickDataCache* prev = currentCache.exchange(nullptr); if (prev != nullptr) { currentRead = prev; } - newestControlWord = controlWord; + // If newest state shows we have a DS attached, just use the + // control word out of the cache, As it will be the one in sync + // with the data. If no data has been updated, at this point, + // and a DS wasn't attached previously, this will still return + // a zeroed out control word, with is the correct state for + // no new data. + if (!dsAttached) { + // If the DS is not attached, we need to zero out the control word. + // This is because HAL_RefreshDSData is called asynchronously from + // the DS data. The dsAttached variable comes directly from netcomm + // and could be updated before the caches are. If that happens, + // we would end up returning the previous cached control word, + // which is out of sync with the current control word and could + // break invariants such as which alliance station is in used. + // Also, when the DS has never been connected the rest of the fields + // in control word are garbage, so we also need to zero out in that + // case too + std::memset(¤tRead->controlWord, 0, sizeof(currentRead->controlWord)); + } + newestControlWord = currentRead->controlWord; return prev != nullptr; } @@ -369,6 +387,7 @@ void NewDriverStationData() { if (gShutdown) { return; } + SimDriverStationData->dsAttached = true; cacheToUpdate->Update(); JoystickDataCache* given = cacheToUpdate; diff --git a/hal/src/main/native/sim/Extensions.cpp b/hal/src/main/native/sim/Extensions.cpp index 9131bcb8090..95495c645d5 100644 --- a/hal/src/main/native/sim/Extensions.cpp +++ b/hal/src/main/native/sim/Extensions.cpp @@ -8,10 +8,10 @@ #include #include -#include #include #include #include +#include #include #if defined(WIN32) || defined(_WIN32) @@ -55,7 +55,7 @@ extern "C" { int HAL_LoadOneExtension(const char* library) { int rc = 1; // It is expected and reasonable not to find an extra simulation - fmt::print("HAL Extensions: Attempting to load: {}\n", + wpi::print("HAL Extensions: Attempting to load: {}\n", fs::path{library}.stem().string()); std::fflush(stdout); HTYPE handle = DLOPEN(library); @@ -66,14 +66,14 @@ int HAL_LoadOneExtension(const char* library) { #else auto libraryName = fmt::format("lib{}.so", library); #endif - fmt::print("HAL Extensions: Load failed: {}\nTrying modified name: {}\n", + wpi::print("HAL Extensions: Load failed: {}\nTrying modified name: {}\n", DLERROR, fs::path{libraryName}.stem().string()); std::fflush(stdout); handle = DLOPEN(libraryName.c_str()); } #endif if (!handle) { - fmt::print("HAL Extensions: Failed to load library: {}\n", DLERROR); + wpi::print("HAL Extensions: Failed to load library: {}\n", DLERROR); std::fflush(stdout); return rc; } diff --git a/hal/src/main/native/sim/HAL.cpp b/hal/src/main/native/sim/HAL.cpp index ce8b6dde5ff..000ad8f80d1 100644 --- a/hal/src/main/native/sim/HAL.cpp +++ b/hal/src/main/native/sim/HAL.cpp @@ -5,6 +5,7 @@ #include "hal/HAL.h" #include +#include #include #include @@ -280,12 +281,12 @@ int64_t HAL_GetFPGARevision(int32_t* status) { return 0; // TODO: Find a better number to return; } -size_t HAL_GetSerialNumber(char* buffer, size_t size) { - return HALSIM_GetRoboRioSerialNumber(buffer, size); +void HAL_GetSerialNumber(struct WPI_String* serialNumber) { + HALSIM_GetRoboRioSerialNumber(serialNumber); } -size_t HAL_GetComments(char* buffer, size_t size) { - return HALSIM_GetRoboRioComments(buffer, size); +void HAL_GetComments(struct WPI_String* comments) { + HALSIM_GetRoboRioComments(comments); } int32_t HAL_GetTeamNumber(void) { @@ -367,12 +368,12 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) { #ifdef _WIN32 TIMECAPS tc; if (timeGetDevCaps(&tc, sizeof(tc)) == TIMERR_NOERROR) { - UINT target = min(1, tc.wPeriodMin); + UINT target = (std::min)(static_cast(1), tc.wPeriodMin); timeBeginPeriod(target); std::atexit([]() { TIMECAPS tc; if (timeGetDevCaps(&tc, sizeof(tc)) == TIMERR_NOERROR) { - UINT target = min(1, tc.wPeriodMin); + UINT target = (std::min)(static_cast(1), tc.wPeriodMin); timeEndPeriod(target); } }); diff --git a/hal/src/main/native/sim/LEDs.cpp b/hal/src/main/native/sim/LEDs.cpp new file mode 100644 index 00000000000..e7d45aa7f7d --- /dev/null +++ b/hal/src/main/native/sim/LEDs.cpp @@ -0,0 +1,21 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "hal/LEDs.h" + +#include "hal/simulation/RoboRioData.h" + +namespace hal::init { +void InitializeLEDs() {} +} // namespace hal::init + +extern "C" { + +void HAL_SetRadioLEDState(HAL_RadioLEDState state, int32_t* status) { + HALSIM_SetRoboRioRadioLEDState(state); +} +HAL_RadioLEDState HAL_GetRadioLEDState(int32_t* status) { + return HALSIM_GetRoboRioRadioLEDState(); +} +} // extern "C" diff --git a/hal/src/main/native/sim/MockHooks.cpp b/hal/src/main/native/sim/MockHooks.cpp index 93c385e2e41..fcc64e9788b 100644 --- a/hal/src/main/native/sim/MockHooks.cpp +++ b/hal/src/main/native/sim/MockHooks.cpp @@ -8,7 +8,7 @@ #include #include -#include +#include #include #include "MockHooksInternal.h" @@ -84,7 +84,7 @@ void HALSIM_WaitForProgramStart(void) { int count = 0; while (!programStarted) { count++; - fmt::print("Waiting for program start signal: {}\n", count); + wpi::print("Waiting for program start signal: {}\n", count); std::this_thread::sleep_for(std::chrono::milliseconds(500)); } } diff --git a/hal/src/main/native/sim/mockdata/DriverStationData.cpp b/hal/src/main/native/sim/mockdata/DriverStationData.cpp index a0cae1c9a2c..d7b8a087fa4 100644 --- a/hal/src/main/native/sim/mockdata/DriverStationData.cpp +++ b/hal/src/main/native/sim/mockdata/DriverStationData.cpp @@ -28,7 +28,7 @@ void DriverStationData::ResetData() { test.Reset(false); eStop.Reset(false); fmsAttached.Reset(false); - dsAttached.Reset(true); + dsAttached.Reset(false); allianceStationId.Reset(static_cast(0)); matchTime.Reset(-1.0); @@ -339,17 +339,14 @@ void DriverStationData::SetJoystickType(int32_t stick, int32_t type) { m_joystickDescriptorCallbacks(stick, &m_joystickData[stick].descriptor); } -void DriverStationData::SetJoystickName(int32_t stick, const char* name, - size_t size) { +void DriverStationData::SetJoystickName(int32_t stick, std::string_view name) { if (stick < 0 || stick >= kNumJoysticks) { return; } std::scoped_lock lock(m_joystickDataMutex); - if (size > sizeof(m_joystickData[stick].descriptor.name) - 1) { - size = sizeof(m_joystickData[stick].descriptor.name) - 1; - } - std::strncpy(m_joystickData[stick].descriptor.name, name, size); - m_joystickData[stick].descriptor.name[size] = '\0'; + auto copied = name.copy(m_joystickData[stick].descriptor.name, + sizeof(m_joystickData[stick].descriptor.name) - 1); + m_joystickData[stick].descriptor.name[copied] = '\0'; m_joystickDescriptorCallbacks(stick, &m_joystickData[stick].descriptor); } @@ -366,27 +363,20 @@ void DriverStationData::SetJoystickAxisType(int32_t stick, int32_t axis, m_joystickDescriptorCallbacks(stick, &m_joystickData[stick].descriptor); } -void DriverStationData::SetGameSpecificMessage(const char* message, - size_t size) { +void DriverStationData::SetGameSpecificMessage(std::string_view message) { std::scoped_lock lock(m_matchInfoMutex); - if (size > sizeof(m_matchInfo.gameSpecificMessage) - 1) { - size = sizeof(m_matchInfo.gameSpecificMessage) - 1; - } - std::strncpy(reinterpret_cast(m_matchInfo.gameSpecificMessage), - message, size); - m_matchInfo.gameSpecificMessage[size] = '\0'; - m_matchInfo.gameSpecificMessageSize = - std::strlen(reinterpret_cast(m_matchInfo.gameSpecificMessage)); + auto copied = + message.copy(reinterpret_cast(m_matchInfo.gameSpecificMessage), + sizeof(m_matchInfo.gameSpecificMessage)); + m_matchInfo.gameSpecificMessageSize = copied; m_matchInfoCallbacks(&m_matchInfo); } -void DriverStationData::SetEventName(const char* name, size_t size) { +void DriverStationData::SetEventName(std::string_view name) { std::scoped_lock lock(m_matchInfoMutex); - if (size > sizeof(m_matchInfo.eventName) - 1) { - size = sizeof(m_matchInfo.eventName) - 1; - } - std::strncpy(m_matchInfo.eventName, name, size); - m_matchInfo.eventName[size] = '\0'; + auto copied = + name.copy(m_matchInfo.eventName, sizeof(m_matchInfo.eventName) - 1); + m_matchInfo.eventName[copied] = '\0'; m_matchInfoCallbacks(&m_matchInfo); } @@ -551,20 +541,20 @@ void HALSIM_SetJoystickType(int32_t stick, int32_t type) { SimDriverStationData->SetJoystickType(stick, type); } -void HALSIM_SetJoystickName(int32_t stick, const char* name, size_t size) { - SimDriverStationData->SetJoystickName(stick, name, size); +void HALSIM_SetJoystickName(int32_t stick, const WPI_String* name) { + SimDriverStationData->SetJoystickName(stick, wpi::to_string_view(name)); } void HALSIM_SetJoystickAxisType(int32_t stick, int32_t axis, int32_t type) { SimDriverStationData->SetJoystickAxisType(stick, axis, type); } -void HALSIM_SetGameSpecificMessage(const char* message, size_t size) { - SimDriverStationData->SetGameSpecificMessage(message, size); +void HALSIM_SetGameSpecificMessage(const WPI_String* message) { + SimDriverStationData->SetGameSpecificMessage(wpi::to_string_view(message)); } -void HALSIM_SetEventName(const char* name, size_t size) { - SimDriverStationData->SetEventName(name, size); +void HALSIM_SetEventName(const WPI_String* name) { + SimDriverStationData->SetEventName(wpi::to_string_view(name)); } void HALSIM_SetMatchType(HAL_MatchType type) { diff --git a/hal/src/main/native/sim/mockdata/DriverStationDataInternal.h b/hal/src/main/native/sim/mockdata/DriverStationDataInternal.h index 763b465f328..01de9cbdb18 100644 --- a/hal/src/main/native/sim/mockdata/DriverStationDataInternal.h +++ b/hal/src/main/native/sim/mockdata/DriverStationDataInternal.h @@ -107,11 +107,11 @@ class DriverStationData { void SetJoystickIsXbox(int32_t stick, HAL_Bool isXbox); void SetJoystickType(int32_t stick, int32_t type); - void SetJoystickName(int32_t stick, const char* name, size_t size); + void SetJoystickName(int32_t stick, std::string_view message); void SetJoystickAxisType(int32_t stick, int32_t axis, int32_t type); - void SetGameSpecificMessage(const char* message, size_t size); - void SetEventName(const char* name, size_t size); + void SetGameSpecificMessage(std::string_view message); + void SetEventName(std::string_view name); void SetMatchType(HAL_MatchType type); void SetMatchNumber(int32_t matchNumber); void SetReplayNumber(int32_t replayNumber); @@ -122,7 +122,7 @@ class DriverStationData { SimDataValue eStop{false}; SimDataValue fmsAttached{ false}; - SimDataValue dsAttached{true}; + SimDataValue dsAttached{false}; SimDataValue allianceStationId{static_cast(0)}; diff --git a/hal/src/main/native/sim/mockdata/RoboRioData.cpp b/hal/src/main/native/sim/mockdata/RoboRioData.cpp index 9a9a1a1d38e..94d61f8972b 100644 --- a/hal/src/main/native/sim/mockdata/RoboRioData.cpp +++ b/hal/src/main/native/sim/mockdata/RoboRioData.cpp @@ -53,25 +53,20 @@ void RoboRioData::CancelSerialNumberCallback(int32_t uid) { m_serialNumberCallbacks.Cancel(uid); } -size_t RoboRioData::GetSerialNumber(char* buffer, size_t size) { +void RoboRioData::GetSerialNumber(struct WPI_String* serialNumber) { std::scoped_lock lock(m_serialNumberMutex); - size_t copied = m_serialNumber.copy(buffer, size); - // Null terminate - if (copied == size) { - copied -= 1; - } - buffer[copied] = '\0'; - return copied; + auto write = WPI_AllocateString(serialNumber, m_serialNumber.size()); + m_serialNumber.copy(write, m_serialNumber.size()); } -void RoboRioData::SetSerialNumber(const char* serialNumber, size_t size) { +void RoboRioData::SetSerialNumber(std::string_view serialNumber) { // Limit serial number to 8 characters internally- serialnum environment // variable is always 8 characters - if (size > 8) { - size = 8; + if (serialNumber.size() > 8) { + serialNumber = serialNumber.substr(0, 8); } std::scoped_lock lock(m_serialNumberMutex); - m_serialNumber = std::string(serialNumber, size); + m_serialNumber = std::string(serialNumber); m_serialNumberCallbacks(m_serialNumber.c_str(), m_serialNumber.size()); } @@ -90,22 +85,18 @@ void RoboRioData::CancelCommentsCallback(int32_t uid) { m_commentsCallbacks.Cancel(uid); } -size_t RoboRioData::GetComments(char* buffer, size_t size) { +void RoboRioData::GetComments(struct WPI_String* comments) { std::scoped_lock lock(m_commentsMutex); - size_t copied = m_comments.copy(buffer, size); - // Null terminate if there is room - if (copied < size) { - buffer[copied] = '\0'; - } - return copied; + auto write = WPI_AllocateString(comments, m_comments.size()); + m_comments.copy(write, m_comments.size()); } -void RoboRioData::SetComments(const char* comments, size_t size) { - if (size > 64) { - size = 64; +void RoboRioData::SetComments(std::string_view comments) { + if (comments.size() > 64) { + comments = comments.substr(0, 64); } std::scoped_lock lock(m_commentsMutex); - m_comments = std::string(comments, size); + m_comments = std::string(comments); m_commentsCallbacks(m_comments.c_str(), m_comments.size()); } @@ -136,6 +127,7 @@ DEFINE_CAPI(int32_t, UserFaults3V3, userFaults3V3) DEFINE_CAPI(double, BrownoutVoltage, brownoutVoltage) DEFINE_CAPI(double, CPUTemp, cpuTemp) DEFINE_CAPI(int32_t, TeamNumber, teamNumber) +DEFINE_CAPI(HAL_RadioLEDState, RadioLEDState, radioLedState) int32_t HALSIM_RegisterRoboRioSerialNumberCallback( HAL_RoboRioStringCallback callback, void* param, HAL_Bool initialNotify) { @@ -145,11 +137,11 @@ int32_t HALSIM_RegisterRoboRioSerialNumberCallback( void HALSIM_CancelRoboRioSerialNumberCallback(int32_t uid) { return SimRoboRioData->CancelSerialNumberCallback(uid); } -size_t HALSIM_GetRoboRioSerialNumber(char* buffer, size_t size) { - return SimRoboRioData->GetSerialNumber(buffer, size); +void HALSIM_GetRoboRioSerialNumber(struct WPI_String* serialNumber) { + SimRoboRioData->GetSerialNumber(serialNumber); } -void HALSIM_SetRoboRioSerialNumber(const char* serialNumber, size_t size) { - SimRoboRioData->SetSerialNumber(serialNumber, size); +void HALSIM_SetRoboRioSerialNumber(const struct WPI_String* serialNumber) { + SimRoboRioData->SetSerialNumber(wpi::to_string_view(serialNumber)); } int32_t HALSIM_RegisterRoboRioCommentsCallback( @@ -160,11 +152,11 @@ int32_t HALSIM_RegisterRoboRioCommentsCallback( void HALSIM_CancelRoboRioCommentsCallback(int32_t uid) { SimRoboRioData->CancelCommentsCallback(uid); } -size_t HALSIM_GetRoboRioComments(char* buffer, size_t size) { - return SimRoboRioData->GetComments(buffer, size); +void HALSIM_GetRoboRioComments(struct WPI_String* comments) { + SimRoboRioData->GetComments(comments); } -void HALSIM_SetRoboRioComments(const char* comments, size_t size) { - SimRoboRioData->SetComments(comments, size); +void HALSIM_SetRoboRioComments(const struct WPI_String* comments) { + SimRoboRioData->SetComments(wpi::to_string_view(comments)); } void HALSIM_RegisterRoboRioAllCallbacks(HAL_NotifyCallback callback, @@ -192,5 +184,6 @@ void HALSIM_RegisterRoboRioAllCallbacks(HAL_NotifyCallback callback, REGISTER(userFaults3V3); REGISTER(brownoutVoltage); REGISTER(cpuTemp); + REGISTER(radioLedState); } } // extern "C" diff --git a/hal/src/main/native/sim/mockdata/RoboRioDataInternal.h b/hal/src/main/native/sim/mockdata/RoboRioDataInternal.h index aef61bea749..6ef523e1829 100644 --- a/hal/src/main/native/sim/mockdata/RoboRioDataInternal.h +++ b/hal/src/main/native/sim/mockdata/RoboRioDataInternal.h @@ -32,10 +32,15 @@ class RoboRioData { HAL_SIMDATAVALUE_DEFINE_NAME(BrownoutVoltage) HAL_SIMDATAVALUE_DEFINE_NAME(CPUTemp) HAL_SIMDATAVALUE_DEFINE_NAME(TeamNumber) + HAL_SIMDATAVALUE_DEFINE_NAME(RadioLEDState) HAL_SIMCALLBACKREGISTRY_DEFINE_NAME(SerialNumber) HAL_SIMCALLBACKREGISTRY_DEFINE_NAME(Comments); + static inline HAL_Value MakeRadioLEDStateValue(HAL_RadioLEDState value) { + return HAL_MakeEnum(value); + } + public: SimDataValue fpgaButton{false}; SimDataValue vInVoltage{12.0}; @@ -61,18 +66,20 @@ class RoboRioData { 6.75}; SimDataValue cpuTemp{45.0}; SimDataValue teamNumber{0}; + SimDataValue + radioLedState{HAL_RadioLED_kOff}; int32_t RegisterSerialNumberCallback(HAL_RoboRioStringCallback callback, void* param, HAL_Bool initialNotify); void CancelSerialNumberCallback(int32_t uid); - size_t GetSerialNumber(char* buffer, size_t size); - void SetSerialNumber(const char* serialNumber, size_t size); + void GetSerialNumber(struct WPI_String* serialNumber); + void SetSerialNumber(std::string_view serialNumber); int32_t RegisterCommentsCallback(HAL_RoboRioStringCallback callback, void* param, HAL_Bool initialNotify); void CancelCommentsCallback(int32_t uid); - size_t GetComments(char* buffer, size_t size); - void SetComments(const char* comments, size_t size); + void GetComments(struct WPI_String* comments); + void SetComments(std::string_view comments); virtual void ResetData(); diff --git a/imgui/CMakeLists.txt b/imgui/CMakeLists.txt index 6ba8455bc73..b4810e9ce01 100644 --- a/imgui/CMakeLists.txt +++ b/imgui/CMakeLists.txt @@ -1,61 +1,57 @@ -INCLUDE(FetchContent) +include(FetchContent) -FetchContent_Declare( +fetchcontent_declare( glfw3 - GIT_REPOSITORY https://github.com/glfw/glfw.git - GIT_TAG 6b57e08bb0078c9834889eab871bac2368198c15 + GIT_REPOSITORY https://github.com/glfw/glfw.git + GIT_TAG 6b57e08bb0078c9834889eab871bac2368198c15 ) -FetchContent_Declare( +fetchcontent_declare( gl3w - GIT_REPOSITORY https://github.com/skaslev/gl3w - GIT_TAG 5f8d7fd191ba22ff2b60c1106d7135bb9a335533 + GIT_REPOSITORY https://github.com/skaslev/gl3w + GIT_TAG 5f8d7fd191ba22ff2b60c1106d7135bb9a335533 ) -FetchContent_Declare( +fetchcontent_declare( imgui - GIT_REPOSITORY https://github.com/ocornut/imgui.git - # docking branch - GIT_TAG 64b1e448d20c9be9275af731c34b4c7bf14a8e95 + GIT_REPOSITORY https://github.com/ocornut/imgui.git + # docking branch + GIT_TAG 64b1e448d20c9be9275af731c34b4c7bf14a8e95 ) -FetchContent_Declare( +fetchcontent_declare( implot - GIT_REPOSITORY https://github.com/epezent/implot.git - # v0.16 - GIT_TAG 18c72431f8265e2b0b5378a3a73d8a883b2175ff + GIT_REPOSITORY https://github.com/epezent/implot.git + # v0.16 + GIT_TAG 18c72431f8265e2b0b5378a3a73d8a883b2175ff ) -FetchContent_Declare( +fetchcontent_declare( fonts - URL https://github.com/wpilibsuite/thirdparty-fonts/releases/download/v0.2/fonts.zip - URL_HASH SHA256=cedf365657fab0770e11f72d49e4f0f889f564d2e635a4d214029d0ab6bcd324 + URL https://github.com/wpilibsuite/thirdparty-fonts/releases/download/v0.2/fonts.zip + URL_HASH SHA256=cedf365657fab0770e11f72d49e4f0f889f564d2e635a4d214029d0ab6bcd324 ) -FetchContent_Declare( +fetchcontent_declare( stb - GIT_REPOSITORY https://github.com/nothings/stb.git - GIT_TAG c9064e317699d2e495f36ba4f9ac037e88ee371a + GIT_REPOSITORY https://github.com/nothings/stb.git + GIT_TAG c9064e317699d2e495f36ba4f9ac037e88ee371a ) -FetchContent_MakeAvailable( - imgui - implot - fonts - stb -) +fetchcontent_makeavailable(imgui implot fonts stb) # Add glfw directly to our build. -FetchContent_GetProperties(glfw3) +fetchcontent_getproperties(glfw3) if(NOT glfw3_POPULATED) - FetchContent_Populate(glfw3) + fetchcontent_populate(glfw3) set(SAVE_BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS}) set(BUILD_SHARED_LIBS OFF) set(GLFW_INSTALL OFF) add_subdirectory(${glfw3_SOURCE_DIR} ${glfw3_BINARY_DIR} EXCLUDE_FROM_ALL) set_property(TARGET glfw PROPERTY POSITION_INDEPENDENT_CODE ON) set(BUILD_SHARED_LIBS ${SAVE_BUILD_SHARED_LIBS}) + export(TARGETS glfw FILE glfw.cmake NAMESPACE glfw::) endif() # Don't use gl3w CMakeLists.txt due to https://github.com/skaslev/gl3w/issues/66 -FetchContent_GetProperties(gl3w) +fetchcontent_getproperties(gl3w) if(NOT gl3w_POPULATED) - FetchContent_Populate(gl3w) + fetchcontent_populate(gl3w) endif() if(NOT EXISTS "${gl3w_BINARY_DIR}/src/gl3w.c") find_package(Python COMPONENTS Interpreter Development REQUIRED) @@ -76,17 +72,18 @@ set(imgui_all_sources ${imgui_SOURCE_DIR}/backends/imgui_impl_opengl3.cpp ${gl3w_BINARY_DIR}/src/gl3w.c ${fonts_sources} - src/stb_image.cpp) -if (MSVC) - add_library(imgui STATIC ${imgui_all_sources}) + src/stb_image.cpp +) +if(MSVC) + add_library(imgui STATIC ${imgui_all_sources}) else() - add_library(imgui ${imgui_all_sources}) + add_library(imgui ${imgui_all_sources}) endif() target_compile_definitions(imgui PUBLIC IMGUI_IMPL_OPENGL_LOADER_GL3W) -if (MSVC) +if(MSVC) target_sources(imgui PRIVATE ${imgui_SOURCE_DIR}/backends/imgui_impl_dx11.cpp) else() - if (APPLE) + if(APPLE) target_compile_options(imgui PRIVATE -fobjc-arc) set_target_properties(imgui PROPERTIES LINK_FLAGS "-framework Metal -framework QuartzCore") target_sources(imgui PRIVATE ${imgui_SOURCE_DIR}/backends/imgui_impl_metal.mm) @@ -95,18 +92,21 @@ else() endif() endif() target_link_libraries(imgui PUBLIC glfw) -target_include_directories(imgui +target_include_directories( + imgui PUBLIC - "$" - "$" - "$" - "$" - "$" - "$" - "$" - PRIVATE - "$" + "$" + "$" + "$" + "$" + "$" + "$" + "$" + PRIVATE "$" ) set_property(TARGET imgui PROPERTY POSITION_INDEPENDENT_CODE ON) target_compile_features(imgui PUBLIC cxx_std_20) + +install(TARGETS imgui EXPORT imgui) +export(TARGETS imgui FILE imgui.cmake NAMESPACE imgui::) diff --git a/myRobot/build.gradle b/myRobot/build.gradle index 17407cd72a2..a513d261118 100644 --- a/myRobot/build.gradle +++ b/myRobot/build.gradle @@ -130,7 +130,7 @@ deploy { myRobotJava(JavaArtifact) { jarTask = shadowJar postdeploy << { ctx -> - ctx.execute("echo '/usr/local/frc/JRE/bin/java -XX:+UseG1GC -XX:MaxGCPauseMillis=1 -XX:GCTimeRatio=1 -Djava.library.path=/usr/local/frc/third-party/lib -Djava.lang.invoke.stringConcat=BC_SB -jar /home/lvuser/myRobot-all.jar' > /home/lvuser/robotCommand") + ctx.execute("echo '/usr/local/frc/JRE/bin/java -XX:+UseSerialGC -Djava.library.path=/usr/local/frc/third-party/lib -Djava.lang.invoke.stringConcat=BC_SB -jar /home/lvuser/myRobot-all.jar' > /home/lvuser/robotCommand") ctx.execute("chmod +x /home/lvuser/robotCommand; chown lvuser /home/lvuser/robotCommand") } } diff --git a/ntcore/.clang-tidy b/ntcore/.clang-tidy new file mode 100644 index 00000000000..41c15bba7d7 --- /dev/null +++ b/ntcore/.clang-tidy @@ -0,0 +1,69 @@ +Checks: + 'bugprone-assert-side-effect, + bugprone-bool-pointer-implicit-conversion, + bugprone-copy-constructor-init, + bugprone-dangling-handle, + bugprone-dynamic-static-initializers, + bugprone-forwarding-reference-overload, + bugprone-inaccurate-erase, + bugprone-incorrect-roundings, + bugprone-integer-division, + bugprone-lambda-function-name, + bugprone-misplaced-operator-in-strlen-in-alloc, + bugprone-misplaced-widening-cast, + bugprone-move-forwarding-reference, + bugprone-multiple-statement-macro, + bugprone-parent-virtual-call, + bugprone-posix-return, + bugprone-sizeof-container, + bugprone-sizeof-expression, + bugprone-spuriously-wake-up-functions, + bugprone-string-constructor, + bugprone-string-integer-assignment, + bugprone-string-literal-with-embedded-nul, + bugprone-suspicious-enum-usage, + bugprone-suspicious-include, + bugprone-suspicious-memset-usage, + bugprone-suspicious-missing-comma, + bugprone-suspicious-semicolon, + bugprone-suspicious-string-compare, + bugprone-throw-keyword-missing, + bugprone-too-small-loop-variable, + bugprone-undefined-memory-manipulation, + bugprone-undelegated-constructor, + bugprone-unhandled-self-assignment, + bugprone-unused-raii, + bugprone-virtual-near-miss, + cert-err52-cpp, + cert-err60-cpp, + cert-mem57-cpp, + cert-oop57-cpp, + cert-oop58-cpp, + clang-diagnostic-*, + -clang-diagnostic-deprecated-declarations, + -clang-diagnostic-#warnings, + -clang-diagnostic-pedantic, + clang-analyzer-*, + cppcoreguidelines-slicing, + google-build-namespaces, + google-explicit-constructor, + google-global-names-in-headers, + google-readability-avoid-underscore-in-googletest-name, + google-readability-casting, + google-runtime-operator, + misc-definitions-in-headers, + misc-misplaced-const, + misc-new-delete-overloads, + misc-non-copyable-objects, + modernize-avoid-bind, + modernize-concat-nested-namespaces, + modernize-make-shared, + modernize-make-unique, + modernize-pass-by-value, + modernize-use-default-member-init, + modernize-use-noexcept, + modernize-use-nullptr, + modernize-use-override, + modernize-use-using, + readability-braces-around-statements' +FormatStyle: file diff --git a/ntcore/.styleguide b/ntcore/.styleguide index 1808bb50ce2..13634e44df6 100644 --- a/ntcore/.styleguide +++ b/ntcore/.styleguide @@ -14,6 +14,8 @@ cppSrcFileInclude { generatedFileExclude { ntcore/doc/ + ntcore/src/generated + .*\.jinja } repoRootNameOverride { diff --git a/ntcore/CMakeLists.txt b/ntcore/CMakeLists.txt index 5216eda5227..5270eda40ca 100644 --- a/ntcore/CMakeLists.txt +++ b/ntcore/CMakeLists.txt @@ -3,30 +3,25 @@ project(ntcore) include(CompileWarnings) include(AddTest) -execute_process(COMMAND python3 ${CMAKE_CURRENT_SOURCE_DIR}/generate_topics.py ${WPILIB_BINARY_DIR}/ntcore RESULT_VARIABLE generateResult) -if(NOT (generateResult EQUAL "0")) - # Try python - execute_process(COMMAND python ${CMAKE_CURRENT_SOURCE_DIR}/generate_topics.py ${WPILIB_BINARY_DIR}/ntcore RESULT_VARIABLE generateResult) - if(NOT (generateResult EQUAL "0")) - message(FATAL_ERROR "python and python3 generate_topics.py failed") - endif() -endif() - -file(GLOB ntcore_native_src +file( + GLOB ntcore_native_src src/main/native/cpp/*.cpp - ${WPILIB_BINARY_DIR}/ntcore/generated/main/native/cpp/*.cpp + src/generated/main/native/cpp/*.cpp src/main/native/cpp/net/*.cpp src/main/native/cpp/net3/*.cpp src/main/native/cpp/networktables/*.cpp - src/main/native/cpp/tables/*.cpp) + src/main/native/cpp/tables/*.cpp +) add_library(ntcore ${ntcore_native_src}) set_target_properties(ntcore PROPERTIES DEBUG_POSTFIX "d") -target_include_directories(ntcore - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/main/native/cpp - PUBLIC - $ - $ - $) +target_include_directories( + ntcore + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/main/native/cpp + PUBLIC + $ + $ + $ +) wpilib_target_warnings(ntcore) target_compile_features(ntcore PUBLIC cxx_std_20) target_link_libraries(ntcore PUBLIC wpinet wpiutil) @@ -34,44 +29,40 @@ target_link_libraries(ntcore PUBLIC wpinet wpiutil) set_property(TARGET ntcore PROPERTY FOLDER "libraries") install(TARGETS ntcore EXPORT ntcore) +export(TARGETS ntcore FILE ntcore.cmake NAMESPACE ntcore::) install(DIRECTORY src/main/native/include/ DESTINATION "${include_dest}/ntcore") -install(DIRECTORY ${WPILIB_BINARY_DIR}/ntcore/generated/main/native/include/ DESTINATION "${include_dest}/ntcore") - -if (WITH_FLAT_INSTALL) - set (ntcore_config_dir ${wpilib_dest}) -else() - set (ntcore_config_dir share/ntcore) -endif() +install(DIRECTORY src/generated/main/native/include/ DESTINATION "${include_dest}/ntcore") -configure_file(ntcore-config.cmake.in ${WPILIB_BINARY_DIR}/ntcore-config.cmake ) -install(FILES ${WPILIB_BINARY_DIR}/ntcore-config.cmake DESTINATION ${ntcore_config_dir}) -install(EXPORT ntcore DESTINATION ${ntcore_config_dir}) +configure_file(ntcore-config.cmake.in ${WPILIB_BINARY_DIR}/ntcore-config.cmake) +install(FILES ${WPILIB_BINARY_DIR}/ntcore-config.cmake DESTINATION share/ntcore) +install(EXPORT ntcore DESTINATION share/ntcore) # Java bindings -if (WITH_JAVA) +if(WITH_JAVA) find_package(Java REQUIRED) find_package(JNI REQUIRED) include(UseJava) set(CMAKE_JAVA_COMPILE_FLAGS "-encoding" "UTF8" "-Xlint:unchecked") - file(GLOB QUICKBUF_JAR - ${WPILIB_BINARY_DIR}/wpiutil/thirdparty/quickbuf/*.jar) + file(GLOB QUICKBUF_JAR ${WPILIB_BINARY_DIR}/wpiutil/thirdparty/quickbuf/*.jar) set(CMAKE_JAVA_INCLUDE_PATH wpimath.jar ${QUICKBUF_JAR}) - file(GLOB ntcore_jni_src - src/main/native/cpp/jni/*.cpp - ${WPILIB_BINARY_DIR}/ntcore/generated/main/native/cpp/jni/*.cpp) + file(GLOB ntcore_jni_src src/main/native/cpp/jni/*.cpp src/generated/main/native/cpp/jni/*.cpp) - file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java ${WPILIB_BINARY_DIR}/ntcore/generated/*.java) + file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java src/generated/main/java/*.java) set(CMAKE_JNI_TARGET true) - add_jar(ntcore_jar ${JAVA_SOURCES} INCLUDE_JARS wpiutil_jar OUTPUT_NAME ntcore GENERATE_NATIVE_HEADERS ntcore_jni_headers) - - get_property(NTCORE_JAR_FILE TARGET ntcore_jar PROPERTY JAR_FILE) - install(FILES ${NTCORE_JAR_FILE} DESTINATION "${java_lib_dest}") + add_jar( + ntcore_jar + ${JAVA_SOURCES} + INCLUDE_JARS wpiutil_jar + OUTPUT_NAME ntcore + GENERATE_NATIVE_HEADERS ntcore_jni_headers + ) - set_property(TARGET ntcore_jar PROPERTY FOLDER "java") + install_jar(ntcore_jar DESTINATION ${java_lib_dest}) + install_jar_exports(TARGETS ntcore_jar FILE ntcore_jar.cmake DESTINATION share/ntcore) add_library(ntcorejni ${ntcore_jni_src}) wpilib_target_warnings(ntcorejni) @@ -79,7 +70,7 @@ if (WITH_JAVA) set_property(TARGET ntcorejni PROPERTY FOLDER "libraries") - if (MSVC) + if(MSVC) install(TARGETS ntcorejni RUNTIME DESTINATION "${jni_lib_dest}" COMPONENT Runtime) endif() @@ -87,16 +78,23 @@ if (WITH_JAVA) add_dependencies(ntcorejni ntcore_jar) install(TARGETS ntcorejni EXPORT ntcorejni) - + export(TARGETS ntcorejni FILE ntcorejni.cmake NAMESPACE ntcorejni::) endif() -if (WITH_JAVA_SOURCE) +if(WITH_JAVA_SOURCE) find_package(Java REQUIRED) include(UseJava) - file(GLOB NTCORE_SOURCES src/main/java/edu/wpi/first/networktables/*.java ${WPILIB_BINARY_DIR}/ntcore/generated/*.java) - add_jar(ntcore_src_jar - RESOURCES NAMESPACE "edu/wpi/first/networktables" ${NTCORE_SOURCES} - OUTPUT_NAME ntcore-sources) + file( + GLOB NTCORE_SOURCES + src/main/java/edu/wpi/first/networktables/*.java + src/generated/main/java/*.java + ) + add_jar( + ntcore_src_jar + RESOURCES + NAMESPACE "edu/wpi/first/networktables" ${NTCORE_SOURCES} + OUTPUT_NAME ntcore-sources + ) get_property(NTCORE_SRC_JAR_FILE TARGET ntcore_src_jar PROPERTY JAR_FILE) install(FILES ${NTCORE_SRC_JAR_FILE} DESTINATION "${java_lib_dest}") @@ -108,7 +106,7 @@ add_executable(ntcoredev src/dev/native/cpp/main.cpp) wpilib_target_warnings(ntcoredev) target_link_libraries(ntcoredev ntcore) -if (WITH_TESTS) +if(WITH_TESTS) wpilib_add_test(ntcore src/test/native/cpp) target_include_directories(ntcore_test PRIVATE src/main/native/cpp) target_link_libraries(ntcore_test ntcore gmock_main wpiutil_testlib) diff --git a/ntcore/build.gradle b/ntcore/build.gradle index c5464cc5f47..510e5c183fe 100644 --- a/ntcore/build.gradle +++ b/ntcore/build.gradle @@ -1,290 +1,24 @@ -import groovy.json.JsonSlurper; -import com.hubspot.jinjava.Jinjava; -import com.hubspot.jinjava.JinjavaConfig; - -def ntcoreTypesInputFile = file("src/generate/types.json") -def ntcoreJavaTypesInputDir = file("src/generate/java") -def ntcoreJavaTypesOutputDir = file("$buildDir/generated/main/java/edu/wpi/first/networktables") - -task ntcoreGenerateJavaTypes() { - description = "Generates ntcore Java type classes" - group = "WPILib" - - inputs.file ntcoreTypesInputFile - inputs.dir ntcoreJavaTypesInputDir - outputs.dir ntcoreJavaTypesOutputDir - - doLast { - def jsonSlurper = new JsonSlurper() - def jsonTypes = jsonSlurper.parse(ntcoreTypesInputFile) - - ntcoreJavaTypesOutputDir.deleteDir() - ntcoreJavaTypesOutputDir.mkdirs() - - def config = new JinjavaConfig() - def jinjava = new Jinjava(config) - - ntcoreJavaTypesInputDir.listFiles().each { File file -> - def template = file.text - def outfn = file.name.substring(0, file.name.length() - 6) - if (file.name.startsWith("NetworkTable") || file.name.startsWith("Generic")) { - def replacements = new HashMap() - replacements.put("types", jsonTypes) - def output = jinjava.render(template, replacements) - new File(ntcoreJavaTypesOutputDir, outfn).write(output) - } else { - jsonTypes.each { Map replacements -> - def output = jinjava.render(template, replacements) - def typename = replacements.get("TypeName") - File outfile - if (outfn == "Timestamped.java") { - outfile = new File(ntcoreJavaTypesOutputDir, "Timestamped${typename}.java") - } else { - outfile = new File(ntcoreJavaTypesOutputDir, "${typename}${outfn}") - } - outfile.write(output) - } - } - } - } -} - -def ntcoreCppTypesInputDir = file("src/generate/include/networktables") -def ntcoreCppTypesOutputDir = file("$buildDir/generated/main/native/include/networktables") - -task ntcoreGenerateCppTypes() { - description = "Generates ntcore C++ type classes" - group = "WPILib" - - inputs.file ntcoreTypesInputFile - inputs.dir ntcoreCppTypesInputDir - outputs.dir ntcoreCppTypesOutputDir - - doLast { - def jsonSlurper = new JsonSlurper() - def jsonTypes = jsonSlurper.parse(ntcoreTypesInputFile) - - ntcoreCppTypesOutputDir.deleteDir() - ntcoreCppTypesOutputDir.mkdirs() - - def config = new JinjavaConfig() - def jinjava = new Jinjava(config) - - ntcoreCppTypesInputDir.listFiles().each { File file -> - def template = file.text - def outfn = file.name.substring(0, file.name.length() - 6) - jsonTypes.each { Map replacements -> - def output = jinjava.render(template, replacements) - def typename = replacements.get("TypeName") - def outfile = new File(ntcoreCppTypesOutputDir, "${typename}${outfn}") - outfile.write(output) - } - } - } -} - -def ntcoreCppHandleSourceInputFile = file("src/generate/cpp/ntcore_cpp_types.cpp.jinja") -def ntcoreCppHandleSourceOutputFile = file("$buildDir/generated/main/native/cpp/ntcore_cpp_types.cpp") - -task ntcoreGenerateCppHandleSource() { - description = "Generates ntcore C++ handle source" - group = "WPILib" - - inputs.files([ - ntcoreTypesInputFile, - ntcoreCppHandleSourceInputFile - ]) - outputs.file ntcoreCppHandleSourceOutputFile - - doLast { - def jsonSlurper = new JsonSlurper() - def jsonTypes = jsonSlurper.parse(ntcoreTypesInputFile) - - ntcoreCppHandleSourceOutputFile.delete() - - def config = new JinjavaConfig() - def jinjava = new Jinjava(config) - - def template = ntcoreCppHandleSourceInputFile.text - def replacements = new HashMap() - replacements.put("types", jsonTypes) - def output = jinjava.render(template, replacements) - ntcoreCppHandleSourceOutputFile.write(output) - } -} - -def ntcoreCppHandleHeaderInputFile = file("src/generate/include/ntcore_cpp_types.h.jinja") -def ntcoreCppHandleHeaderOutputFile = file("$buildDir/generated/main/native/include/ntcore_cpp_types.h") - -task ntcoreGenerateCppHandleHeader() { - description = "Generates ntcore C++ handle header" - group = "WPILib" - - inputs.files([ - ntcoreTypesInputFile, - ntcoreCppHandleHeaderInputFile - ]) - outputs.file ntcoreCppHandleHeaderOutputFile - - doLast { - def jsonSlurper = new JsonSlurper() - def jsonTypes = jsonSlurper.parse(ntcoreTypesInputFile) - - ntcoreCppHandleHeaderOutputFile.delete() - - def config = new JinjavaConfig() - def jinjava = new Jinjava(config) - - def template = ntcoreCppHandleHeaderInputFile.text - def replacements = new HashMap() - replacements.put("types", jsonTypes) - def output = jinjava.render(template, replacements) - ntcoreCppHandleHeaderOutputFile.write(output) - } -} - -def ntcoreCHandleSourceInputFile = file("src/generate/cpp/ntcore_c_types.cpp.jinja") -def ntcoreCHandleSourceOutputFile = file("$buildDir/generated/main/native/cpp/ntcore_c_types.cpp") - -task ntcoreGenerateCHandleSource() { - description = "Generates ntcore C handle source" - group = "WPILib" - - inputs.files([ - ntcoreTypesInputFile, - ntcoreCHandleSourceInputFile - ]) - outputs.file ntcoreCHandleSourceOutputFile - - doLast { - def jsonSlurper = new JsonSlurper() - def jsonTypes = jsonSlurper.parse(ntcoreTypesInputFile) - - ntcoreCHandleSourceOutputFile.delete() - - def config = new JinjavaConfig() - def jinjava = new Jinjava(config) - - def template = ntcoreCHandleSourceInputFile.text - def replacements = new HashMap() - replacements.put("types", jsonTypes) - def output = jinjava.render(template, replacements) - ntcoreCHandleSourceOutputFile.write(output) - } -} - -def ntcoreCHandleHeaderInputFile = file("src/generate/include/ntcore_c_types.h.jinja") -def ntcoreCHandleHeaderOutputFile = file("$buildDir/generated/main/native/include/ntcore_c_types.h") - -task ntcoreGenerateCHandleHeader() { - description = "Generates ntcore C handle header" - group = "WPILib" - - inputs.files([ - ntcoreTypesInputFile, - ntcoreCHandleHeaderInputFile - ]) - outputs.file ntcoreCHandleHeaderOutputFile - - doLast { - def jsonSlurper = new JsonSlurper() - def jsonTypes = jsonSlurper.parse(ntcoreTypesInputFile) - - ntcoreCHandleHeaderOutputFile.delete() - - def config = new JinjavaConfig() - def jinjava = new Jinjava(config) - - def template = ntcoreCHandleHeaderInputFile.text - def replacements = new HashMap() - replacements.put("types", jsonTypes) - def output = jinjava.render(template, replacements) - ntcoreCHandleHeaderOutputFile.write(output) - } -} - -def ntcoreJniSourceInputFile = file("src/generate/cpp/jni/types_jni.cpp.jinja") -def ntcoreJniSourceOutputFile = file("$buildDir/generated/main/native/cpp/jni/types_jni.cpp") - -task ntcoreGenerateJniSource() { - description = "Generates ntcore JNI types source" - group = "WPILib" - - inputs.files([ - ntcoreTypesInputFile, - ntcoreJniSourceInputFile - ]) - outputs.file ntcoreJniSourceOutputFile - - doLast { - def jsonSlurper = new JsonSlurper() - def jsonTypes = jsonSlurper.parse(ntcoreTypesInputFile) - - ntcoreJniSourceOutputFile.delete() - - def config = new JinjavaConfig() - def jinjava = new Jinjava(config) - - def template = ntcoreJniSourceInputFile.text - def replacements = new HashMap() - replacements.put("types", jsonTypes) - def output = jinjava.render(template, replacements) - ntcoreJniSourceOutputFile.write(output) - } -} - ext { addNtcoreDependency = { binary, shared-> - binary.tasks.withType(AbstractNativeSourceCompileTask) { - it.dependsOn ntcoreGenerateCppTypes - it.dependsOn ntcoreGenerateCppHandleHeader - it.dependsOn ntcoreGenerateCHandleHeader - } binary.lib project: ':ntcore', library: 'ntcore', linkage: shared } addNtcoreJniDependency = { binary-> - binary.tasks.withType(AbstractNativeSourceCompileTask) { - it.dependsOn ntcoreGenerateCppTypes - it.dependsOn ntcoreGenerateCppHandleHeader - it.dependsOn ntcoreGenerateCHandleHeader - } binary.lib project: ':ntcore', library: 'ntcoreJNIShared', linkage: 'shared' } nativeName = 'ntcore' devMain = 'edu.wpi.first.ntcore.DevMain' - generatedSources = "$buildDir/generated/main/native/cpp" - generatedHeaders = "$buildDir/generated/main/native/include" + generatedSources = "$projectDir/src/generated/main/native/cpp" + generatedHeaders = "$projectDir/src/generated/main/native/include" jniSplitSetup = { - it.tasks.withType(CppCompile) { - it.dependsOn ntcoreGenerateCppTypes - it.dependsOn ntcoreGenerateCppHandleSource - it.dependsOn ntcoreGenerateCppHandleHeader - it.dependsOn ntcoreGenerateCHandleSource - it.dependsOn ntcoreGenerateCHandleHeader - it.dependsOn ntcoreGenerateJniSource - } } splitSetup = { it.tasks.withType(CppCompile) { - it.dependsOn ntcoreGenerateCppTypes - it.dependsOn ntcoreGenerateCppHandleSource - it.dependsOn ntcoreGenerateCppHandleHeader - it.dependsOn ntcoreGenerateCHandleSource - it.dependsOn ntcoreGenerateCHandleHeader - it.dependsOn ntcoreGenerateJniSource it.includes 'src/main/native/cpp' } } exeSplitSetup = { - it.tasks.withType(CppCompile) { - it.dependsOn ntcoreGenerateCppTypes - it.dependsOn ntcoreGenerateCppHandleSource - it.dependsOn ntcoreGenerateCppHandleHeader - it.dependsOn ntcoreGenerateCHandleSource - it.dependsOn ntcoreGenerateCHandleHeader - } } } @@ -308,13 +42,9 @@ model { } } -sourceSets.main.java.srcDir "${buildDir}/generated/main/java" -compileJava.dependsOn ntcoreGenerateJavaTypes +sourceSets.main.java.srcDir "${projectDir}/src/generated/main/java" cppHeadersZip { - dependsOn ntcoreGenerateCppTypes - dependsOn ntcoreGenerateCppHandleHeader - dependsOn ntcoreGenerateCHandleHeader from(generatedHeaders) { into '/' } diff --git a/ntcore/doc/alloy-model.adoc b/ntcore/doc/alloy-model.adoc index 35ca7d85adb..fb7b372b7e4 100644 --- a/ntcore/doc/alloy-model.adoc +++ b/ntcore/doc/alloy-model.adoc @@ -1,6 +1,6 @@ = Network Tables Alloy Model -Alloy (http://alloy.mit.edu/alloy/) is a formal logic tool that can analyze +[Alloy](https://www.csail.mit.edu/research/alloy) is a formal logic tool that can analyze first-order logic expressions. Under the proposed sequence number -based protocol, assuming that all nodes start from the same state, Alloy is unable to find a way where two nodes with the same sequence number have different state diff --git a/ntcore/doc/networktables4.adoc b/ntcore/doc/networktables4.adoc index da157e59a40..29e74a14e64 100644 --- a/ntcore/doc/networktables4.adoc +++ b/ntcore/doc/networktables4.adoc @@ -23,7 +23,7 @@ Version 4.1 makes the following key changes to address these weaknesses: * Recommend that timestamp synchronization occur immediately following connection establishment and prior to any other control messages * Recommend text and binary combining into a single WebSockets frame be limited to the network MTU (unless necessary to transport the message) * Recommend WebSockets fragmentation be used on large frames to enable rapid handling of PING messages -* Add an option for topics to be marked transient (in which case no last value is retained by the server or sent to clients on initial subscription) +* Add a (default true) option for topics to be marked cached (in which case the last value is retained by the server and sent to clients on initial subscription) * Recommend clients subscribe to the `$sub$` meta-topic for each topic published by the client, and use this information to control what value updates are sent over the network to the server Version 4.1 uses a different WebSockets subprotocol string than version 4.0, so it is easy for both clients and servers to simultaneously support both versions 4.0 and 4.1. Due to WebSockets implementation bugs in version 4.0, version 4.1 implementations must not send WebSockets PING messages on version 4.0 connections. @@ -100,7 +100,7 @@ If using timestamp messages for aliveness checking on the primary connection, th [[reconnection]] === Caching and Reconnection Handling -Servers shall keep a retained value for each topic for the purposes of <> requests; the retained value shall be the value in the largest timestamp (greater-than or equal-to) message received for that topic. This retained value is deleted if the topic is deleted (e.g. there are no more publishers). +Servers shall keep a retained value for each cached topic for the purposes of <> requests; the retained value shall be the value in the largest timestamp (greater-than or equal-to) message received for that topic. This retained value is deleted if the topic is deleted (e.g. there are no more publishers). Clients may similarly keep a retained value for each topic for ease of use by user code. If this is done, this retained value shall be updated by both locally published values and received messages for that topic with greater-than/equal-to timestamps, and the retained value shall be deleted when a <> is received. @@ -419,6 +419,7 @@ Each published topic may also have properties associated to it. Properties are |Property|Type|Description|Notes |`persistent`|boolean|Persistent Flag|If true, the last set value will be periodically saved to persistent storage on the server and be restored during server startup. Topics with this property set to true will not be deleted by the server when the last publisher stops publishing. |`retained`|boolean|Retained Flag|Topics with this property set to true will not be deleted by the server when the last publisher stops publishing. +|`cached`|boolean|Cached Flag|If false, the server and clients will not store the value of the topic. This means that only value updates will be available for the topic. |=== [[sub-options]] @@ -619,7 +620,7 @@ If a property is not included in the update map, its value is not changed. If a [[msg-subscribe]] ==== Subscribe Message (`subscribe`) -Sent from a client to the server to indicate the client wants to subscribe to value changes for the specified topics / groups of topics. The server shall send MessagePack messages containing the current values for any existing topics upon receipt, and continue sending MessagePack messages for future value changes. If a topic does not yet exist, no message is sent until it is created (via a publish), at which point a <> will be sent and MessagePack messages will automatically follow as they are published. +Sent from a client to the server to indicate the client wants to subscribe to value changes for the specified topics / groups of topics. The server shall send MessagePack messages containing the current values for any existing cached topics upon receipt, and continue sending MessagePack messages for future value changes. If a topic does not yet exist, no message is sent until it is created (via a publish), at which point a <> will be sent and MessagePack messages will automatically follow as they are published. Subscriptions may overlap; only one MessagePack message is sent per value change regardless of the number of subscriptions. Sending a `subscribe` message with the same subscription UID as a previous `subscribe` message results in updating the subscription (replacing the array of identifiers and updating any specified options). diff --git a/ntcore/generate_topics.py b/ntcore/generate_topics.py old mode 100644 new mode 100755 index ece7df29881..5afd61a722e --- a/ntcore/generate_topics.py +++ b/ntcore/generate_topics.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python3 + import glob import os import sys @@ -17,23 +19,22 @@ def Output(outPath, outfn, contents): return # File either doesn't exist or has different contents - with open(outpathname, "w") as f: + with open(outpathname, "w", newline="\n") as f: f.write(contents) def main(): dirname, _ = os.path.split(os.path.abspath(__file__)) - cmake_binary_dir = sys.argv[1] with open(f"{dirname}/src/generate/types.json") as f: types = json.load(f) # Java files env = Environment( - loader=FileSystemLoader(f"{dirname}/src/generate/java"), autoescape=False + loader=FileSystemLoader(f"{dirname}/src/generate/main/java"), autoescape=False ) - rootPath = f"{cmake_binary_dir}/generated/main/java/edu/wpi/first/networktables" - for fn in glob.glob(f"{dirname}/src/generate/java/*.jinja"): + rootPath = f"{dirname}/src/generated/main/java/edu/wpi/first/networktables" + for fn in glob.glob(f"{dirname}/src/generate/main/java/*.jinja"): template = env.get_template(os.path.basename(fn)) outfn = os.path.basename(fn)[:-6] # drop ".jinja" if os.path.basename(fn).startswith("NetworkTable") or os.path.basename( @@ -52,11 +53,15 @@ def main(): # C++ classes env = Environment( - loader=FileSystemLoader(f"{dirname}/src/generate/include/networktables"), + loader=FileSystemLoader( + f"{dirname}/src/generate/main/native/include/networktables" + ), autoescape=False, ) - rootPath = f"{cmake_binary_dir}/generated/main/native/include/networktables" - for fn in glob.glob(f"{dirname}/src/generate/include/networktables/*.jinja"): + rootPath = f"{dirname}/src/generated/main/native/include/networktables" + for fn in glob.glob( + f"{dirname}/src/generate/main/native/include/networktables/*.jinja" + ): template = env.get_template(os.path.basename(fn)) outfn = os.path.basename(fn)[:-6] # drop ".jinja" for replacements in types: @@ -66,55 +71,56 @@ def main(): # C++ handle API (header) env = Environment( - loader=FileSystemLoader(f"{dirname}/src/generate/include"), autoescape=False + loader=FileSystemLoader(f"{dirname}/src/generate/main/native/include"), + autoescape=False, ) template = env.get_template("ntcore_cpp_types.h.jinja") output = template.render(types=types) Output( - f"{cmake_binary_dir}/generated/main/native/include", + f"{dirname}/src/generated/main/native/include", "ntcore_cpp_types.h", output, ) # C++ handle API (source) env = Environment( - loader=FileSystemLoader(f"{dirname}/src/generate/cpp"), autoescape=False + loader=FileSystemLoader(f"{dirname}/src/generate/main/native/cpp"), + autoescape=False, ) template = env.get_template("ntcore_cpp_types.cpp.jinja") output = template.render(types=types) - Output( - f"{cmake_binary_dir}/generated/main/native/cpp", "ntcore_cpp_types.cpp", output - ) + Output(f"{dirname}/src/generated/main/native/cpp", "ntcore_cpp_types.cpp", output) # C handle API (header) env = Environment( - loader=FileSystemLoader(f"{dirname}/src/generate/include"), autoescape=False + loader=FileSystemLoader(f"{dirname}/src/generate/main/native/include"), + autoescape=False, ) template = env.get_template("ntcore_c_types.h.jinja") output = template.render(types=types) Output( - f"{cmake_binary_dir}/generated/main/native/include", + f"{dirname}/src/generated/main/native/include", "ntcore_c_types.h", output, ) # C handle API (source) env = Environment( - loader=FileSystemLoader(f"{dirname}/src/generate/cpp"), autoescape=False + loader=FileSystemLoader(f"{dirname}/src/generate/main/native/cpp"), + autoescape=False, ) template = env.get_template("ntcore_c_types.cpp.jinja") output = template.render(types=types) - Output( - f"{cmake_binary_dir}/generated/main/native/cpp", "ntcore_c_types.cpp", output - ) + Output(f"{dirname}/src/generated/main/native/cpp", "ntcore_c_types.cpp", output) # JNI env = Environment( - loader=FileSystemLoader(f"{dirname}/src/generate/cpp/jni"), autoescape=False + loader=FileSystemLoader(f"{dirname}/src/generate/main/native/cpp/jni"), + autoescape=False, ) template = env.get_template("types_jni.cpp.jinja") output = template.render(types=types) - Output(f"{cmake_binary_dir}/generated/main/native/cpp/jni", "types_jni.cpp", output) + Output(f"{dirname}/src/generated/main/native/cpp/jni", "types_jni.cpp", output) if __name__ == "__main__": diff --git a/ntcore/ntcore-config.cmake.in b/ntcore/ntcore-config.cmake.in index 0a85f8b09d7..9642d635ae4 100644 --- a/ntcore/ntcore-config.cmake.in +++ b/ntcore/ntcore-config.cmake.in @@ -5,3 +5,6 @@ include(CMakeFindDependencyMacro) @FILENAME_DEP_REPLACE@ include(${SELF_DIR}/ntcore.cmake) +if(@WITH_JAVA@) + include(${SELF_DIR}/ntcore_jar.cmake) +endif() diff --git a/ntcore/src/dev/native/cpp/main.cpp b/ntcore/src/dev/native/cpp/main.cpp index 6e43fdb41e0..1318b2975e0 100644 --- a/ntcore/src/dev/native/cpp/main.cpp +++ b/ntcore/src/dev/native/cpp/main.cpp @@ -13,7 +13,9 @@ #include #include +#include #include +#include #include #include "ntcore.h" @@ -24,7 +26,7 @@ void bench2(); void stress(); int main(int argc, char* argv[]) { - wpi::impl::SetupNowRio(); + wpi::impl::SetupNowDefaultOnRio(); if (argc == 2 && std::string_view{argv[1]} == "bench") { bench(); @@ -43,7 +45,7 @@ int main(int argc, char* argv[]) { nt::SetEntryValue(myValue, nt::Value::MakeString("Hello World")); - fmt::print("{}\n", nt::GetEntryValue(myValue).GetString()); + wpi::print("{}\n", nt::GetEntryValue(myValue).GetString()); } void PrintTimes(std::vector& times) { @@ -57,9 +59,9 @@ void PrintTimes(std::vector& times) { std::inner_product(times.begin(), times.end(), times.begin(), 0); double stdev = std::sqrt(sq_sum / times.size() - mean * mean); - fmt::print("min: {} max: {}, mean: {}, stdev: {}\n", min, max, mean, stdev); - fmt::print("min 10: {}\n", fmt::join(times.begin(), times.begin() + 10, ",")); - fmt::print("max 10: {}\n", fmt::join(times.end() - 10, times.end(), ",")); + wpi::print("min: {} max: {}, mean: {}, stdev: {}\n", min, max, mean, stdev); + wpi::print("min 10: {}\n", fmt::join(times.begin(), times.begin() + 10, ",")); + wpi::print("max 10: {}\n", fmt::join(times.end() - 10, times.end(), ",")); } // benchmark @@ -115,11 +117,11 @@ void bench() { } auto stop = std::chrono::high_resolution_clock::now(); - fmt::print("total time: {}us\n", + wpi::print("total time: {}us\n", std::chrono::duration_cast(stop - start) .count()); PrintTimes(times); - fmt::print("-- Flush --\n"); + wpi::print("-- Flush --\n"); PrintTimes(flushTimes); } @@ -188,11 +190,11 @@ void bench2() { } auto stop = std::chrono::high_resolution_clock::now(); - fmt::print("total time: {}us\n", + wpi::print("total time: {}us\n", std::chrono::duration_cast(stop - start) .count()); PrintTimes(times); - fmt::print("-- Flush --\n"); + wpi::print("-- Flush --\n"); PrintTimes(flushTimes); } diff --git a/ntcore/src/generate/java/NetworkTablesJNI.java.jinja b/ntcore/src/generate/java/NetworkTablesJNI.java.jinja deleted file mode 100644 index 6ff9c1627b6..00000000000 --- a/ntcore/src/generate/java/NetworkTablesJNI.java.jinja +++ /dev/null @@ -1,355 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.networktables; - -import edu.wpi.first.util.RuntimeLoader; -import edu.wpi.first.util.datalog.DataLog; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.EnumSet; -import java.util.OptionalLong; -import java.util.concurrent.atomic.AtomicBoolean; - -public final class NetworkTablesJNI { - static boolean libraryLoaded = false; - static RuntimeLoader loader = null; - - public static class Helper { - private static AtomicBoolean extractOnStaticLoad = new AtomicBoolean(true); - - public static boolean getExtractOnStaticLoad() { - return extractOnStaticLoad.get(); - } - - public static void setExtractOnStaticLoad(boolean load) { - extractOnStaticLoad.set(load); - } - } - - static { - if (Helper.getExtractOnStaticLoad()) { - try { - loader = - new RuntimeLoader<>( - "ntcorejni", RuntimeLoader.getDefaultExtractionRoot(), NetworkTablesJNI.class); - loader.loadLibrary(); - } catch (IOException ex) { - ex.printStackTrace(); - System.exit(1); - } - libraryLoaded = true; - } - } - - /** - * Force load the library. - * - * @throws IOException if the library fails to load - */ - public static synchronized void forceLoad() throws IOException { - if (libraryLoaded) { - return; - } - loader = - new RuntimeLoader<>( - "ntcorejni", RuntimeLoader.getDefaultExtractionRoot(), NetworkTablesJNI.class); - loader.loadLibrary(); - libraryLoaded = true; - } - - private static PubSubOptions buildOptions(PubSubOption... options) { - if (options.length == 0) { - return null; // optimize common case (JNI checks for null) - } - return new PubSubOptions(options); - } - - public static native int getDefaultInstance(); - - public static native int createInstance(); - - public static native void destroyInstance(int inst); - - public static native int getInstanceFromHandle(int handle); - - private static native int getEntryImpl( - int topic, int type, String typeStr, PubSubOptions options); - - public static native int getEntry(int inst, String key); - - public static int getEntry( - int topic, int type, String typeStr, PubSubOptions options) { - return getEntryImpl(topic, type, typeStr, options); - } - - public static int getEntry( - int topic, int type, String typeStr, PubSubOption... options) { - return getEntryImpl(topic, type, typeStr, buildOptions(options)); - } - - public static native String getEntryName(int entry); - - public static native long getEntryLastChange(int entry); - - public static native int getType(int entry); - - /* Topic functions */ - - public static native int[] getTopics(int inst, String prefix, int types); - - public static native int[] getTopicsStr(int inst, String prefix, String[] types); - - public static native TopicInfo[] getTopicInfos( - NetworkTableInstance instObject, int inst, String prefix, int types); - - public static native TopicInfo[] getTopicInfosStr( - NetworkTableInstance instObject, int inst, String prefix, String[] types); - - public static native int getTopic(int inst, String name); - - public static native String getTopicName(int topic); - - public static native int getTopicType(int topic); - - public static native void setTopicPersistent(int topic, boolean value); - - public static native boolean getTopicPersistent(int topic); - - public static native void setTopicRetained(int topic, boolean value); - - public static native boolean getTopicRetained(int topic); - - public static native String getTopicTypeString(int topic); - - public static native boolean getTopicExists(int topic); - - public static native String getTopicProperty(int topic, String name); - - public static native void setTopicProperty(int topic, String name, String value); - - public static native void deleteTopicProperty(int topic, String name); - - public static native String getTopicProperties(int topic); - - public static native void setTopicProperties(int topic, String properties); - - public static native int subscribe( - int topic, int type, String typeStr, PubSubOptions options); - - public static int subscribe( - int topic, int type, String typeStr, PubSubOption... options) { - return subscribe(topic, type, typeStr, buildOptions(options)); - } - - public static native void unsubscribe(int sub); - - public static native int publish( - int topic, int type, String typeStr, PubSubOptions options); - - public static int publish( - int topic, int type, String typeStr, PubSubOption... options) { - return publish(topic, type, typeStr, buildOptions(options)); - } - - public static native int publishEx( - int topic, int type, String typeStr, String properties, PubSubOptions options); - - public static int publishEx( - int topic, int type, String typeStr, String properties, PubSubOption... options) { - return publishEx(topic, type, typeStr, properties, buildOptions(options)); - } - - public static native void unpublish(int pubentry); - - public static native void releaseEntry(int entry); - - public static native void release(int pubsubentry); - - public static native int getTopicFromHandle(int pubsubentry); - - public static native int subscribeMultiple(int inst, String[] prefixes, PubSubOptions options); - - public static int subscribeMultiple(int inst, String[] prefixes, PubSubOption... options) { - return subscribeMultiple(inst, prefixes, buildOptions(options)); - } - - public static native void unsubscribeMultiple(int sub); -{% for t in types %} - public static native Timestamped{{ t.TypeName }} getAtomic{{ t.TypeName }}( - int subentry, {{ t.java.ValueType }} defaultValue); - - public static native Timestamped{{ t.TypeName }}[] readQueue{{ t.TypeName }}(int subentry); - - public static native {{ t.java.ValueType }}[] readQueueValues{{ t.TypeName }}(int subentry); -{% if t.TypeName == "Raw" %} - public static boolean setRaw(int entry, long time, byte[] value) { - return setRaw(entry, time, value, 0, value.length); - } - - public static native boolean setRaw(int entry, long time, byte[] value, int start, int len); - - public static boolean setRaw(int entry, long time, ByteBuffer value) { - int pos = value.position(); - return setRaw(entry, time, value, pos, value.capacity() - pos); - } - - public static boolean setRaw(int entry, long time, ByteBuffer value, int start, int len) { - if (value.isDirect()) { - if (start < 0) { - throw new IndexOutOfBoundsException("start must be >= 0"); - } - if (len < 0) { - throw new IndexOutOfBoundsException("len must be >= 0"); - } - if ((start + len) > value.capacity()) { - throw new IndexOutOfBoundsException("start + len must be smaller than buffer capacity"); - } - return setRawBuffer(entry, time, value, start, len); - } else if (value.hasArray()) { - return setRaw(entry, time, value.array(), value.arrayOffset() + start, len); - } else { - throw new UnsupportedOperationException("ByteBuffer must be direct or have a backing array"); - } - } - - private static native boolean setRawBuffer(int entry, long time, ByteBuffer value, int start, int len); -{% else %} - public static native boolean set{{ t.TypeName }}(int entry, long time, {{ t.java.ValueType }} value); -{% endif %} - public static native {{ t.java.ValueType }} get{{ t.TypeName }}(int entry, {{ t.java.ValueType }} defaultValue); -{% if t.TypeName == "Raw" %} - public static boolean setDefaultRaw(int entry, long time, byte[] defaultValue) { - return setDefaultRaw(entry, time, defaultValue, 0, defaultValue.length); - } - - public static native boolean setDefaultRaw(int entry, long time, byte[] defaultValue, int start, int len); - - public static boolean setDefaultRaw(int entry, long time, ByteBuffer defaultValue) { - int pos = defaultValue.position(); - return setDefaultRaw(entry, time, defaultValue, pos, defaultValue.limit() - pos); - } - - public static boolean setDefaultRaw(int entry, long time, ByteBuffer defaultValue, int start, int len) { - if (defaultValue.isDirect()) { - if (start < 0) { - throw new IndexOutOfBoundsException("start must be >= 0"); - } - if (len < 0) { - throw new IndexOutOfBoundsException("len must be >= 0"); - } - if ((start + len) > defaultValue.capacity()) { - throw new IndexOutOfBoundsException("start + len must be smaller than buffer capacity"); - } - return setDefaultRawBuffer(entry, time, defaultValue, start, len); - } else if (defaultValue.hasArray()) { - return setDefaultRaw(entry, time, defaultValue.array(), defaultValue.arrayOffset() + start, len); - } else { - throw new UnsupportedOperationException("ByteBuffer must be direct or have a backing array"); - } - } - - private static native boolean setDefaultRawBuffer(int entry, long time, ByteBuffer defaultValue, int start, int len); -{% else %} - public static native boolean setDefault{{ t.TypeName }}(int entry, long time, {{ t.java.ValueType }} defaultValue); -{% endif %} -{% endfor %} - public static native NetworkTableValue[] readQueueValue(int subentry); - - public static native NetworkTableValue getValue(int entry); - - public static native void setEntryFlags(int entry, int flags); - - public static native int getEntryFlags(int entry); - - public static native TopicInfo getTopicInfo(NetworkTableInstance inst, int topic); - - public static native int createListenerPoller(int inst); - - public static native void destroyListenerPoller(int poller); - - private static int kindsToMask(EnumSet kinds) { - int mask = 0; - for (NetworkTableEvent.Kind kind : kinds) { - mask |= kind.getValue(); - } - return mask; - } - - public static int addListener(int poller, String[] prefixes, EnumSet kinds) { - return addListener(poller, prefixes, kindsToMask(kinds)); - } - - public static int addListener(int poller, int handle, EnumSet kinds) { - return addListener(poller, handle, kindsToMask(kinds)); - } - - public static native int addListener(int poller, String[] prefixes, int mask); - - public static native int addListener(int poller, int handle, int mask); - - public static native NetworkTableEvent[] readListenerQueue( - NetworkTableInstance inst, int poller); - - public static native void removeListener(int listener); - - public static native int getNetworkMode(int inst); - - public static native void startLocal(int inst); - - public static native void stopLocal(int inst); - - public static native void startServer( - int inst, String persistFilename, String listenAddress, int port3, int port4); - - public static native void stopServer(int inst); - - public static native void startClient3(int inst, String identity); - - public static native void startClient4(int inst, String identity); - - public static native void stopClient(int inst); - - public static native void setServer(int inst, String serverName, int port); - - public static native void setServer(int inst, String[] serverNames, int[] ports); - - public static native void setServerTeam(int inst, int team, int port); - - public static native void disconnect(int inst); - - public static native void startDSClient(int inst, int port); - - public static native void stopDSClient(int inst); - - public static native void flushLocal(int inst); - - public static native void flush(int inst); - - public static native ConnectionInfo[] getConnections(int inst); - - public static native boolean isConnected(int inst); - - public static native OptionalLong getServerTimeOffset(int inst); - - public static native long now(); - - private static native int startEntryDataLog(int inst, long log, String prefix, String logPrefix); - - public static int startEntryDataLog(int inst, DataLog log, String prefix, String logPrefix) { - return startEntryDataLog(inst, log.getImpl(), prefix, logPrefix); - } - - public static native void stopEntryDataLog(int logger); - - private static native int startConnectionDataLog(int inst, long log, String name); - - public static int startConnectionDataLog(int inst, DataLog log, String name) { - return startConnectionDataLog(inst, log.getImpl(), name); - } - - public static native void stopConnectionDataLog(int logger); - - public static native int addLogger(int poller, int minLevel, int maxLevel); -} diff --git a/ntcore/src/generate/java/Entry.java.jinja b/ntcore/src/generate/main/java/Entry.java.jinja similarity index 87% rename from ntcore/src/generate/java/Entry.java.jinja rename to ntcore/src/generate/main/java/Entry.java.jinja index cbaa782c207..43c424f7139 100644 --- a/ntcore/src/generate/java/Entry.java.jinja +++ b/ntcore/src/generate/main/java/Entry.java.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + package edu.wpi.first.networktables; /** @@ -13,3 +15,4 @@ public interface {{ TypeName }}Entry extends {{ TypeName }}Subscriber, {{ TypeNa /** Stops publishing the entry if it's published. */ void unpublish(); } + diff --git a/ntcore/src/generate/java/EntryImpl.java.jinja b/ntcore/src/generate/main/java/EntryImpl.java.jinja similarity index 97% rename from ntcore/src/generate/java/EntryImpl.java.jinja rename to ntcore/src/generate/main/java/EntryImpl.java.jinja index b7432a7e319..5053e10cdb4 100644 --- a/ntcore/src/generate/java/EntryImpl.java.jinja +++ b/ntcore/src/generate/main/java/EntryImpl.java.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + package edu.wpi.first.networktables; {% if TypeName == "Raw" %} import java.nio.ByteBuffer; @@ -95,3 +97,4 @@ final class {{ TypeName }}EntryImpl extends EntryBase implements {{ TypeName }}E private final {{ TypeName }}Topic m_topic; private final {{ java.ValueType }} m_defaultValue; } + diff --git a/ntcore/src/generate/java/GenericEntryImpl.java.jinja b/ntcore/src/generate/main/java/GenericEntryImpl.java.jinja similarity index 99% rename from ntcore/src/generate/java/GenericEntryImpl.java.jinja rename to ntcore/src/generate/main/java/GenericEntryImpl.java.jinja index 29666bb79e5..0bc4fed246c 100644 --- a/ntcore/src/generate/java/GenericEntryImpl.java.jinja +++ b/ntcore/src/generate/main/java/GenericEntryImpl.java.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + package edu.wpi.first.networktables; import java.nio.ByteBuffer; @@ -373,3 +375,4 @@ final class GenericEntryImpl extends EntryBase implements GenericEntry { private final Topic m_topic; } + diff --git a/ntcore/src/generate/java/GenericPublisher.java.jinja b/ntcore/src/generate/main/java/GenericPublisher.java.jinja similarity index 96% rename from ntcore/src/generate/java/GenericPublisher.java.jinja rename to ntcore/src/generate/main/java/GenericPublisher.java.jinja index 881aba63d53..5af0d3b3e25 100644 --- a/ntcore/src/generate/java/GenericPublisher.java.jinja +++ b/ntcore/src/generate/main/java/GenericPublisher.java.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + package edu.wpi.first.networktables; import java.nio.ByteBuffer; @@ -234,6 +236,12 @@ public interface GenericPublisher extends Publisher, Consumer boolean setDefault{{ t.TypeName }}({{ t.java.ValueType }} defaultValue); {% endif -%} {% if t.java.WrapValueType %} + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ boolean setDefault{{ t.TypeName }}({{ t.java.WrapValueType }} defaultValue); {% endif -%} {% endfor %} @@ -242,3 +250,4 @@ public interface GenericPublisher extends Publisher, Consumer set(value); } } + diff --git a/ntcore/src/generate/java/GenericSubscriber.java.jinja b/ntcore/src/generate/main/java/GenericSubscriber.java.jinja similarity index 96% rename from ntcore/src/generate/java/GenericSubscriber.java.jinja rename to ntcore/src/generate/main/java/GenericSubscriber.java.jinja index 63ecebcf202..c0ed6611a98 100644 --- a/ntcore/src/generate/java/GenericSubscriber.java.jinja +++ b/ntcore/src/generate/main/java/GenericSubscriber.java.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + package edu.wpi.first.networktables; import java.util.function.Supplier; @@ -56,3 +58,4 @@ public interface GenericSubscriber extends Subscriber, Supplier m_schemas = new ConcurrentHashMap<>(); } + diff --git a/ntcore/src/generate/java/NetworkTableValue.java.jinja b/ntcore/src/generate/main/java/NetworkTableValue.java.jinja similarity index 98% rename from ntcore/src/generate/java/NetworkTableValue.java.jinja rename to ntcore/src/generate/main/java/NetworkTableValue.java.jinja index d2c8d11fe21..cb97570a82e 100644 --- a/ntcore/src/generate/java/NetworkTableValue.java.jinja +++ b/ntcore/src/generate/main/java/NetworkTableValue.java.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + package edu.wpi.first.networktables; import java.util.Objects; @@ -246,3 +248,4 @@ public final class NetworkTableValue { private long m_time; private long m_serverTime; } + diff --git a/ntcore/src/generate/main/java/NetworkTablesJNI.java.jinja b/ntcore/src/generate/main/java/NetworkTablesJNI.java.jinja new file mode 100644 index 00000000000..5c43b44e7d1 --- /dev/null +++ b/ntcore/src/generate/main/java/NetworkTablesJNI.java.jinja @@ -0,0 +1,1098 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import edu.wpi.first.util.RuntimeLoader; +import edu.wpi.first.util.datalog.DataLog; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.EnumSet; +import java.util.OptionalLong; +import java.util.concurrent.atomic.AtomicBoolean; + +/** NetworkTables JNI. */ +public final class NetworkTablesJNI { + static boolean libraryLoaded = false; + static RuntimeLoader loader = null; + + /** Sets whether JNI should be loaded in the static block. */ + public static class Helper { + private static AtomicBoolean extractOnStaticLoad = new AtomicBoolean(true); + + /** + * Returns true if the JNI should be loaded in the static block. + * + * @return True if the JNI should be loaded in the static block. + */ + public static boolean getExtractOnStaticLoad() { + return extractOnStaticLoad.get(); + } + + /** + * Sets whether the JNI should be loaded in the static block. + * + * @param load Whether the JNI should be loaded in the static block. + */ + public static void setExtractOnStaticLoad(boolean load) { + extractOnStaticLoad.set(load); + } + + /** Utility class. */ + private Helper() {} + } + + static { + if (Helper.getExtractOnStaticLoad()) { + try { + loader = + new RuntimeLoader<>( + "ntcorejni", RuntimeLoader.getDefaultExtractionRoot(), NetworkTablesJNI.class); + loader.loadLibrary(); + } catch (IOException ex) { + ex.printStackTrace(); + System.exit(1); + } + libraryLoaded = true; + } + } + + /** + * Force load the library. + * + * @throws IOException if the library fails to load + */ + public static synchronized void forceLoad() throws IOException { + if (libraryLoaded) { + return; + } + loader = + new RuntimeLoader<>( + "ntcorejni", RuntimeLoader.getDefaultExtractionRoot(), NetworkTablesJNI.class); + loader.loadLibrary(); + libraryLoaded = true; + } + + private static PubSubOptions buildOptions(PubSubOption... options) { + if (options.length == 0) { + return null; // optimize common case (JNI checks for null) + } + return new PubSubOptions(options); + } + + /** + * Returns default instance handle. + * + * @return Default instance handle. + */ + public static native int getDefaultInstance(); + + /** + * Creates an NT instance. + * + * @return NT instance handle. + */ + public static native int createInstance(); + + /** + * Destroys an NT instance. + * + * @param inst NT instance handle. + */ + public static native void destroyInstance(int inst); + + /** + * Returns NT instance from handle. + * + * @param handle NT instance handle. + * @return NT instance. + */ + public static native int getInstanceFromHandle(int handle); + + private static native int getEntryImpl( + int topic, int type, String typeStr, PubSubOptions options); + + /** + * Returns NT entry handle. + * + * @param inst NT instance handle. + * @param key NT entry key. + * @return NT entry handle. + */ + public static native int getEntry(int inst, String key); + + /** + * Returns NT entry handle. + * + * @param topic NT entry topic. + * @param type NT entry type. + * @param typeStr NT entry type as a string. + * @param options NT entry pubsub options. + * @return NT entry handle. + */ + public static int getEntry( + int topic, int type, String typeStr, PubSubOptions options) { + return getEntryImpl(topic, type, typeStr, options); + } + + /** + * Returns NT entry handle. + * + * @param topic NT entry topic. + * @param type NT entry type. + * @param typeStr NT entry type as a string. + * @param options NT entry pubsub options. + * @return NT entry handle. + */ + public static int getEntry( + int topic, int type, String typeStr, PubSubOption... options) { + return getEntryImpl(topic, type, typeStr, buildOptions(options)); + } + + /** + * Returns NT entry name. + * + * @param entry NT entry handle. + * @return NT entry name. + */ + public static native String getEntryName(int entry); + + /** + * Returns NT entry last change time in microseconds. + * + * @param entry NT entry handle. + * @return NT entry last change time in microseconds. + */ + public static native long getEntryLastChange(int entry); + + /** + * Returns NT entry type. + * + * @param entry NT entry handle. + * @return NT entry type. + */ + public static native int getType(int entry); + + /* Topic functions */ + + /** + * Returns list of topic handles. + * + * @param inst NT instance handle. + * @param prefix Topic prefix. + * @param types Topic types. + * @return List of topic handles. + */ + public static native int[] getTopics(int inst, String prefix, int types); + + /** + * Returns list of topic handles. + * + * @param inst NT instance handle. + * @param prefix Topic prefix. + * @param types Topic types as strings. + * @return List of topic handles. + */ + public static native int[] getTopicsStr(int inst, String prefix, String[] types); + + /** + * Returns list of topic infos. + * + * @param instObject NT instance. + * @param inst NT instance handle. + * @param prefix Topic prefix. + * @param types Topic types. + * @return List of topic infos. + */ + public static native TopicInfo[] getTopicInfos( + NetworkTableInstance instObject, int inst, String prefix, int types); + + /** + * Returns list of topic infos. + * + * @param instObject NT instance. + * @param inst NT instance handle. + * @param prefix Topic prefix. + * @param types Topic types as strings. + * @return List of topic infos. + */ + public static native TopicInfo[] getTopicInfosStr( + NetworkTableInstance instObject, int inst, String prefix, String[] types); + + /** + * Returns Topic handle. + * + * @param inst NT instance handle. + * @param name Topic name. + * @return Topic handle. + */ + public static native int getTopic(int inst, String name); + + /** + * Returns topic name. + * + * @param topic Topic handle. + * @return Topic name. + */ + public static native String getTopicName(int topic); + + /** + * Returns topic type. + * + * @param topic Topic handle. + * @return Topic type. + */ + public static native int getTopicType(int topic); + + /** + * Sets topic persistency. + * + * @param topic Topic handle. + * @param value True if topic should be persistent. + */ + public static native void setTopicPersistent(int topic, boolean value); + + /** + * Returns true if topic is persistent. + * + * @param topic Topic handle. + * @return True if topic is persistent. + */ + public static native boolean getTopicPersistent(int topic); + + /** + * Sets whether topic is retained. + * + * @param topic Topic handle. + * @param value True if topic should be retained. + */ + public static native void setTopicRetained(int topic, boolean value); + + /** + * Returns true if topic is retained. + * + * @param topic Topic handle. + * @return True if topic is retained. + */ + public static native boolean getTopicRetained(int topic); + + /** + * Sets topic caching. + * + * @param topic Topic handle. + * @param value True if topic should be cached. + */ + public static native void setTopicCached(int topic, boolean value); + + /** + * Returns true if topic is cached. + * + * @param topic Topic handle. + * @return True if topic is cached. + */ + public static native boolean getTopicCached(int topic); + + /** + * Returns topic type as string. + * + * @param topic Topic handle. + * @return Topic type as string. + */ + public static native String getTopicTypeString(int topic); + + /** + * Returns true if topic exists. + * + * @param topic Topic handle. + * @return True if topic exists. + */ + public static native boolean getTopicExists(int topic); + + /** + * Returns topic property. + * + * @param topic Topic handle. + * @param name Property name. + * @return Topic property. + */ + public static native String getTopicProperty(int topic, String name); + + /** + * Sets topic property. + * + * @param topic Topic handle. + * @param name Property name. + * @param value Property value. + */ + public static native void setTopicProperty(int topic, String name, String value); + + /** + * Deletes topic property. + * + * @param topic Topic handle. + * @param name Property name. + */ + public static native void deleteTopicProperty(int topic, String name); + + /** + * Returns topic properties. + * + * @param topic Topic handle. + * @return Topic properties. + */ + public static native String getTopicProperties(int topic); + + /** + * Sets topic properties. + * + * @param topic Topic handle. + * @param properties Topic properties. + */ + public static native void setTopicProperties(int topic, String properties); + + /** + * Subscribes to topic. + * + * @param topic Topic handle. + * @param type Topic type. + * @param typeStr Topic type as a string. + * @param options Pubsub options. + * @return Subscriber handle. + */ + public static native int subscribe( + int topic, int type, String typeStr, PubSubOptions options); + + /** + * Subscribes to topic. + * + * @param topic Topic handle. + * @param type Topic type. + * @param typeStr Topic type as a string. + * @param options Pubsub options. + * @return Subscriber handle. + */ + public static int subscribe( + int topic, int type, String typeStr, PubSubOption... options) { + return subscribe(topic, type, typeStr, buildOptions(options)); + } + + /** + * Unsubscribes from topic. + * + * @param sub Subscriber handle. + */ + public static native void unsubscribe(int sub); + + /** + * Publishes topic. + * + * @param topic Topic handle. + * @param type Topic type. + * @param typeStr Topic type as a string. + * @param options Pubsub options. + * @return Publish handle. + */ + public static native int publish( + int topic, int type, String typeStr, PubSubOptions options); + + /** + * Publishes topic. + * + * @param topic Topic handle. + * @param type Topic type. + * @param typeStr Topic type as a string. + * @param options Pubsub options. + * @return Publish handle. + */ + public static int publish( + int topic, int type, String typeStr, PubSubOption... options) { + return publish(topic, type, typeStr, buildOptions(options)); + } + + /** + * Publishes topic. + * + * @param topic Topic handle. + * @param type Topic type. + * @param typeStr Topic type as a string. + * @param properties Topic properties. + * @param options Pubsub options. + * @return Publish handle. + */ + public static native int publishEx( + int topic, int type, String typeStr, String properties, PubSubOptions options); + + /** + * Publishes topic. + * + * @param topic Topic handle. + * @param type Topic type. + * @param typeStr Topic type as a string. + * @param properties Topic properties. + * @param options Pubsub options. + * @return Publish handle. + */ + public static int publishEx( + int topic, int type, String typeStr, String properties, PubSubOption... options) { + return publishEx(topic, type, typeStr, properties, buildOptions(options)); + } + + /** + * Unpublishes topic. + * + * @param pubentry Publish entry handle. + */ + public static native void unpublish(int pubentry); + + /** + * Releases NT entry. + * + * @param entry NT entry handle. + */ + public static native void releaseEntry(int entry); + + /** + * Relesaes pubsub entry. + * + * @param pubsubentry Pubsub entry handle. + */ + public static native void release(int pubsubentry); + + /** + * Returns topic from pubsub entry handle. + * + * @param pubsubentry Pubsub entry handle. + * @return Topic handle. + */ + public static native int getTopicFromHandle(int pubsubentry); + + /** + * Subscribes to multiple topics. + * + * @param inst NT instance handle. + * @param prefixes List of topic prefixes. + * @param options Pubsub options. + * @return Subscribe handle. + */ + public static native int subscribeMultiple(int inst, String[] prefixes, PubSubOptions options); + + /** + * Subscribes to multiple topics. + * + * @param inst NT instance handle. + * @param prefixes List of topic prefixes. + * @param options Pubsub options. + * @return Subscribe handle. + */ + public static int subscribeMultiple(int inst, String[] prefixes, PubSubOption... options) { + return subscribeMultiple(inst, prefixes, buildOptions(options)); + } + + /** + * Unsubscribes from multiple topics. + * + * @param sub Subscribe handle. + */ + public static native void unsubscribeMultiple(int sub); +{% for t in types %} + /** + * Returns timestamped topic value as an atomic {{ t.TypeName }}. + * + * @param subentry Subentry handle. + * @param defaultValue Default value. + * @return Timestamped topic value. + */ + public static native Timestamped{{ t.TypeName }} getAtomic{{ t.TypeName }}( + int subentry, {{ t.java.ValueType }} defaultValue); + + /** + * Returns queued timestamped topic values. + * + * @param subentry Subentry handle. + * @return List of timestamped topic values. + */ + public static native Timestamped{{ t.TypeName }}[] readQueue{{ t.TypeName }}(int subentry); + + /** + * Returns queued topic values. + * + * @param subentry Subentry handle. + * @return List of topic values. + */ + public static native {{ t.java.ValueType }}[] readQueueValues{{ t.TypeName }}(int subentry); +{% if t.TypeName == "Raw" %} + /** + * Sets raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Raw value buffer. + * @return True if set succeeded. + */ + public static boolean setRaw(int entry, long time, byte[] value) { + return setRaw(entry, time, value, 0, value.length); + } + + /** + * Sets raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Raw value buffer. + * @param start Value's offset into buffer. + * @param len Length of value in buffer. + * @return True if set succeeded. + */ + public static native boolean setRaw(int entry, long time, byte[] value, int start, int len); + + /** + * Sets raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Raw value buffer. + * @return True if set succeeded. + */ + public static boolean setRaw(int entry, long time, ByteBuffer value) { + int pos = value.position(); + return setRaw(entry, time, value, pos, value.capacity() - pos); + } + + /** + * Sets raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Raw value buffer. + * @param start Value's offset into buffer. + * @param len Length of value in buffer. + * @return True if set succeeded. + */ + public static boolean setRaw(int entry, long time, ByteBuffer value, int start, int len) { + if (value.isDirect()) { + if (start < 0) { + throw new IndexOutOfBoundsException("start must be >= 0"); + } + if (len < 0) { + throw new IndexOutOfBoundsException("len must be >= 0"); + } + if ((start + len) > value.capacity()) { + throw new IndexOutOfBoundsException("start + len must be smaller than buffer capacity"); + } + return setRawBuffer(entry, time, value, start, len); + } else if (value.hasArray()) { + return setRaw(entry, time, value.array(), value.arrayOffset() + start, len); + } else { + throw new UnsupportedOperationException("ByteBuffer must be direct or have a backing array"); + } + } + + /** + * Sets raw topic value buffer. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Raw value buffer. + * @param start Value's offset into buffer. + * @param len Length of value in buffer. + * @return True if set succeeded. + */ + private static native boolean setRawBuffer(int entry, long time, ByteBuffer value, int start, int len); +{% else %} + /** + * Sets topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Topic value. + * @return True if set succeeded. + */ + public static native boolean set{{ t.TypeName }}(int entry, long time, {{ t.java.ValueType }} value); +{% endif %} + /** + * Returns topic value. + * + * @param entry Entry handle. + * @param defaultValue Default value. + * @return Topic value. + */ + public static native {{ t.java.ValueType }} get{{ t.TypeName }}(int entry, {{ t.java.ValueType }} defaultValue); +{% if t.TypeName == "Raw" %} + /** + * Sets default raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static boolean setDefaultRaw(int entry, long time, byte[] defaultValue) { + return setDefaultRaw(entry, time, defaultValue, 0, defaultValue.length); + } + + /** + * Sets default raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @param start Value's offset into buffer. + * @param len Length of value in buffer. + * @return True if set succeeded. + */ + public static native boolean setDefaultRaw(int entry, long time, byte[] defaultValue, int start, int len); + + /** + * Sets default raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static boolean setDefaultRaw(int entry, long time, ByteBuffer defaultValue) { + int pos = defaultValue.position(); + return setDefaultRaw(entry, time, defaultValue, pos, defaultValue.limit() - pos); + } + + /** + * Sets default raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @param start Value's offset into buffer. + * @param len Length of value in buffer. + * @return True if set succeeded. + */ + public static boolean setDefaultRaw(int entry, long time, ByteBuffer defaultValue, int start, int len) { + if (defaultValue.isDirect()) { + if (start < 0) { + throw new IndexOutOfBoundsException("start must be >= 0"); + } + if (len < 0) { + throw new IndexOutOfBoundsException("len must be >= 0"); + } + if ((start + len) > defaultValue.capacity()) { + throw new IndexOutOfBoundsException("start + len must be smaller than buffer capacity"); + } + return setDefaultRawBuffer(entry, time, defaultValue, start, len); + } else if (defaultValue.hasArray()) { + return setDefaultRaw(entry, time, defaultValue.array(), defaultValue.arrayOffset() + start, len); + } else { + throw new UnsupportedOperationException("ByteBuffer must be direct or have a backing array"); + } + } + + /** + * Sets default raw topic value buffer. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @param start Value's offset into buffer. + * @param len Length of value in buffer. + * @return True if set succeeded. + */ + private static native boolean setDefaultRawBuffer(int entry, long time, ByteBuffer defaultValue, int start, int len); +{% else %} + /** + * Sets default topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static native boolean setDefault{{ t.TypeName }}(int entry, long time, {{ t.java.ValueType }} defaultValue); +{% endif %} +{% endfor %} + /** + * Returns queued subentry values. + * + * @param subentry Subentry handle. + * @return List of queued subentry values. + */ + public static native NetworkTableValue[] readQueueValue(int subentry); + + /** + * Returns entry's NT value. + * + * @param entry Entry handle. + * @return Entry's NT value. + */ + public static native NetworkTableValue getValue(int entry); + + /** + * Sets entry flags. + * + * @param entry Entry handle. + * @param flags Entry flags. + */ + public static native void setEntryFlags(int entry, int flags); + + /** + * Returns entry flags. + * + * @param entry Entry handle. + * @return Entry flags. + */ + public static native int getEntryFlags(int entry); + + /** + * Returns topic info. + * + * @param inst NT instance handle. + * @param topic Topic handle. + * @return Topic info. + */ + public static native TopicInfo getTopicInfo(NetworkTableInstance inst, int topic); + + /** + * Creates a listener poller. + * + * @param inst NT instance handle. + * @return Listener poller handle. + */ + public static native int createListenerPoller(int inst); + + /** + * Destroys listener poller. + * + * @param poller Listener poller handle. + */ + public static native void destroyListenerPoller(int poller); + + /** + * Converts NT event kinds to mask. + * + * @param kinds Enum set of NT event kinds. + * @return NT event mask. + */ + private static int kindsToMask(EnumSet kinds) { + int mask = 0; + for (NetworkTableEvent.Kind kind : kinds) { + mask |= kind.getValue(); + } + return mask; + } + + /** + * Adds listener. + * + * @param poller Listener poller handle. + * @param prefixes Topic prefixes. + * @param kinds Enum set of NT event kinds. + * @return Listener handle. + */ + public static int addListener(int poller, String[] prefixes, EnumSet kinds) { + return addListener(poller, prefixes, kindsToMask(kinds)); + } + + /** + * Adds listener. + * + * @param poller Listener poller handle. + * @param handle Topic handle. + * @param kinds Enum set of NT event kinds. + * @return Listener handle. + */ + public static int addListener(int poller, int handle, EnumSet kinds) { + return addListener(poller, handle, kindsToMask(kinds)); + } + + /** + * Adds listener. + * + * @param poller Listener poller handle. + * @param prefixes Topic prefixes. + * @param mask NT event mask. + * @return Listener handle. + */ + public static native int addListener(int poller, String[] prefixes, int mask); + + /** + * Adds listener. + * + * @param poller Listener poller handle. + * @param handle Topic handle. + * @param mask NT event mask. + * @return Listener handle. + */ + public static native int addListener(int poller, int handle, int mask); + + /** + * Returns NT events from listener queue. + * + * @param inst NT instance handle. + * @param poller Listener poller handle. + * @return List of NT events. + */ + public static native NetworkTableEvent[] readListenerQueue( + NetworkTableInstance inst, int poller); + + /** + * Removes listener. + * + * @param listener Listener handle. + */ + public static native void removeListener(int listener); + + /** + * Returns network mode. + * + * @param inst NT instance handle. + * @return Network mode. + */ + public static native int getNetworkMode(int inst); + + /** + * Starts local-only operation. Prevents calls to startServer or startClient from taking effect. + * Has no effect if startServer or startClient has already been called. + * + * @param inst NT instance handle. + */ + public static native void startLocal(int inst); + + /** + * Stops local-only operation. startServer or startClient can be called after this call to start + * a server or client. + * + * @param inst NT instance handle. + */ + public static native void stopLocal(int inst); + + /** + * Starts a server using the specified filename, listening address, and port. + * + * @param inst NT instance handle. + * @param persistFilename the name of the persist file to use + * @param listenAddress the address to listen on, or empty to listen on any address + * @param port3 port to communicate over (NT3) + * @param port4 port to communicate over (NT4) + */ + public static native void startServer( + int inst, String persistFilename, String listenAddress, int port3, int port4); + + /** + * Stops the server if it is running. + * + * @param inst NT instance handle. + */ + public static native void stopServer(int inst); + + /** + * Starts a NT3 client. Use SetServer or SetServerTeam to set the server name and port. + * + * @param inst NT instance handle. + * @param identity network identity to advertise (cannot be empty string) + */ + public static native void startClient3(int inst, String identity); + + /** + * Starts a NT4 client. Use SetServer or SetServerTeam to set the server name and port. + * + * @param inst NT instance handle. + * @param identity network identity to advertise (cannot be empty string) + */ + public static native void startClient4(int inst, String identity); + + /** + * Stops the client if it is running. + * + * @param inst NT instance handle. + */ + public static native void stopClient(int inst); + + /** + * Sets server address and port for client (without restarting client). + * + * @param inst NT instance handle. + * @param serverName server name + * @param port port to communicate over + */ + public static native void setServer(int inst, String serverName, int port); + + /** + * Sets server addresses and ports for client (without restarting client). The client will + * attempt to connect to each server in round robin fashion. + * + * @param inst NT instance handle. + * @param serverNames array of server names + * @param ports array of port numbers (0=default) + */ + public static native void setServer(int inst, String[] serverNames, int[] ports); + + /** + * Sets server addresses and port for client (without restarting client). Connects using commonly + * known robot addresses for the specified team. + * + * @param inst NT instance handle. + * @param team team number + * @param port port to communicate over + */ + public static native void setServerTeam(int inst, int team, int port); + + /** + * Disconnects the client if it's running and connected. This will automatically start + * reconnection attempts to the current server list. + * + * @param inst NT instance handle. + */ + public static native void disconnect(int inst); + + /** + * Starts requesting server address from Driver Station. This connects to the Driver Station + * running on localhost to obtain the server IP address. + * + * @param inst NT instance handle. + * @param port server port to use in combination with IP from DS + */ + public static native void startDSClient(int inst, int port); + + /** + * Stops requesting server address from Driver Station. + * + * @param inst NT instance handle. + */ + public static native void stopDSClient(int inst); + + /** + * Flushes all updated values immediately to the local client/server. This does not flush to the + * network. + * + * @param inst NT instance handle. + */ + public static native void flushLocal(int inst); + + /** + * Flushes all updated values immediately to the network. Note: This is rate-limited to protect + * the network from flooding. This is primarily useful for synchronizing network updates with + * user code. + * + * @param inst NT instance handle. + */ + public static native void flush(int inst); + + /** + * Gets information on the currently established network connections. If operating as a client, + * this will return either zero or one values. + * + * @param inst NT instance handle. + * @return array of connection information + */ + public static native ConnectionInfo[] getConnections(int inst); + + /** + * Return whether or not the instance is connected to another node. + * + * @param inst NT instance handle. + * @return True if connected. + */ + public static native boolean isConnected(int inst); + + /** + * Get the time offset between server time and local time. Add this value to local time to get + * the estimated equivalent server time. In server mode, this always returns 0. In client mode, + * this returns the time offset only if the client and server are connected and have exchanged + * synchronization messages. Note the time offset may change over time as it is periodically + * updated; to receive updates as events, add a listener to the "time sync" event. + * + * @param inst NT instance handle. + * @return Time offset in microseconds (optional) + */ + public static native OptionalLong getServerTimeOffset(int inst); + + /** + * Returns the current timestamp in microseconds. + * + * @return The current timestsamp in microseconds. + */ + public static native long now(); + + /** + * Starts logging entry changes to a DataLog. + * + * @param inst NT instance handle. + * @param log data log handle; lifetime must extend until StopEntryDataLog is called or the + * instance is destroyed + * @param prefix only store entries with names that start with this prefix; the prefix is not + * included in the data log entry name + * @param logPrefix prefix to add to data log entry names + * @return Data logger handle + */ + private static native int startEntryDataLog(int inst, long log, String prefix, String logPrefix); + + /** + * Starts logging entry changes to a DataLog. + * + * @param inst NT instance handle. + * @param log data log object; lifetime must extend until StopEntryDataLog is called or the + * instance is destroyed + * @param prefix only store entries with names that start with this prefix; the prefix is not + * included in the data log entry name + * @param logPrefix prefix to add to data log entry names + * @return Data logger handle + */ + public static int startEntryDataLog(int inst, DataLog log, String prefix, String logPrefix) { + return startEntryDataLog(inst, log.getImpl(), prefix, logPrefix); + } + + /** + * Stops logging entry changes to a DataLog. + * + * @param logger data logger handle + */ + public static native void stopEntryDataLog(int logger); + + /** + * Starts logging connection changes to a DataLog. + * + * @param inst NT instance handle. + * @param log data log handle; lifetime must extend until StopConnectionDataLog is called or the + * instance is destroyed + * @param name data log entry name + * @return Data logger handle + */ + private static native int startConnectionDataLog(int inst, long log, String name); + + /** + * Starts logging connection changes to a DataLog. + * + * @param inst NT instance handle. + * @param log data log object; lifetime must extend until StopConnectionDataLog is called or the + * instance is destroyed + * @param name data log entry name + * @return Data logger handle + */ + public static int startConnectionDataLog(int inst, DataLog log, String name) { + return startConnectionDataLog(inst, log.getImpl(), name); + } + + /** + * Stops logging connection changes to a DataLog. + * + * @param logger data logger handle + */ + public static native void stopConnectionDataLog(int logger); + + /** + * Add logger callback function. By default, log messages are sent to stderr; this function sends + * log messages with the specified levels to the provided callback function instead. The callback + * function will only be called for log messages with level greater than or equal to minLevel and + * less than or equal to maxLevel; messages outside this range will be silently ignored. + * + * @param poller Listener poller handle. + * @param minLevel minimum log level + * @param maxLevel maximum log level + * @return Listener handle + */ + public static native int addLogger(int poller, int minLevel, int maxLevel); + + /** Utility class. */ + private NetworkTablesJNI() {} +} + diff --git a/ntcore/src/generate/java/Publisher.java.jinja b/ntcore/src/generate/main/java/Publisher.java.jinja similarity index 98% rename from ntcore/src/generate/java/Publisher.java.jinja rename to ntcore/src/generate/main/java/Publisher.java.jinja index a403d910fc3..d35c9413119 100644 --- a/ntcore/src/generate/java/Publisher.java.jinja +++ b/ntcore/src/generate/main/java/Publisher.java.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + package edu.wpi.first.networktables; {% if TypeName == "Raw" %} @@ -168,3 +170,4 @@ public interface {{ TypeName }}Publisher extends Publisher, {{ java.FunctionType set(value); } } + diff --git a/ntcore/src/generate/java/Subscriber.java.jinja b/ntcore/src/generate/main/java/Subscriber.java.jinja similarity index 97% rename from ntcore/src/generate/java/Subscriber.java.jinja rename to ntcore/src/generate/main/java/Subscriber.java.jinja index 0ea09a36e69..73e61903793 100644 --- a/ntcore/src/generate/java/Subscriber.java.jinja +++ b/ntcore/src/generate/main/java/Subscriber.java.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + package edu.wpi.first.networktables; import {{ java.SupplierFunctionPackage|default('java.util.function') }}.{{ java.FunctionTypePrefix }}Supplier; @@ -81,3 +83,4 @@ public interface {{ TypeName }}Subscriber extends Subscriber, {{ java.FunctionTy */ {{ java.ValueType }}[] readQueueValues(); } + diff --git a/ntcore/src/generate/java/Timestamped.java.jinja b/ntcore/src/generate/main/java/Timestamped.java.jinja similarity index 93% rename from ntcore/src/generate/java/Timestamped.java.jinja rename to ntcore/src/generate/main/java/Timestamped.java.jinja index 288af81b794..21e50e244fb 100644 --- a/ntcore/src/generate/java/Timestamped.java.jinja +++ b/ntcore/src/generate/main/java/Timestamped.java.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + package edu.wpi.first.networktables; /** NetworkTables timestamped {{ TypeName }}. */ @@ -38,3 +40,4 @@ public final class Timestamped{{ TypeName }} { @SuppressWarnings("MemberName") public final {{ java.ValueType }} value; } + diff --git a/ntcore/src/generate/java/Topic.java.jinja b/ntcore/src/generate/main/java/Topic.java.jinja similarity index 99% rename from ntcore/src/generate/java/Topic.java.jinja rename to ntcore/src/generate/main/java/Topic.java.jinja index e22fa3baf88..6407a4b18e5 100644 --- a/ntcore/src/generate/java/Topic.java.jinja +++ b/ntcore/src/generate/main/java/Topic.java.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + package edu.wpi.first.networktables; /** NetworkTables {{ TypeName }} topic. */ @@ -221,3 +223,4 @@ public final class {{ TypeName }}Topic extends Topic { } {% endif %} } + diff --git a/ntcore/src/generate/cpp/jni/types_jni.cpp.jinja b/ntcore/src/generate/main/native/cpp/jni/types_jni.cpp.jinja similarity index 99% rename from ntcore/src/generate/cpp/jni/types_jni.cpp.jinja rename to ntcore/src/generate/main/native/cpp/jni/types_jni.cpp.jinja index 29cf570377c..fc811f54cd5 100644 --- a/ntcore/src/generate/cpp/jni/types_jni.cpp.jinja +++ b/ntcore/src/generate/main/native/cpp/jni/types_jni.cpp.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + #include #include @@ -367,3 +369,4 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefault{{ t.TypeName }} {% endif %} {% endfor %} } // extern "C" + diff --git a/ntcore/src/generate/cpp/ntcore_c_types.cpp.jinja b/ntcore/src/generate/main/native/cpp/ntcore_c_types.cpp.jinja similarity index 75% rename from ntcore/src/generate/cpp/ntcore_c_types.cpp.jinja rename to ntcore/src/generate/main/native/cpp/ntcore_c_types.cpp.jinja index e74e5cf776c..ccfe1833ac2 100644 --- a/ntcore/src/generate/cpp/ntcore_c_types.cpp.jinja +++ b/ntcore/src/generate/main/native/cpp/ntcore_c_types.cpp.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + #include "ntcore_c_types.h" #include "Value_internal.h" @@ -14,11 +16,11 @@ static inline std::span ConvertFromC(const T* arr, size_t size) { return {arr, size}; } -static inline std::string_view ConvertFromC(const char* arr, size_t size) { - return {arr, size}; +static inline std::string_view ConvertFromC(const struct WPI_String* str) { + return wpi::to_string_view(str); } -static std::vector ConvertFromC(const NT_String* arr, size_t size) { +static std::vector ConvertFromC(const struct WPI_String* arr, size_t size) { std::vector v; v.reserve(size); for (size_t i = 0; i < size; ++i) { @@ -33,6 +35,8 @@ static void ConvertToC(const nt::Timestamped{{ t.TypeName }}& in, NT_Timestamped out->serverTime = in.serverTime; {%- if t.c.IsArray %} out->value = ConvertToC<{{ t.c.ValueType[:-1] }}>(in.value, &out->len); +{% elif t.c.ValueInline %} + ConvertToC(in.value, &out->value); {% else %} out->value = in.value; {% endif -%} @@ -44,6 +48,8 @@ extern "C" { NT_Bool NT_Set{{ t.TypeName }}(NT_Handle pubentry, int64_t time, {{ t.c.ParamType }} value{% if t.c.IsArray %}, size_t len{% endif %}) { {%- if t.c.IsArray %} return nt::Set{{ t.TypeName }}(pubentry, ConvertFromC(value, len), time); +{%- elif t.c.ValueInline %} + return nt::Set{{ t.TypeName }}(pubentry, ConvertFromC(value), time); {%- else %} return nt::Set{{ t.TypeName }}(pubentry, value, time); {%- endif %} @@ -52,11 +58,21 @@ NT_Bool NT_Set{{ t.TypeName }}(NT_Handle pubentry, int64_t time, {{ t.c.ParamTyp NT_Bool NT_SetDefault{{ t.TypeName }}(NT_Handle pubentry, {{ t.c.ParamType }} defaultValue{% if t.c.IsArray %}, size_t defaultValueLen{% endif %}) { {%- if t.c.IsArray %} return nt::SetDefault{{ t.TypeName }}(pubentry, ConvertFromC(defaultValue, defaultValueLen)); +{%- elif t.c.ValueInline %} + return nt::SetDefault{{ t.TypeName }}(pubentry, ConvertFromC(defaultValue)); {%- else %} return nt::SetDefault{{ t.TypeName }}(pubentry, defaultValue); {%- endif %} } +{%- if t.c.ValueInline %} + +void NT_Get{{ t.TypeName }}(NT_Handle subentry, {{ t.c.ParamType }} defaultValue, {{ t.c.ValueType }} value) { + auto cppValue = nt::Get{{ t.TypeName }}(subentry, ConvertFromC(defaultValue)); + ConvertToC(cppValue, value); +} +{%- else %} + {{ t.c.ValueType }} NT_Get{{ t.TypeName }}(NT_Handle subentry, {{ t.c.ParamType }} defaultValue{% if t.c.IsArray %}, size_t defaultValueLen, size_t* len{% endif %}) { {%- if t.c.IsArray %} auto cppValue = nt::Get{{ t.TypeName }}(subentry, ConvertFromC(defaultValue, defaultValueLen)); @@ -65,10 +81,13 @@ NT_Bool NT_SetDefault{{ t.TypeName }}(NT_Handle pubentry, {{ t.c.ParamType }} de return nt::Get{{ t.TypeName }}(subentry, defaultValue); {%- endif %} } +{%- endif %} void NT_GetAtomic{{ t.TypeName }}(NT_Handle subentry, {{ t.c.ParamType }} defaultValue{% if t.c.IsArray %}, size_t defaultValueLen{% endif %}, struct NT_Timestamped{{ t.TypeName }}* value) { {%- if t.c.IsArray %} auto cppValue = nt::GetAtomic{{ t.TypeName }}(subentry, ConvertFromC(defaultValue, defaultValueLen)); +{%- elif t.c.ValueInline %} + auto cppValue = nt::GetAtomic{{ t.TypeName }}(subentry, ConvertFromC(defaultValue)); {%- else %} auto cppValue = nt::GetAtomic{{ t.TypeName }}(subentry, defaultValue); {%- endif %} @@ -77,7 +96,9 @@ void NT_GetAtomic{{ t.TypeName }}(NT_Handle subentry, {{ t.c.ParamType }} defaul void NT_DisposeTimestamped{{ t.TypeName }}(struct NT_Timestamped{{ t.TypeName }}* value) { {%- if t.TypeName == "StringArray" %} - NT_FreeStringArray(value->value, value->len); + WPI_FreeStringArray(value->value, value->len); +{%- elif t.TypeName == "String" %} + WPI_FreeString(&value->value); {%- elif t.c.IsArray %} std::free(value->value); {%- endif %} @@ -95,7 +116,7 @@ void NT_FreeQueue{{ t.TypeName }}(struct NT_Timestamped{{ t.TypeName }}* arr, si std::free(arr); } -{%- if not t.c.IsArray %} +{%- if not t.c.IsArray and not t.c.ValueInline %} {{ t.c.ValueType }}* NT_ReadQueueValues{{ t.TypeName }}(NT_Handle subentry, size_t* len) { auto arr = nt::ReadQueueValues{{ t.TypeName }}(subentry); return ConvertToC<{{ t.c.ValueType }}>(arr, len); @@ -104,3 +125,4 @@ void NT_FreeQueue{{ t.TypeName }}(struct NT_Timestamped{{ t.TypeName }}* arr, si {% endfor %} } // extern "C" + diff --git a/ntcore/src/generate/cpp/ntcore_cpp_types.cpp.jinja b/ntcore/src/generate/main/native/cpp/ntcore_cpp_types.cpp.jinja similarity index 98% rename from ntcore/src/generate/cpp/ntcore_cpp_types.cpp.jinja rename to ntcore/src/generate/main/native/cpp/ntcore_cpp_types.cpp.jinja index cdaf27fb6ef..d9501f899a3 100644 --- a/ntcore/src/generate/cpp/ntcore_cpp_types.cpp.jinja +++ b/ntcore/src/generate/main/native/cpp/ntcore_cpp_types.cpp.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + #include "ntcore_cpp_types.h" #include "Handle.h" @@ -129,3 +131,4 @@ Timestamped{{ t.TypeName }}View GetAtomic{{ t.TypeName }}( {% endif %} {% endfor %} } // namespace nt + diff --git a/ntcore/src/generate/include/networktables/Topic.h.jinja b/ntcore/src/generate/main/native/include/networktables/Topic.h.jinja similarity index 99% rename from ntcore/src/generate/include/networktables/Topic.h.jinja rename to ntcore/src/generate/main/native/include/networktables/Topic.h.jinja index ec2a915ee6f..93abc498713 100644 --- a/ntcore/src/generate/include/networktables/Topic.h.jinja +++ b/ntcore/src/generate/main/native/include/networktables/Topic.h.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + #pragma once #include @@ -435,3 +437,4 @@ class {{ TypeName }}Topic final : public Topic { } // namespace nt #include "networktables/{{ TypeName }}Topic.inc" + diff --git a/ntcore/src/generate/include/networktables/Topic.inc.jinja b/ntcore/src/generate/main/native/include/networktables/Topic.inc.jinja similarity index 98% rename from ntcore/src/generate/include/networktables/Topic.inc.jinja rename to ntcore/src/generate/main/native/include/networktables/Topic.inc.jinja index 4e7a167d67c..ce343d99fe1 100644 --- a/ntcore/src/generate/include/networktables/Topic.inc.jinja +++ b/ntcore/src/generate/main/native/include/networktables/Topic.inc.jinja @@ -2,8 +2,12 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + #pragma once +#include + #include "networktables/{{ TypeName }}Topic.h" #include "networktables/NetworkTableType.h" #include "ntcore_cpp.h" @@ -133,3 +137,4 @@ inline {{ TypeName }}Entry {{ TypeName }}Topic::GetEntryEx( } {% endif %} } // namespace nt + diff --git a/ntcore/src/generate/include/ntcore_c_types.h.jinja b/ntcore/src/generate/main/native/include/ntcore_c_types.h.jinja similarity index 89% rename from ntcore/src/generate/include/ntcore_c_types.h.jinja rename to ntcore/src/generate/main/native/include/ntcore_c_types.h.jinja index 83cc8073531..93359ffce52 100644 --- a/ntcore/src/generate/include/ntcore_c_types.h.jinja +++ b/ntcore/src/generate/main/native/include/ntcore_c_types.h.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + #pragma once #include @@ -31,7 +33,11 @@ struct NT_Timestamped{{ t.TypeName }} { /** * Value. */ +{%- if t.c.ValueInline %} + {{ t.c.ValueInline }} value; +{%- else %} {{ t.c.ValueType }} value; +{%- endif %} {%- if t.c.IsArray %} /** * Value length. @@ -77,13 +83,22 @@ NT_Bool NT_SetDefault{{ t.TypeName }}(NT_Handle pubentry, {{ t.c.ParamType }} de * * @param subentry subscriber or entry handle * @param defaultValue default value to return if no value has been published +{%- if t.c.ValueInline %} + * @param value returned value (output) +{% endif %} {%- if t.c.IsArray %} * @param defaultValueLen length of default value * @param len length of returned value (output) {% endif %} +{%- if not t.c.ValueInline %} * @return value +{%- endif %} */ +{%- if t.c.ValueInline %} +void NT_Get{{ t.TypeName }}(NT_Handle subentry, {{ t.c.ParamType }} defaultValue, {{ t.c.ValueType }} value); +{%- else %} {{ t.c.ValueType }} NT_Get{{ t.TypeName }}(NT_Handle subentry, {{ t.c.ParamType }} defaultValue{% if t.c.IsArray %}, size_t defaultValueLen, size_t* len{% endif %}); +{%- endif %} /** * Get the last published value along with its timestamp. @@ -128,7 +143,7 @@ struct NT_Timestamped{{ t.TypeName }}* NT_ReadQueue{{ t.TypeName }}(NT_Handle su */ void NT_FreeQueue{{ t.TypeName }}(struct NT_Timestamped{{ t.TypeName }}* arr, size_t len); -{%- if not t.c.IsArray %} +{%- if not t.c.IsArray and not t.c.ValueInline %} /** * Get an array of all value changes since the last call to ReadQueue. * @@ -149,3 +164,4 @@ void NT_FreeQueue{{ t.TypeName }}(struct NT_Timestamped{{ t.TypeName }}* arr, si #ifdef __cplusplus } // extern "C" #endif + diff --git a/ntcore/src/generate/include/ntcore_cpp_types.h.jinja b/ntcore/src/generate/main/native/include/ntcore_cpp_types.h.jinja similarity index 98% rename from ntcore/src/generate/include/ntcore_cpp_types.h.jinja rename to ntcore/src/generate/main/native/include/ntcore_cpp_types.h.jinja index df919de05aa..941414d671d 100644 --- a/ntcore/src/generate/include/ntcore_cpp_types.h.jinja +++ b/ntcore/src/generate/main/native/include/ntcore_cpp_types.h.jinja @@ -2,6 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + #pragma once #include @@ -139,3 +141,4 @@ Timestamped{{ t.TypeName }}View GetAtomic{{ t.TypeName }}( /** @} */ {% endfor %} } // namespace nt + diff --git a/ntcore/src/generate/types.json b/ntcore/src/generate/types.json index 3f9f252d54c..1ce48d950db 100644 --- a/ntcore/src/generate/types.json +++ b/ntcore/src/generate/types.json @@ -133,9 +133,9 @@ "TypeName": "String", "TypeString": "\"string\"", "c": { - "ValueType": "char*", - "ParamType": "const char*", - "IsArray": true + "ValueType": "struct WPI_String*", + "ParamType": "const struct WPI_String*", + "ValueInline": "struct WPI_String" }, "cpp": { "ValueType": "std::string", @@ -345,8 +345,8 @@ "TypeName": "StringArray", "TypeString": "\"string[]\"", "c": { - "ValueType": "struct NT_String*", - "ParamType": "const struct NT_String*", + "ValueType": "struct WPI_String*", + "ParamType": "const struct WPI_String*", "IsArray": true }, "cpp": { diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArrayEntry.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArrayEntry.java new file mode 100644 index 00000000000..bcc72e06c31 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArrayEntry.java @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** + * NetworkTables BooleanArray entry. + * + *

Unlike NetworkTableEntry, the entry goes away when close() is called. + */ +public interface BooleanArrayEntry extends BooleanArraySubscriber, BooleanArrayPublisher { + /** Stops publishing the entry if it's published. */ + void unpublish(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArrayEntryImpl.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArrayEntryImpl.java new file mode 100644 index 00000000000..40e455ccac6 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArrayEntryImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables BooleanArray implementation. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +final class BooleanArrayEntryImpl extends EntryBase implements BooleanArrayEntry { + /** + * Constructor. + * + * @param topic Topic + * @param handle Native handle + * @param defaultValue Default value for get() + */ + BooleanArrayEntryImpl(BooleanArrayTopic topic, int handle, boolean[] defaultValue) { + super(handle); + m_topic = topic; + m_defaultValue = defaultValue; + } + + @Override + public BooleanArrayTopic getTopic() { + return m_topic; + } + + @Override + public boolean[] get() { + return NetworkTablesJNI.getBooleanArray(m_handle, m_defaultValue); + } + + @Override + public boolean[] get(boolean[] defaultValue) { + return NetworkTablesJNI.getBooleanArray(m_handle, defaultValue); + } + + @Override + public TimestampedBooleanArray getAtomic() { + return NetworkTablesJNI.getAtomicBooleanArray(m_handle, m_defaultValue); + } + + @Override + public TimestampedBooleanArray getAtomic(boolean[] defaultValue) { + return NetworkTablesJNI.getAtomicBooleanArray(m_handle, defaultValue); + } + + @Override + public TimestampedBooleanArray[] readQueue() { + return NetworkTablesJNI.readQueueBooleanArray(m_handle); + } + + @Override + public boolean[][] readQueueValues() { + return NetworkTablesJNI.readQueueValuesBooleanArray(m_handle); + } + + @Override + public void set(boolean[] value, long time) { + NetworkTablesJNI.setBooleanArray(m_handle, time, value); + } + + @Override + public void setDefault(boolean[] value) { + NetworkTablesJNI.setDefaultBooleanArray(m_handle, 0, value); + } + + @Override + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + private final BooleanArrayTopic m_topic; + private final boolean[] m_defaultValue; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArrayPublisher.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArrayPublisher.java new file mode 100644 index 00000000000..3e40bdbb925 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArrayPublisher.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Consumer; + +/** NetworkTables BooleanArray publisher. */ +public interface BooleanArrayPublisher extends Publisher, Consumer { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + BooleanArrayTopic getTopic(); + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + */ + default void set(boolean[] value) { + set(value, 0); + } + + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void set(boolean[] value, long time); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void setDefault(boolean[] value); + + @Override + default void accept(boolean[] value) { + set(value); + } +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArraySubscriber.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArraySubscriber.java new file mode 100644 index 00000000000..ff071198405 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArraySubscriber.java @@ -0,0 +1,80 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Supplier; + +/** NetworkTables BooleanArray subscriber. */ +@SuppressWarnings("PMD.MissingOverride") +public interface BooleanArraySubscriber extends Subscriber, Supplier { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + BooleanArrayTopic getTopic(); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + boolean[] get(); + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + boolean[] get(boolean[] defaultValue); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedBooleanArray getAtomic(); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedBooleanArray getAtomic(boolean[] defaultValue); + + /** + * Get an array of all value changes since the last call to readQueue. + * Also provides a timestamp for each value. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + TimestampedBooleanArray[] readQueue(); + + /** + * Get an array of all value changes since the last call to readQueue. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of values; empty array if no new changes have been + * published since the previous call. + */ + boolean[][] readQueueValues(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArrayTopic.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArrayTopic.java new file mode 100644 index 00000000000..7d18f312875 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanArrayTopic.java @@ -0,0 +1,206 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables BooleanArray topic. */ +public final class BooleanArrayTopic extends Topic { + /** The default type string for this topic type. */ + public static final String kTypeString = "boolean[]"; + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + public BooleanArrayTopic(Topic topic) { + super(topic.m_inst, topic.m_handle); + } + + /** + * Constructor; use NetworkTableInstance.getBooleanArrayTopic() instead. + * + * @param inst Instance + * @param handle Native handle + */ + public BooleanArrayTopic(NetworkTableInstance inst, int handle) { + super(inst, handle); + } + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public BooleanArraySubscriber subscribe( + boolean[] defaultValue, + PubSubOption... options) { + return new BooleanArrayEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kBooleanArray.getValue(), + "boolean[]", options), + defaultValue); + } + + /** + * Create a new subscriber to the topic, with specified type string. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public BooleanArraySubscriber subscribeEx( + String typeString, + boolean[] defaultValue, + PubSubOption... options) { + return new BooleanArrayEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kBooleanArray.getValue(), + typeString, options), + defaultValue); + } + + /** + * Create a new publisher to the topic. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + public BooleanArrayPublisher publish( + PubSubOption... options) { + return new BooleanArrayEntryImpl( + this, + NetworkTablesJNI.publish( + m_handle, NetworkTableType.kBooleanArray.getValue(), + "boolean[]", options), + new boolean[] {}); + } + + /** + * Create a new publisher to the topic, with type string and initial properties. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + * @throws IllegalArgumentException if properties is not a JSON object + */ + public BooleanArrayPublisher publishEx( + String typeString, + String properties, + PubSubOption... options) { + return new BooleanArrayEntryImpl( + this, + NetworkTablesJNI.publishEx( + m_handle, NetworkTableType.kBooleanArray.getValue(), + typeString, properties, options), + new boolean[] {}); + } + + /** + * Create a new entry for the topic. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public BooleanArrayEntry getEntry( + boolean[] defaultValue, + PubSubOption... options) { + return new BooleanArrayEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kBooleanArray.getValue(), + "boolean[]", options), + defaultValue); + } + + /** + * Create a new entry for the topic, with specified type string. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public BooleanArrayEntry getEntryEx( + String typeString, + boolean[] defaultValue, + PubSubOption... options) { + return new BooleanArrayEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kBooleanArray.getValue(), + typeString, options), + defaultValue); + } + +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanEntry.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanEntry.java new file mode 100644 index 00000000000..1821c06a381 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanEntry.java @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** + * NetworkTables Boolean entry. + * + *

Unlike NetworkTableEntry, the entry goes away when close() is called. + */ +public interface BooleanEntry extends BooleanSubscriber, BooleanPublisher { + /** Stops publishing the entry if it's published. */ + void unpublish(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanEntryImpl.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanEntryImpl.java new file mode 100644 index 00000000000..f099afc0da8 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanEntryImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables Boolean implementation. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +final class BooleanEntryImpl extends EntryBase implements BooleanEntry { + /** + * Constructor. + * + * @param topic Topic + * @param handle Native handle + * @param defaultValue Default value for get() + */ + BooleanEntryImpl(BooleanTopic topic, int handle, boolean defaultValue) { + super(handle); + m_topic = topic; + m_defaultValue = defaultValue; + } + + @Override + public BooleanTopic getTopic() { + return m_topic; + } + + @Override + public boolean get() { + return NetworkTablesJNI.getBoolean(m_handle, m_defaultValue); + } + + @Override + public boolean get(boolean defaultValue) { + return NetworkTablesJNI.getBoolean(m_handle, defaultValue); + } + + @Override + public TimestampedBoolean getAtomic() { + return NetworkTablesJNI.getAtomicBoolean(m_handle, m_defaultValue); + } + + @Override + public TimestampedBoolean getAtomic(boolean defaultValue) { + return NetworkTablesJNI.getAtomicBoolean(m_handle, defaultValue); + } + + @Override + public TimestampedBoolean[] readQueue() { + return NetworkTablesJNI.readQueueBoolean(m_handle); + } + + @Override + public boolean[] readQueueValues() { + return NetworkTablesJNI.readQueueValuesBoolean(m_handle); + } + + @Override + public void set(boolean value, long time) { + NetworkTablesJNI.setBoolean(m_handle, time, value); + } + + @Override + public void setDefault(boolean value) { + NetworkTablesJNI.setDefaultBoolean(m_handle, 0, value); + } + + @Override + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + private final BooleanTopic m_topic; + private final boolean m_defaultValue; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanPublisher.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanPublisher.java new file mode 100644 index 00000000000..1254ff333d4 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanPublisher.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import edu.wpi.first.util.function.BooleanConsumer; + +/** NetworkTables Boolean publisher. */ +public interface BooleanPublisher extends Publisher, BooleanConsumer { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + BooleanTopic getTopic(); + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + */ + default void set(boolean value) { + set(value, 0); + } + + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void set(boolean value, long time); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void setDefault(boolean value); + + @Override + default void accept(boolean value) { + set(value); + } +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanSubscriber.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanSubscriber.java new file mode 100644 index 00000000000..7f54f4b3fdb --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanSubscriber.java @@ -0,0 +1,85 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.BooleanSupplier; + +/** NetworkTables Boolean subscriber. */ +@SuppressWarnings("PMD.MissingOverride") +public interface BooleanSubscriber extends Subscriber, BooleanSupplier { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + BooleanTopic getTopic(); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + boolean get(); + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + boolean get(boolean defaultValue); + + @Override + default boolean getAsBoolean() { + return get(); + } + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedBoolean getAtomic(); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedBoolean getAtomic(boolean defaultValue); + + /** + * Get an array of all value changes since the last call to readQueue. + * Also provides a timestamp for each value. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + TimestampedBoolean[] readQueue(); + + /** + * Get an array of all value changes since the last call to readQueue. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of values; empty array if no new changes have been + * published since the previous call. + */ + boolean[] readQueueValues(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanTopic.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanTopic.java new file mode 100644 index 00000000000..8ac03473e77 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/BooleanTopic.java @@ -0,0 +1,206 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables Boolean topic. */ +public final class BooleanTopic extends Topic { + /** The default type string for this topic type. */ + public static final String kTypeString = "boolean"; + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + public BooleanTopic(Topic topic) { + super(topic.m_inst, topic.m_handle); + } + + /** + * Constructor; use NetworkTableInstance.getBooleanTopic() instead. + * + * @param inst Instance + * @param handle Native handle + */ + public BooleanTopic(NetworkTableInstance inst, int handle) { + super(inst, handle); + } + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public BooleanSubscriber subscribe( + boolean defaultValue, + PubSubOption... options) { + return new BooleanEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kBoolean.getValue(), + "boolean", options), + defaultValue); + } + + /** + * Create a new subscriber to the topic, with specified type string. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public BooleanSubscriber subscribeEx( + String typeString, + boolean defaultValue, + PubSubOption... options) { + return new BooleanEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kBoolean.getValue(), + typeString, options), + defaultValue); + } + + /** + * Create a new publisher to the topic. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + public BooleanPublisher publish( + PubSubOption... options) { + return new BooleanEntryImpl( + this, + NetworkTablesJNI.publish( + m_handle, NetworkTableType.kBoolean.getValue(), + "boolean", options), + false); + } + + /** + * Create a new publisher to the topic, with type string and initial properties. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + * @throws IllegalArgumentException if properties is not a JSON object + */ + public BooleanPublisher publishEx( + String typeString, + String properties, + PubSubOption... options) { + return new BooleanEntryImpl( + this, + NetworkTablesJNI.publishEx( + m_handle, NetworkTableType.kBoolean.getValue(), + typeString, properties, options), + false); + } + + /** + * Create a new entry for the topic. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public BooleanEntry getEntry( + boolean defaultValue, + PubSubOption... options) { + return new BooleanEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kBoolean.getValue(), + "boolean", options), + defaultValue); + } + + /** + * Create a new entry for the topic, with specified type string. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public BooleanEntry getEntryEx( + String typeString, + boolean defaultValue, + PubSubOption... options) { + return new BooleanEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kBoolean.getValue(), + typeString, options), + defaultValue); + } + +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArrayEntry.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArrayEntry.java new file mode 100644 index 00000000000..8a40d8bd32e --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArrayEntry.java @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** + * NetworkTables DoubleArray entry. + * + *

Unlike NetworkTableEntry, the entry goes away when close() is called. + */ +public interface DoubleArrayEntry extends DoubleArraySubscriber, DoubleArrayPublisher { + /** Stops publishing the entry if it's published. */ + void unpublish(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArrayEntryImpl.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArrayEntryImpl.java new file mode 100644 index 00000000000..7bb270ac37e --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArrayEntryImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables DoubleArray implementation. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +final class DoubleArrayEntryImpl extends EntryBase implements DoubleArrayEntry { + /** + * Constructor. + * + * @param topic Topic + * @param handle Native handle + * @param defaultValue Default value for get() + */ + DoubleArrayEntryImpl(DoubleArrayTopic topic, int handle, double[] defaultValue) { + super(handle); + m_topic = topic; + m_defaultValue = defaultValue; + } + + @Override + public DoubleArrayTopic getTopic() { + return m_topic; + } + + @Override + public double[] get() { + return NetworkTablesJNI.getDoubleArray(m_handle, m_defaultValue); + } + + @Override + public double[] get(double[] defaultValue) { + return NetworkTablesJNI.getDoubleArray(m_handle, defaultValue); + } + + @Override + public TimestampedDoubleArray getAtomic() { + return NetworkTablesJNI.getAtomicDoubleArray(m_handle, m_defaultValue); + } + + @Override + public TimestampedDoubleArray getAtomic(double[] defaultValue) { + return NetworkTablesJNI.getAtomicDoubleArray(m_handle, defaultValue); + } + + @Override + public TimestampedDoubleArray[] readQueue() { + return NetworkTablesJNI.readQueueDoubleArray(m_handle); + } + + @Override + public double[][] readQueueValues() { + return NetworkTablesJNI.readQueueValuesDoubleArray(m_handle); + } + + @Override + public void set(double[] value, long time) { + NetworkTablesJNI.setDoubleArray(m_handle, time, value); + } + + @Override + public void setDefault(double[] value) { + NetworkTablesJNI.setDefaultDoubleArray(m_handle, 0, value); + } + + @Override + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + private final DoubleArrayTopic m_topic; + private final double[] m_defaultValue; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArrayPublisher.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArrayPublisher.java new file mode 100644 index 00000000000..39b367a88d0 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArrayPublisher.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Consumer; + +/** NetworkTables DoubleArray publisher. */ +public interface DoubleArrayPublisher extends Publisher, Consumer { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + DoubleArrayTopic getTopic(); + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + */ + default void set(double[] value) { + set(value, 0); + } + + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void set(double[] value, long time); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void setDefault(double[] value); + + @Override + default void accept(double[] value) { + set(value); + } +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArraySubscriber.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArraySubscriber.java new file mode 100644 index 00000000000..a807d66efc0 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArraySubscriber.java @@ -0,0 +1,80 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Supplier; + +/** NetworkTables DoubleArray subscriber. */ +@SuppressWarnings("PMD.MissingOverride") +public interface DoubleArraySubscriber extends Subscriber, Supplier { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + DoubleArrayTopic getTopic(); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + double[] get(); + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + double[] get(double[] defaultValue); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedDoubleArray getAtomic(); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedDoubleArray getAtomic(double[] defaultValue); + + /** + * Get an array of all value changes since the last call to readQueue. + * Also provides a timestamp for each value. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + TimestampedDoubleArray[] readQueue(); + + /** + * Get an array of all value changes since the last call to readQueue. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of values; empty array if no new changes have been + * published since the previous call. + */ + double[][] readQueueValues(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArrayTopic.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArrayTopic.java new file mode 100644 index 00000000000..f0128697e02 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleArrayTopic.java @@ -0,0 +1,206 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables DoubleArray topic. */ +public final class DoubleArrayTopic extends Topic { + /** The default type string for this topic type. */ + public static final String kTypeString = "double[]"; + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + public DoubleArrayTopic(Topic topic) { + super(topic.m_inst, topic.m_handle); + } + + /** + * Constructor; use NetworkTableInstance.getDoubleArrayTopic() instead. + * + * @param inst Instance + * @param handle Native handle + */ + public DoubleArrayTopic(NetworkTableInstance inst, int handle) { + super(inst, handle); + } + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public DoubleArraySubscriber subscribe( + double[] defaultValue, + PubSubOption... options) { + return new DoubleArrayEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kDoubleArray.getValue(), + "double[]", options), + defaultValue); + } + + /** + * Create a new subscriber to the topic, with specified type string. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public DoubleArraySubscriber subscribeEx( + String typeString, + double[] defaultValue, + PubSubOption... options) { + return new DoubleArrayEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kDoubleArray.getValue(), + typeString, options), + defaultValue); + } + + /** + * Create a new publisher to the topic. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + public DoubleArrayPublisher publish( + PubSubOption... options) { + return new DoubleArrayEntryImpl( + this, + NetworkTablesJNI.publish( + m_handle, NetworkTableType.kDoubleArray.getValue(), + "double[]", options), + new double[] {}); + } + + /** + * Create a new publisher to the topic, with type string and initial properties. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + * @throws IllegalArgumentException if properties is not a JSON object + */ + public DoubleArrayPublisher publishEx( + String typeString, + String properties, + PubSubOption... options) { + return new DoubleArrayEntryImpl( + this, + NetworkTablesJNI.publishEx( + m_handle, NetworkTableType.kDoubleArray.getValue(), + typeString, properties, options), + new double[] {}); + } + + /** + * Create a new entry for the topic. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public DoubleArrayEntry getEntry( + double[] defaultValue, + PubSubOption... options) { + return new DoubleArrayEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kDoubleArray.getValue(), + "double[]", options), + defaultValue); + } + + /** + * Create a new entry for the topic, with specified type string. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public DoubleArrayEntry getEntryEx( + String typeString, + double[] defaultValue, + PubSubOption... options) { + return new DoubleArrayEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kDoubleArray.getValue(), + typeString, options), + defaultValue); + } + +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleEntry.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleEntry.java new file mode 100644 index 00000000000..b91e3243d30 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleEntry.java @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** + * NetworkTables Double entry. + * + *

Unlike NetworkTableEntry, the entry goes away when close() is called. + */ +public interface DoubleEntry extends DoubleSubscriber, DoublePublisher { + /** Stops publishing the entry if it's published. */ + void unpublish(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleEntryImpl.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleEntryImpl.java new file mode 100644 index 00000000000..968686d502f --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleEntryImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables Double implementation. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +final class DoubleEntryImpl extends EntryBase implements DoubleEntry { + /** + * Constructor. + * + * @param topic Topic + * @param handle Native handle + * @param defaultValue Default value for get() + */ + DoubleEntryImpl(DoubleTopic topic, int handle, double defaultValue) { + super(handle); + m_topic = topic; + m_defaultValue = defaultValue; + } + + @Override + public DoubleTopic getTopic() { + return m_topic; + } + + @Override + public double get() { + return NetworkTablesJNI.getDouble(m_handle, m_defaultValue); + } + + @Override + public double get(double defaultValue) { + return NetworkTablesJNI.getDouble(m_handle, defaultValue); + } + + @Override + public TimestampedDouble getAtomic() { + return NetworkTablesJNI.getAtomicDouble(m_handle, m_defaultValue); + } + + @Override + public TimestampedDouble getAtomic(double defaultValue) { + return NetworkTablesJNI.getAtomicDouble(m_handle, defaultValue); + } + + @Override + public TimestampedDouble[] readQueue() { + return NetworkTablesJNI.readQueueDouble(m_handle); + } + + @Override + public double[] readQueueValues() { + return NetworkTablesJNI.readQueueValuesDouble(m_handle); + } + + @Override + public void set(double value, long time) { + NetworkTablesJNI.setDouble(m_handle, time, value); + } + + @Override + public void setDefault(double value) { + NetworkTablesJNI.setDefaultDouble(m_handle, 0, value); + } + + @Override + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + private final DoubleTopic m_topic; + private final double m_defaultValue; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoublePublisher.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoublePublisher.java new file mode 100644 index 00000000000..d47792118d8 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoublePublisher.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.DoubleConsumer; + +/** NetworkTables Double publisher. */ +public interface DoublePublisher extends Publisher, DoubleConsumer { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + DoubleTopic getTopic(); + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + */ + default void set(double value) { + set(value, 0); + } + + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void set(double value, long time); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void setDefault(double value); + + @Override + default void accept(double value) { + set(value); + } +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleSubscriber.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleSubscriber.java new file mode 100644 index 00000000000..688f6eaed79 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleSubscriber.java @@ -0,0 +1,85 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.DoubleSupplier; + +/** NetworkTables Double subscriber. */ +@SuppressWarnings("PMD.MissingOverride") +public interface DoubleSubscriber extends Subscriber, DoubleSupplier { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + DoubleTopic getTopic(); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + double get(); + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + double get(double defaultValue); + + @Override + default double getAsDouble() { + return get(); + } + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedDouble getAtomic(); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedDouble getAtomic(double defaultValue); + + /** + * Get an array of all value changes since the last call to readQueue. + * Also provides a timestamp for each value. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + TimestampedDouble[] readQueue(); + + /** + * Get an array of all value changes since the last call to readQueue. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of values; empty array if no new changes have been + * published since the previous call. + */ + double[] readQueueValues(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleTopic.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleTopic.java new file mode 100644 index 00000000000..2456841eaab --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/DoubleTopic.java @@ -0,0 +1,206 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables Double topic. */ +public final class DoubleTopic extends Topic { + /** The default type string for this topic type. */ + public static final String kTypeString = "double"; + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + public DoubleTopic(Topic topic) { + super(topic.m_inst, topic.m_handle); + } + + /** + * Constructor; use NetworkTableInstance.getDoubleTopic() instead. + * + * @param inst Instance + * @param handle Native handle + */ + public DoubleTopic(NetworkTableInstance inst, int handle) { + super(inst, handle); + } + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public DoubleSubscriber subscribe( + double defaultValue, + PubSubOption... options) { + return new DoubleEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kDouble.getValue(), + "double", options), + defaultValue); + } + + /** + * Create a new subscriber to the topic, with specified type string. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public DoubleSubscriber subscribeEx( + String typeString, + double defaultValue, + PubSubOption... options) { + return new DoubleEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kDouble.getValue(), + typeString, options), + defaultValue); + } + + /** + * Create a new publisher to the topic. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + public DoublePublisher publish( + PubSubOption... options) { + return new DoubleEntryImpl( + this, + NetworkTablesJNI.publish( + m_handle, NetworkTableType.kDouble.getValue(), + "double", options), + 0); + } + + /** + * Create a new publisher to the topic, with type string and initial properties. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + * @throws IllegalArgumentException if properties is not a JSON object + */ + public DoublePublisher publishEx( + String typeString, + String properties, + PubSubOption... options) { + return new DoubleEntryImpl( + this, + NetworkTablesJNI.publishEx( + m_handle, NetworkTableType.kDouble.getValue(), + typeString, properties, options), + 0); + } + + /** + * Create a new entry for the topic. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public DoubleEntry getEntry( + double defaultValue, + PubSubOption... options) { + return new DoubleEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kDouble.getValue(), + "double", options), + defaultValue); + } + + /** + * Create a new entry for the topic, with specified type string. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public DoubleEntry getEntryEx( + String typeString, + double defaultValue, + PubSubOption... options) { + return new DoubleEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kDouble.getValue(), + typeString, options), + defaultValue); + } + +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArrayEntry.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArrayEntry.java new file mode 100644 index 00000000000..b4cd353fea4 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArrayEntry.java @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** + * NetworkTables FloatArray entry. + * + *

Unlike NetworkTableEntry, the entry goes away when close() is called. + */ +public interface FloatArrayEntry extends FloatArraySubscriber, FloatArrayPublisher { + /** Stops publishing the entry if it's published. */ + void unpublish(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArrayEntryImpl.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArrayEntryImpl.java new file mode 100644 index 00000000000..1afe83728b1 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArrayEntryImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables FloatArray implementation. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +final class FloatArrayEntryImpl extends EntryBase implements FloatArrayEntry { + /** + * Constructor. + * + * @param topic Topic + * @param handle Native handle + * @param defaultValue Default value for get() + */ + FloatArrayEntryImpl(FloatArrayTopic topic, int handle, float[] defaultValue) { + super(handle); + m_topic = topic; + m_defaultValue = defaultValue; + } + + @Override + public FloatArrayTopic getTopic() { + return m_topic; + } + + @Override + public float[] get() { + return NetworkTablesJNI.getFloatArray(m_handle, m_defaultValue); + } + + @Override + public float[] get(float[] defaultValue) { + return NetworkTablesJNI.getFloatArray(m_handle, defaultValue); + } + + @Override + public TimestampedFloatArray getAtomic() { + return NetworkTablesJNI.getAtomicFloatArray(m_handle, m_defaultValue); + } + + @Override + public TimestampedFloatArray getAtomic(float[] defaultValue) { + return NetworkTablesJNI.getAtomicFloatArray(m_handle, defaultValue); + } + + @Override + public TimestampedFloatArray[] readQueue() { + return NetworkTablesJNI.readQueueFloatArray(m_handle); + } + + @Override + public float[][] readQueueValues() { + return NetworkTablesJNI.readQueueValuesFloatArray(m_handle); + } + + @Override + public void set(float[] value, long time) { + NetworkTablesJNI.setFloatArray(m_handle, time, value); + } + + @Override + public void setDefault(float[] value) { + NetworkTablesJNI.setDefaultFloatArray(m_handle, 0, value); + } + + @Override + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + private final FloatArrayTopic m_topic; + private final float[] m_defaultValue; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArrayPublisher.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArrayPublisher.java new file mode 100644 index 00000000000..afaf9f27214 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArrayPublisher.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Consumer; + +/** NetworkTables FloatArray publisher. */ +public interface FloatArrayPublisher extends Publisher, Consumer { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + FloatArrayTopic getTopic(); + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + */ + default void set(float[] value) { + set(value, 0); + } + + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void set(float[] value, long time); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void setDefault(float[] value); + + @Override + default void accept(float[] value) { + set(value); + } +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArraySubscriber.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArraySubscriber.java new file mode 100644 index 00000000000..b70bece391f --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArraySubscriber.java @@ -0,0 +1,80 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Supplier; + +/** NetworkTables FloatArray subscriber. */ +@SuppressWarnings("PMD.MissingOverride") +public interface FloatArraySubscriber extends Subscriber, Supplier { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + FloatArrayTopic getTopic(); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + float[] get(); + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + float[] get(float[] defaultValue); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedFloatArray getAtomic(); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedFloatArray getAtomic(float[] defaultValue); + + /** + * Get an array of all value changes since the last call to readQueue. + * Also provides a timestamp for each value. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + TimestampedFloatArray[] readQueue(); + + /** + * Get an array of all value changes since the last call to readQueue. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of values; empty array if no new changes have been + * published since the previous call. + */ + float[][] readQueueValues(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArrayTopic.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArrayTopic.java new file mode 100644 index 00000000000..e20ea7ffd2c --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatArrayTopic.java @@ -0,0 +1,206 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables FloatArray topic. */ +public final class FloatArrayTopic extends Topic { + /** The default type string for this topic type. */ + public static final String kTypeString = "float[]"; + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + public FloatArrayTopic(Topic topic) { + super(topic.m_inst, topic.m_handle); + } + + /** + * Constructor; use NetworkTableInstance.getFloatArrayTopic() instead. + * + * @param inst Instance + * @param handle Native handle + */ + public FloatArrayTopic(NetworkTableInstance inst, int handle) { + super(inst, handle); + } + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public FloatArraySubscriber subscribe( + float[] defaultValue, + PubSubOption... options) { + return new FloatArrayEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kFloatArray.getValue(), + "float[]", options), + defaultValue); + } + + /** + * Create a new subscriber to the topic, with specified type string. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public FloatArraySubscriber subscribeEx( + String typeString, + float[] defaultValue, + PubSubOption... options) { + return new FloatArrayEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kFloatArray.getValue(), + typeString, options), + defaultValue); + } + + /** + * Create a new publisher to the topic. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + public FloatArrayPublisher publish( + PubSubOption... options) { + return new FloatArrayEntryImpl( + this, + NetworkTablesJNI.publish( + m_handle, NetworkTableType.kFloatArray.getValue(), + "float[]", options), + new float[] {}); + } + + /** + * Create a new publisher to the topic, with type string and initial properties. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + * @throws IllegalArgumentException if properties is not a JSON object + */ + public FloatArrayPublisher publishEx( + String typeString, + String properties, + PubSubOption... options) { + return new FloatArrayEntryImpl( + this, + NetworkTablesJNI.publishEx( + m_handle, NetworkTableType.kFloatArray.getValue(), + typeString, properties, options), + new float[] {}); + } + + /** + * Create a new entry for the topic. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public FloatArrayEntry getEntry( + float[] defaultValue, + PubSubOption... options) { + return new FloatArrayEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kFloatArray.getValue(), + "float[]", options), + defaultValue); + } + + /** + * Create a new entry for the topic, with specified type string. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public FloatArrayEntry getEntryEx( + String typeString, + float[] defaultValue, + PubSubOption... options) { + return new FloatArrayEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kFloatArray.getValue(), + typeString, options), + defaultValue); + } + +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatEntry.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatEntry.java new file mode 100644 index 00000000000..9830123fd58 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatEntry.java @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** + * NetworkTables Float entry. + * + *

Unlike NetworkTableEntry, the entry goes away when close() is called. + */ +public interface FloatEntry extends FloatSubscriber, FloatPublisher { + /** Stops publishing the entry if it's published. */ + void unpublish(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatEntryImpl.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatEntryImpl.java new file mode 100644 index 00000000000..f7efebfce4a --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatEntryImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables Float implementation. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +final class FloatEntryImpl extends EntryBase implements FloatEntry { + /** + * Constructor. + * + * @param topic Topic + * @param handle Native handle + * @param defaultValue Default value for get() + */ + FloatEntryImpl(FloatTopic topic, int handle, float defaultValue) { + super(handle); + m_topic = topic; + m_defaultValue = defaultValue; + } + + @Override + public FloatTopic getTopic() { + return m_topic; + } + + @Override + public float get() { + return NetworkTablesJNI.getFloat(m_handle, m_defaultValue); + } + + @Override + public float get(float defaultValue) { + return NetworkTablesJNI.getFloat(m_handle, defaultValue); + } + + @Override + public TimestampedFloat getAtomic() { + return NetworkTablesJNI.getAtomicFloat(m_handle, m_defaultValue); + } + + @Override + public TimestampedFloat getAtomic(float defaultValue) { + return NetworkTablesJNI.getAtomicFloat(m_handle, defaultValue); + } + + @Override + public TimestampedFloat[] readQueue() { + return NetworkTablesJNI.readQueueFloat(m_handle); + } + + @Override + public float[] readQueueValues() { + return NetworkTablesJNI.readQueueValuesFloat(m_handle); + } + + @Override + public void set(float value, long time) { + NetworkTablesJNI.setFloat(m_handle, time, value); + } + + @Override + public void setDefault(float value) { + NetworkTablesJNI.setDefaultFloat(m_handle, 0, value); + } + + @Override + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + private final FloatTopic m_topic; + private final float m_defaultValue; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatPublisher.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatPublisher.java new file mode 100644 index 00000000000..3f4b320fca9 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatPublisher.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import edu.wpi.first.util.function.FloatConsumer; + +/** NetworkTables Float publisher. */ +public interface FloatPublisher extends Publisher, FloatConsumer { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + FloatTopic getTopic(); + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + */ + default void set(float value) { + set(value, 0); + } + + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void set(float value, long time); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void setDefault(float value); + + @Override + default void accept(float value) { + set(value); + } +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatSubscriber.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatSubscriber.java new file mode 100644 index 00000000000..758463b89eb --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatSubscriber.java @@ -0,0 +1,85 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import edu.wpi.first.util.function.FloatSupplier; + +/** NetworkTables Float subscriber. */ +@SuppressWarnings("PMD.MissingOverride") +public interface FloatSubscriber extends Subscriber, FloatSupplier { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + FloatTopic getTopic(); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + float get(); + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + float get(float defaultValue); + + @Override + default float getAsFloat() { + return get(); + } + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedFloat getAtomic(); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedFloat getAtomic(float defaultValue); + + /** + * Get an array of all value changes since the last call to readQueue. + * Also provides a timestamp for each value. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + TimestampedFloat[] readQueue(); + + /** + * Get an array of all value changes since the last call to readQueue. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of values; empty array if no new changes have been + * published since the previous call. + */ + float[] readQueueValues(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatTopic.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatTopic.java new file mode 100644 index 00000000000..2ac7c7ca2ce --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/FloatTopic.java @@ -0,0 +1,206 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables Float topic. */ +public final class FloatTopic extends Topic { + /** The default type string for this topic type. */ + public static final String kTypeString = "float"; + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + public FloatTopic(Topic topic) { + super(topic.m_inst, topic.m_handle); + } + + /** + * Constructor; use NetworkTableInstance.getFloatTopic() instead. + * + * @param inst Instance + * @param handle Native handle + */ + public FloatTopic(NetworkTableInstance inst, int handle) { + super(inst, handle); + } + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public FloatSubscriber subscribe( + float defaultValue, + PubSubOption... options) { + return new FloatEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kFloat.getValue(), + "float", options), + defaultValue); + } + + /** + * Create a new subscriber to the topic, with specified type string. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public FloatSubscriber subscribeEx( + String typeString, + float defaultValue, + PubSubOption... options) { + return new FloatEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kFloat.getValue(), + typeString, options), + defaultValue); + } + + /** + * Create a new publisher to the topic. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + public FloatPublisher publish( + PubSubOption... options) { + return new FloatEntryImpl( + this, + NetworkTablesJNI.publish( + m_handle, NetworkTableType.kFloat.getValue(), + "float", options), + 0); + } + + /** + * Create a new publisher to the topic, with type string and initial properties. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + * @throws IllegalArgumentException if properties is not a JSON object + */ + public FloatPublisher publishEx( + String typeString, + String properties, + PubSubOption... options) { + return new FloatEntryImpl( + this, + NetworkTablesJNI.publishEx( + m_handle, NetworkTableType.kFloat.getValue(), + typeString, properties, options), + 0); + } + + /** + * Create a new entry for the topic. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public FloatEntry getEntry( + float defaultValue, + PubSubOption... options) { + return new FloatEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kFloat.getValue(), + "float", options), + defaultValue); + } + + /** + * Create a new entry for the topic, with specified type string. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public FloatEntry getEntryEx( + String typeString, + float defaultValue, + PubSubOption... options) { + return new FloatEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kFloat.getValue(), + typeString, options), + defaultValue); + } + +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/GenericEntryImpl.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/GenericEntryImpl.java new file mode 100644 index 00000000000..b467c83f022 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/GenericEntryImpl.java @@ -0,0 +1,815 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.nio.ByteBuffer; + +/** NetworkTables generic implementation. */ +final class GenericEntryImpl extends EntryBase implements GenericEntry { + /** + * Constructor. + * + * @param topic Topic + * @param handle Native handle + */ + GenericEntryImpl(Topic topic, int handle) { + super(handle); + m_topic = topic; + } + + @Override + public Topic getTopic() { + return m_topic; + } + + @Override + public NetworkTableValue get() { + return NetworkTablesJNI.getValue(m_handle); + } + + /** + * Gets the entry's value as a boolean. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public boolean getBoolean(boolean defaultValue) { + return NetworkTablesJNI.getBoolean(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a long. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public long getInteger(long defaultValue) { + return NetworkTablesJNI.getInteger(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a float. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public float getFloat(float defaultValue) { + return NetworkTablesJNI.getFloat(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a double. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public double getDouble(double defaultValue) { + return NetworkTablesJNI.getDouble(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a String. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public String getString(String defaultValue) { + return NetworkTablesJNI.getString(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a byte[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public byte[] getRaw(byte[] defaultValue) { + return NetworkTablesJNI.getRaw(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a boolean[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public boolean[] getBooleanArray(boolean[] defaultValue) { + return NetworkTablesJNI.getBooleanArray(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a boolean array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public Boolean[] getBooleanArray(Boolean[] defaultValue) { + return NetworkTableValue.fromNativeBooleanArray( + getBooleanArray(NetworkTableValue.toNativeBooleanArray(defaultValue))); + } + + /** + * Gets the entry's value as a long[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public long[] getIntegerArray(long[] defaultValue) { + return NetworkTablesJNI.getIntegerArray(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a boolean array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public Long[] getIntegerArray(Long[] defaultValue) { + return NetworkTableValue.fromNativeIntegerArray( + getIntegerArray(NetworkTableValue.toNativeIntegerArray(defaultValue))); + } + + /** + * Gets the entry's value as a float[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public float[] getFloatArray(float[] defaultValue) { + return NetworkTablesJNI.getFloatArray(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a boolean array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public Float[] getFloatArray(Float[] defaultValue) { + return NetworkTableValue.fromNativeFloatArray( + getFloatArray(NetworkTableValue.toNativeFloatArray(defaultValue))); + } + + /** + * Gets the entry's value as a double[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public double[] getDoubleArray(double[] defaultValue) { + return NetworkTablesJNI.getDoubleArray(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a boolean array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public Double[] getDoubleArray(Double[] defaultValue) { + return NetworkTableValue.fromNativeDoubleArray( + getDoubleArray(NetworkTableValue.toNativeDoubleArray(defaultValue))); + } + + /** + * Gets the entry's value as a String[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + @Override + public String[] getStringArray(String[] defaultValue) { + return NetworkTablesJNI.getStringArray(m_handle, defaultValue); + } + + @Override + public NetworkTableValue[] readQueue() { + return NetworkTablesJNI.readQueueValue(m_handle); + } + + @Override + public boolean set(NetworkTableValue value) { + long time = value.getTime(); + Object otherValue = value.getValue(); + switch (value.getType()) { + case kBoolean: + return NetworkTablesJNI.setBoolean(m_handle, time, (Boolean) otherValue); + case kInteger: + return NetworkTablesJNI.setInteger( + m_handle, time, ((Number) otherValue).longValue()); + case kFloat: + return NetworkTablesJNI.setFloat( + m_handle, time, ((Number) otherValue).floatValue()); + case kDouble: + return NetworkTablesJNI.setDouble( + m_handle, time, ((Number) otherValue).doubleValue()); + case kString: + return NetworkTablesJNI.setString(m_handle, time, (String) otherValue); + case kRaw: + return NetworkTablesJNI.setRaw(m_handle, time, (byte[]) otherValue); + case kBooleanArray: + return NetworkTablesJNI.setBooleanArray(m_handle, time, (boolean[]) otherValue); + case kIntegerArray: + return NetworkTablesJNI.setIntegerArray(m_handle, time, (long[]) otherValue); + case kFloatArray: + return NetworkTablesJNI.setFloatArray(m_handle, time, (float[]) otherValue); + case kDoubleArray: + return NetworkTablesJNI.setDoubleArray(m_handle, time, (double[]) otherValue); + case kStringArray: + return NetworkTablesJNI.setStringArray(m_handle, time, (String[]) otherValue); + default: + return true; + } + } + + /** + * Sets the entry's value. + * + * @param value the value that will be assigned + * @return False if the table key already exists with a different type + * @throws IllegalArgumentException if the value is not a known type + */ + @Override + public boolean setValue(Object value, long time) { + if (value instanceof NetworkTableValue) { + return set((NetworkTableValue) value); + } else if (value instanceof Boolean) { + return setBoolean((Boolean) value, time); + } else if (value instanceof Long) { + return setInteger((Long) value, time); + } else if (value instanceof Float) { + return setFloat((Float) value, time); + } else if (value instanceof Number) { + return setNumber((Number) value, time); + } else if (value instanceof String) { + return setString((String) value, time); + } else if (value instanceof byte[]) { + return setRaw((byte[]) value, time); + } else if (value instanceof boolean[]) { + return setBooleanArray((boolean[]) value, time); + } else if (value instanceof long[]) { + return setIntegerArray((long[]) value, time); + } else if (value instanceof float[]) { + return setFloatArray((float[]) value, time); + } else if (value instanceof double[]) { + return setDoubleArray((double[]) value, time); + } else if (value instanceof Boolean[]) { + return setBooleanArray((Boolean[]) value, time); + } else if (value instanceof Long[]) { + return setIntegerArray((Long[]) value, time); + } else if (value instanceof Float[]) { + return setFloatArray((Float[]) value, time); + } else if (value instanceof Number[]) { + return setNumberArray((Number[]) value, time); + } else if (value instanceof String[]) { + return setStringArray((String[]) value, time); + } else { + throw new IllegalArgumentException( + "Value of type " + value.getClass().getName() + " cannot be put into a table"); + } + } + + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setBoolean(boolean value, long time) { + return NetworkTablesJNI.setBoolean(m_handle, time, value); + } + + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setInteger(long value, long time) { + return NetworkTablesJNI.setInteger(m_handle, time, value); + } + + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setFloat(float value, long time) { + return NetworkTablesJNI.setFloat(m_handle, time, value); + } + + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDouble(double value, long time) { + return NetworkTablesJNI.setDouble(m_handle, time, value); + } + + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setString(String value, long time) { + return NetworkTablesJNI.setString(m_handle, time, value); + } + + + /** + * Sets the entry's value. + * + * @param value the value to set + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.length - start) + * @return False if the entry exists with a different type + */ + @Override + public boolean setRaw(byte[] value, int start, int len, long time) { + return NetworkTablesJNI.setRaw(m_handle, time, value, start, len); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.capacity() - start) + * @return False if the entry exists with a different type + */ + @Override + public boolean setRaw(ByteBuffer value, int start, int len, long time) { + return NetworkTablesJNI.setRaw(m_handle, time, value, start, len); + } + + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setBooleanArray(boolean[] value, long time) { + return NetworkTablesJNI.setBooleanArray(m_handle, time, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setBooleanArray(Boolean[] value, long time) { + return setBooleanArray(NetworkTableValue.toNativeBooleanArray(value), time); + } + + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setIntegerArray(long[] value, long time) { + return NetworkTablesJNI.setIntegerArray(m_handle, time, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setIntegerArray(Long[] value, long time) { + return setIntegerArray(NetworkTableValue.toNativeIntegerArray(value), time); + } + + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setFloatArray(float[] value, long time) { + return NetworkTablesJNI.setFloatArray(m_handle, time, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setFloatArray(Float[] value, long time) { + return setFloatArray(NetworkTableValue.toNativeFloatArray(value), time); + } + + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDoubleArray(double[] value, long time) { + return NetworkTablesJNI.setDoubleArray(m_handle, time, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDoubleArray(Double[] value, long time) { + return setDoubleArray(NetworkTableValue.toNativeDoubleArray(value), time); + } + + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setStringArray(String[] value, long time) { + return NetworkTablesJNI.setStringArray(m_handle, time, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setNumber(Number value, long time) { + return setDouble(value.doubleValue(), time); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setNumberArray(Number[] value, long time) { + return setDoubleArray(NetworkTableValue.toNativeDoubleArray(value), time); + } + + @Override + public boolean setDefault(NetworkTableValue defaultValue) { + long time = defaultValue.getTime(); + Object otherValue = defaultValue.getValue(); + switch (defaultValue.getType()) { + case kBoolean: + return NetworkTablesJNI.setDefaultBoolean(m_handle, time, (Boolean) otherValue); + case kInteger: + return NetworkTablesJNI.setDefaultInteger( + m_handle, time, ((Number) otherValue).longValue()); + case kFloat: + return NetworkTablesJNI.setDefaultFloat( + m_handle, time, ((Number) otherValue).floatValue()); + case kDouble: + return NetworkTablesJNI.setDefaultDouble( + m_handle, time, ((Number) otherValue).doubleValue()); + case kString: + return NetworkTablesJNI.setDefaultString(m_handle, time, (String) otherValue); + case kRaw: + return NetworkTablesJNI.setDefaultRaw(m_handle, time, (byte[]) otherValue); + case kBooleanArray: + return NetworkTablesJNI.setDefaultBooleanArray(m_handle, time, (boolean[]) otherValue); + case kIntegerArray: + return NetworkTablesJNI.setDefaultIntegerArray(m_handle, time, (long[]) otherValue); + case kFloatArray: + return NetworkTablesJNI.setDefaultFloatArray(m_handle, time, (float[]) otherValue); + case kDoubleArray: + return NetworkTablesJNI.setDefaultDoubleArray(m_handle, time, (double[]) otherValue); + case kStringArray: + return NetworkTablesJNI.setDefaultStringArray(m_handle, time, (String[]) otherValue); + default: + return true; + } + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + * @throws IllegalArgumentException if the value is not a known type + */ + @Override + public boolean setDefaultValue(Object defaultValue) { + if (defaultValue instanceof NetworkTableValue) { + return setDefault((NetworkTableValue) defaultValue); + } else if (defaultValue instanceof Boolean) { + return setDefaultBoolean((Boolean) defaultValue); + } else if (defaultValue instanceof Integer) { + return setDefaultInteger((Integer) defaultValue); + } else if (defaultValue instanceof Float) { + return setDefaultFloat((Float) defaultValue); + } else if (defaultValue instanceof Number) { + return setDefaultNumber((Number) defaultValue); + } else if (defaultValue instanceof String) { + return setDefaultString((String) defaultValue); + } else if (defaultValue instanceof byte[]) { + return setDefaultRaw((byte[]) defaultValue); + } else if (defaultValue instanceof boolean[]) { + return setDefaultBooleanArray((boolean[]) defaultValue); + } else if (defaultValue instanceof long[]) { + return setDefaultIntegerArray((long[]) defaultValue); + } else if (defaultValue instanceof float[]) { + return setDefaultFloatArray((float[]) defaultValue); + } else if (defaultValue instanceof double[]) { + return setDefaultDoubleArray((double[]) defaultValue); + } else if (defaultValue instanceof Boolean[]) { + return setDefaultBooleanArray((Boolean[]) defaultValue); + } else if (defaultValue instanceof Long[]) { + return setDefaultIntegerArray((Long[]) defaultValue); + } else if (defaultValue instanceof Float[]) { + return setDefaultFloatArray((Float[]) defaultValue); + } else if (defaultValue instanceof Number[]) { + return setDefaultNumberArray((Number[]) defaultValue); + } else if (defaultValue instanceof String[]) { + return setDefaultStringArray((String[]) defaultValue); + } else { + throw new IllegalArgumentException( + "Value of type " + defaultValue.getClass().getName() + " cannot be put into a table"); + } + } + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultBoolean(boolean defaultValue) { + return NetworkTablesJNI.setDefaultBoolean(m_handle, 0, defaultValue); + } + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultInteger(long defaultValue) { + return NetworkTablesJNI.setDefaultInteger(m_handle, 0, defaultValue); + } + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultFloat(float defaultValue) { + return NetworkTablesJNI.setDefaultFloat(m_handle, 0, defaultValue); + } + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultDouble(double defaultValue) { + return NetworkTablesJNI.setDefaultDouble(m_handle, 0, defaultValue); + } + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultString(String defaultValue) { + return NetworkTablesJNI.setDefaultString(m_handle, 0, defaultValue); + } + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.length - start) + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultRaw(byte[] defaultValue, int start, int len) { + return NetworkTablesJNI.setDefaultRaw(m_handle, 0, defaultValue, start, len); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.capacity() - start) + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultRaw(ByteBuffer defaultValue, int start, int len) { + return NetworkTablesJNI.setDefaultRaw(m_handle, 0, defaultValue, start, len); + } + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultBooleanArray(boolean[] defaultValue) { + return NetworkTablesJNI.setDefaultBooleanArray(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultBooleanArray(Boolean[] defaultValue) { + return setDefaultBooleanArray(NetworkTableValue.toNativeBooleanArray(defaultValue)); + } + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultIntegerArray(long[] defaultValue) { + return NetworkTablesJNI.setDefaultIntegerArray(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultIntegerArray(Long[] defaultValue) { + return setDefaultIntegerArray(NetworkTableValue.toNativeIntegerArray(defaultValue)); + } + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultFloatArray(float[] defaultValue) { + return NetworkTablesJNI.setDefaultFloatArray(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultFloatArray(Float[] defaultValue) { + return setDefaultFloatArray(NetworkTableValue.toNativeFloatArray(defaultValue)); + } + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultDoubleArray(double[] defaultValue) { + return NetworkTablesJNI.setDefaultDoubleArray(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultDoubleArray(Double[] defaultValue) { + return setDefaultDoubleArray(NetworkTableValue.toNativeDoubleArray(defaultValue)); + } + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + @Override + public boolean setDefaultStringArray(String[] defaultValue) { + return NetworkTablesJNI.setDefaultStringArray(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultNumber(Number defaultValue) { + return setDefaultDouble(defaultValue.doubleValue()); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultNumberArray(Number[] defaultValue) { + return setDefaultDoubleArray(NetworkTableValue.toNativeDoubleArray(defaultValue)); + } + + @Override + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + private final Topic m_topic; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/GenericPublisher.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/GenericPublisher.java new file mode 100644 index 00000000000..f589e9f5497 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/GenericPublisher.java @@ -0,0 +1,592 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.nio.ByteBuffer; +import java.util.function.Consumer; + +/** NetworkTables generic publisher. */ +public interface GenericPublisher extends Publisher, Consumer { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + Topic getTopic(); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + boolean set(NetworkTableValue value); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + * @throws IllegalArgumentException if the value is not a known type + */ + default boolean setValue(Object value) { + return setValue(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + * @throws IllegalArgumentException if the value is not a known type + */ + boolean setValue(Object value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setBoolean(boolean value) { + return setBoolean(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setBoolean(boolean value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setInteger(long value) { + return setInteger(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setInteger(long value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setFloat(float value) { + return setFloat(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setFloat(float value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setDouble(double value) { + return setDouble(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setDouble(double value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setString(String value) { + return setString(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setString(String value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setRaw(byte[] value) { + return setRaw(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setRaw(ByteBuffer value) { + return setRaw(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + default boolean setRaw(byte[] value, long time) { + return setRaw(value, 0, value.length, time); + } + + /** + * Publish a new value. + * + * @param value value to publish; will send from value.position() to value.limit() + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + default boolean setRaw(ByteBuffer value, long time) { + int pos = value.position(); + return setRaw(value, pos, value.limit() - pos, time); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.length - start) + * @return False if the topic already exists with a different type + */ + default boolean setRaw(byte[] value, int start, int len) { + return setRaw(value, start, len, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.length - start) + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setRaw(byte[] value, int start, int len, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.capacity() - start) + * @return False if the topic already exists with a different type + */ + default boolean setRaw(ByteBuffer value, int start, int len) { + return setRaw(value, start, len, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.capacity() - start) + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setRaw(ByteBuffer value, int start, int len, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setBooleanArray(boolean[] value) { + return setBooleanArray(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setBooleanArray(boolean[] value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setBooleanArray(Boolean[] value) { + return setBooleanArray(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setBooleanArray(Boolean[] value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setIntegerArray(long[] value) { + return setIntegerArray(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setIntegerArray(long[] value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setIntegerArray(Long[] value) { + return setIntegerArray(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setIntegerArray(Long[] value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setFloatArray(float[] value) { + return setFloatArray(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setFloatArray(float[] value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setFloatArray(Float[] value) { + return setFloatArray(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setFloatArray(Float[] value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setDoubleArray(double[] value) { + return setDoubleArray(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setDoubleArray(double[] value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setDoubleArray(Double[] value) { + return setDoubleArray(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setDoubleArray(Double[] value, long time); + + /** + * Publish a new value. + * + * @param value value to publish + * @return False if the topic already exists with a different type + */ + default boolean setStringArray(String[] value) { + return setStringArray(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + * @return False if the topic already exists with a different type + */ + boolean setStringArray(String[] value, long time); + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefault(NetworkTableValue defaultValue); + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + * @throws IllegalArgumentException if the value is not a known type + */ + boolean setDefaultValue(Object defaultValue); + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultBoolean(boolean defaultValue); + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultInteger(long defaultValue); + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultFloat(float defaultValue); + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultDouble(double defaultValue); + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultString(String defaultValue); + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + default boolean setDefaultRaw(byte[] defaultValue) { + return setDefaultRaw(defaultValue, 0, defaultValue.length); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set; will send from defaultValue.position() to + * defaultValue.limit() + * @return False if the entry exists with a different type + */ + default boolean setDefaultRaw(ByteBuffer defaultValue) { + int pos = defaultValue.position(); + return setDefaultRaw(defaultValue, pos, defaultValue.limit() - pos); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.length - start) + * @return False if the entry exists with a different type + */ + boolean setDefaultRaw(byte[] defaultValue, int start, int len); + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.capacity() - start) + * @return False if the entry exists with a different type + */ + boolean setDefaultRaw(ByteBuffer defaultValue, int start, int len); + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultBooleanArray(boolean[] defaultValue); + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultBooleanArray(Boolean[] defaultValue); + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultIntegerArray(long[] defaultValue); + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultIntegerArray(Long[] defaultValue); + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultFloatArray(float[] defaultValue); + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultFloatArray(Float[] defaultValue); + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultDoubleArray(double[] defaultValue); + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultDoubleArray(Double[] defaultValue); + + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + boolean setDefaultStringArray(String[] defaultValue); + + @Override + default void accept(NetworkTableValue value) { + set(value); + } +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/GenericSubscriber.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/GenericSubscriber.java new file mode 100644 index 00000000000..7d7ca9639b0 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/GenericSubscriber.java @@ -0,0 +1,176 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Supplier; + +/** NetworkTables generic subscriber. */ +@SuppressWarnings("PMD.MissingOverride") +public interface GenericSubscriber extends Subscriber, Supplier { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + Topic getTopic(); + + /** + * Get the last published value. + * If no value has been published, returns a value with type NetworkTableType.kUnassigned. + * + * @return value + */ + NetworkTableValue get(); + + /** + * Gets the entry's value as a boolean. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + boolean getBoolean(boolean defaultValue); + + /** + * Gets the entry's value as a long. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + long getInteger(long defaultValue); + + /** + * Gets the entry's value as a float. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + float getFloat(float defaultValue); + + /** + * Gets the entry's value as a double. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + double getDouble(double defaultValue); + + /** + * Gets the entry's value as a String. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + String getString(String defaultValue); + + /** + * Gets the entry's value as a byte[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + byte[] getRaw(byte[] defaultValue); + + /** + * Gets the entry's value as a boolean[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + boolean[] getBooleanArray(boolean[] defaultValue); + + /** + * Gets the entry's value as a boolean array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + Boolean[] getBooleanArray(Boolean[] defaultValue); + + /** + * Gets the entry's value as a long[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + long[] getIntegerArray(long[] defaultValue); + + /** + * Gets the entry's value as a boolean array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + Long[] getIntegerArray(Long[] defaultValue); + + /** + * Gets the entry's value as a float[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + float[] getFloatArray(float[] defaultValue); + + /** + * Gets the entry's value as a boolean array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + Float[] getFloatArray(Float[] defaultValue); + + /** + * Gets the entry's value as a double[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + double[] getDoubleArray(double[] defaultValue); + + /** + * Gets the entry's value as a boolean array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + Double[] getDoubleArray(Double[] defaultValue); + + /** + * Gets the entry's value as a String[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + String[] getStringArray(String[] defaultValue); + + /** + * Get an array of all value changes since the last call to readQueue. + * Also provides a timestamp for each value. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + NetworkTableValue[] readQueue(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArrayEntry.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArrayEntry.java new file mode 100644 index 00000000000..fd8f9c2cec0 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArrayEntry.java @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** + * NetworkTables IntegerArray entry. + * + *

Unlike NetworkTableEntry, the entry goes away when close() is called. + */ +public interface IntegerArrayEntry extends IntegerArraySubscriber, IntegerArrayPublisher { + /** Stops publishing the entry if it's published. */ + void unpublish(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArrayEntryImpl.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArrayEntryImpl.java new file mode 100644 index 00000000000..e74f4893b9e --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArrayEntryImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables IntegerArray implementation. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +final class IntegerArrayEntryImpl extends EntryBase implements IntegerArrayEntry { + /** + * Constructor. + * + * @param topic Topic + * @param handle Native handle + * @param defaultValue Default value for get() + */ + IntegerArrayEntryImpl(IntegerArrayTopic topic, int handle, long[] defaultValue) { + super(handle); + m_topic = topic; + m_defaultValue = defaultValue; + } + + @Override + public IntegerArrayTopic getTopic() { + return m_topic; + } + + @Override + public long[] get() { + return NetworkTablesJNI.getIntegerArray(m_handle, m_defaultValue); + } + + @Override + public long[] get(long[] defaultValue) { + return NetworkTablesJNI.getIntegerArray(m_handle, defaultValue); + } + + @Override + public TimestampedIntegerArray getAtomic() { + return NetworkTablesJNI.getAtomicIntegerArray(m_handle, m_defaultValue); + } + + @Override + public TimestampedIntegerArray getAtomic(long[] defaultValue) { + return NetworkTablesJNI.getAtomicIntegerArray(m_handle, defaultValue); + } + + @Override + public TimestampedIntegerArray[] readQueue() { + return NetworkTablesJNI.readQueueIntegerArray(m_handle); + } + + @Override + public long[][] readQueueValues() { + return NetworkTablesJNI.readQueueValuesIntegerArray(m_handle); + } + + @Override + public void set(long[] value, long time) { + NetworkTablesJNI.setIntegerArray(m_handle, time, value); + } + + @Override + public void setDefault(long[] value) { + NetworkTablesJNI.setDefaultIntegerArray(m_handle, 0, value); + } + + @Override + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + private final IntegerArrayTopic m_topic; + private final long[] m_defaultValue; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArrayPublisher.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArrayPublisher.java new file mode 100644 index 00000000000..b864ba1e6b4 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArrayPublisher.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Consumer; + +/** NetworkTables IntegerArray publisher. */ +public interface IntegerArrayPublisher extends Publisher, Consumer { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + IntegerArrayTopic getTopic(); + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + */ + default void set(long[] value) { + set(value, 0); + } + + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void set(long[] value, long time); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void setDefault(long[] value); + + @Override + default void accept(long[] value) { + set(value); + } +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArraySubscriber.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArraySubscriber.java new file mode 100644 index 00000000000..cbb2e6fe818 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArraySubscriber.java @@ -0,0 +1,80 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Supplier; + +/** NetworkTables IntegerArray subscriber. */ +@SuppressWarnings("PMD.MissingOverride") +public interface IntegerArraySubscriber extends Subscriber, Supplier { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + IntegerArrayTopic getTopic(); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + long[] get(); + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + long[] get(long[] defaultValue); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedIntegerArray getAtomic(); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedIntegerArray getAtomic(long[] defaultValue); + + /** + * Get an array of all value changes since the last call to readQueue. + * Also provides a timestamp for each value. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + TimestampedIntegerArray[] readQueue(); + + /** + * Get an array of all value changes since the last call to readQueue. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of values; empty array if no new changes have been + * published since the previous call. + */ + long[][] readQueueValues(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArrayTopic.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArrayTopic.java new file mode 100644 index 00000000000..d020e8a62c8 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerArrayTopic.java @@ -0,0 +1,206 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables IntegerArray topic. */ +public final class IntegerArrayTopic extends Topic { + /** The default type string for this topic type. */ + public static final String kTypeString = "int[]"; + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + public IntegerArrayTopic(Topic topic) { + super(topic.m_inst, topic.m_handle); + } + + /** + * Constructor; use NetworkTableInstance.getIntegerArrayTopic() instead. + * + * @param inst Instance + * @param handle Native handle + */ + public IntegerArrayTopic(NetworkTableInstance inst, int handle) { + super(inst, handle); + } + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public IntegerArraySubscriber subscribe( + long[] defaultValue, + PubSubOption... options) { + return new IntegerArrayEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kIntegerArray.getValue(), + "int[]", options), + defaultValue); + } + + /** + * Create a new subscriber to the topic, with specified type string. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public IntegerArraySubscriber subscribeEx( + String typeString, + long[] defaultValue, + PubSubOption... options) { + return new IntegerArrayEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kIntegerArray.getValue(), + typeString, options), + defaultValue); + } + + /** + * Create a new publisher to the topic. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + public IntegerArrayPublisher publish( + PubSubOption... options) { + return new IntegerArrayEntryImpl( + this, + NetworkTablesJNI.publish( + m_handle, NetworkTableType.kIntegerArray.getValue(), + "int[]", options), + new long[] {}); + } + + /** + * Create a new publisher to the topic, with type string and initial properties. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + * @throws IllegalArgumentException if properties is not a JSON object + */ + public IntegerArrayPublisher publishEx( + String typeString, + String properties, + PubSubOption... options) { + return new IntegerArrayEntryImpl( + this, + NetworkTablesJNI.publishEx( + m_handle, NetworkTableType.kIntegerArray.getValue(), + typeString, properties, options), + new long[] {}); + } + + /** + * Create a new entry for the topic. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public IntegerArrayEntry getEntry( + long[] defaultValue, + PubSubOption... options) { + return new IntegerArrayEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kIntegerArray.getValue(), + "int[]", options), + defaultValue); + } + + /** + * Create a new entry for the topic, with specified type string. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public IntegerArrayEntry getEntryEx( + String typeString, + long[] defaultValue, + PubSubOption... options) { + return new IntegerArrayEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kIntegerArray.getValue(), + typeString, options), + defaultValue); + } + +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerEntry.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerEntry.java new file mode 100644 index 00000000000..ccd614e3128 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerEntry.java @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** + * NetworkTables Integer entry. + * + *

Unlike NetworkTableEntry, the entry goes away when close() is called. + */ +public interface IntegerEntry extends IntegerSubscriber, IntegerPublisher { + /** Stops publishing the entry if it's published. */ + void unpublish(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerEntryImpl.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerEntryImpl.java new file mode 100644 index 00000000000..a8db1bff9dd --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerEntryImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables Integer implementation. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +final class IntegerEntryImpl extends EntryBase implements IntegerEntry { + /** + * Constructor. + * + * @param topic Topic + * @param handle Native handle + * @param defaultValue Default value for get() + */ + IntegerEntryImpl(IntegerTopic topic, int handle, long defaultValue) { + super(handle); + m_topic = topic; + m_defaultValue = defaultValue; + } + + @Override + public IntegerTopic getTopic() { + return m_topic; + } + + @Override + public long get() { + return NetworkTablesJNI.getInteger(m_handle, m_defaultValue); + } + + @Override + public long get(long defaultValue) { + return NetworkTablesJNI.getInteger(m_handle, defaultValue); + } + + @Override + public TimestampedInteger getAtomic() { + return NetworkTablesJNI.getAtomicInteger(m_handle, m_defaultValue); + } + + @Override + public TimestampedInteger getAtomic(long defaultValue) { + return NetworkTablesJNI.getAtomicInteger(m_handle, defaultValue); + } + + @Override + public TimestampedInteger[] readQueue() { + return NetworkTablesJNI.readQueueInteger(m_handle); + } + + @Override + public long[] readQueueValues() { + return NetworkTablesJNI.readQueueValuesInteger(m_handle); + } + + @Override + public void set(long value, long time) { + NetworkTablesJNI.setInteger(m_handle, time, value); + } + + @Override + public void setDefault(long value) { + NetworkTablesJNI.setDefaultInteger(m_handle, 0, value); + } + + @Override + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + private final IntegerTopic m_topic; + private final long m_defaultValue; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerPublisher.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerPublisher.java new file mode 100644 index 00000000000..be734eddd1e --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerPublisher.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.LongConsumer; + +/** NetworkTables Integer publisher. */ +public interface IntegerPublisher extends Publisher, LongConsumer { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + IntegerTopic getTopic(); + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + */ + default void set(long value) { + set(value, 0); + } + + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void set(long value, long time); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void setDefault(long value); + + @Override + default void accept(long value) { + set(value); + } +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerSubscriber.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerSubscriber.java new file mode 100644 index 00000000000..81a9740ef7d --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerSubscriber.java @@ -0,0 +1,85 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.LongSupplier; + +/** NetworkTables Integer subscriber. */ +@SuppressWarnings("PMD.MissingOverride") +public interface IntegerSubscriber extends Subscriber, LongSupplier { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + IntegerTopic getTopic(); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + long get(); + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + long get(long defaultValue); + + @Override + default long getAsLong() { + return get(); + } + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedInteger getAtomic(); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedInteger getAtomic(long defaultValue); + + /** + * Get an array of all value changes since the last call to readQueue. + * Also provides a timestamp for each value. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + TimestampedInteger[] readQueue(); + + /** + * Get an array of all value changes since the last call to readQueue. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of values; empty array if no new changes have been + * published since the previous call. + */ + long[] readQueueValues(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerTopic.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerTopic.java new file mode 100644 index 00000000000..ebf87c4b0d4 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/IntegerTopic.java @@ -0,0 +1,206 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables Integer topic. */ +public final class IntegerTopic extends Topic { + /** The default type string for this topic type. */ + public static final String kTypeString = "int"; + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + public IntegerTopic(Topic topic) { + super(topic.m_inst, topic.m_handle); + } + + /** + * Constructor; use NetworkTableInstance.getIntegerTopic() instead. + * + * @param inst Instance + * @param handle Native handle + */ + public IntegerTopic(NetworkTableInstance inst, int handle) { + super(inst, handle); + } + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public IntegerSubscriber subscribe( + long defaultValue, + PubSubOption... options) { + return new IntegerEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kInteger.getValue(), + "int", options), + defaultValue); + } + + /** + * Create a new subscriber to the topic, with specified type string. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public IntegerSubscriber subscribeEx( + String typeString, + long defaultValue, + PubSubOption... options) { + return new IntegerEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kInteger.getValue(), + typeString, options), + defaultValue); + } + + /** + * Create a new publisher to the topic. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + public IntegerPublisher publish( + PubSubOption... options) { + return new IntegerEntryImpl( + this, + NetworkTablesJNI.publish( + m_handle, NetworkTableType.kInteger.getValue(), + "int", options), + 0); + } + + /** + * Create a new publisher to the topic, with type string and initial properties. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + * @throws IllegalArgumentException if properties is not a JSON object + */ + public IntegerPublisher publishEx( + String typeString, + String properties, + PubSubOption... options) { + return new IntegerEntryImpl( + this, + NetworkTablesJNI.publishEx( + m_handle, NetworkTableType.kInteger.getValue(), + typeString, properties, options), + 0); + } + + /** + * Create a new entry for the topic. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public IntegerEntry getEntry( + long defaultValue, + PubSubOption... options) { + return new IntegerEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kInteger.getValue(), + "int", options), + defaultValue); + } + + /** + * Create a new entry for the topic, with specified type string. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public IntegerEntry getEntryEx( + String typeString, + long defaultValue, + PubSubOption... options) { + return new IntegerEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kInteger.getValue(), + typeString, options), + defaultValue); + } + +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/NetworkTableEntry.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/NetworkTableEntry.java new file mode 100644 index 00000000000..09926bff6ca --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/NetworkTableEntry.java @@ -0,0 +1,962 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.nio.ByteBuffer; + +/** + * NetworkTables Entry. + * + *

For backwards compatibility, the NetworkTableEntry close() does not release the entry. + */ +@SuppressWarnings("UnnecessaryParentheses") +public final class NetworkTableEntry implements Publisher, Subscriber { + /** + * Construct from native handle. + * + * @param inst Instance + * @param handle Native handle + */ + public NetworkTableEntry(NetworkTableInstance inst, int handle) { + this(new Topic(inst, NetworkTablesJNI.getTopicFromHandle(handle)), handle); + } + + /** + * Construct from native handle. + * + * @param topic Topic + * @param handle Native handle + */ + public NetworkTableEntry(Topic topic, int handle) { + m_topic = topic; + m_handle = handle; + } + + @Override + public void close() {} + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + @Override + public boolean isValid() { + return m_handle != 0; + } + + /** + * Gets the native handle for the entry. + * + * @return Native handle + */ + @Override + public int getHandle() { + return m_handle; + } + + /** + * Gets the subscribed-to / published-to topic. + * + * @return Topic + */ + @Override + public Topic getTopic() { + return m_topic; + } + + /** + * Gets the instance for the entry. + * + * @return Instance + */ + public NetworkTableInstance getInstance() { + return m_topic.getInstance(); + } + + /** + * Determines if the entry currently exists. + * + * @return True if the entry exists, false otherwise. + */ + @Override + public boolean exists() { + return NetworkTablesJNI.getType(m_handle) != 0; + } + + /** + * Gets the name of the entry (the key). + * + * @return the entry's name + */ + public String getName() { + return NetworkTablesJNI.getEntryName(m_handle); + } + + /** + * Gets the type of the entry. + * + * @return the entry's type + */ + public NetworkTableType getType() { + return NetworkTableType.getFromInt(NetworkTablesJNI.getType(m_handle)); + } + + /** + * Gets the last time the entry's value was changed. + * + * @return Entry last change time + */ + @Override + public long getLastChange() { + return NetworkTablesJNI.getEntryLastChange(m_handle); + } + + /** + * Gets the entry's value. Returns a value with type NetworkTableType.kUnassigned if the value + * does not exist. + * + * @return the entry's value + */ + public NetworkTableValue getValue() { + return NetworkTablesJNI.getValue(m_handle); + } + + /** + * Gets the entry's value as a boolean. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public boolean getBoolean(boolean defaultValue) { + return NetworkTablesJNI.getBoolean(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a long. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public long getInteger(long defaultValue) { + return NetworkTablesJNI.getInteger(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a float. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public float getFloat(float defaultValue) { + return NetworkTablesJNI.getFloat(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a double. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public double getDouble(double defaultValue) { + return NetworkTablesJNI.getDouble(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a String. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public String getString(String defaultValue) { + return NetworkTablesJNI.getString(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a byte[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public byte[] getRaw(byte[] defaultValue) { + return NetworkTablesJNI.getRaw(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a boolean[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public boolean[] getBooleanArray(boolean[] defaultValue) { + return NetworkTablesJNI.getBooleanArray(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a boolean array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public Boolean[] getBooleanArray(Boolean[] defaultValue) { + return NetworkTableValue.fromNativeBooleanArray( + getBooleanArray(NetworkTableValue.toNativeBooleanArray(defaultValue))); + } + + /** + * Gets the entry's value as a long[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public long[] getIntegerArray(long[] defaultValue) { + return NetworkTablesJNI.getIntegerArray(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a boolean array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public Long[] getIntegerArray(Long[] defaultValue) { + return NetworkTableValue.fromNativeIntegerArray( + getIntegerArray(NetworkTableValue.toNativeIntegerArray(defaultValue))); + } + + /** + * Gets the entry's value as a float[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public float[] getFloatArray(float[] defaultValue) { + return NetworkTablesJNI.getFloatArray(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a boolean array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public Float[] getFloatArray(Float[] defaultValue) { + return NetworkTableValue.fromNativeFloatArray( + getFloatArray(NetworkTableValue.toNativeFloatArray(defaultValue))); + } + + /** + * Gets the entry's value as a double[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public double[] getDoubleArray(double[] defaultValue) { + return NetworkTablesJNI.getDoubleArray(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a boolean array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public Double[] getDoubleArray(Double[] defaultValue) { + return NetworkTableValue.fromNativeDoubleArray( + getDoubleArray(NetworkTableValue.toNativeDoubleArray(defaultValue))); + } + + /** + * Gets the entry's value as a String[]. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public String[] getStringArray(String[] defaultValue) { + return NetworkTablesJNI.getStringArray(m_handle, defaultValue); + } + + /** + * Gets the entry's value as a double. If the entry does not exist or is of different type, it + * will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public Number getNumber(Number defaultValue) { + return getDouble(defaultValue.doubleValue()); + } + + /** + * Gets the entry's value as a double array. If the entry does not exist or is of different type, + * it will return the default value. + * + * @param defaultValue the value to be returned if no value is found + * @return the entry's value or the given default value + */ + public Number[] getNumberArray(Number[] defaultValue) { + return NetworkTableValue.fromNativeDoubleArray( + getDoubleArray(NetworkTableValue.toNativeDoubleArray(defaultValue))); + } + + /** + * Get an array of all value changes since the last call to readQueue. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of values; empty array if no new changes have been + * published since the previous call. + */ + public NetworkTableValue[] readQueue() { + return NetworkTablesJNI.readQueueValue(m_handle); + } + + /** + * Checks if a data value is of a type that can be placed in a NetworkTable entry. + * + * @param data the data to check + * @return true if the data can be placed in an entry, false if it cannot + */ + public static boolean isValidDataType(Object data) { + return data instanceof Number + || data instanceof Boolean + || data instanceof String + || data instanceof long[] + || data instanceof Long[] + || data instanceof float[] + || data instanceof Float[] + || data instanceof double[] + || data instanceof Double[] + || data instanceof Number[] + || data instanceof boolean[] + || data instanceof Boolean[] + || data instanceof String[] + || data instanceof byte[] + || data instanceof Byte[]; + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + * @throws IllegalArgumentException if the value is not a known type + */ + public boolean setDefaultValue(Object defaultValue) { + if (defaultValue instanceof NetworkTableValue) { + long time = ((NetworkTableValue) defaultValue).getTime(); + Object otherValue = ((NetworkTableValue) defaultValue).getValue(); + switch (((NetworkTableValue) defaultValue).getType()) { + case kBoolean: + return NetworkTablesJNI.setDefaultBoolean(m_handle, time, (Boolean) otherValue); + case kInteger: + return NetworkTablesJNI.setDefaultInteger( + m_handle, time, ((Number) otherValue).longValue()); + case kFloat: + return NetworkTablesJNI.setDefaultFloat( + m_handle, time, ((Number) otherValue).floatValue()); + case kDouble: + return NetworkTablesJNI.setDefaultDouble( + m_handle, time, ((Number) otherValue).doubleValue()); + case kString: + return NetworkTablesJNI.setDefaultString(m_handle, time, (String) otherValue); + case kRaw: + return NetworkTablesJNI.setDefaultRaw(m_handle, time, (byte[]) otherValue); + case kBooleanArray: + return NetworkTablesJNI.setDefaultBooleanArray(m_handle, time, (boolean[]) otherValue); + case kIntegerArray: + return NetworkTablesJNI.setDefaultIntegerArray(m_handle, time, (long[]) otherValue); + case kFloatArray: + return NetworkTablesJNI.setDefaultFloatArray(m_handle, time, (float[]) otherValue); + case kDoubleArray: + return NetworkTablesJNI.setDefaultDoubleArray(m_handle, time, (double[]) otherValue); + case kStringArray: + return NetworkTablesJNI.setDefaultStringArray(m_handle, time, (String[]) otherValue); + default: + return true; + } + } else if (defaultValue instanceof Boolean) { + return setDefaultBoolean((Boolean) defaultValue); + } else if (defaultValue instanceof Integer) { + return setDefaultInteger((Integer) defaultValue); + } else if (defaultValue instanceof Float) { + return setDefaultFloat((Float) defaultValue); + } else if (defaultValue instanceof Number) { + return setDefaultNumber((Number) defaultValue); + } else if (defaultValue instanceof String) { + return setDefaultString((String) defaultValue); + } else if (defaultValue instanceof byte[]) { + return setDefaultRaw((byte[]) defaultValue); + } else if (defaultValue instanceof boolean[]) { + return setDefaultBooleanArray((boolean[]) defaultValue); + } else if (defaultValue instanceof long[]) { + return setDefaultIntegerArray((long[]) defaultValue); + } else if (defaultValue instanceof float[]) { + return setDefaultFloatArray((float[]) defaultValue); + } else if (defaultValue instanceof double[]) { + return setDefaultDoubleArray((double[]) defaultValue); + } else if (defaultValue instanceof Boolean[]) { + return setDefaultBooleanArray((Boolean[]) defaultValue); + } else if (defaultValue instanceof Long[]) { + return setDefaultIntegerArray((Long[]) defaultValue); + } else if (defaultValue instanceof Float[]) { + return setDefaultFloatArray((Float[]) defaultValue); + } else if (defaultValue instanceof Number[]) { + return setDefaultNumberArray((Number[]) defaultValue); + } else if (defaultValue instanceof String[]) { + return setDefaultStringArray((String[]) defaultValue); + } else { + throw new IllegalArgumentException( + "Value of type " + defaultValue.getClass().getName() + " cannot be put into a table"); + } + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultBoolean(boolean defaultValue) { + return NetworkTablesJNI.setDefaultBoolean(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultInteger(long defaultValue) { + return NetworkTablesJNI.setDefaultInteger(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultFloat(float defaultValue) { + return NetworkTablesJNI.setDefaultFloat(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultDouble(double defaultValue) { + return NetworkTablesJNI.setDefaultDouble(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultString(String defaultValue) { + return NetworkTablesJNI.setDefaultString(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultRaw(byte[] defaultValue) { + return NetworkTablesJNI.setDefaultRaw(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set; will send from defaultValue.position() to + * defaultValue.capacity() + * @return False if the entry exists with a different type + */ + public boolean setDefaultRaw(ByteBuffer defaultValue) { + return NetworkTablesJNI.setDefaultRaw(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.length - start) + * @return False if the entry exists with a different type + */ + public boolean setDefaultRaw(byte[] defaultValue, int start, int len) { + return NetworkTablesJNI.setDefaultRaw(m_handle, 0, defaultValue, start, len); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.capacity() - start) + * @return False if the entry exists with a different type + */ + public boolean setDefaultRaw(ByteBuffer defaultValue, int start, int len) { + return NetworkTablesJNI.setDefaultRaw(m_handle, 0, defaultValue, start, len); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultBooleanArray(boolean[] defaultValue) { + return NetworkTablesJNI.setDefaultBooleanArray(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultBooleanArray(Boolean[] defaultValue) { + return setDefaultBooleanArray(NetworkTableValue.toNativeBooleanArray(defaultValue)); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultIntegerArray(long[] defaultValue) { + return NetworkTablesJNI.setDefaultIntegerArray(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultIntegerArray(Long[] defaultValue) { + return setDefaultIntegerArray(NetworkTableValue.toNativeIntegerArray(defaultValue)); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultFloatArray(float[] defaultValue) { + return NetworkTablesJNI.setDefaultFloatArray(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultFloatArray(Float[] defaultValue) { + return setDefaultFloatArray(NetworkTableValue.toNativeFloatArray(defaultValue)); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultDoubleArray(double[] defaultValue) { + return NetworkTablesJNI.setDefaultDoubleArray(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultDoubleArray(Double[] defaultValue) { + return setDefaultDoubleArray(NetworkTableValue.toNativeDoubleArray(defaultValue)); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultStringArray(String[] defaultValue) { + return NetworkTablesJNI.setDefaultStringArray(m_handle, 0, defaultValue); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultNumber(Number defaultValue) { + return setDefaultDouble(defaultValue.doubleValue()); + } + + /** + * Sets the entry's value if it does not exist. + * + * @param defaultValue the default value to set + * @return False if the entry exists with a different type + */ + public boolean setDefaultNumberArray(Number[] defaultValue) { + return setDefaultDoubleArray(NetworkTableValue.toNativeDoubleArray(defaultValue)); + } + + /** + * Sets the entry's value. + * + * @param value the value that will be assigned + * @return False if the table key already exists with a different type + * @throws IllegalArgumentException if the value is not a known type + */ + public boolean setValue(Object value) { + if (value instanceof NetworkTableValue) { + long time = ((NetworkTableValue) value).getTime(); + Object otherValue = ((NetworkTableValue) value).getValue(); + switch (((NetworkTableValue) value).getType()) { + case kBoolean: + return NetworkTablesJNI.setBoolean(m_handle, time, (Boolean) otherValue); + case kInteger: + return NetworkTablesJNI.setInteger( + m_handle, time, ((Number) otherValue).longValue()); + case kFloat: + return NetworkTablesJNI.setFloat( + m_handle, time, ((Number) otherValue).floatValue()); + case kDouble: + return NetworkTablesJNI.setDouble( + m_handle, time, ((Number) otherValue).doubleValue()); + case kString: + return NetworkTablesJNI.setString(m_handle, time, (String) otherValue); + case kRaw: + return NetworkTablesJNI.setRaw(m_handle, time, (byte[]) otherValue); + case kBooleanArray: + return NetworkTablesJNI.setBooleanArray(m_handle, time, (boolean[]) otherValue); + case kIntegerArray: + return NetworkTablesJNI.setIntegerArray(m_handle, time, (long[]) otherValue); + case kFloatArray: + return NetworkTablesJNI.setFloatArray(m_handle, time, (float[]) otherValue); + case kDoubleArray: + return NetworkTablesJNI.setDoubleArray(m_handle, time, (double[]) otherValue); + case kStringArray: + return NetworkTablesJNI.setStringArray(m_handle, time, (String[]) otherValue); + default: + return true; + } + } else if (value instanceof Boolean) { + return setBoolean((Boolean) value); + } else if (value instanceof Long) { + return setInteger((Long) value); + } else if (value instanceof Float) { + return setFloat((Float) value); + } else if (value instanceof Number) { + return setNumber((Number) value); + } else if (value instanceof String) { + return setString((String) value); + } else if (value instanceof byte[]) { + return setRaw((byte[]) value); + } else if (value instanceof boolean[]) { + return setBooleanArray((boolean[]) value); + } else if (value instanceof long[]) { + return setIntegerArray((long[]) value); + } else if (value instanceof float[]) { + return setFloatArray((float[]) value); + } else if (value instanceof double[]) { + return setDoubleArray((double[]) value); + } else if (value instanceof Boolean[]) { + return setBooleanArray((Boolean[]) value); + } else if (value instanceof Long[]) { + return setIntegerArray((Long[]) value); + } else if (value instanceof Float[]) { + return setFloatArray((Float[]) value); + } else if (value instanceof Number[]) { + return setNumberArray((Number[]) value); + } else if (value instanceof String[]) { + return setStringArray((String[]) value); + } else { + throw new IllegalArgumentException( + "Value of type " + value.getClass().getName() + " cannot be put into a table"); + } + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setBoolean(boolean value) { + return NetworkTablesJNI.setBoolean(m_handle, 0, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setInteger(long value) { + return NetworkTablesJNI.setInteger(m_handle, 0, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setFloat(float value) { + return NetworkTablesJNI.setFloat(m_handle, 0, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setDouble(double value) { + return NetworkTablesJNI.setDouble(m_handle, 0, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setString(String value) { + return NetworkTablesJNI.setString(m_handle, 0, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setRaw(byte[] value) { + return NetworkTablesJNI.setRaw(m_handle, 0, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set; will send from value.position() to value.capacity() + * @return False if the entry exists with a different type + */ + public boolean setRaw(ByteBuffer value) { + return NetworkTablesJNI.setRaw(m_handle, 0, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.length - start) + * @return False if the entry exists with a different type + */ + public boolean setRaw(byte[] value, int start, int len) { + return NetworkTablesJNI.setRaw(m_handle, 0, value, start, len); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.capacity() - start) + * @return False if the entry exists with a different type + */ + public boolean setRaw(ByteBuffer value, int start, int len) { + return NetworkTablesJNI.setRaw(m_handle, 0, value, start, len); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setBooleanArray(boolean[] value) { + return NetworkTablesJNI.setBooleanArray(m_handle, 0, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setBooleanArray(Boolean[] value) { + return setBooleanArray(NetworkTableValue.toNativeBooleanArray(value)); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setIntegerArray(long[] value) { + return NetworkTablesJNI.setIntegerArray(m_handle, 0, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setIntegerArray(Long[] value) { + return setIntegerArray(NetworkTableValue.toNativeIntegerArray(value)); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setFloatArray(float[] value) { + return NetworkTablesJNI.setFloatArray(m_handle, 0, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setFloatArray(Float[] value) { + return setFloatArray(NetworkTableValue.toNativeFloatArray(value)); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setDoubleArray(double[] value) { + return NetworkTablesJNI.setDoubleArray(m_handle, 0, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setDoubleArray(Double[] value) { + return setDoubleArray(NetworkTableValue.toNativeDoubleArray(value)); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setStringArray(String[] value) { + return NetworkTablesJNI.setStringArray(m_handle, 0, value); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setNumber(Number value) { + return setDouble(value.doubleValue()); + } + + /** + * Sets the entry's value. + * + * @param value the value to set + * @return False if the entry exists with a different type + */ + public boolean setNumberArray(Number[] value) { + return setDoubleArray(NetworkTableValue.toNativeDoubleArray(value)); + } + + /** Make value persistent through program restarts. */ + public void setPersistent() { + NetworkTablesJNI.setTopicPersistent(m_topic.getHandle(), true); + } + + /** Stop making value persistent through program restarts. */ + public void clearPersistent() { + NetworkTablesJNI.setTopicPersistent(m_topic.getHandle(), false); + } + + /** + * Returns whether the value is persistent through program restarts. + * + * @return True if the value is persistent. + */ + public boolean isPersistent() { + return NetworkTablesJNI.getTopicPersistent(m_topic.getHandle()); + } + + /** Stops publishing the entry if it's been published. */ + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof NetworkTableEntry)) { + return false; + } + + return m_handle == ((NetworkTableEntry) other).m_handle; + } + + @Override + public int hashCode() { + return m_handle; + } + + private final Topic m_topic; + private final int m_handle; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/NetworkTableInstance.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/NetworkTableInstance.java new file mode 100644 index 00000000000..344e061a828 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/NetworkTableInstance.java @@ -0,0 +1,1558 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import edu.wpi.first.util.WPIUtilJNI; +import edu.wpi.first.util.concurrent.Event; +import edu.wpi.first.util.datalog.DataLog; +import edu.wpi.first.util.protobuf.Protobuf; +import edu.wpi.first.util.struct.Struct; +import java.nio.charset.StandardCharsets; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.OptionalLong; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; +import us.hebi.quickbuf.ProtoMessage; + +/** + * NetworkTables Instance. + * + *

Instances are completely independent from each other. Table operations on one instance will + * not be visible to other instances unless the instances are connected via the network. The main + * limitation on instances is that you cannot have two servers on the same network port. The main + * utility of instances is for unit testing, but they can also enable one program to connect to two + * different NetworkTables networks. + * + *

The global "default" instance (as returned by {@link #getDefault()}) is always available, and + * is intended for the common case when there is only a single NetworkTables instance being used in + * the program. + * + *

Additional instances can be created with the {@link #create()} function. A reference must be + * kept to the NetworkTableInstance returned by this function to keep it from being garbage + * collected. + */ +@SuppressWarnings("PMD.CouplingBetweenObjects") +public final class NetworkTableInstance implements AutoCloseable { + /** Client/server mode flag values (as returned by {@link #getNetworkMode()}). */ + public enum NetworkMode { + /** Running in server mode. */ + kServer(0x01), + + /** Running in NT3 client mode. */ + kClient3(0x02), + + /** Running in NT4 client mode. */ + kClient4(0x04), + + /** Currently starting up (either client or server). */ + kStarting(0x08), + + /** Running in local-only mode. */ + kLocal(0x10); + + private final int value; + + NetworkMode(int value) { + this.value = value; + } + + /** + * Returns the network mode value. + * + * @return The network mode value. + */ + public int getValue() { + return value; + } + } + + /** The default port that network tables operates on for NT3. */ + public static final int kDefaultPort3 = 1735; + + /** The default port that network tables operates on for NT4. */ + public static final int kDefaultPort4 = 5810; + + /** + * Construct from native handle. + * + * @param handle Native handle + */ + private NetworkTableInstance(int handle) { + m_owned = false; + m_handle = handle; + } + + /** Destroys the instance (if created by {@link #create()}). */ + @Override + public synchronized void close() { + if (m_owned && m_handle != 0) { + m_listeners.close(); + m_schemas.forEach((k, v) -> v.close()); + NetworkTablesJNI.destroyInstance(m_handle); + m_handle = 0; + } + } + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + public boolean isValid() { + return m_handle != 0; + } + + /* The default instance. */ + private static NetworkTableInstance s_defaultInstance; + + /** + * Get global default instance. + * + * @return Global default instance + */ + public static synchronized NetworkTableInstance getDefault() { + if (s_defaultInstance == null) { + s_defaultInstance = new NetworkTableInstance(NetworkTablesJNI.getDefaultInstance()); + } + return s_defaultInstance; + } + + /** + * Create an instance. Note: A reference to the returned instance must be retained to ensure the + * instance is not garbage collected. + * + * @return Newly created instance + */ + public static NetworkTableInstance create() { + NetworkTableInstance inst = new NetworkTableInstance(NetworkTablesJNI.createInstance()); + inst.m_owned = true; + return inst; + } + + /** + * Gets the native handle for the instance. + * + * @return Native handle + */ + public int getHandle() { + return m_handle; + } + + /** + * Get (generic) topic. + * + * @param name topic name + * @return Topic + */ + public Topic getTopic(String name) { + Topic topic = m_topics.get(name); + if (topic == null) { + int handle = NetworkTablesJNI.getTopic(m_handle, name); + topic = new Topic(this, handle); + Topic oldTopic = m_topics.putIfAbsent(name, topic); + if (oldTopic != null) { + topic = oldTopic; + } + // also cache by handle + m_topicsByHandle.putIfAbsent(handle, topic); + } + return topic; + } + + /** + * Get boolean topic. + * + * @param name topic name + * @return BooleanTopic + */ + public BooleanTopic getBooleanTopic(String name) { + Topic topic = m_topics.get(name); + if (topic instanceof BooleanTopic) { + return (BooleanTopic) topic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + BooleanTopic wrapTopic = new BooleanTopic(this, handle); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + /** + * Get long topic. + * + * @param name topic name + * @return IntegerTopic + */ + public IntegerTopic getIntegerTopic(String name) { + Topic topic = m_topics.get(name); + if (topic instanceof IntegerTopic) { + return (IntegerTopic) topic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + IntegerTopic wrapTopic = new IntegerTopic(this, handle); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + /** + * Get float topic. + * + * @param name topic name + * @return FloatTopic + */ + public FloatTopic getFloatTopic(String name) { + Topic topic = m_topics.get(name); + if (topic instanceof FloatTopic) { + return (FloatTopic) topic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + FloatTopic wrapTopic = new FloatTopic(this, handle); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + /** + * Get double topic. + * + * @param name topic name + * @return DoubleTopic + */ + public DoubleTopic getDoubleTopic(String name) { + Topic topic = m_topics.get(name); + if (topic instanceof DoubleTopic) { + return (DoubleTopic) topic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + DoubleTopic wrapTopic = new DoubleTopic(this, handle); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + /** + * Get String topic. + * + * @param name topic name + * @return StringTopic + */ + public StringTopic getStringTopic(String name) { + Topic topic = m_topics.get(name); + if (topic instanceof StringTopic) { + return (StringTopic) topic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + StringTopic wrapTopic = new StringTopic(this, handle); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + /** + * Get byte[] topic. + * + * @param name topic name + * @return RawTopic + */ + public RawTopic getRawTopic(String name) { + Topic topic = m_topics.get(name); + if (topic instanceof RawTopic) { + return (RawTopic) topic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + RawTopic wrapTopic = new RawTopic(this, handle); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + /** + * Get boolean[] topic. + * + * @param name topic name + * @return BooleanArrayTopic + */ + public BooleanArrayTopic getBooleanArrayTopic(String name) { + Topic topic = m_topics.get(name); + if (topic instanceof BooleanArrayTopic) { + return (BooleanArrayTopic) topic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + BooleanArrayTopic wrapTopic = new BooleanArrayTopic(this, handle); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + /** + * Get long[] topic. + * + * @param name topic name + * @return IntegerArrayTopic + */ + public IntegerArrayTopic getIntegerArrayTopic(String name) { + Topic topic = m_topics.get(name); + if (topic instanceof IntegerArrayTopic) { + return (IntegerArrayTopic) topic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + IntegerArrayTopic wrapTopic = new IntegerArrayTopic(this, handle); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + /** + * Get float[] topic. + * + * @param name topic name + * @return FloatArrayTopic + */ + public FloatArrayTopic getFloatArrayTopic(String name) { + Topic topic = m_topics.get(name); + if (topic instanceof FloatArrayTopic) { + return (FloatArrayTopic) topic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + FloatArrayTopic wrapTopic = new FloatArrayTopic(this, handle); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + /** + * Get double[] topic. + * + * @param name topic name + * @return DoubleArrayTopic + */ + public DoubleArrayTopic getDoubleArrayTopic(String name) { + Topic topic = m_topics.get(name); + if (topic instanceof DoubleArrayTopic) { + return (DoubleArrayTopic) topic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + DoubleArrayTopic wrapTopic = new DoubleArrayTopic(this, handle); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + /** + * Get String[] topic. + * + * @param name topic name + * @return StringArrayTopic + */ + public StringArrayTopic getStringArrayTopic(String name) { + Topic topic = m_topics.get(name); + if (topic instanceof StringArrayTopic) { + return (StringArrayTopic) topic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + StringArrayTopic wrapTopic = new StringArrayTopic(this, handle); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + + /** + * Get protobuf-encoded value topic. + * + * @param value class (inferred from proto) + * @param protobuf message type (inferred from proto) + * @param name topic name + * @param proto protobuf serialization implementation + * @return ProtobufTopic + */ + public > + ProtobufTopic getProtobufTopic(String name, Protobuf proto) { + Topic topic = m_topics.get(name); + if (topic instanceof ProtobufTopic + && ((ProtobufTopic) topic).getProto().equals(proto)) { + @SuppressWarnings("unchecked") + ProtobufTopic wrapTopic = (ProtobufTopic) topic; + return wrapTopic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + ProtobufTopic wrapTopic = ProtobufTopic.wrap(this, handle, proto); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + /** + * Get struct-encoded value topic. + * + * @param value class (inferred from struct) + * @param name topic name + * @param struct struct serialization implementation + * @return StructTopic + */ + public + StructTopic getStructTopic(String name, Struct struct) { + Topic topic = m_topics.get(name); + if (topic instanceof StructTopic + && ((StructTopic) topic).getStruct().equals(struct)) { + @SuppressWarnings("unchecked") + StructTopic wrapTopic = (StructTopic) topic; + return wrapTopic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + StructTopic wrapTopic = StructTopic.wrap(this, handle, struct); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + /** + * Get struct-encoded value array topic. + * + * @param value class (inferred from struct) + * @param name topic name + * @param struct struct serialization implementation + * @return StructArrayTopic + */ + public + StructArrayTopic getStructArrayTopic(String name, Struct struct) { + Topic topic = m_topics.get(name); + if (topic instanceof StructArrayTopic + && ((StructArrayTopic) topic).getStruct().equals(struct)) { + @SuppressWarnings("unchecked") + StructArrayTopic wrapTopic = (StructArrayTopic) topic; + return wrapTopic; + } + + int handle; + if (topic == null) { + handle = NetworkTablesJNI.getTopic(m_handle, name); + } else { + handle = topic.getHandle(); + } + + StructArrayTopic wrapTopic = StructArrayTopic.wrap(this, handle, struct); + m_topics.put(name, wrapTopic); + + // also cache by handle + m_topicsByHandle.put(handle, wrapTopic); + + return wrapTopic; + } + + private Topic[] topicHandlesToTopics(int[] handles) { + Topic[] topics = new Topic[handles.length]; + for (int i = 0; i < handles.length; i++) { + topics[i] = getCachedTopic(handles[i]); + } + return topics; + } + + /** + * Get all published topics. + * + * @return Array of topics. + */ + public Topic[] getTopics() { + return topicHandlesToTopics(NetworkTablesJNI.getTopics(m_handle, "", 0)); + } + + /** + * Get published topics starting with the given prefix. The results are optionally filtered by + * string prefix to only return a subset of all topics. + * + * @param prefix topic name required prefix; only topics whose name starts with this string are + * returned + * @return Array of topic information. + */ + public Topic[] getTopics(String prefix) { + return topicHandlesToTopics(NetworkTablesJNI.getTopics(m_handle, prefix, 0)); + } + + /** + * Get published topics starting with the given prefix. The results are optionally filtered by + * string prefix and data type to only return a subset of all topics. + * + * @param prefix topic name required prefix; only topics whose name starts with this string are + * returned + * @param types bitmask of data types; 0 is treated as a "don't care" + * @return Array of topic information. + */ + public Topic[] getTopics(String prefix, int types) { + return topicHandlesToTopics(NetworkTablesJNI.getTopics(m_handle, prefix, types)); + } + + /** + * Get published topics starting with the given prefix. The results are optionally filtered by + * string prefix and data type to only return a subset of all topics. + * + * @param prefix topic name required prefix; only topics whose name starts with this string are + * returned + * @param types array of data type strings + * @return Array of topic information. + */ + public Topic[] getTopics(String prefix, String[] types) { + return topicHandlesToTopics(NetworkTablesJNI.getTopicsStr(m_handle, prefix, types)); + } + + /** + * Get information about all topics. + * + * @return Array of topic information. + */ + public TopicInfo[] getTopicInfo() { + return NetworkTablesJNI.getTopicInfos(this, m_handle, "", 0); + } + + /** + * Get information about topics starting with the given prefix. The results are optionally + * filtered by string prefix to only return a subset of all topics. + * + * @param prefix topic name required prefix; only topics whose name starts with this string are + * returned + * @return Array of topic information. + */ + public TopicInfo[] getTopicInfo(String prefix) { + return NetworkTablesJNI.getTopicInfos(this, m_handle, prefix, 0); + } + + /** + * Get information about topics starting with the given prefix. The results are optionally + * filtered by string prefix and data type to only return a subset of all topics. + * + * @param prefix topic name required prefix; only topics whose name starts with this string are + * returned + * @param types bitmask of data types; 0 is treated as a "don't care" + * @return Array of topic information. + */ + public TopicInfo[] getTopicInfo(String prefix, int types) { + return NetworkTablesJNI.getTopicInfos(this, m_handle, prefix, types); + } + + /** + * Get information about topics starting with the given prefix. The results are optionally + * filtered by string prefix and data type to only return a subset of all topics. + * + * @param prefix topic name required prefix; only topics whose name starts with this string are + * returned + * @param types array of data type strings + * @return Array of topic information. + */ + public TopicInfo[] getTopicInfo(String prefix, String[] types) { + return NetworkTablesJNI.getTopicInfosStr(this, m_handle, prefix, types); + } + + /* Cache of created entries. */ + private final ConcurrentMap m_entries = new ConcurrentHashMap<>(); + + /** + * Gets the entry for a key. + * + * @param name Key + * @return Network table entry. + */ + public NetworkTableEntry getEntry(String name) { + NetworkTableEntry entry = m_entries.get(name); + if (entry == null) { + entry = new NetworkTableEntry(this, NetworkTablesJNI.getEntry(m_handle, name)); + NetworkTableEntry oldEntry = m_entries.putIfAbsent(name, entry); + if (oldEntry != null) { + entry = oldEntry; + } + } + return entry; + } + + /* Cache of created topics. */ + private final ConcurrentMap m_topics = new ConcurrentHashMap<>(); + private final ConcurrentMap m_topicsByHandle = new ConcurrentHashMap<>(); + + Topic getCachedTopic(String name) { + Topic topic = m_topics.get(name); + if (topic == null) { + int handle = NetworkTablesJNI.getTopic(m_handle, name); + topic = new Topic(this, handle); + Topic oldTopic = m_topics.putIfAbsent(name, topic); + if (oldTopic != null) { + topic = oldTopic; + } + // also cache by handle + m_topicsByHandle.putIfAbsent(handle, topic); + } + return topic; + } + + Topic getCachedTopic(int handle) { + Topic topic = m_topicsByHandle.get(handle); + if (topic == null) { + topic = new Topic(this, handle); + Topic oldTopic = m_topicsByHandle.putIfAbsent(handle, topic); + if (oldTopic != null) { + topic = oldTopic; + } + } + return topic; + } + + /* Cache of created tables. */ + private final ConcurrentMap m_tables = new ConcurrentHashMap<>(); + + /** + * Gets the table with the specified key. + * + * @param key the key name + * @return The network table + */ + public NetworkTable getTable(String key) { + // prepend leading / if not present + String theKey; + if (key.isEmpty() || "/".equals(key)) { + theKey = ""; + } else if (key.charAt(0) == NetworkTable.PATH_SEPARATOR) { + theKey = key; + } else { + theKey = NetworkTable.PATH_SEPARATOR + key; + } + + // cache created tables + NetworkTable table = m_tables.get(theKey); + if (table == null) { + table = new NetworkTable(this, theKey); + NetworkTable oldTable = m_tables.putIfAbsent(theKey, table); + if (oldTable != null) { + table = oldTable; + } + } + return table; + } + + /* + * Callback Creation Functions + */ + + private static class ListenerStorage implements AutoCloseable { + private final ReentrantLock m_lock = new ReentrantLock(); + private final Map> m_listeners = new HashMap<>(); + private Thread m_thread; + private int m_poller; + private boolean m_waitQueue; + private final Event m_waitQueueEvent = new Event(); + private final Condition m_waitQueueCond = m_lock.newCondition(); + private final NetworkTableInstance m_inst; + + ListenerStorage(NetworkTableInstance inst) { + m_inst = inst; + } + + int add( + String[] prefixes, + EnumSet eventKinds, + Consumer listener) { + m_lock.lock(); + try { + if (m_poller == 0) { + m_poller = NetworkTablesJNI.createListenerPoller(m_inst.getHandle()); + startThread(); + } + int h = NetworkTablesJNI.addListener(m_poller, prefixes, eventKinds); + m_listeners.put(h, listener); + return h; + } finally { + m_lock.unlock(); + } + } + + int add( + int handle, + EnumSet eventKinds, + Consumer listener) { + m_lock.lock(); + try { + if (m_poller == 0) { + m_poller = NetworkTablesJNI.createListenerPoller(m_inst.getHandle()); + startThread(); + } + int h = NetworkTablesJNI.addListener(m_poller, handle, eventKinds); + m_listeners.put(h, listener); + return h; + } finally { + m_lock.unlock(); + } + } + + int addLogger(int minLevel, int maxLevel, Consumer listener) { + m_lock.lock(); + try { + if (m_poller == 0) { + m_poller = NetworkTablesJNI.createListenerPoller(m_inst.getHandle()); + startThread(); + } + int h = NetworkTablesJNI.addLogger(m_poller, minLevel, maxLevel); + m_listeners.put(h, listener); + return h; + } finally { + m_lock.unlock(); + } + } + + void remove(int listener) { + m_lock.lock(); + try { + m_listeners.remove(listener); + } finally { + m_lock.unlock(); + } + NetworkTablesJNI.removeListener(listener); + } + + @Override + public void close() { + if (m_poller != 0) { + NetworkTablesJNI.destroyListenerPoller(m_poller); + } + m_poller = 0; + } + + private void startThread() { + m_thread = + new Thread( + () -> { + boolean wasInterrupted = false; + int[] handles = new int[] { m_poller, m_waitQueueEvent.getHandle() }; + while (!Thread.interrupted()) { + try { + WPIUtilJNI.waitForObjects(handles); + } catch (InterruptedException ex) { + m_lock.lock(); + try { + if (m_waitQueue) { + m_waitQueue = false; + m_waitQueueCond.signalAll(); + } + } finally { + m_lock.unlock(); + } + Thread.currentThread().interrupt(); + // don't try to destroy poller, as its handle is likely no longer valid + wasInterrupted = true; + break; + } + for (NetworkTableEvent event : + NetworkTablesJNI.readListenerQueue(m_inst, m_poller)) { + Consumer listener; + m_lock.lock(); + try { + listener = m_listeners.get(event.listener); + } finally { + m_lock.unlock(); + } + if (listener != null) { + try { + listener.accept(event); + } catch (Throwable throwable) { + System.err.println( + "Unhandled exception during listener callback: " + + throwable.toString()); + throwable.printStackTrace(); + } + } + } + m_lock.lock(); + try { + if (m_waitQueue) { + m_waitQueue = false; + m_waitQueueCond.signalAll(); + } + } finally { + m_lock.unlock(); + } + } + m_lock.lock(); + try { + if (!wasInterrupted) { + NetworkTablesJNI.destroyListenerPoller(m_poller); + } + m_poller = 0; + } finally { + m_lock.unlock(); + } + }, + "NTListener"); + m_thread.setDaemon(true); + m_thread.start(); + } + + boolean waitForQueue(double timeout) { + m_lock.lock(); + try { + if (m_poller != 0) { + m_waitQueue = true; + m_waitQueueEvent.set(); + while (m_waitQueue) { + try { + if (timeout < 0) { + m_waitQueueCond.await(); + } else { + return m_waitQueueCond.await((long) (timeout * 1e9), TimeUnit.NANOSECONDS); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + return true; + } + } + } + } finally { + m_lock.unlock(); + } + return true; + } + } + + private final ListenerStorage m_listeners = new ListenerStorage(this); + + /** + * Remove a connection listener. + * + * @param listener Listener handle to remove + */ + public void removeListener(int listener) { + m_listeners.remove(listener); + } + + /** + * Wait for the listener queue to be empty. This is primarily useful for deterministic + * testing. This blocks until either the listener queue is empty (e.g. there are no + * more events that need to be passed along to callbacks or poll queues) or the timeout expires. + * + * @param timeout timeout, in seconds. Set to 0 for non-blocking behavior, or a negative value to + * block indefinitely + * @return False if timed out, otherwise true. + */ + public boolean waitForListenerQueue(double timeout) { + return m_listeners.waitForQueue(timeout); + } + + /** + * Add a connection listener. The callback function is called asynchronously on a separate + * thread, so it's important to use synchronization or atomics when accessing any shared state + * from the callback function. + * + * @param immediateNotify Notify listener of all existing connections + * @param listener Listener to add + * @return Listener handle + */ + public int addConnectionListener( + boolean immediateNotify, Consumer listener) { + EnumSet eventKinds = EnumSet.of(NetworkTableEvent.Kind.kConnection); + if (immediateNotify) { + eventKinds.add(NetworkTableEvent.Kind.kImmediate); + } + return m_listeners.add(m_handle, eventKinds, listener); + } + + /** + * Add a time synchronization listener. The callback function is called asynchronously on a + * separate thread, so it's important to use synchronization or atomics when accessing any shared + * state from the callback function. + * + * @param immediateNotify Notify listener of current time synchronization value + * @param listener Listener to add + * @return Listener handle + */ + public int addTimeSyncListener( + boolean immediateNotify, Consumer listener) { + EnumSet eventKinds = EnumSet.of(NetworkTableEvent.Kind.kTimeSync); + if (immediateNotify) { + eventKinds.add(NetworkTableEvent.Kind.kImmediate); + } + return m_listeners.add(m_handle, eventKinds, listener); + } + + /** + * Add a listener for changes on a particular topic. The callback function is called + * asynchronously on a separate thread, so it's important to use synchronization or atomics when + * accessing any shared state from the callback function. + * + *

This creates a corresponding internal subscriber with the lifetime of the + * listener. + * + * @param topic Topic + * @param eventKinds set of event kinds to listen to + * @param listener Listener function + * @return Listener handle + */ + public int addListener( + Topic topic, + EnumSet eventKinds, + Consumer listener) { + if (topic.getInstance().getHandle() != m_handle) { + throw new IllegalArgumentException("topic is not from this instance"); + } + return m_listeners.add(topic.getHandle(), eventKinds, listener); + } + + /** + * Add a listener for changes on a subscriber. The callback function is called + * asynchronously on a separate thread, so it's important to use synchronization or atomics when + * accessing any shared state from the callback function. This does NOT keep the subscriber + * active. + * + * @param subscriber Subscriber + * @param eventKinds set of event kinds to listen to + * @param listener Listener function + * @return Listener handle + */ + public int addListener( + Subscriber subscriber, + EnumSet eventKinds, + Consumer listener) { + if (subscriber.getTopic().getInstance().getHandle() != m_handle) { + throw new IllegalArgumentException("subscriber is not from this instance"); + } + return m_listeners.add(subscriber.getHandle(), eventKinds, listener); + } + + /** + * Add a listener for changes on a subscriber. The callback function is called + * asynchronously on a separate thread, so it's important to use synchronization or atomics when + * accessing any shared state from the callback function. This does NOT keep the subscriber + * active. + * + * @param subscriber Subscriber + * @param eventKinds set of event kinds to listen to + * @param listener Listener function + * @return Listener handle + */ + public int addListener( + MultiSubscriber subscriber, + EnumSet eventKinds, + Consumer listener) { + if (subscriber.getInstance().getHandle() != m_handle) { + throw new IllegalArgumentException("subscriber is not from this instance"); + } + return m_listeners.add(subscriber.getHandle(), eventKinds, listener); + } + + /** + * Add a listener for changes on an entry. The callback function is called + * asynchronously on a separate thread, so it's important to use synchronization or atomics when + * accessing any shared state from the callback function. + * + * @param entry Entry + * @param eventKinds set of event kinds to listen to + * @param listener Listener function + * @return Listener handle + */ + public int addListener( + NetworkTableEntry entry, + EnumSet eventKinds, + Consumer listener) { + if (entry.getTopic().getInstance().getHandle() != m_handle) { + throw new IllegalArgumentException("entry is not from this instance"); + } + return m_listeners.add(entry.getHandle(), eventKinds, listener); + } + + /** + * Add a listener for changes to topics with names that start with any of the given + * prefixes. The callback function is called asynchronously on a separate thread, so it's + * important to use synchronization or atomics when accessing any shared state from the callback + * function. + * + *

This creates a corresponding internal subscriber with the lifetime of the + * listener. + * + * @param prefixes Topic name string prefixes + * @param eventKinds set of event kinds to listen to + * @param listener Listener function + * @return Listener handle + */ + public int addListener( + String[] prefixes, + EnumSet eventKinds, + Consumer listener) { + return m_listeners.add(prefixes, eventKinds, listener); + } + + /* + * Client/Server Functions + */ + + /** + * Get the current network mode. + * + * @return Enum set of NetworkMode. + */ + public EnumSet getNetworkMode() { + int flags = NetworkTablesJNI.getNetworkMode(m_handle); + EnumSet rv = EnumSet.noneOf(NetworkMode.class); + for (NetworkMode mode : NetworkMode.values()) { + if ((flags & mode.getValue()) != 0) { + rv.add(mode); + } + } + return rv; + } + + /** + * Starts local-only operation. Prevents calls to startServer or startClient from taking effect. + * Has no effect if startServer or startClient has already been called. + */ + public void startLocal() { + NetworkTablesJNI.startLocal(m_handle); + } + + /** + * Stops local-only operation. startServer or startClient can be called after this call to start + * a server or client. + */ + public void stopLocal() { + NetworkTablesJNI.stopLocal(m_handle); + } + + /** + * Starts a server using the networktables.json as the persistent file, using the default + * listening address and port. + */ + public void startServer() { + startServer("networktables.json"); + } + + /** + * Starts a server using the specified persistent filename, using the default listening address + * and port. + * + * @param persistFilename the name of the persist file to use + */ + public void startServer(String persistFilename) { + startServer(persistFilename, ""); + } + + /** + * Starts a server using the specified filename and listening address, using the default port. + * + * @param persistFilename the name of the persist file to use + * @param listenAddress the address to listen on, or empty to listen on any address + */ + public void startServer(String persistFilename, String listenAddress) { + startServer(persistFilename, listenAddress, kDefaultPort3, kDefaultPort4); + } + + /** + * Starts a server using the specified filename, listening address, and port. + * + * @param persistFilename the name of the persist file to use + * @param listenAddress the address to listen on, or empty to listen on any address + * @param port3 port to communicate over (NT3) + */ + public void startServer(String persistFilename, String listenAddress, int port3) { + startServer(persistFilename, listenAddress, port3, kDefaultPort4); + } + + /** + * Starts a server using the specified filename, listening address, and port. + * + * @param persistFilename the name of the persist file to use + * @param listenAddress the address to listen on, or empty to listen on any address + * @param port3 port to communicate over (NT3) + * @param port4 port to communicate over (NT4) + */ + public void startServer(String persistFilename, String listenAddress, int port3, int port4) { + NetworkTablesJNI.startServer(m_handle, persistFilename, listenAddress, port3, port4); + } + + /** Stops the server if it is running. */ + public void stopServer() { + NetworkTablesJNI.stopServer(m_handle); + } + + /** + * Starts a NT3 client. Use SetServer or SetServerTeam to set the server name and port. + * + * @param identity network identity to advertise (cannot be empty string) + */ + public void startClient3(String identity) { + NetworkTablesJNI.startClient3(m_handle, identity); + } + + /** + * Starts a NT4 client. Use SetServer or SetServerTeam to set the server name and port. + * + * @param identity network identity to advertise (cannot be empty string) + */ + public void startClient4(String identity) { + NetworkTablesJNI.startClient4(m_handle, identity); + } + + /** Stops the client if it is running. */ + public void stopClient() { + NetworkTablesJNI.stopClient(m_handle); + } + + /** + * Sets server address and port for client (without restarting client). Changes the port to the + * default port. + * + * @param serverName server name + */ + public void setServer(String serverName) { + setServer(serverName, 0); + } + + /** + * Sets server address and port for client (without restarting client). + * + * @param serverName server name + * @param port port to communicate over (0=default) + */ + public void setServer(String serverName, int port) { + NetworkTablesJNI.setServer(m_handle, serverName, port); + } + + /** + * Sets server addresses and port for client (without restarting client). Changes the port to the + * default port. The client will attempt to connect to each server in round robin fashion. + * + * @param serverNames array of server names + */ + public void setServer(String[] serverNames) { + setServer(serverNames, 0); + } + + /** + * Sets server addresses and port for client (without restarting client). The client will attempt + * to connect to each server in round robin fashion. + * + * @param serverNames array of server names + * @param port port to communicate over (0=default) + */ + public void setServer(String[] serverNames, int port) { + int[] ports = new int[serverNames.length]; + for (int i = 0; i < serverNames.length; i++) { + ports[i] = port; + } + setServer(serverNames, ports); + } + + /** + * Sets server addresses and ports for client (without restarting client). The client will + * attempt to connect to each server in round robin fashion. + * + * @param serverNames array of server names + * @param ports array of port numbers (0=default) + */ + public void setServer(String[] serverNames, int[] ports) { + NetworkTablesJNI.setServer(m_handle, serverNames, ports); + } + + /** + * Sets server addresses and port for client (without restarting client). Changes the port to the + * default port. The client will attempt to connect to each server in round robin fashion. + * + * @param team team number + */ + public void setServerTeam(int team) { + setServerTeam(team, 0); + } + + /** + * Sets server addresses and port for client (without restarting client). Connects using commonly + * known robot addresses for the specified team. + * + * @param team team number + * @param port port to communicate over (0=default) + */ + public void setServerTeam(int team, int port) { + NetworkTablesJNI.setServerTeam(m_handle, team, port); + } + + /** + * Disconnects the client if it's running and connected. This will automatically start + * reconnection attempts to the current server list. + */ + public void disconnect() { + NetworkTablesJNI.disconnect(m_handle); + } + + /** + * Starts requesting server address from Driver Station. This connects to the Driver Station + * running on localhost to obtain the server IP address, and connects with the default port. + */ + public void startDSClient() { + startDSClient(0); + } + + /** + * Starts requesting server address from Driver Station. This connects to the Driver Station + * running on localhost to obtain the server IP address. + * + * @param port server port to use in combination with IP from DS (0=default) + */ + public void startDSClient(int port) { + NetworkTablesJNI.startDSClient(m_handle, port); + } + + /** Stops requesting server address from Driver Station. */ + public void stopDSClient() { + NetworkTablesJNI.stopDSClient(m_handle); + } + + /** + * Flushes all updated values immediately to the local client/server. This does not flush to the + * network. + */ + public void flushLocal() { + NetworkTablesJNI.flushLocal(m_handle); + } + + /** + * Flushes all updated values immediately to the network. Note: This is rate-limited to protect + * the network from flooding. This is primarily useful for synchronizing network updates with + * user code. + */ + public void flush() { + NetworkTablesJNI.flush(m_handle); + } + + /** + * Gets information on the currently established network connections. If operating as a client, + * this will return either zero or one values. + * + * @return array of connection information + */ + public ConnectionInfo[] getConnections() { + return NetworkTablesJNI.getConnections(m_handle); + } + + /** + * Return whether or not the instance is connected to another node. + * + * @return True if connected. + */ + public boolean isConnected() { + return NetworkTablesJNI.isConnected(m_handle); + } + + /** + * Get the time offset between server time and local time. Add this value to local time to get + * the estimated equivalent server time. In server mode, this always returns 0. In client mode, + * this returns the time offset only if the client and server are connected and have exchanged + * synchronization messages. Note the time offset may change over time as it is periodically + * updated; to receive updates as events, add a listener to the "time sync" event. + * + * @return Time offset in microseconds (optional) + */ + public OptionalLong getServerTimeOffset() { + return NetworkTablesJNI.getServerTimeOffset(m_handle); + } + + /** + * Starts logging entry changes to a DataLog. + * + * @param log data log object; lifetime must extend until StopEntryDataLog is called or the + * instance is destroyed + * @param prefix only store entries with names that start with this prefix; the prefix is not + * included in the data log entry name + * @param logPrefix prefix to add to data log entry names + * @return Data logger handle + */ + public int startEntryDataLog(DataLog log, String prefix, String logPrefix) { + return NetworkTablesJNI.startEntryDataLog(m_handle, log, prefix, logPrefix); + } + + /** + * Stops logging entry changes to a DataLog. + * + * @param logger data logger handle + */ + public static void stopEntryDataLog(int logger) { + NetworkTablesJNI.stopEntryDataLog(logger); + } + + /** + * Starts logging connection changes to a DataLog. + * + * @param log data log object; lifetime must extend until StopConnectionDataLog is called or the + * instance is destroyed + * @param name data log entry name + * @return Data logger handle + */ + public int startConnectionDataLog(DataLog log, String name) { + return NetworkTablesJNI.startConnectionDataLog(m_handle, log, name); + } + + /** + * Stops logging connection changes to a DataLog. + * + * @param logger data logger handle + */ + public static void stopConnectionDataLog(int logger) { + NetworkTablesJNI.stopConnectionDataLog(logger); + } + + /** + * Add logger callback function. By default, log messages are sent to stderr; this function sends + * log messages with the specified levels to the provided callback function instead. The callback + * function will only be called for log messages with level greater than or equal to minLevel and + * less than or equal to maxLevel; messages outside this range will be silently ignored. + * + * @param minLevel minimum log level + * @param maxLevel maximum log level + * @param func callback function + * @return Listener handle + */ + public int addLogger(int minLevel, int maxLevel, Consumer func) { + return m_listeners.addLogger(minLevel, maxLevel, func); + } + + /** + * Returns whether there is a data schema already registered with the given name that this + * instance has published. This does NOT perform a check as to whether the schema has already + * been published by another node on the network. + * + * @param name Name (the string passed as the data type for topics using this schema) + * @return True if schema already registered + */ + public boolean hasSchema(String name) { + return m_schemas.containsKey("/.schema/" + name); + } + + /** + * Registers a data schema. Data schemas provide information for how a certain data type string + * can be decoded. The type string of a data schema indicates the type of the schema itself (e.g. + * "protobuf" for protobuf schemas, "struct" for struct schemas, etc). In NetworkTables, schemas + * are published just like normal topics, with the name being generated from the provided name: + * "/.schema/name". Duplicate calls to this function with the same name are silently ignored. + * + * @param name Name (the string passed as the data type for topics using this schema) + * @param type Type of schema (e.g. "protobuf", "struct", etc) + * @param schema Schema data + */ + public void addSchema(String name, String type, byte[] schema) { + m_schemas.computeIfAbsent("/.schema/" + name, k -> { + RawPublisher pub = getRawTopic(k).publishEx(type, "{\"retained\":true}"); + pub.setDefault(schema); + return pub; + }); + } + + /** + * Registers a data schema. Data schemas provide information for how a certain data type string + * can be decoded. The type string of a data schema indicates the type of the schema itself (e.g. + * "protobuf" for protobuf schemas, "struct" for struct schemas, etc). In NetworkTables, schemas + * are published just like normal topics, with the name being generated from the provided name: + * "/.schema/name". Duplicate calls to this function with the same name are silently ignored. + * + * @param name Name (the string passed as the data type for topics using this schema) + * @param type Type of schema (e.g. "protobuf", "struct", etc) + * @param schema Schema data + */ + public void addSchema(String name, String type, String schema) { + m_schemas.computeIfAbsent("/.schema/" + name, k -> { + RawPublisher pub = getRawTopic(k).publishEx(type, "{\"retained\":true}"); + pub.setDefault(StandardCharsets.UTF_8.encode(schema)); + return pub; + }); + } + + /** + * Registers a protobuf schema. Duplicate calls to this function with the same name are silently + * ignored. + * + * @param proto protobuf serialization object + */ + public void addSchema(Protobuf proto) { + proto.forEachDescriptor( + this::hasSchema, + (typeString, schema) -> addSchema(typeString, "proto:FileDescriptorProto", schema)); + } + + /** + * Registers a struct schema. Duplicate calls to this function with the same name are silently + * ignored. + * + * @param struct struct serialization object + */ + public void addSchema(Struct struct) { + addSchemaImpl(struct, new HashSet<>()); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof NetworkTableInstance)) { + return false; + } + + return m_handle == ((NetworkTableInstance) other).m_handle; + } + + @Override + public int hashCode() { + return m_handle; + } + + private void addSchemaImpl(Struct struct, Set seen) { + String typeString = struct.getTypeString(); + if (hasSchema(typeString)) { + return; + } + if (!seen.add(typeString)) { + throw new UnsupportedOperationException(typeString + ": circular reference with " + seen); + } + addSchema(typeString, "structschema", struct.getSchema()); + for (Struct inner : struct.getNested()) { + addSchemaImpl(inner, seen); + } + seen.remove(typeString); + } + + private boolean m_owned; + private int m_handle; + private final ConcurrentMap m_schemas = new ConcurrentHashMap<>(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/NetworkTableValue.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/NetworkTableValue.java new file mode 100644 index 00000000000..3045d284a50 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/NetworkTableValue.java @@ -0,0 +1,742 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.Objects; + +/** A network table entry value. */ +@SuppressWarnings({"UnnecessaryParentheses", "PMD.MethodReturnsInternalArray"}) +public final class NetworkTableValue { + NetworkTableValue(NetworkTableType type, Object value, long time, long serverTime) { + m_type = type; + m_value = value; + m_time = time; + m_serverTime = serverTime; + } + + NetworkTableValue(NetworkTableType type, Object value, long time) { + this(type, value, time, time == 0 ? 0 : 1); + } + + NetworkTableValue(NetworkTableType type, Object value) { + this(type, value, NetworkTablesJNI.now(), 1); + } + + NetworkTableValue(int type, Object value, long time, long serverTime) { + this(NetworkTableType.getFromInt(type), value, time, serverTime); + } + + /** + * Get the data type. + * + * @return The type. + */ + public NetworkTableType getType() { + return m_type; + } + + /** + * Get the data value stored. + * + * @return The type. + */ + public Object getValue() { + return m_value; + } + + /** + * Get the creation time of the value in local time. + * + * @return The time, in the units returned by NetworkTablesJNI.now(). + */ + public long getTime() { + return m_time; + } + + /** + * Get the creation time of the value in server time. + * + * @return The server time. + */ + public long getServerTime() { + return m_serverTime; + } + + /* + * Type Checkers + */ + + /** + * Determine if entry value contains a value or is unassigned. + * + * @return True if the entry value contains a value. + */ + public boolean isValid() { + return m_type != NetworkTableType.kUnassigned; + } + + /** + * Determine if entry value contains a boolean. + * + * @return True if the entry value is of boolean type. + */ + public boolean isBoolean() { + return m_type == NetworkTableType.kBoolean; + } + + /** + * Determine if entry value contains a long. + * + * @return True if the entry value is of long type. + */ + public boolean isInteger() { + return m_type == NetworkTableType.kInteger; + } + + /** + * Determine if entry value contains a float. + * + * @return True if the entry value is of float type. + */ + public boolean isFloat() { + return m_type == NetworkTableType.kFloat; + } + + /** + * Determine if entry value contains a double. + * + * @return True if the entry value is of double type. + */ + public boolean isDouble() { + return m_type == NetworkTableType.kDouble; + } + + /** + * Determine if entry value contains a String. + * + * @return True if the entry value is of String type. + */ + public boolean isString() { + return m_type == NetworkTableType.kString; + } + + /** + * Determine if entry value contains a byte[]. + * + * @return True if the entry value is of byte[] type. + */ + public boolean isRaw() { + return m_type == NetworkTableType.kRaw; + } + + /** + * Determine if entry value contains a boolean[]. + * + * @return True if the entry value is of boolean[] type. + */ + public boolean isBooleanArray() { + return m_type == NetworkTableType.kBooleanArray; + } + + /** + * Determine if entry value contains a long[]. + * + * @return True if the entry value is of long[] type. + */ + public boolean isIntegerArray() { + return m_type == NetworkTableType.kIntegerArray; + } + + /** + * Determine if entry value contains a float[]. + * + * @return True if the entry value is of float[] type. + */ + public boolean isFloatArray() { + return m_type == NetworkTableType.kFloatArray; + } + + /** + * Determine if entry value contains a double[]. + * + * @return True if the entry value is of double[] type. + */ + public boolean isDoubleArray() { + return m_type == NetworkTableType.kDoubleArray; + } + + /** + * Determine if entry value contains a String[]. + * + * @return True if the entry value is of String[] type. + */ + public boolean isStringArray() { + return m_type == NetworkTableType.kStringArray; + } + + /* + * Type-Safe Getters + */ + + /** + * Get the boolean value. + * + * @return The boolean value. + * @throws ClassCastException if the entry value is not of boolean type. + */ + public boolean getBoolean() { + if (m_type != NetworkTableType.kBoolean) { + throw new ClassCastException("cannot convert " + m_type + " to boolean"); + } + return (Boolean) m_value; + } + + /** + * Get the long value. + * + * @return The long value. + * @throws ClassCastException if the entry value is not of long type. + */ + public long getInteger() { + if (m_type != NetworkTableType.kInteger) { + throw new ClassCastException("cannot convert " + m_type + " to long"); + } + return ((Number) m_value).longValue(); + } + + /** + * Get the float value. + * + * @return The float value. + * @throws ClassCastException if the entry value is not of float type. + */ + public float getFloat() { + if (m_type != NetworkTableType.kFloat) { + throw new ClassCastException("cannot convert " + m_type + " to float"); + } + return ((Number) m_value).floatValue(); + } + + /** + * Get the double value. + * + * @return The double value. + * @throws ClassCastException if the entry value is not of double type. + */ + public double getDouble() { + if (m_type != NetworkTableType.kDouble) { + throw new ClassCastException("cannot convert " + m_type + " to double"); + } + return ((Number) m_value).doubleValue(); + } + + /** + * Get the String value. + * + * @return The String value. + * @throws ClassCastException if the entry value is not of String type. + */ + public String getString() { + if (m_type != NetworkTableType.kString) { + throw new ClassCastException("cannot convert " + m_type + " to String"); + } + return (String) m_value; + } + + /** + * Get the byte[] value. + * + * @return The byte[] value. + * @throws ClassCastException if the entry value is not of byte[] type. + */ + public byte[] getRaw() { + if (m_type != NetworkTableType.kRaw) { + throw new ClassCastException("cannot convert " + m_type + " to byte[]"); + } + return (byte[]) m_value; + } + + /** + * Get the boolean[] value. + * + * @return The boolean[] value. + * @throws ClassCastException if the entry value is not of boolean[] type. + */ + public boolean[] getBooleanArray() { + if (m_type != NetworkTableType.kBooleanArray) { + throw new ClassCastException("cannot convert " + m_type + " to boolean[]"); + } + return (boolean[]) m_value; + } + + /** + * Get the long[] value. + * + * @return The long[] value. + * @throws ClassCastException if the entry value is not of long[] type. + */ + public long[] getIntegerArray() { + if (m_type != NetworkTableType.kIntegerArray) { + throw new ClassCastException("cannot convert " + m_type + " to long[]"); + } + return (long[]) m_value; + } + + /** + * Get the float[] value. + * + * @return The float[] value. + * @throws ClassCastException if the entry value is not of float[] type. + */ + public float[] getFloatArray() { + if (m_type != NetworkTableType.kFloatArray) { + throw new ClassCastException("cannot convert " + m_type + " to float[]"); + } + return (float[]) m_value; + } + + /** + * Get the double[] value. + * + * @return The double[] value. + * @throws ClassCastException if the entry value is not of double[] type. + */ + public double[] getDoubleArray() { + if (m_type != NetworkTableType.kDoubleArray) { + throw new ClassCastException("cannot convert " + m_type + " to double[]"); + } + return (double[]) m_value; + } + + /** + * Get the String[] value. + * + * @return The String[] value. + * @throws ClassCastException if the entry value is not of String[] type. + */ + public String[] getStringArray() { + if (m_type != NetworkTableType.kStringArray) { + throw new ClassCastException("cannot convert " + m_type + " to String[]"); + } + return (String[]) m_value; + } + + /* + * Factory functions. + */ + + /** + * Creates a boolean value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeBoolean(boolean value) { + return new NetworkTableValue(NetworkTableType.kBoolean, Boolean.valueOf(value)); + } + + /** + * Creates a boolean value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeBoolean(boolean value, long time) { + return new NetworkTableValue(NetworkTableType.kBoolean, Boolean.valueOf(value), time); + } + + /** + * Creates a long value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeInteger(long value) { + return new NetworkTableValue(NetworkTableType.kInteger, Long.valueOf(value)); + } + + /** + * Creates a long value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeInteger(long value, long time) { + return new NetworkTableValue(NetworkTableType.kInteger, Long.valueOf(value), time); + } + + /** + * Creates a float value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeFloat(float value) { + return new NetworkTableValue(NetworkTableType.kFloat, Float.valueOf(value)); + } + + /** + * Creates a float value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeFloat(float value, long time) { + return new NetworkTableValue(NetworkTableType.kFloat, Float.valueOf(value), time); + } + + /** + * Creates a double value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeDouble(double value) { + return new NetworkTableValue(NetworkTableType.kDouble, Double.valueOf(value)); + } + + /** + * Creates a double value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeDouble(double value, long time) { + return new NetworkTableValue(NetworkTableType.kDouble, Double.valueOf(value), time); + } + + /** + * Creates a String value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeString(String value) { + return new NetworkTableValue(NetworkTableType.kString, (value)); + } + + /** + * Creates a String value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeString(String value, long time) { + return new NetworkTableValue(NetworkTableType.kString, (value), time); + } + + /** + * Creates a byte[] value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeRaw(byte[] value) { + return new NetworkTableValue(NetworkTableType.kRaw, (value)); + } + + /** + * Creates a byte[] value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeRaw(byte[] value, long time) { + return new NetworkTableValue(NetworkTableType.kRaw, (value), time); + } + + /** + * Creates a boolean[] value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeBooleanArray(boolean[] value) { + return new NetworkTableValue(NetworkTableType.kBooleanArray, (value)); + } + + /** + * Creates a boolean[] value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeBooleanArray(boolean[] value, long time) { + return new NetworkTableValue(NetworkTableType.kBooleanArray, (value), time); + } + + /** + * Creates a boolean[] value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeBooleanArray(Boolean[] value) { + return new NetworkTableValue(NetworkTableType.kBooleanArray, toNativeBooleanArray(value)); + } + + /** + * Creates a boolean[] value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeBooleanArray(Boolean[] value, long time) { + return new NetworkTableValue(NetworkTableType.kBooleanArray, toNativeBooleanArray(value), time); + } + + /** + * Creates a long[] value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeIntegerArray(long[] value) { + return new NetworkTableValue(NetworkTableType.kIntegerArray, (value)); + } + + /** + * Creates a long[] value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeIntegerArray(long[] value, long time) { + return new NetworkTableValue(NetworkTableType.kIntegerArray, (value), time); + } + + /** + * Creates a long[] value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeIntegerArray(Long[] value) { + return new NetworkTableValue(NetworkTableType.kIntegerArray, toNativeIntegerArray(value)); + } + + /** + * Creates a long[] value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeIntegerArray(Long[] value, long time) { + return new NetworkTableValue(NetworkTableType.kIntegerArray, toNativeIntegerArray(value), time); + } + + /** + * Creates a float[] value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeFloatArray(float[] value) { + return new NetworkTableValue(NetworkTableType.kFloatArray, (value)); + } + + /** + * Creates a float[] value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeFloatArray(float[] value, long time) { + return new NetworkTableValue(NetworkTableType.kFloatArray, (value), time); + } + + /** + * Creates a float[] value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeFloatArray(Float[] value) { + return new NetworkTableValue(NetworkTableType.kFloatArray, toNativeFloatArray(value)); + } + + /** + * Creates a float[] value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeFloatArray(Float[] value, long time) { + return new NetworkTableValue(NetworkTableType.kFloatArray, toNativeFloatArray(value), time); + } + + /** + * Creates a double[] value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeDoubleArray(double[] value) { + return new NetworkTableValue(NetworkTableType.kDoubleArray, (value)); + } + + /** + * Creates a double[] value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeDoubleArray(double[] value, long time) { + return new NetworkTableValue(NetworkTableType.kDoubleArray, (value), time); + } + + /** + * Creates a double[] value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeDoubleArray(Double[] value) { + return new NetworkTableValue(NetworkTableType.kDoubleArray, toNativeDoubleArray(value)); + } + + /** + * Creates a double[] value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeDoubleArray(Double[] value, long time) { + return new NetworkTableValue(NetworkTableType.kDoubleArray, toNativeDoubleArray(value), time); + } + + /** + * Creates a String[] value. + * + * @param value the value + * @return The entry value + */ + public static NetworkTableValue makeStringArray(String[] value) { + return new NetworkTableValue(NetworkTableType.kStringArray, (value)); + } + + /** + * Creates a String[] value. + * + * @param value the value + * @param time the creation time to use (instead of the current time) + * @return The entry value + */ + public static NetworkTableValue makeStringArray(String[] value, long time) { + return new NetworkTableValue(NetworkTableType.kStringArray, (value), time); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof NetworkTableValue)) { + return false; + } + NetworkTableValue ntOther = (NetworkTableValue) other; + return m_type == ntOther.m_type && m_value.equals(ntOther.m_value); + } + + @Override + public int hashCode() { + return Objects.hash(m_type, m_value); + } + + // arraycopy() doesn't know how to unwrap boxed values; this is a false positive in PMD + // (see https://sourceforge.net/p/pmd/bugs/804/) + @SuppressWarnings("PMD.AvoidArrayLoops") + static boolean[] toNativeBooleanArray(Boolean[] arr) { + boolean[] out = new boolean[arr.length]; + for (int i = 0; i < arr.length; i++) { + out[i] = arr[i]; + } + return out; + } + + @SuppressWarnings("PMD.AvoidArrayLoops") + static double[] toNativeDoubleArray(Number[] arr) { + double[] out = new double[arr.length]; + for (int i = 0; i < arr.length; i++) { + out[i] = arr[i].doubleValue(); + } + return out; + } + + @SuppressWarnings("PMD.AvoidArrayLoops") + static long[] toNativeIntegerArray(Number[] arr) { + long[] out = new long[arr.length]; + for (int i = 0; i < arr.length; i++) { + out[i] = arr[i].longValue(); + } + return out; + } + + @SuppressWarnings("PMD.AvoidArrayLoops") + static float[] toNativeFloatArray(Number[] arr) { + float[] out = new float[arr.length]; + for (int i = 0; i < arr.length; i++) { + out[i] = arr[i].floatValue(); + } + return out; + } + + @SuppressWarnings("PMD.AvoidArrayLoops") + static Boolean[] fromNativeBooleanArray(boolean[] arr) { + Boolean[] out = new Boolean[arr.length]; + for (int i = 0; i < arr.length; i++) { + out[i] = arr[i]; + } + return out; + } + + @SuppressWarnings("PMD.AvoidArrayLoops") + static Long[] fromNativeIntegerArray(long[] arr) { + Long[] out = new Long[arr.length]; + for (int i = 0; i < arr.length; i++) { + out[i] = arr[i]; + } + return out; + } + + @SuppressWarnings("PMD.AvoidArrayLoops") + static Float[] fromNativeFloatArray(float[] arr) { + Float[] out = new Float[arr.length]; + for (int i = 0; i < arr.length; i++) { + out[i] = arr[i]; + } + return out; + } + + @SuppressWarnings("PMD.AvoidArrayLoops") + static Double[] fromNativeDoubleArray(double[] arr) { + Double[] out = new Double[arr.length]; + for (int i = 0; i < arr.length; i++) { + out[i] = arr[i]; + } + return out; + } + + private NetworkTableType m_type; + private Object m_value; + private long m_time; + private long m_serverTime; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/NetworkTablesJNI.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/NetworkTablesJNI.java new file mode 100644 index 00000000000..4b4fa5cb6ed --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/NetworkTablesJNI.java @@ -0,0 +1,1637 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import edu.wpi.first.util.RuntimeLoader; +import edu.wpi.first.util.datalog.DataLog; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.EnumSet; +import java.util.OptionalLong; +import java.util.concurrent.atomic.AtomicBoolean; + +/** NetworkTables JNI. */ +public final class NetworkTablesJNI { + static boolean libraryLoaded = false; + static RuntimeLoader loader = null; + + /** Sets whether JNI should be loaded in the static block. */ + public static class Helper { + private static AtomicBoolean extractOnStaticLoad = new AtomicBoolean(true); + + /** + * Returns true if the JNI should be loaded in the static block. + * + * @return True if the JNI should be loaded in the static block. + */ + public static boolean getExtractOnStaticLoad() { + return extractOnStaticLoad.get(); + } + + /** + * Sets whether the JNI should be loaded in the static block. + * + * @param load Whether the JNI should be loaded in the static block. + */ + public static void setExtractOnStaticLoad(boolean load) { + extractOnStaticLoad.set(load); + } + + /** Utility class. */ + private Helper() {} + } + + static { + if (Helper.getExtractOnStaticLoad()) { + try { + loader = + new RuntimeLoader<>( + "ntcorejni", RuntimeLoader.getDefaultExtractionRoot(), NetworkTablesJNI.class); + loader.loadLibrary(); + } catch (IOException ex) { + ex.printStackTrace(); + System.exit(1); + } + libraryLoaded = true; + } + } + + /** + * Force load the library. + * + * @throws IOException if the library fails to load + */ + public static synchronized void forceLoad() throws IOException { + if (libraryLoaded) { + return; + } + loader = + new RuntimeLoader<>( + "ntcorejni", RuntimeLoader.getDefaultExtractionRoot(), NetworkTablesJNI.class); + loader.loadLibrary(); + libraryLoaded = true; + } + + private static PubSubOptions buildOptions(PubSubOption... options) { + if (options.length == 0) { + return null; // optimize common case (JNI checks for null) + } + return new PubSubOptions(options); + } + + /** + * Returns default instance handle. + * + * @return Default instance handle. + */ + public static native int getDefaultInstance(); + + /** + * Creates an NT instance. + * + * @return NT instance handle. + */ + public static native int createInstance(); + + /** + * Destroys an NT instance. + * + * @param inst NT instance handle. + */ + public static native void destroyInstance(int inst); + + /** + * Returns NT instance from handle. + * + * @param handle NT instance handle. + * @return NT instance. + */ + public static native int getInstanceFromHandle(int handle); + + private static native int getEntryImpl( + int topic, int type, String typeStr, PubSubOptions options); + + /** + * Returns NT entry handle. + * + * @param inst NT instance handle. + * @param key NT entry key. + * @return NT entry handle. + */ + public static native int getEntry(int inst, String key); + + /** + * Returns NT entry handle. + * + * @param topic NT entry topic. + * @param type NT entry type. + * @param typeStr NT entry type as a string. + * @param options NT entry pubsub options. + * @return NT entry handle. + */ + public static int getEntry( + int topic, int type, String typeStr, PubSubOptions options) { + return getEntryImpl(topic, type, typeStr, options); + } + + /** + * Returns NT entry handle. + * + * @param topic NT entry topic. + * @param type NT entry type. + * @param typeStr NT entry type as a string. + * @param options NT entry pubsub options. + * @return NT entry handle. + */ + public static int getEntry( + int topic, int type, String typeStr, PubSubOption... options) { + return getEntryImpl(topic, type, typeStr, buildOptions(options)); + } + + /** + * Returns NT entry name. + * + * @param entry NT entry handle. + * @return NT entry name. + */ + public static native String getEntryName(int entry); + + /** + * Returns NT entry last change time in microseconds. + * + * @param entry NT entry handle. + * @return NT entry last change time in microseconds. + */ + public static native long getEntryLastChange(int entry); + + /** + * Returns NT entry type. + * + * @param entry NT entry handle. + * @return NT entry type. + */ + public static native int getType(int entry); + + /* Topic functions */ + + /** + * Returns list of topic handles. + * + * @param inst NT instance handle. + * @param prefix Topic prefix. + * @param types Topic types. + * @return List of topic handles. + */ + public static native int[] getTopics(int inst, String prefix, int types); + + /** + * Returns list of topic handles. + * + * @param inst NT instance handle. + * @param prefix Topic prefix. + * @param types Topic types as strings. + * @return List of topic handles. + */ + public static native int[] getTopicsStr(int inst, String prefix, String[] types); + + /** + * Returns list of topic infos. + * + * @param instObject NT instance. + * @param inst NT instance handle. + * @param prefix Topic prefix. + * @param types Topic types. + * @return List of topic infos. + */ + public static native TopicInfo[] getTopicInfos( + NetworkTableInstance instObject, int inst, String prefix, int types); + + /** + * Returns list of topic infos. + * + * @param instObject NT instance. + * @param inst NT instance handle. + * @param prefix Topic prefix. + * @param types Topic types as strings. + * @return List of topic infos. + */ + public static native TopicInfo[] getTopicInfosStr( + NetworkTableInstance instObject, int inst, String prefix, String[] types); + + /** + * Returns Topic handle. + * + * @param inst NT instance handle. + * @param name Topic name. + * @return Topic handle. + */ + public static native int getTopic(int inst, String name); + + /** + * Returns topic name. + * + * @param topic Topic handle. + * @return Topic name. + */ + public static native String getTopicName(int topic); + + /** + * Returns topic type. + * + * @param topic Topic handle. + * @return Topic type. + */ + public static native int getTopicType(int topic); + + /** + * Sets topic persistency. + * + * @param topic Topic handle. + * @param value True if topic should be persistent. + */ + public static native void setTopicPersistent(int topic, boolean value); + + /** + * Returns true if topic is persistent. + * + * @param topic Topic handle. + * @return True if topic is persistent. + */ + public static native boolean getTopicPersistent(int topic); + + /** + * Sets whether topic is retained. + * + * @param topic Topic handle. + * @param value True if topic should be retained. + */ + public static native void setTopicRetained(int topic, boolean value); + + /** + * Returns true if topic is retained. + * + * @param topic Topic handle. + * @return True if topic is retained. + */ + public static native boolean getTopicRetained(int topic); + + /** + * Sets topic caching. + * + * @param topic Topic handle. + * @param value True if topic should be cached. + */ + public static native void setTopicCached(int topic, boolean value); + + /** + * Returns true if topic is cached. + * + * @param topic Topic handle. + * @return True if topic is cached. + */ + public static native boolean getTopicCached(int topic); + + /** + * Returns topic type as string. + * + * @param topic Topic handle. + * @return Topic type as string. + */ + public static native String getTopicTypeString(int topic); + + /** + * Returns true if topic exists. + * + * @param topic Topic handle. + * @return True if topic exists. + */ + public static native boolean getTopicExists(int topic); + + /** + * Returns topic property. + * + * @param topic Topic handle. + * @param name Property name. + * @return Topic property. + */ + public static native String getTopicProperty(int topic, String name); + + /** + * Sets topic property. + * + * @param topic Topic handle. + * @param name Property name. + * @param value Property value. + */ + public static native void setTopicProperty(int topic, String name, String value); + + /** + * Deletes topic property. + * + * @param topic Topic handle. + * @param name Property name. + */ + public static native void deleteTopicProperty(int topic, String name); + + /** + * Returns topic properties. + * + * @param topic Topic handle. + * @return Topic properties. + */ + public static native String getTopicProperties(int topic); + + /** + * Sets topic properties. + * + * @param topic Topic handle. + * @param properties Topic properties. + */ + public static native void setTopicProperties(int topic, String properties); + + /** + * Subscribes to topic. + * + * @param topic Topic handle. + * @param type Topic type. + * @param typeStr Topic type as a string. + * @param options Pubsub options. + * @return Subscriber handle. + */ + public static native int subscribe( + int topic, int type, String typeStr, PubSubOptions options); + + /** + * Subscribes to topic. + * + * @param topic Topic handle. + * @param type Topic type. + * @param typeStr Topic type as a string. + * @param options Pubsub options. + * @return Subscriber handle. + */ + public static int subscribe( + int topic, int type, String typeStr, PubSubOption... options) { + return subscribe(topic, type, typeStr, buildOptions(options)); + } + + /** + * Unsubscribes from topic. + * + * @param sub Subscriber handle. + */ + public static native void unsubscribe(int sub); + + /** + * Publishes topic. + * + * @param topic Topic handle. + * @param type Topic type. + * @param typeStr Topic type as a string. + * @param options Pubsub options. + * @return Publish handle. + */ + public static native int publish( + int topic, int type, String typeStr, PubSubOptions options); + + /** + * Publishes topic. + * + * @param topic Topic handle. + * @param type Topic type. + * @param typeStr Topic type as a string. + * @param options Pubsub options. + * @return Publish handle. + */ + public static int publish( + int topic, int type, String typeStr, PubSubOption... options) { + return publish(topic, type, typeStr, buildOptions(options)); + } + + /** + * Publishes topic. + * + * @param topic Topic handle. + * @param type Topic type. + * @param typeStr Topic type as a string. + * @param properties Topic properties. + * @param options Pubsub options. + * @return Publish handle. + */ + public static native int publishEx( + int topic, int type, String typeStr, String properties, PubSubOptions options); + + /** + * Publishes topic. + * + * @param topic Topic handle. + * @param type Topic type. + * @param typeStr Topic type as a string. + * @param properties Topic properties. + * @param options Pubsub options. + * @return Publish handle. + */ + public static int publishEx( + int topic, int type, String typeStr, String properties, PubSubOption... options) { + return publishEx(topic, type, typeStr, properties, buildOptions(options)); + } + + /** + * Unpublishes topic. + * + * @param pubentry Publish entry handle. + */ + public static native void unpublish(int pubentry); + + /** + * Releases NT entry. + * + * @param entry NT entry handle. + */ + public static native void releaseEntry(int entry); + + /** + * Relesaes pubsub entry. + * + * @param pubsubentry Pubsub entry handle. + */ + public static native void release(int pubsubentry); + + /** + * Returns topic from pubsub entry handle. + * + * @param pubsubentry Pubsub entry handle. + * @return Topic handle. + */ + public static native int getTopicFromHandle(int pubsubentry); + + /** + * Subscribes to multiple topics. + * + * @param inst NT instance handle. + * @param prefixes List of topic prefixes. + * @param options Pubsub options. + * @return Subscribe handle. + */ + public static native int subscribeMultiple(int inst, String[] prefixes, PubSubOptions options); + + /** + * Subscribes to multiple topics. + * + * @param inst NT instance handle. + * @param prefixes List of topic prefixes. + * @param options Pubsub options. + * @return Subscribe handle. + */ + public static int subscribeMultiple(int inst, String[] prefixes, PubSubOption... options) { + return subscribeMultiple(inst, prefixes, buildOptions(options)); + } + + /** + * Unsubscribes from multiple topics. + * + * @param sub Subscribe handle. + */ + public static native void unsubscribeMultiple(int sub); + + /** + * Returns timestamped topic value as an atomic Boolean. + * + * @param subentry Subentry handle. + * @param defaultValue Default value. + * @return Timestamped topic value. + */ + public static native TimestampedBoolean getAtomicBoolean( + int subentry, boolean defaultValue); + + /** + * Returns queued timestamped topic values. + * + * @param subentry Subentry handle. + * @return List of timestamped topic values. + */ + public static native TimestampedBoolean[] readQueueBoolean(int subentry); + + /** + * Returns queued topic values. + * + * @param subentry Subentry handle. + * @return List of topic values. + */ + public static native boolean[] readQueueValuesBoolean(int subentry); + + /** + * Sets topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Topic value. + * @return True if set succeeded. + */ + public static native boolean setBoolean(int entry, long time, boolean value); + + /** + * Returns topic value. + * + * @param entry Entry handle. + * @param defaultValue Default value. + * @return Topic value. + */ + public static native boolean getBoolean(int entry, boolean defaultValue); + + /** + * Sets default topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static native boolean setDefaultBoolean(int entry, long time, boolean defaultValue); + + + /** + * Returns timestamped topic value as an atomic Integer. + * + * @param subentry Subentry handle. + * @param defaultValue Default value. + * @return Timestamped topic value. + */ + public static native TimestampedInteger getAtomicInteger( + int subentry, long defaultValue); + + /** + * Returns queued timestamped topic values. + * + * @param subentry Subentry handle. + * @return List of timestamped topic values. + */ + public static native TimestampedInteger[] readQueueInteger(int subentry); + + /** + * Returns queued topic values. + * + * @param subentry Subentry handle. + * @return List of topic values. + */ + public static native long[] readQueueValuesInteger(int subentry); + + /** + * Sets topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Topic value. + * @return True if set succeeded. + */ + public static native boolean setInteger(int entry, long time, long value); + + /** + * Returns topic value. + * + * @param entry Entry handle. + * @param defaultValue Default value. + * @return Topic value. + */ + public static native long getInteger(int entry, long defaultValue); + + /** + * Sets default topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static native boolean setDefaultInteger(int entry, long time, long defaultValue); + + + /** + * Returns timestamped topic value as an atomic Float. + * + * @param subentry Subentry handle. + * @param defaultValue Default value. + * @return Timestamped topic value. + */ + public static native TimestampedFloat getAtomicFloat( + int subentry, float defaultValue); + + /** + * Returns queued timestamped topic values. + * + * @param subentry Subentry handle. + * @return List of timestamped topic values. + */ + public static native TimestampedFloat[] readQueueFloat(int subentry); + + /** + * Returns queued topic values. + * + * @param subentry Subentry handle. + * @return List of topic values. + */ + public static native float[] readQueueValuesFloat(int subentry); + + /** + * Sets topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Topic value. + * @return True if set succeeded. + */ + public static native boolean setFloat(int entry, long time, float value); + + /** + * Returns topic value. + * + * @param entry Entry handle. + * @param defaultValue Default value. + * @return Topic value. + */ + public static native float getFloat(int entry, float defaultValue); + + /** + * Sets default topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static native boolean setDefaultFloat(int entry, long time, float defaultValue); + + + /** + * Returns timestamped topic value as an atomic Double. + * + * @param subentry Subentry handle. + * @param defaultValue Default value. + * @return Timestamped topic value. + */ + public static native TimestampedDouble getAtomicDouble( + int subentry, double defaultValue); + + /** + * Returns queued timestamped topic values. + * + * @param subentry Subentry handle. + * @return List of timestamped topic values. + */ + public static native TimestampedDouble[] readQueueDouble(int subentry); + + /** + * Returns queued topic values. + * + * @param subentry Subentry handle. + * @return List of topic values. + */ + public static native double[] readQueueValuesDouble(int subentry); + + /** + * Sets topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Topic value. + * @return True if set succeeded. + */ + public static native boolean setDouble(int entry, long time, double value); + + /** + * Returns topic value. + * + * @param entry Entry handle. + * @param defaultValue Default value. + * @return Topic value. + */ + public static native double getDouble(int entry, double defaultValue); + + /** + * Sets default topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static native boolean setDefaultDouble(int entry, long time, double defaultValue); + + + /** + * Returns timestamped topic value as an atomic String. + * + * @param subentry Subentry handle. + * @param defaultValue Default value. + * @return Timestamped topic value. + */ + public static native TimestampedString getAtomicString( + int subentry, String defaultValue); + + /** + * Returns queued timestamped topic values. + * + * @param subentry Subentry handle. + * @return List of timestamped topic values. + */ + public static native TimestampedString[] readQueueString(int subentry); + + /** + * Returns queued topic values. + * + * @param subentry Subentry handle. + * @return List of topic values. + */ + public static native String[] readQueueValuesString(int subentry); + + /** + * Sets topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Topic value. + * @return True if set succeeded. + */ + public static native boolean setString(int entry, long time, String value); + + /** + * Returns topic value. + * + * @param entry Entry handle. + * @param defaultValue Default value. + * @return Topic value. + */ + public static native String getString(int entry, String defaultValue); + + /** + * Sets default topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static native boolean setDefaultString(int entry, long time, String defaultValue); + + + /** + * Returns timestamped topic value as an atomic Raw. + * + * @param subentry Subentry handle. + * @param defaultValue Default value. + * @return Timestamped topic value. + */ + public static native TimestampedRaw getAtomicRaw( + int subentry, byte[] defaultValue); + + /** + * Returns queued timestamped topic values. + * + * @param subentry Subentry handle. + * @return List of timestamped topic values. + */ + public static native TimestampedRaw[] readQueueRaw(int subentry); + + /** + * Returns queued topic values. + * + * @param subentry Subentry handle. + * @return List of topic values. + */ + public static native byte[][] readQueueValuesRaw(int subentry); + + /** + * Sets raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Raw value buffer. + * @return True if set succeeded. + */ + public static boolean setRaw(int entry, long time, byte[] value) { + return setRaw(entry, time, value, 0, value.length); + } + + /** + * Sets raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Raw value buffer. + * @param start Value's offset into buffer. + * @param len Length of value in buffer. + * @return True if set succeeded. + */ + public static native boolean setRaw(int entry, long time, byte[] value, int start, int len); + + /** + * Sets raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Raw value buffer. + * @return True if set succeeded. + */ + public static boolean setRaw(int entry, long time, ByteBuffer value) { + int pos = value.position(); + return setRaw(entry, time, value, pos, value.capacity() - pos); + } + + /** + * Sets raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Raw value buffer. + * @param start Value's offset into buffer. + * @param len Length of value in buffer. + * @return True if set succeeded. + */ + public static boolean setRaw(int entry, long time, ByteBuffer value, int start, int len) { + if (value.isDirect()) { + if (start < 0) { + throw new IndexOutOfBoundsException("start must be >= 0"); + } + if (len < 0) { + throw new IndexOutOfBoundsException("len must be >= 0"); + } + if ((start + len) > value.capacity()) { + throw new IndexOutOfBoundsException("start + len must be smaller than buffer capacity"); + } + return setRawBuffer(entry, time, value, start, len); + } else if (value.hasArray()) { + return setRaw(entry, time, value.array(), value.arrayOffset() + start, len); + } else { + throw new UnsupportedOperationException("ByteBuffer must be direct or have a backing array"); + } + } + + /** + * Sets raw topic value buffer. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Raw value buffer. + * @param start Value's offset into buffer. + * @param len Length of value in buffer. + * @return True if set succeeded. + */ + private static native boolean setRawBuffer(int entry, long time, ByteBuffer value, int start, int len); + + /** + * Returns topic value. + * + * @param entry Entry handle. + * @param defaultValue Default value. + * @return Topic value. + */ + public static native byte[] getRaw(int entry, byte[] defaultValue); + + /** + * Sets default raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static boolean setDefaultRaw(int entry, long time, byte[] defaultValue) { + return setDefaultRaw(entry, time, defaultValue, 0, defaultValue.length); + } + + /** + * Sets default raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @param start Value's offset into buffer. + * @param len Length of value in buffer. + * @return True if set succeeded. + */ + public static native boolean setDefaultRaw(int entry, long time, byte[] defaultValue, int start, int len); + + /** + * Sets default raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static boolean setDefaultRaw(int entry, long time, ByteBuffer defaultValue) { + int pos = defaultValue.position(); + return setDefaultRaw(entry, time, defaultValue, pos, defaultValue.limit() - pos); + } + + /** + * Sets default raw topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @param start Value's offset into buffer. + * @param len Length of value in buffer. + * @return True if set succeeded. + */ + public static boolean setDefaultRaw(int entry, long time, ByteBuffer defaultValue, int start, int len) { + if (defaultValue.isDirect()) { + if (start < 0) { + throw new IndexOutOfBoundsException("start must be >= 0"); + } + if (len < 0) { + throw new IndexOutOfBoundsException("len must be >= 0"); + } + if ((start + len) > defaultValue.capacity()) { + throw new IndexOutOfBoundsException("start + len must be smaller than buffer capacity"); + } + return setDefaultRawBuffer(entry, time, defaultValue, start, len); + } else if (defaultValue.hasArray()) { + return setDefaultRaw(entry, time, defaultValue.array(), defaultValue.arrayOffset() + start, len); + } else { + throw new UnsupportedOperationException("ByteBuffer must be direct or have a backing array"); + } + } + + /** + * Sets default raw topic value buffer. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @param start Value's offset into buffer. + * @param len Length of value in buffer. + * @return True if set succeeded. + */ + private static native boolean setDefaultRawBuffer(int entry, long time, ByteBuffer defaultValue, int start, int len); + + + /** + * Returns timestamped topic value as an atomic BooleanArray. + * + * @param subentry Subentry handle. + * @param defaultValue Default value. + * @return Timestamped topic value. + */ + public static native TimestampedBooleanArray getAtomicBooleanArray( + int subentry, boolean[] defaultValue); + + /** + * Returns queued timestamped topic values. + * + * @param subentry Subentry handle. + * @return List of timestamped topic values. + */ + public static native TimestampedBooleanArray[] readQueueBooleanArray(int subentry); + + /** + * Returns queued topic values. + * + * @param subentry Subentry handle. + * @return List of topic values. + */ + public static native boolean[][] readQueueValuesBooleanArray(int subentry); + + /** + * Sets topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Topic value. + * @return True if set succeeded. + */ + public static native boolean setBooleanArray(int entry, long time, boolean[] value); + + /** + * Returns topic value. + * + * @param entry Entry handle. + * @param defaultValue Default value. + * @return Topic value. + */ + public static native boolean[] getBooleanArray(int entry, boolean[] defaultValue); + + /** + * Sets default topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static native boolean setDefaultBooleanArray(int entry, long time, boolean[] defaultValue); + + + /** + * Returns timestamped topic value as an atomic IntegerArray. + * + * @param subentry Subentry handle. + * @param defaultValue Default value. + * @return Timestamped topic value. + */ + public static native TimestampedIntegerArray getAtomicIntegerArray( + int subentry, long[] defaultValue); + + /** + * Returns queued timestamped topic values. + * + * @param subentry Subentry handle. + * @return List of timestamped topic values. + */ + public static native TimestampedIntegerArray[] readQueueIntegerArray(int subentry); + + /** + * Returns queued topic values. + * + * @param subentry Subentry handle. + * @return List of topic values. + */ + public static native long[][] readQueueValuesIntegerArray(int subentry); + + /** + * Sets topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Topic value. + * @return True if set succeeded. + */ + public static native boolean setIntegerArray(int entry, long time, long[] value); + + /** + * Returns topic value. + * + * @param entry Entry handle. + * @param defaultValue Default value. + * @return Topic value. + */ + public static native long[] getIntegerArray(int entry, long[] defaultValue); + + /** + * Sets default topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static native boolean setDefaultIntegerArray(int entry, long time, long[] defaultValue); + + + /** + * Returns timestamped topic value as an atomic FloatArray. + * + * @param subentry Subentry handle. + * @param defaultValue Default value. + * @return Timestamped topic value. + */ + public static native TimestampedFloatArray getAtomicFloatArray( + int subentry, float[] defaultValue); + + /** + * Returns queued timestamped topic values. + * + * @param subentry Subentry handle. + * @return List of timestamped topic values. + */ + public static native TimestampedFloatArray[] readQueueFloatArray(int subentry); + + /** + * Returns queued topic values. + * + * @param subentry Subentry handle. + * @return List of topic values. + */ + public static native float[][] readQueueValuesFloatArray(int subentry); + + /** + * Sets topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Topic value. + * @return True if set succeeded. + */ + public static native boolean setFloatArray(int entry, long time, float[] value); + + /** + * Returns topic value. + * + * @param entry Entry handle. + * @param defaultValue Default value. + * @return Topic value. + */ + public static native float[] getFloatArray(int entry, float[] defaultValue); + + /** + * Sets default topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static native boolean setDefaultFloatArray(int entry, long time, float[] defaultValue); + + + /** + * Returns timestamped topic value as an atomic DoubleArray. + * + * @param subentry Subentry handle. + * @param defaultValue Default value. + * @return Timestamped topic value. + */ + public static native TimestampedDoubleArray getAtomicDoubleArray( + int subentry, double[] defaultValue); + + /** + * Returns queued timestamped topic values. + * + * @param subentry Subentry handle. + * @return List of timestamped topic values. + */ + public static native TimestampedDoubleArray[] readQueueDoubleArray(int subentry); + + /** + * Returns queued topic values. + * + * @param subentry Subentry handle. + * @return List of topic values. + */ + public static native double[][] readQueueValuesDoubleArray(int subentry); + + /** + * Sets topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Topic value. + * @return True if set succeeded. + */ + public static native boolean setDoubleArray(int entry, long time, double[] value); + + /** + * Returns topic value. + * + * @param entry Entry handle. + * @param defaultValue Default value. + * @return Topic value. + */ + public static native double[] getDoubleArray(int entry, double[] defaultValue); + + /** + * Sets default topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static native boolean setDefaultDoubleArray(int entry, long time, double[] defaultValue); + + + /** + * Returns timestamped topic value as an atomic StringArray. + * + * @param subentry Subentry handle. + * @param defaultValue Default value. + * @return Timestamped topic value. + */ + public static native TimestampedStringArray getAtomicStringArray( + int subentry, String[] defaultValue); + + /** + * Returns queued timestamped topic values. + * + * @param subentry Subentry handle. + * @return List of timestamped topic values. + */ + public static native TimestampedStringArray[] readQueueStringArray(int subentry); + + /** + * Returns queued topic values. + * + * @param subentry Subentry handle. + * @return List of topic values. + */ + public static native String[][] readQueueValuesStringArray(int subentry); + + /** + * Sets topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param value Topic value. + * @return True if set succeeded. + */ + public static native boolean setStringArray(int entry, long time, String[] value); + + /** + * Returns topic value. + * + * @param entry Entry handle. + * @param defaultValue Default value. + * @return Topic value. + */ + public static native String[] getStringArray(int entry, String[] defaultValue); + + /** + * Sets default topic value. + * + * @param entry Entry handle. + * @param time Time in microseconds. + * @param defaultValue Default value. + * @return True if set succeeded. + */ + public static native boolean setDefaultStringArray(int entry, long time, String[] defaultValue); + + + /** + * Returns queued subentry values. + * + * @param subentry Subentry handle. + * @return List of queued subentry values. + */ + public static native NetworkTableValue[] readQueueValue(int subentry); + + /** + * Returns entry's NT value. + * + * @param entry Entry handle. + * @return Entry's NT value. + */ + public static native NetworkTableValue getValue(int entry); + + /** + * Sets entry flags. + * + * @param entry Entry handle. + * @param flags Entry flags. + */ + public static native void setEntryFlags(int entry, int flags); + + /** + * Returns entry flags. + * + * @param entry Entry handle. + * @return Entry flags. + */ + public static native int getEntryFlags(int entry); + + /** + * Returns topic info. + * + * @param inst NT instance handle. + * @param topic Topic handle. + * @return Topic info. + */ + public static native TopicInfo getTopicInfo(NetworkTableInstance inst, int topic); + + /** + * Creates a listener poller. + * + * @param inst NT instance handle. + * @return Listener poller handle. + */ + public static native int createListenerPoller(int inst); + + /** + * Destroys listener poller. + * + * @param poller Listener poller handle. + */ + public static native void destroyListenerPoller(int poller); + + /** + * Converts NT event kinds to mask. + * + * @param kinds Enum set of NT event kinds. + * @return NT event mask. + */ + private static int kindsToMask(EnumSet kinds) { + int mask = 0; + for (NetworkTableEvent.Kind kind : kinds) { + mask |= kind.getValue(); + } + return mask; + } + + /** + * Adds listener. + * + * @param poller Listener poller handle. + * @param prefixes Topic prefixes. + * @param kinds Enum set of NT event kinds. + * @return Listener handle. + */ + public static int addListener(int poller, String[] prefixes, EnumSet kinds) { + return addListener(poller, prefixes, kindsToMask(kinds)); + } + + /** + * Adds listener. + * + * @param poller Listener poller handle. + * @param handle Topic handle. + * @param kinds Enum set of NT event kinds. + * @return Listener handle. + */ + public static int addListener(int poller, int handle, EnumSet kinds) { + return addListener(poller, handle, kindsToMask(kinds)); + } + + /** + * Adds listener. + * + * @param poller Listener poller handle. + * @param prefixes Topic prefixes. + * @param mask NT event mask. + * @return Listener handle. + */ + public static native int addListener(int poller, String[] prefixes, int mask); + + /** + * Adds listener. + * + * @param poller Listener poller handle. + * @param handle Topic handle. + * @param mask NT event mask. + * @return Listener handle. + */ + public static native int addListener(int poller, int handle, int mask); + + /** + * Returns NT events from listener queue. + * + * @param inst NT instance handle. + * @param poller Listener poller handle. + * @return List of NT events. + */ + public static native NetworkTableEvent[] readListenerQueue( + NetworkTableInstance inst, int poller); + + /** + * Removes listener. + * + * @param listener Listener handle. + */ + public static native void removeListener(int listener); + + /** + * Returns network mode. + * + * @param inst NT instance handle. + * @return Network mode. + */ + public static native int getNetworkMode(int inst); + + /** + * Starts local-only operation. Prevents calls to startServer or startClient from taking effect. + * Has no effect if startServer or startClient has already been called. + * + * @param inst NT instance handle. + */ + public static native void startLocal(int inst); + + /** + * Stops local-only operation. startServer or startClient can be called after this call to start + * a server or client. + * + * @param inst NT instance handle. + */ + public static native void stopLocal(int inst); + + /** + * Starts a server using the specified filename, listening address, and port. + * + * @param inst NT instance handle. + * @param persistFilename the name of the persist file to use + * @param listenAddress the address to listen on, or empty to listen on any address + * @param port3 port to communicate over (NT3) + * @param port4 port to communicate over (NT4) + */ + public static native void startServer( + int inst, String persistFilename, String listenAddress, int port3, int port4); + + /** + * Stops the server if it is running. + * + * @param inst NT instance handle. + */ + public static native void stopServer(int inst); + + /** + * Starts a NT3 client. Use SetServer or SetServerTeam to set the server name and port. + * + * @param inst NT instance handle. + * @param identity network identity to advertise (cannot be empty string) + */ + public static native void startClient3(int inst, String identity); + + /** + * Starts a NT4 client. Use SetServer or SetServerTeam to set the server name and port. + * + * @param inst NT instance handle. + * @param identity network identity to advertise (cannot be empty string) + */ + public static native void startClient4(int inst, String identity); + + /** + * Stops the client if it is running. + * + * @param inst NT instance handle. + */ + public static native void stopClient(int inst); + + /** + * Sets server address and port for client (without restarting client). + * + * @param inst NT instance handle. + * @param serverName server name + * @param port port to communicate over + */ + public static native void setServer(int inst, String serverName, int port); + + /** + * Sets server addresses and ports for client (without restarting client). The client will + * attempt to connect to each server in round robin fashion. + * + * @param inst NT instance handle. + * @param serverNames array of server names + * @param ports array of port numbers (0=default) + */ + public static native void setServer(int inst, String[] serverNames, int[] ports); + + /** + * Sets server addresses and port for client (without restarting client). Connects using commonly + * known robot addresses for the specified team. + * + * @param inst NT instance handle. + * @param team team number + * @param port port to communicate over + */ + public static native void setServerTeam(int inst, int team, int port); + + /** + * Disconnects the client if it's running and connected. This will automatically start + * reconnection attempts to the current server list. + * + * @param inst NT instance handle. + */ + public static native void disconnect(int inst); + + /** + * Starts requesting server address from Driver Station. This connects to the Driver Station + * running on localhost to obtain the server IP address. + * + * @param inst NT instance handle. + * @param port server port to use in combination with IP from DS + */ + public static native void startDSClient(int inst, int port); + + /** + * Stops requesting server address from Driver Station. + * + * @param inst NT instance handle. + */ + public static native void stopDSClient(int inst); + + /** + * Flushes all updated values immediately to the local client/server. This does not flush to the + * network. + * + * @param inst NT instance handle. + */ + public static native void flushLocal(int inst); + + /** + * Flushes all updated values immediately to the network. Note: This is rate-limited to protect + * the network from flooding. This is primarily useful for synchronizing network updates with + * user code. + * + * @param inst NT instance handle. + */ + public static native void flush(int inst); + + /** + * Gets information on the currently established network connections. If operating as a client, + * this will return either zero or one values. + * + * @param inst NT instance handle. + * @return array of connection information + */ + public static native ConnectionInfo[] getConnections(int inst); + + /** + * Return whether or not the instance is connected to another node. + * + * @param inst NT instance handle. + * @return True if connected. + */ + public static native boolean isConnected(int inst); + + /** + * Get the time offset between server time and local time. Add this value to local time to get + * the estimated equivalent server time. In server mode, this always returns 0. In client mode, + * this returns the time offset only if the client and server are connected and have exchanged + * synchronization messages. Note the time offset may change over time as it is periodically + * updated; to receive updates as events, add a listener to the "time sync" event. + * + * @param inst NT instance handle. + * @return Time offset in microseconds (optional) + */ + public static native OptionalLong getServerTimeOffset(int inst); + + /** + * Returns the current timestamp in microseconds. + * + * @return The current timestsamp in microseconds. + */ + public static native long now(); + + /** + * Starts logging entry changes to a DataLog. + * + * @param inst NT instance handle. + * @param log data log handle; lifetime must extend until StopEntryDataLog is called or the + * instance is destroyed + * @param prefix only store entries with names that start with this prefix; the prefix is not + * included in the data log entry name + * @param logPrefix prefix to add to data log entry names + * @return Data logger handle + */ + private static native int startEntryDataLog(int inst, long log, String prefix, String logPrefix); + + /** + * Starts logging entry changes to a DataLog. + * + * @param inst NT instance handle. + * @param log data log object; lifetime must extend until StopEntryDataLog is called or the + * instance is destroyed + * @param prefix only store entries with names that start with this prefix; the prefix is not + * included in the data log entry name + * @param logPrefix prefix to add to data log entry names + * @return Data logger handle + */ + public static int startEntryDataLog(int inst, DataLog log, String prefix, String logPrefix) { + return startEntryDataLog(inst, log.getImpl(), prefix, logPrefix); + } + + /** + * Stops logging entry changes to a DataLog. + * + * @param logger data logger handle + */ + public static native void stopEntryDataLog(int logger); + + /** + * Starts logging connection changes to a DataLog. + * + * @param inst NT instance handle. + * @param log data log handle; lifetime must extend until StopConnectionDataLog is called or the + * instance is destroyed + * @param name data log entry name + * @return Data logger handle + */ + private static native int startConnectionDataLog(int inst, long log, String name); + + /** + * Starts logging connection changes to a DataLog. + * + * @param inst NT instance handle. + * @param log data log object; lifetime must extend until StopConnectionDataLog is called or the + * instance is destroyed + * @param name data log entry name + * @return Data logger handle + */ + public static int startConnectionDataLog(int inst, DataLog log, String name) { + return startConnectionDataLog(inst, log.getImpl(), name); + } + + /** + * Stops logging connection changes to a DataLog. + * + * @param logger data logger handle + */ + public static native void stopConnectionDataLog(int logger); + + /** + * Add logger callback function. By default, log messages are sent to stderr; this function sends + * log messages with the specified levels to the provided callback function instead. The callback + * function will only be called for log messages with level greater than or equal to minLevel and + * less than or equal to maxLevel; messages outside this range will be silently ignored. + * + * @param poller Listener poller handle. + * @param minLevel minimum log level + * @param maxLevel maximum log level + * @return Listener handle + */ + public static native int addLogger(int poller, int minLevel, int maxLevel); + + /** Utility class. */ + private NetworkTablesJNI() {} +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawEntry.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawEntry.java new file mode 100644 index 00000000000..407cdd55ad1 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawEntry.java @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** + * NetworkTables Raw entry. + * + *

Unlike NetworkTableEntry, the entry goes away when close() is called. + */ +public interface RawEntry extends RawSubscriber, RawPublisher { + /** Stops publishing the entry if it's published. */ + void unpublish(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawEntryImpl.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawEntryImpl.java new file mode 100644 index 00000000000..55767f73eae --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawEntryImpl.java @@ -0,0 +1,89 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.nio.ByteBuffer; + +/** NetworkTables Raw implementation. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +final class RawEntryImpl extends EntryBase implements RawEntry { + /** + * Constructor. + * + * @param topic Topic + * @param handle Native handle + * @param defaultValue Default value for get() + */ + RawEntryImpl(RawTopic topic, int handle, byte[] defaultValue) { + super(handle); + m_topic = topic; + m_defaultValue = defaultValue; + } + + @Override + public RawTopic getTopic() { + return m_topic; + } + + @Override + public byte[] get() { + return NetworkTablesJNI.getRaw(m_handle, m_defaultValue); + } + + @Override + public byte[] get(byte[] defaultValue) { + return NetworkTablesJNI.getRaw(m_handle, defaultValue); + } + + @Override + public TimestampedRaw getAtomic() { + return NetworkTablesJNI.getAtomicRaw(m_handle, m_defaultValue); + } + + @Override + public TimestampedRaw getAtomic(byte[] defaultValue) { + return NetworkTablesJNI.getAtomicRaw(m_handle, defaultValue); + } + + @Override + public TimestampedRaw[] readQueue() { + return NetworkTablesJNI.readQueueRaw(m_handle); + } + + @Override + public byte[][] readQueueValues() { + return NetworkTablesJNI.readQueueValuesRaw(m_handle); + } + + @Override + public void set(byte[] value, int start, int len, long time) { + NetworkTablesJNI.setRaw(m_handle, time, value, start, len); + } + + @Override + public void set(ByteBuffer value, int start, int len, long time) { + NetworkTablesJNI.setRaw(m_handle, time, value, start, len); + } + + @Override + public void setDefault(byte[] value, int start, int len) { + NetworkTablesJNI.setDefaultRaw(m_handle, 0, value, start, len); + } + + @Override + public void setDefault(ByteBuffer value, int start, int len) { + NetworkTablesJNI.setDefaultRaw(m_handle, 0, value, start, len); + } + + @Override + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + private final RawTopic m_topic; + private final byte[] m_defaultValue; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawPublisher.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawPublisher.java new file mode 100644 index 00000000000..0cd578e507b --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawPublisher.java @@ -0,0 +1,154 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + + +import java.nio.ByteBuffer; +import java.util.function.Consumer; + +/** NetworkTables Raw publisher. */ +public interface RawPublisher extends Publisher, Consumer { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + RawTopic getTopic(); + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + */ + default void set(byte[] value) { + set(value, 0); + } + + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + default void set(byte[] value, long time) { + set(value, 0, value.length, time); + } + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.length - start) + */ + default void set(byte[] value, int start, int len) { + set(value, start, len, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.length - start) + * @param time timestamp; 0 indicates current NT time should be used + */ + void set(byte[] value, int start, int len, long time); + + /** + * Publish a new value using current NT time. + * + * @param value value to publish; will send from value.position() to value.limit() + */ + default void set(ByteBuffer value) { + set(value, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish; will send from value.position() to value.limit() + * @param time timestamp; 0 indicates current NT time should be used + */ + default void set(ByteBuffer value, long time) { + int pos = value.position(); + set(value, pos, value.limit() - pos, time); + } + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.capacity() - start) + */ + default void set(ByteBuffer value, int start, int len) { + set(value, start, len, 0); + } + + /** + * Publish a new value. + * + * @param value value to publish + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.capacity() - start) + * @param time timestamp; 0 indicates current NT time should be used + */ + void set(ByteBuffer value, int start, int len, long time); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + default void setDefault(byte[] value) { + setDefault(value, 0, value.length); + } + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.length - start) + */ + void setDefault(byte[] value, int start, int len); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value; will send from value.position() to value.limit() + */ + default void setDefault(ByteBuffer value) { + int pos = value.position(); + setDefault(value, pos, value.limit() - pos); + } + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + * @param start Start position of data (in buffer) + * @param len Length of data (must be less than or equal to value.capacity() - start) + */ + void setDefault(ByteBuffer value, int start, int len); + + @Override + default void accept(byte[] value) { + set(value); + } +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawSubscriber.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawSubscriber.java new file mode 100644 index 00000000000..089d999dc29 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawSubscriber.java @@ -0,0 +1,80 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Supplier; + +/** NetworkTables Raw subscriber. */ +@SuppressWarnings("PMD.MissingOverride") +public interface RawSubscriber extends Subscriber, Supplier { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + RawTopic getTopic(); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + byte[] get(); + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + byte[] get(byte[] defaultValue); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedRaw getAtomic(); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedRaw getAtomic(byte[] defaultValue); + + /** + * Get an array of all value changes since the last call to readQueue. + * Also provides a timestamp for each value. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + TimestampedRaw[] readQueue(); + + /** + * Get an array of all value changes since the last call to readQueue. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of values; empty array if no new changes have been + * published since the previous call. + */ + byte[][] readQueueValues(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawTopic.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawTopic.java new file mode 100644 index 00000000000..173a88b3ce9 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/RawTopic.java @@ -0,0 +1,154 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables Raw topic. */ +public final class RawTopic extends Topic { + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + public RawTopic(Topic topic) { + super(topic.m_inst, topic.m_handle); + } + + /** + * Constructor; use NetworkTableInstance.getRawTopic() instead. + * + * @param inst Instance + * @param handle Native handle + */ + public RawTopic(NetworkTableInstance inst, int handle) { + super(inst, handle); + } + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public RawSubscriber subscribe( + String typeString, + + byte[] defaultValue, + PubSubOption... options) { + return new RawEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kRaw.getValue(), + typeString, options), + defaultValue); + } + + /** + * Create a new publisher to the topic. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + + * @param options publish options + * @return publisher + */ + public RawPublisher publish( + String typeString, + + PubSubOption... options) { + return new RawEntryImpl( + this, + NetworkTablesJNI.publish( + m_handle, NetworkTableType.kRaw.getValue(), + typeString, options), + new byte[] {}); + } + + /** + * Create a new publisher to the topic, with type string and initial properties. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + * @throws IllegalArgumentException if properties is not a JSON object + */ + public RawPublisher publishEx( + String typeString, + String properties, + PubSubOption... options) { + return new RawEntryImpl( + this, + NetworkTablesJNI.publishEx( + m_handle, NetworkTableType.kRaw.getValue(), + typeString, properties, options), + new byte[] {}); + } + + /** + * Create a new entry for the topic. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public RawEntry getEntry( + String typeString, + + byte[] defaultValue, + PubSubOption... options) { + return new RawEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kRaw.getValue(), + typeString, options), + defaultValue); + } + +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArrayEntry.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArrayEntry.java new file mode 100644 index 00000000000..9169e9071b3 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArrayEntry.java @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** + * NetworkTables StringArray entry. + * + *

Unlike NetworkTableEntry, the entry goes away when close() is called. + */ +public interface StringArrayEntry extends StringArraySubscriber, StringArrayPublisher { + /** Stops publishing the entry if it's published. */ + void unpublish(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArrayEntryImpl.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArrayEntryImpl.java new file mode 100644 index 00000000000..536db7b8ac9 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArrayEntryImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables StringArray implementation. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +final class StringArrayEntryImpl extends EntryBase implements StringArrayEntry { + /** + * Constructor. + * + * @param topic Topic + * @param handle Native handle + * @param defaultValue Default value for get() + */ + StringArrayEntryImpl(StringArrayTopic topic, int handle, String[] defaultValue) { + super(handle); + m_topic = topic; + m_defaultValue = defaultValue; + } + + @Override + public StringArrayTopic getTopic() { + return m_topic; + } + + @Override + public String[] get() { + return NetworkTablesJNI.getStringArray(m_handle, m_defaultValue); + } + + @Override + public String[] get(String[] defaultValue) { + return NetworkTablesJNI.getStringArray(m_handle, defaultValue); + } + + @Override + public TimestampedStringArray getAtomic() { + return NetworkTablesJNI.getAtomicStringArray(m_handle, m_defaultValue); + } + + @Override + public TimestampedStringArray getAtomic(String[] defaultValue) { + return NetworkTablesJNI.getAtomicStringArray(m_handle, defaultValue); + } + + @Override + public TimestampedStringArray[] readQueue() { + return NetworkTablesJNI.readQueueStringArray(m_handle); + } + + @Override + public String[][] readQueueValues() { + return NetworkTablesJNI.readQueueValuesStringArray(m_handle); + } + + @Override + public void set(String[] value, long time) { + NetworkTablesJNI.setStringArray(m_handle, time, value); + } + + @Override + public void setDefault(String[] value) { + NetworkTablesJNI.setDefaultStringArray(m_handle, 0, value); + } + + @Override + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + private final StringArrayTopic m_topic; + private final String[] m_defaultValue; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArrayPublisher.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArrayPublisher.java new file mode 100644 index 00000000000..d32350c92b1 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArrayPublisher.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Consumer; + +/** NetworkTables StringArray publisher. */ +public interface StringArrayPublisher extends Publisher, Consumer { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + StringArrayTopic getTopic(); + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + */ + default void set(String[] value) { + set(value, 0); + } + + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void set(String[] value, long time); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void setDefault(String[] value); + + @Override + default void accept(String[] value) { + set(value); + } +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArraySubscriber.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArraySubscriber.java new file mode 100644 index 00000000000..62a05759bf0 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArraySubscriber.java @@ -0,0 +1,80 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Supplier; + +/** NetworkTables StringArray subscriber. */ +@SuppressWarnings("PMD.MissingOverride") +public interface StringArraySubscriber extends Subscriber, Supplier { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + StringArrayTopic getTopic(); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + String[] get(); + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + String[] get(String[] defaultValue); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedStringArray getAtomic(); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedStringArray getAtomic(String[] defaultValue); + + /** + * Get an array of all value changes since the last call to readQueue. + * Also provides a timestamp for each value. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + TimestampedStringArray[] readQueue(); + + /** + * Get an array of all value changes since the last call to readQueue. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of values; empty array if no new changes have been + * published since the previous call. + */ + String[][] readQueueValues(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArrayTopic.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArrayTopic.java new file mode 100644 index 00000000000..bde93c08f4d --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringArrayTopic.java @@ -0,0 +1,206 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables StringArray topic. */ +public final class StringArrayTopic extends Topic { + /** The default type string for this topic type. */ + public static final String kTypeString = "string[]"; + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + public StringArrayTopic(Topic topic) { + super(topic.m_inst, topic.m_handle); + } + + /** + * Constructor; use NetworkTableInstance.getStringArrayTopic() instead. + * + * @param inst Instance + * @param handle Native handle + */ + public StringArrayTopic(NetworkTableInstance inst, int handle) { + super(inst, handle); + } + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public StringArraySubscriber subscribe( + String[] defaultValue, + PubSubOption... options) { + return new StringArrayEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kStringArray.getValue(), + "string[]", options), + defaultValue); + } + + /** + * Create a new subscriber to the topic, with specified type string. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public StringArraySubscriber subscribeEx( + String typeString, + String[] defaultValue, + PubSubOption... options) { + return new StringArrayEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kStringArray.getValue(), + typeString, options), + defaultValue); + } + + /** + * Create a new publisher to the topic. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + public StringArrayPublisher publish( + PubSubOption... options) { + return new StringArrayEntryImpl( + this, + NetworkTablesJNI.publish( + m_handle, NetworkTableType.kStringArray.getValue(), + "string[]", options), + new String[] {}); + } + + /** + * Create a new publisher to the topic, with type string and initial properties. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + * @throws IllegalArgumentException if properties is not a JSON object + */ + public StringArrayPublisher publishEx( + String typeString, + String properties, + PubSubOption... options) { + return new StringArrayEntryImpl( + this, + NetworkTablesJNI.publishEx( + m_handle, NetworkTableType.kStringArray.getValue(), + typeString, properties, options), + new String[] {}); + } + + /** + * Create a new entry for the topic. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public StringArrayEntry getEntry( + String[] defaultValue, + PubSubOption... options) { + return new StringArrayEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kStringArray.getValue(), + "string[]", options), + defaultValue); + } + + /** + * Create a new entry for the topic, with specified type string. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public StringArrayEntry getEntryEx( + String typeString, + String[] defaultValue, + PubSubOption... options) { + return new StringArrayEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kStringArray.getValue(), + typeString, options), + defaultValue); + } + +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringEntry.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringEntry.java new file mode 100644 index 00000000000..6914179c311 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringEntry.java @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** + * NetworkTables String entry. + * + *

Unlike NetworkTableEntry, the entry goes away when close() is called. + */ +public interface StringEntry extends StringSubscriber, StringPublisher { + /** Stops publishing the entry if it's published. */ + void unpublish(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringEntryImpl.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringEntryImpl.java new file mode 100644 index 00000000000..76c9b985459 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringEntryImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables String implementation. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +final class StringEntryImpl extends EntryBase implements StringEntry { + /** + * Constructor. + * + * @param topic Topic + * @param handle Native handle + * @param defaultValue Default value for get() + */ + StringEntryImpl(StringTopic topic, int handle, String defaultValue) { + super(handle); + m_topic = topic; + m_defaultValue = defaultValue; + } + + @Override + public StringTopic getTopic() { + return m_topic; + } + + @Override + public String get() { + return NetworkTablesJNI.getString(m_handle, m_defaultValue); + } + + @Override + public String get(String defaultValue) { + return NetworkTablesJNI.getString(m_handle, defaultValue); + } + + @Override + public TimestampedString getAtomic() { + return NetworkTablesJNI.getAtomicString(m_handle, m_defaultValue); + } + + @Override + public TimestampedString getAtomic(String defaultValue) { + return NetworkTablesJNI.getAtomicString(m_handle, defaultValue); + } + + @Override + public TimestampedString[] readQueue() { + return NetworkTablesJNI.readQueueString(m_handle); + } + + @Override + public String[] readQueueValues() { + return NetworkTablesJNI.readQueueValuesString(m_handle); + } + + @Override + public void set(String value, long time) { + NetworkTablesJNI.setString(m_handle, time, value); + } + + @Override + public void setDefault(String value) { + NetworkTablesJNI.setDefaultString(m_handle, 0, value); + } + + @Override + public void unpublish() { + NetworkTablesJNI.unpublish(m_handle); + } + + private final StringTopic m_topic; + private final String m_defaultValue; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringPublisher.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringPublisher.java new file mode 100644 index 00000000000..c11f11cb88a --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringPublisher.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Consumer; + +/** NetworkTables String publisher. */ +public interface StringPublisher extends Publisher, Consumer { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + StringTopic getTopic(); + + /** + * Publish a new value using current NT time. + * + * @param value value to publish + */ + default void set(String value) { + set(value, 0); + } + + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void set(String value, long time); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void setDefault(String value); + + @Override + default void accept(String value) { + set(value); + } +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringSubscriber.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringSubscriber.java new file mode 100644 index 00000000000..8c453b03a43 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringSubscriber.java @@ -0,0 +1,80 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +import java.util.function.Supplier; + +/** NetworkTables String subscriber. */ +@SuppressWarnings("PMD.MissingOverride") +public interface StringSubscriber extends Subscriber, Supplier { + /** + * Get the corresponding topic. + * + * @return Topic + */ + @Override + StringTopic getTopic(); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + String get(); + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + String get(String defaultValue); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedString getAtomic(); + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedString getAtomic(String defaultValue); + + /** + * Get an array of all value changes since the last call to readQueue. + * Also provides a timestamp for each value. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + TimestampedString[] readQueue(); + + /** + * Get an array of all value changes since the last call to readQueue. + * + *

The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of values; empty array if no new changes have been + * published since the previous call. + */ + String[] readQueueValues(); +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringTopic.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringTopic.java new file mode 100644 index 00000000000..a6341808ff3 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/StringTopic.java @@ -0,0 +1,206 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables String topic. */ +public final class StringTopic extends Topic { + /** The default type string for this topic type. */ + public static final String kTypeString = "string"; + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + public StringTopic(Topic topic) { + super(topic.m_inst, topic.m_handle); + } + + /** + * Constructor; use NetworkTableInstance.getStringTopic() instead. + * + * @param inst Instance + * @param handle Native handle + */ + public StringTopic(NetworkTableInstance inst, int handle) { + super(inst, handle); + } + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public StringSubscriber subscribe( + String defaultValue, + PubSubOption... options) { + return new StringEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kString.getValue(), + "string", options), + defaultValue); + } + + /** + * Create a new subscriber to the topic, with specified type string. + * + *

The subscriber is only active as long as the returned object + * is not closed. + * + *

Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + public StringSubscriber subscribeEx( + String typeString, + String defaultValue, + PubSubOption... options) { + return new StringEntryImpl( + this, + NetworkTablesJNI.subscribe( + m_handle, NetworkTableType.kString.getValue(), + typeString, options), + defaultValue); + } + + /** + * Create a new publisher to the topic. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + public StringPublisher publish( + PubSubOption... options) { + return new StringEntryImpl( + this, + NetworkTablesJNI.publish( + m_handle, NetworkTableType.kString.getValue(), + "string", options), + ""); + } + + /** + * Create a new publisher to the topic, with type string and initial properties. + * + *

The publisher is only active as long as the returned object + * is not closed. + * + *

It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored). To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + * @throws IllegalArgumentException if properties is not a JSON object + */ + public StringPublisher publishEx( + String typeString, + String properties, + PubSubOption... options) { + return new StringEntryImpl( + this, + NetworkTablesJNI.publishEx( + m_handle, NetworkTableType.kString.getValue(), + typeString, properties, options), + ""); + } + + /** + * Create a new entry for the topic. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public StringEntry getEntry( + String defaultValue, + PubSubOption... options) { + return new StringEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kString.getValue(), + "string", options), + defaultValue); + } + + /** + * Create a new entry for the topic, with specified type string. + * + *

Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not closed. The publisher is + * created when the entry is first written to, and remains active until either + * unpublish() is called or the entry is closed. + * + *

It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the server on + * a first-come, first-served basis. Any published values that do not match + * the topic's data type are dropped (ignored), and the entry will show no new + * values if the data type does not match. To determine if the data type + * matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + public StringEntry getEntryEx( + String typeString, + String defaultValue, + PubSubOption... options) { + return new StringEntryImpl( + this, + NetworkTablesJNI.getEntry( + m_handle, NetworkTableType.kString.getValue(), + typeString, options), + defaultValue); + } + +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedBoolean.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedBoolean.java new file mode 100644 index 00000000000..05497fcb3b5 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedBoolean.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables timestamped Boolean. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +public final class TimestampedBoolean { + /** + * Create a timestamped value. + * + * @param timestamp timestamp in local time base + * @param serverTime timestamp in server time base + * @param value value + */ + public TimestampedBoolean(long timestamp, long serverTime, boolean value) { + this.timestamp = timestamp; + this.serverTime = serverTime; + this.value = value; + } + + /** + * Timestamp in local time base. + */ + @SuppressWarnings("MemberName") + public final long timestamp; + + /** + * Timestamp in server time base. May be 0 or 1 for locally set values. + */ + @SuppressWarnings("MemberName") + public final long serverTime; + + /** + * Value. + */ + @SuppressWarnings("MemberName") + public final boolean value; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedBooleanArray.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedBooleanArray.java new file mode 100644 index 00000000000..51e25912919 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedBooleanArray.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables timestamped BooleanArray. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +public final class TimestampedBooleanArray { + /** + * Create a timestamped value. + * + * @param timestamp timestamp in local time base + * @param serverTime timestamp in server time base + * @param value value + */ + public TimestampedBooleanArray(long timestamp, long serverTime, boolean[] value) { + this.timestamp = timestamp; + this.serverTime = serverTime; + this.value = value; + } + + /** + * Timestamp in local time base. + */ + @SuppressWarnings("MemberName") + public final long timestamp; + + /** + * Timestamp in server time base. May be 0 or 1 for locally set values. + */ + @SuppressWarnings("MemberName") + public final long serverTime; + + /** + * Value. + */ + @SuppressWarnings("MemberName") + public final boolean[] value; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedDouble.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedDouble.java new file mode 100644 index 00000000000..586c9fc1d17 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedDouble.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables timestamped Double. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +public final class TimestampedDouble { + /** + * Create a timestamped value. + * + * @param timestamp timestamp in local time base + * @param serverTime timestamp in server time base + * @param value value + */ + public TimestampedDouble(long timestamp, long serverTime, double value) { + this.timestamp = timestamp; + this.serverTime = serverTime; + this.value = value; + } + + /** + * Timestamp in local time base. + */ + @SuppressWarnings("MemberName") + public final long timestamp; + + /** + * Timestamp in server time base. May be 0 or 1 for locally set values. + */ + @SuppressWarnings("MemberName") + public final long serverTime; + + /** + * Value. + */ + @SuppressWarnings("MemberName") + public final double value; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedDoubleArray.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedDoubleArray.java new file mode 100644 index 00000000000..aaeafd788eb --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedDoubleArray.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables timestamped DoubleArray. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +public final class TimestampedDoubleArray { + /** + * Create a timestamped value. + * + * @param timestamp timestamp in local time base + * @param serverTime timestamp in server time base + * @param value value + */ + public TimestampedDoubleArray(long timestamp, long serverTime, double[] value) { + this.timestamp = timestamp; + this.serverTime = serverTime; + this.value = value; + } + + /** + * Timestamp in local time base. + */ + @SuppressWarnings("MemberName") + public final long timestamp; + + /** + * Timestamp in server time base. May be 0 or 1 for locally set values. + */ + @SuppressWarnings("MemberName") + public final long serverTime; + + /** + * Value. + */ + @SuppressWarnings("MemberName") + public final double[] value; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedFloat.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedFloat.java new file mode 100644 index 00000000000..4d8aa095df8 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedFloat.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables timestamped Float. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +public final class TimestampedFloat { + /** + * Create a timestamped value. + * + * @param timestamp timestamp in local time base + * @param serverTime timestamp in server time base + * @param value value + */ + public TimestampedFloat(long timestamp, long serverTime, float value) { + this.timestamp = timestamp; + this.serverTime = serverTime; + this.value = value; + } + + /** + * Timestamp in local time base. + */ + @SuppressWarnings("MemberName") + public final long timestamp; + + /** + * Timestamp in server time base. May be 0 or 1 for locally set values. + */ + @SuppressWarnings("MemberName") + public final long serverTime; + + /** + * Value. + */ + @SuppressWarnings("MemberName") + public final float value; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedFloatArray.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedFloatArray.java new file mode 100644 index 00000000000..85fe7bcac71 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedFloatArray.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables timestamped FloatArray. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +public final class TimestampedFloatArray { + /** + * Create a timestamped value. + * + * @param timestamp timestamp in local time base + * @param serverTime timestamp in server time base + * @param value value + */ + public TimestampedFloatArray(long timestamp, long serverTime, float[] value) { + this.timestamp = timestamp; + this.serverTime = serverTime; + this.value = value; + } + + /** + * Timestamp in local time base. + */ + @SuppressWarnings("MemberName") + public final long timestamp; + + /** + * Timestamp in server time base. May be 0 or 1 for locally set values. + */ + @SuppressWarnings("MemberName") + public final long serverTime; + + /** + * Value. + */ + @SuppressWarnings("MemberName") + public final float[] value; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedInteger.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedInteger.java new file mode 100644 index 00000000000..0ee78553630 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedInteger.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables timestamped Integer. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +public final class TimestampedInteger { + /** + * Create a timestamped value. + * + * @param timestamp timestamp in local time base + * @param serverTime timestamp in server time base + * @param value value + */ + public TimestampedInteger(long timestamp, long serverTime, long value) { + this.timestamp = timestamp; + this.serverTime = serverTime; + this.value = value; + } + + /** + * Timestamp in local time base. + */ + @SuppressWarnings("MemberName") + public final long timestamp; + + /** + * Timestamp in server time base. May be 0 or 1 for locally set values. + */ + @SuppressWarnings("MemberName") + public final long serverTime; + + /** + * Value. + */ + @SuppressWarnings("MemberName") + public final long value; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedIntegerArray.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedIntegerArray.java new file mode 100644 index 00000000000..8686326996b --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedIntegerArray.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables timestamped IntegerArray. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +public final class TimestampedIntegerArray { + /** + * Create a timestamped value. + * + * @param timestamp timestamp in local time base + * @param serverTime timestamp in server time base + * @param value value + */ + public TimestampedIntegerArray(long timestamp, long serverTime, long[] value) { + this.timestamp = timestamp; + this.serverTime = serverTime; + this.value = value; + } + + /** + * Timestamp in local time base. + */ + @SuppressWarnings("MemberName") + public final long timestamp; + + /** + * Timestamp in server time base. May be 0 or 1 for locally set values. + */ + @SuppressWarnings("MemberName") + public final long serverTime; + + /** + * Value. + */ + @SuppressWarnings("MemberName") + public final long[] value; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedRaw.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedRaw.java new file mode 100644 index 00000000000..12ec095e3ff --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedRaw.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables timestamped Raw. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +public final class TimestampedRaw { + /** + * Create a timestamped value. + * + * @param timestamp timestamp in local time base + * @param serverTime timestamp in server time base + * @param value value + */ + public TimestampedRaw(long timestamp, long serverTime, byte[] value) { + this.timestamp = timestamp; + this.serverTime = serverTime; + this.value = value; + } + + /** + * Timestamp in local time base. + */ + @SuppressWarnings("MemberName") + public final long timestamp; + + /** + * Timestamp in server time base. May be 0 or 1 for locally set values. + */ + @SuppressWarnings("MemberName") + public final long serverTime; + + /** + * Value. + */ + @SuppressWarnings("MemberName") + public final byte[] value; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedString.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedString.java new file mode 100644 index 00000000000..a51432ee494 --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedString.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables timestamped String. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +public final class TimestampedString { + /** + * Create a timestamped value. + * + * @param timestamp timestamp in local time base + * @param serverTime timestamp in server time base + * @param value value + */ + public TimestampedString(long timestamp, long serverTime, String value) { + this.timestamp = timestamp; + this.serverTime = serverTime; + this.value = value; + } + + /** + * Timestamp in local time base. + */ + @SuppressWarnings("MemberName") + public final long timestamp; + + /** + * Timestamp in server time base. May be 0 or 1 for locally set values. + */ + @SuppressWarnings("MemberName") + public final long serverTime; + + /** + * Value. + */ + @SuppressWarnings("MemberName") + public final String value; +} diff --git a/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedStringArray.java b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedStringArray.java new file mode 100644 index 00000000000..420a4685a9f --- /dev/null +++ b/ntcore/src/generated/main/java/edu/wpi/first/networktables/TimestampedStringArray.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +package edu.wpi.first.networktables; + +/** NetworkTables timestamped StringArray. */ +@SuppressWarnings("PMD.ArrayIsStoredDirectly") +public final class TimestampedStringArray { + /** + * Create a timestamped value. + * + * @param timestamp timestamp in local time base + * @param serverTime timestamp in server time base + * @param value value + */ + public TimestampedStringArray(long timestamp, long serverTime, String[] value) { + this.timestamp = timestamp; + this.serverTime = serverTime; + this.value = value; + } + + /** + * Timestamp in local time base. + */ + @SuppressWarnings("MemberName") + public final long timestamp; + + /** + * Timestamp in server time base. May be 0 or 1 for locally set values. + */ + @SuppressWarnings("MemberName") + public final long serverTime; + + /** + * Value. + */ + @SuppressWarnings("MemberName") + public final String[] value; +} diff --git a/ntcore/src/generated/main/native/cpp/jni/types_jni.cpp b/ntcore/src/generated/main/native/cpp/jni/types_jni.cpp new file mode 100644 index 00000000000..de14d538de9 --- /dev/null +++ b/ntcore/src/generated/main/native/cpp/jni/types_jni.cpp @@ -0,0 +1,1436 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#include + +#include + +#include "edu_wpi_first_networktables_NetworkTablesJNI.h" +#include "ntcore.h" + +using namespace wpi::java; + +// +// Globals and load/unload +// + +static JClass timestampedBooleanCls; +static JClass timestampedIntegerCls; +static JClass timestampedFloatCls; +static JClass timestampedDoubleCls; +static JClass timestampedStringCls; +static JClass timestampedRawCls; +static JClass timestampedBooleanArrayCls; +static JClass timestampedIntegerArrayCls; +static JClass timestampedFloatArrayCls; +static JClass timestampedDoubleArrayCls; +static JClass timestampedStringArrayCls; +static JClass jbyteArrayCls; +static JClass jbooleanArrayCls; +static JClass jlongArrayCls; +static JClass jfloatArrayCls; +static JClass jdoubleArrayCls; +static JClass jobjectArrayCls; +static JException illegalArgEx; +static JException indexOobEx; +static JException nullPointerEx; + +static const JClassInit classes[] = { + {"edu/wpi/first/networktables/TimestampedBoolean", ×tampedBooleanCls}, + {"edu/wpi/first/networktables/TimestampedInteger", ×tampedIntegerCls}, + {"edu/wpi/first/networktables/TimestampedFloat", ×tampedFloatCls}, + {"edu/wpi/first/networktables/TimestampedDouble", ×tampedDoubleCls}, + {"edu/wpi/first/networktables/TimestampedString", ×tampedStringCls}, + {"edu/wpi/first/networktables/TimestampedRaw", ×tampedRawCls}, + {"edu/wpi/first/networktables/TimestampedBooleanArray", ×tampedBooleanArrayCls}, + {"edu/wpi/first/networktables/TimestampedIntegerArray", ×tampedIntegerArrayCls}, + {"edu/wpi/first/networktables/TimestampedFloatArray", ×tampedFloatArrayCls}, + {"edu/wpi/first/networktables/TimestampedDoubleArray", ×tampedDoubleArrayCls}, + {"edu/wpi/first/networktables/TimestampedStringArray", ×tampedStringArrayCls}, + {"[B", &jbyteArrayCls}, + {"[Z", &jbooleanArrayCls}, + {"[J", &jlongArrayCls}, + {"[F", &jfloatArrayCls}, + {"[D", &jdoubleArrayCls}, + {"[Ljava/lang/Object;", &jobjectArrayCls}, +}; + +static const JExceptionInit exceptions[] = { + {"java/lang/IllegalArgumentException", &illegalArgEx}, + {"java/lang/IndexOutOfBoundsException", &indexOobEx}, + {"java/lang/NullPointerException", &nullPointerEx}, +}; + +namespace nt { + +bool JNI_LoadTypes(JNIEnv* env) { + // Cache references to classes + for (auto& c : classes) { + *c.cls = JClass(env, c.name); + if (!*c.cls) { + return false; + } + } + + for (auto& c : exceptions) { + *c.cls = JException(env, c.name); + if (!*c.cls) { + return false; + } + } + + return true; +} + +void JNI_UnloadTypes(JNIEnv* env) { + // Delete global references + for (auto& c : classes) { + c.cls->free(env); + } + for (auto& c : exceptions) { + c.cls->free(env); + } +} + +} // namespace nt + +static std::vector FromJavaBooleanArray(JNIEnv* env, jbooleanArray jarr) { + CriticalJSpan ref{env, jarr}; + if (!ref) { + return {}; + } + std::span elements{ref}; + size_t len = elements.size(); + std::vector arr; + arr.reserve(len); + for (size_t i = 0; i < len; ++i) { + arr.push_back(elements[i]); + } + return arr; +} + +static std::vector FromJavaStringArray(JNIEnv* env, jobjectArray jarr) { + size_t len = env->GetArrayLength(jarr); + std::vector arr; + arr.reserve(len); + for (size_t i = 0; i < len; ++i) { + JLocal elem{ + env, static_cast(env->GetObjectArrayElement(jarr, i))}; + if (!elem) { + return {}; + } + arr.emplace_back(JStringRef{env, elem}.str()); + } + return arr; +} + + +static jobject MakeJObject(JNIEnv* env, nt::TimestampedBoolean value) { + static jmethodID constructor = env->GetMethodID( + timestampedBooleanCls, "", "(JJZ)V"); + return env->NewObject(timestampedBooleanCls, constructor, + static_cast(value.time), + static_cast(value.serverTime), + static_cast(value.value)); +} + +static jobject MakeJObject(JNIEnv* env, nt::TimestampedInteger value) { + static jmethodID constructor = env->GetMethodID( + timestampedIntegerCls, "", "(JJJ)V"); + return env->NewObject(timestampedIntegerCls, constructor, + static_cast(value.time), + static_cast(value.serverTime), + static_cast(value.value)); +} + +static jobject MakeJObject(JNIEnv* env, nt::TimestampedFloat value) { + static jmethodID constructor = env->GetMethodID( + timestampedFloatCls, "", "(JJF)V"); + return env->NewObject(timestampedFloatCls, constructor, + static_cast(value.time), + static_cast(value.serverTime), + static_cast(value.value)); +} + +static jobject MakeJObject(JNIEnv* env, nt::TimestampedDouble value) { + static jmethodID constructor = env->GetMethodID( + timestampedDoubleCls, "", "(JJD)V"); + return env->NewObject(timestampedDoubleCls, constructor, + static_cast(value.time), + static_cast(value.serverTime), + static_cast(value.value)); +} + +static jobject MakeJObject(JNIEnv* env, nt::TimestampedString value) { + static jmethodID constructor = env->GetMethodID( + timestampedStringCls, "", "(JJLjava/lang/String;)V"); + JLocal val{env, MakeJString(env, value.value)}; + return env->NewObject(timestampedStringCls, constructor, + static_cast(value.time), + static_cast(value.serverTime), val.obj()); +} + +static jobject MakeJObject(JNIEnv* env, nt::TimestampedRaw value) { + static jmethodID constructor = env->GetMethodID( + timestampedRawCls, "", "(JJ[B)V"); + JLocal val{env, MakeJByteArray(env, value.value)}; + return env->NewObject(timestampedRawCls, constructor, + static_cast(value.time), + static_cast(value.serverTime), val.obj()); +} + +static jobject MakeJObject(JNIEnv* env, nt::TimestampedBooleanArray value) { + static jmethodID constructor = env->GetMethodID( + timestampedBooleanArrayCls, "", "(JJ[Z)V"); + JLocal val{env, MakeJBooleanArray(env, value.value)}; + return env->NewObject(timestampedBooleanArrayCls, constructor, + static_cast(value.time), + static_cast(value.serverTime), val.obj()); +} + +static jobject MakeJObject(JNIEnv* env, nt::TimestampedIntegerArray value) { + static jmethodID constructor = env->GetMethodID( + timestampedIntegerArrayCls, "", "(JJ[J)V"); + JLocal val{env, MakeJLongArray(env, value.value)}; + return env->NewObject(timestampedIntegerArrayCls, constructor, + static_cast(value.time), + static_cast(value.serverTime), val.obj()); +} + +static jobject MakeJObject(JNIEnv* env, nt::TimestampedFloatArray value) { + static jmethodID constructor = env->GetMethodID( + timestampedFloatArrayCls, "", "(JJ[F)V"); + JLocal val{env, MakeJFloatArray(env, value.value)}; + return env->NewObject(timestampedFloatArrayCls, constructor, + static_cast(value.time), + static_cast(value.serverTime), val.obj()); +} + +static jobject MakeJObject(JNIEnv* env, nt::TimestampedDoubleArray value) { + static jmethodID constructor = env->GetMethodID( + timestampedDoubleArrayCls, "", "(JJ[D)V"); + JLocal val{env, MakeJDoubleArray(env, value.value)}; + return env->NewObject(timestampedDoubleArrayCls, constructor, + static_cast(value.time), + static_cast(value.serverTime), val.obj()); +} + +static jobject MakeJObject(JNIEnv* env, nt::TimestampedStringArray value) { + static jmethodID constructor = env->GetMethodID( + timestampedStringArrayCls, "", "(JJ[Ljava/lang/Object;)V"); + JLocal val{env, MakeJStringArray(env, value.value)}; + return env->NewObject(timestampedStringArrayCls, constructor, + static_cast(value.time), + static_cast(value.serverTime), val.obj()); +} + +static jobjectArray MakeJObject(JNIEnv* env, + std::span arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), timestampedBooleanCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJObject(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObject(JNIEnv* env, + std::span arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), timestampedIntegerCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJObject(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObject(JNIEnv* env, + std::span arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), timestampedFloatCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJObject(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObject(JNIEnv* env, + std::span arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), timestampedDoubleCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJObject(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObject(JNIEnv* env, + std::span arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), timestampedStringCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJObject(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObject(JNIEnv* env, + std::span arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), timestampedRawCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJObject(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObject(JNIEnv* env, + std::span arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), timestampedBooleanArrayCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJObject(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObject(JNIEnv* env, + std::span arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), timestampedIntegerArrayCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJObject(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObject(JNIEnv* env, + std::span arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), timestampedFloatArrayCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJObject(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObject(JNIEnv* env, + std::span arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), timestampedDoubleArrayCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJObject(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObject(JNIEnv* env, + std::span arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), timestampedStringArrayCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJObject(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObjectArray(JNIEnv* env, std::span> arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), jbyteArrayCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJByteArray(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObjectArray(JNIEnv* env, std::span> arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), jbooleanArrayCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJBooleanArray(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObjectArray(JNIEnv* env, std::span> arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), jlongArrayCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJLongArray(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObjectArray(JNIEnv* env, std::span> arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), jfloatArrayCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJFloatArray(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObjectArray(JNIEnv* env, std::span> arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), jdoubleArrayCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJDoubleArray(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + +static jobjectArray MakeJObjectArray(JNIEnv* env, std::span> arr) { + jobjectArray jarr = + env->NewObjectArray(arr.size(), jobjectArrayCls, nullptr); + if (!jarr) { + return nullptr; + } + for (size_t i = 0; i < arr.size(); ++i) { + JLocal elem{env, MakeJStringArray(env, arr[i])}; + env->SetObjectArrayElement(jarr, i, elem.obj()); + } + return jarr; +} + + +extern "C" { + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getAtomicBoolean + * Signature: (IZ)Ledu/wpi/first/networktables/TimestampedBoolean; + */ +JNIEXPORT jobject JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getAtomicBoolean + (JNIEnv* env, jclass, jint subentry, jboolean defaultValue) +{ + return MakeJObject(env, nt::GetAtomicBoolean(subentry, defaultValue != JNI_FALSE)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueBoolean + * Signature: (I)[Ledu/wpi/first/networktables/TimestampedBoolean; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueBoolean + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObject(env, nt::ReadQueueBoolean(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueValuesBoolean + * Signature: (I)[Z + */ +JNIEXPORT jbooleanArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueValuesBoolean + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJBooleanArray(env, nt::ReadQueueValuesBoolean(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setBoolean + * Signature: (IJZ)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setBoolean + (JNIEnv*, jclass, jint entry, jlong time, jboolean value) +{ + return nt::SetBoolean(entry, value != JNI_FALSE, time); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getBoolean + * Signature: (IZ)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getBoolean + (JNIEnv*, jclass, jint entry, jboolean defaultValue) +{ + return nt::GetBoolean(entry, defaultValue); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDefaultBoolean + * Signature: (IJZ)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefaultBoolean + (JNIEnv*, jclass, jint entry, jlong, jboolean defaultValue) +{ + return nt::SetDefaultBoolean(entry, defaultValue != JNI_FALSE); +} + + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getAtomicInteger + * Signature: (IJ)Ledu/wpi/first/networktables/TimestampedInteger; + */ +JNIEXPORT jobject JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getAtomicInteger + (JNIEnv* env, jclass, jint subentry, jlong defaultValue) +{ + return MakeJObject(env, nt::GetAtomicInteger(subentry, defaultValue)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueInteger + * Signature: (I)[Ledu/wpi/first/networktables/TimestampedInteger; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueInteger + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObject(env, nt::ReadQueueInteger(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueValuesInteger + * Signature: (I)[J + */ +JNIEXPORT jlongArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueValuesInteger + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJLongArray(env, nt::ReadQueueValuesInteger(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setInteger + * Signature: (IJJ)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setInteger + (JNIEnv*, jclass, jint entry, jlong time, jlong value) +{ + return nt::SetInteger(entry, value, time); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getInteger + * Signature: (IJ)J + */ +JNIEXPORT jlong JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getInteger + (JNIEnv*, jclass, jint entry, jlong defaultValue) +{ + return nt::GetInteger(entry, defaultValue); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDefaultInteger + * Signature: (IJJ)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefaultInteger + (JNIEnv*, jclass, jint entry, jlong, jlong defaultValue) +{ + return nt::SetDefaultInteger(entry, defaultValue); +} + + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getAtomicFloat + * Signature: (IF)Ledu/wpi/first/networktables/TimestampedFloat; + */ +JNIEXPORT jobject JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getAtomicFloat + (JNIEnv* env, jclass, jint subentry, jfloat defaultValue) +{ + return MakeJObject(env, nt::GetAtomicFloat(subentry, defaultValue)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueFloat + * Signature: (I)[Ledu/wpi/first/networktables/TimestampedFloat; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueFloat + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObject(env, nt::ReadQueueFloat(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueValuesFloat + * Signature: (I)[F + */ +JNIEXPORT jfloatArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueValuesFloat + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJFloatArray(env, nt::ReadQueueValuesFloat(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setFloat + * Signature: (IJF)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setFloat + (JNIEnv*, jclass, jint entry, jlong time, jfloat value) +{ + return nt::SetFloat(entry, value, time); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getFloat + * Signature: (IF)F + */ +JNIEXPORT jfloat JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getFloat + (JNIEnv*, jclass, jint entry, jfloat defaultValue) +{ + return nt::GetFloat(entry, defaultValue); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDefaultFloat + * Signature: (IJF)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefaultFloat + (JNIEnv*, jclass, jint entry, jlong, jfloat defaultValue) +{ + return nt::SetDefaultFloat(entry, defaultValue); +} + + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getAtomicDouble + * Signature: (ID)Ledu/wpi/first/networktables/TimestampedDouble; + */ +JNIEXPORT jobject JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getAtomicDouble + (JNIEnv* env, jclass, jint subentry, jdouble defaultValue) +{ + return MakeJObject(env, nt::GetAtomicDouble(subentry, defaultValue)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueDouble + * Signature: (I)[Ledu/wpi/first/networktables/TimestampedDouble; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueDouble + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObject(env, nt::ReadQueueDouble(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueValuesDouble + * Signature: (I)[D + */ +JNIEXPORT jdoubleArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueValuesDouble + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJDoubleArray(env, nt::ReadQueueValuesDouble(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDouble + * Signature: (IJD)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDouble + (JNIEnv*, jclass, jint entry, jlong time, jdouble value) +{ + return nt::SetDouble(entry, value, time); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getDouble + * Signature: (ID)D + */ +JNIEXPORT jdouble JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getDouble + (JNIEnv*, jclass, jint entry, jdouble defaultValue) +{ + return nt::GetDouble(entry, defaultValue); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDefaultDouble + * Signature: (IJD)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefaultDouble + (JNIEnv*, jclass, jint entry, jlong, jdouble defaultValue) +{ + return nt::SetDefaultDouble(entry, defaultValue); +} + + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getAtomicString + * Signature: (ILjava/lang/String;)Ledu/wpi/first/networktables/TimestampedString; + */ +JNIEXPORT jobject JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getAtomicString + (JNIEnv* env, jclass, jint subentry, jstring defaultValue) +{ + return MakeJObject(env, nt::GetAtomicString(subentry, JStringRef{env, defaultValue})); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueString + * Signature: (I)[Ledu/wpi/first/networktables/TimestampedString; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueString + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObject(env, nt::ReadQueueString(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueValuesString + * Signature: (I)[Ljava/lang/String; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueValuesString + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJStringArray(env, nt::ReadQueueValuesString(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setString + * Signature: (IJLjava/lang/String;)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setString + (JNIEnv* env, jclass, jint entry, jlong time, jstring value) +{ + if (!value) { + nullPointerEx.Throw(env, "value cannot be null"); + return false; + } + return nt::SetString(entry, JStringRef{env, value}, time); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getString + * Signature: (ILjava/lang/String;)Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getString + (JNIEnv* env, jclass, jint entry, jstring defaultValue) +{ + auto val = nt::GetEntryValue(entry); + if (!val || !val.IsString()) { + return defaultValue; + } + return MakeJString(env, val.GetString()); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDefaultString + * Signature: (IJLjava/lang/String;)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefaultString + (JNIEnv* env, jclass, jint entry, jlong, jstring defaultValue) +{ + if (!defaultValue) { + nullPointerEx.Throw(env, "defaultValue cannot be null"); + return false; + } + return nt::SetDefaultString(entry, JStringRef{env, defaultValue}); +} + + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getAtomicRaw + * Signature: (I[B)Ledu/wpi/first/networktables/TimestampedRaw; + */ +JNIEXPORT jobject JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getAtomicRaw + (JNIEnv* env, jclass, jint subentry, jbyteArray defaultValue) +{ + return MakeJObject(env, nt::GetAtomicRaw(subentry, CriticalJSpan{env, defaultValue}.uarray())); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueRaw + * Signature: (I)[Ledu/wpi/first/networktables/TimestampedRaw; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueRaw + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObject(env, nt::ReadQueueRaw(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueValuesRaw + * Signature: (I)[[B + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueValuesRaw + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObjectArray(env, nt::ReadQueueValuesRaw(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setRaw + * Signature: (IJ[BII)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setRaw + (JNIEnv* env, jclass, jint entry, jlong time, jbyteArray value, jint start, jint len) +{ + if (!value) { + nullPointerEx.Throw(env, "value is null"); + return false; + } + if (start < 0) { + indexOobEx.Throw(env, "start must be >= 0"); + return false; + } + if (len < 0) { + indexOobEx.Throw(env, "len must be >= 0"); + return false; + } + CriticalJSpan cvalue{env, value}; + if (static_cast(start + len) > cvalue.size()) { + indexOobEx.Throw(env, "start + len must be smaller than array length"); + return false; + } + return nt::SetRaw(entry, cvalue.uarray().subspan(start, len), time); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setRawBuffer + * Signature: (IJLjava/nio/ByteBuffer;II)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setRawBuffer + (JNIEnv* env, jclass, jint entry, jlong time, jobject value, jint start, jint len) +{ + if (!value) { + nullPointerEx.Throw(env, "value is null"); + return false; + } + if (start < 0) { + indexOobEx.Throw(env, "start must be >= 0"); + return false; + } + if (len < 0) { + indexOobEx.Throw(env, "len must be >= 0"); + return false; + } + JSpan cvalue{env, value, static_cast(start + len)}; + if (!cvalue) { + illegalArgEx.Throw(env, "value must be a native ByteBuffer"); + return false; + } + return nt::SetRaw(entry, cvalue.uarray().subspan(start, len), time); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getRaw + * Signature: (I[B)[B + */ +JNIEXPORT jbyteArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getRaw + (JNIEnv* env, jclass, jint entry, jbyteArray defaultValue) +{ + auto val = nt::GetEntryValue(entry); + if (!val || !val.IsRaw()) { + return defaultValue; + } + return MakeJByteArray(env, val.GetRaw()); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDefaultRaw + * Signature: (IJ[BII)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefaultRaw + (JNIEnv* env, jclass, jint entry, jlong, jbyteArray defaultValue, jint start, jint len) +{ + if (!defaultValue) { + nullPointerEx.Throw(env, "value is null"); + return false; + } + if (start < 0) { + indexOobEx.Throw(env, "start must be >= 0"); + return false; + } + if (len < 0) { + indexOobEx.Throw(env, "len must be >= 0"); + return false; + } + CriticalJSpan cvalue{env, defaultValue}; + if (static_cast(start + len) > cvalue.size()) { + indexOobEx.Throw(env, "start + len must be smaller than array length"); + return false; + } + return nt::SetDefaultRaw(entry, cvalue.uarray().subspan(start, len)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDefaultRawBuffer + * Signature: (IJLjava/nio/ByteBuffer;II)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefaultRawBuffer + (JNIEnv* env, jclass, jint entry, jlong, jobject defaultValue, jint start, jint len) +{ + if (!defaultValue) { + nullPointerEx.Throw(env, "value is null"); + return false; + } + if (start < 0) { + indexOobEx.Throw(env, "start must be >= 0"); + return false; + } + if (len < 0) { + indexOobEx.Throw(env, "len must be >= 0"); + return false; + } + JSpan cvalue{env, defaultValue, static_cast(start + len)}; + if (!cvalue) { + illegalArgEx.Throw(env, "value must be a native ByteBuffer"); + return false; + } + return nt::SetDefaultRaw(entry, cvalue.uarray().subspan(start, len)); +} + + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getAtomicBooleanArray + * Signature: (I[Z)Ledu/wpi/first/networktables/TimestampedBooleanArray; + */ +JNIEXPORT jobject JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getAtomicBooleanArray + (JNIEnv* env, jclass, jint subentry, jbooleanArray defaultValue) +{ + return MakeJObject(env, nt::GetAtomicBooleanArray(subentry, FromJavaBooleanArray(env, defaultValue))); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueBooleanArray + * Signature: (I)[Ledu/wpi/first/networktables/TimestampedBooleanArray; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueBooleanArray + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObject(env, nt::ReadQueueBooleanArray(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueValuesBooleanArray + * Signature: (I)[[Z + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueValuesBooleanArray + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObjectArray(env, nt::ReadQueueValuesBooleanArray(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setBooleanArray + * Signature: (IJ[Z)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setBooleanArray + (JNIEnv* env, jclass, jint entry, jlong time, jbooleanArray value) +{ + if (!value) { + nullPointerEx.Throw(env, "value cannot be null"); + return false; + } + return nt::SetBooleanArray(entry, FromJavaBooleanArray(env, value), time); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getBooleanArray + * Signature: (I[Z)[Z + */ +JNIEXPORT jbooleanArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getBooleanArray + (JNIEnv* env, jclass, jint entry, jbooleanArray defaultValue) +{ + auto val = nt::GetEntryValue(entry); + if (!val || !val.IsBooleanArray()) { + return defaultValue; + } + return MakeJBooleanArray(env, val.GetBooleanArray()); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDefaultBooleanArray + * Signature: (IJ[Z)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefaultBooleanArray + (JNIEnv* env, jclass, jint entry, jlong, jbooleanArray defaultValue) +{ + if (!defaultValue) { + nullPointerEx.Throw(env, "defaultValue cannot be null"); + return false; + } + return nt::SetDefaultBooleanArray(entry, FromJavaBooleanArray(env, defaultValue)); +} + + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getAtomicIntegerArray + * Signature: (I[J)Ledu/wpi/first/networktables/TimestampedIntegerArray; + */ +JNIEXPORT jobject JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getAtomicIntegerArray + (JNIEnv* env, jclass, jint subentry, jlongArray defaultValue) +{ + return MakeJObject(env, nt::GetAtomicIntegerArray(subentry, CriticalJSpan{env, defaultValue})); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueIntegerArray + * Signature: (I)[Ledu/wpi/first/networktables/TimestampedIntegerArray; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueIntegerArray + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObject(env, nt::ReadQueueIntegerArray(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueValuesIntegerArray + * Signature: (I)[[J + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueValuesIntegerArray + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObjectArray(env, nt::ReadQueueValuesIntegerArray(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setIntegerArray + * Signature: (IJ[J)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setIntegerArray + (JNIEnv* env, jclass, jint entry, jlong time, jlongArray value) +{ + if (!value) { + nullPointerEx.Throw(env, "value cannot be null"); + return false; + } + return nt::SetIntegerArray(entry, CriticalJSpan{env, value}, time); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getIntegerArray + * Signature: (I[J)[J + */ +JNIEXPORT jlongArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getIntegerArray + (JNIEnv* env, jclass, jint entry, jlongArray defaultValue) +{ + auto val = nt::GetEntryValue(entry); + if (!val || !val.IsIntegerArray()) { + return defaultValue; + } + return MakeJLongArray(env, val.GetIntegerArray()); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDefaultIntegerArray + * Signature: (IJ[J)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefaultIntegerArray + (JNIEnv* env, jclass, jint entry, jlong, jlongArray defaultValue) +{ + if (!defaultValue) { + nullPointerEx.Throw(env, "defaultValue cannot be null"); + return false; + } + return nt::SetDefaultIntegerArray(entry, CriticalJSpan{env, defaultValue}); +} + + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getAtomicFloatArray + * Signature: (I[F)Ledu/wpi/first/networktables/TimestampedFloatArray; + */ +JNIEXPORT jobject JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getAtomicFloatArray + (JNIEnv* env, jclass, jint subentry, jfloatArray defaultValue) +{ + return MakeJObject(env, nt::GetAtomicFloatArray(subentry, CriticalJSpan{env, defaultValue})); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueFloatArray + * Signature: (I)[Ledu/wpi/first/networktables/TimestampedFloatArray; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueFloatArray + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObject(env, nt::ReadQueueFloatArray(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueValuesFloatArray + * Signature: (I)[[F + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueValuesFloatArray + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObjectArray(env, nt::ReadQueueValuesFloatArray(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setFloatArray + * Signature: (IJ[F)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setFloatArray + (JNIEnv* env, jclass, jint entry, jlong time, jfloatArray value) +{ + if (!value) { + nullPointerEx.Throw(env, "value cannot be null"); + return false; + } + return nt::SetFloatArray(entry, CriticalJSpan{env, value}, time); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getFloatArray + * Signature: (I[F)[F + */ +JNIEXPORT jfloatArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getFloatArray + (JNIEnv* env, jclass, jint entry, jfloatArray defaultValue) +{ + auto val = nt::GetEntryValue(entry); + if (!val || !val.IsFloatArray()) { + return defaultValue; + } + return MakeJFloatArray(env, val.GetFloatArray()); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDefaultFloatArray + * Signature: (IJ[F)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefaultFloatArray + (JNIEnv* env, jclass, jint entry, jlong, jfloatArray defaultValue) +{ + if (!defaultValue) { + nullPointerEx.Throw(env, "defaultValue cannot be null"); + return false; + } + return nt::SetDefaultFloatArray(entry, CriticalJSpan{env, defaultValue}); +} + + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getAtomicDoubleArray + * Signature: (I[D)Ledu/wpi/first/networktables/TimestampedDoubleArray; + */ +JNIEXPORT jobject JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getAtomicDoubleArray + (JNIEnv* env, jclass, jint subentry, jdoubleArray defaultValue) +{ + return MakeJObject(env, nt::GetAtomicDoubleArray(subentry, CriticalJSpan{env, defaultValue})); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueDoubleArray + * Signature: (I)[Ledu/wpi/first/networktables/TimestampedDoubleArray; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueDoubleArray + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObject(env, nt::ReadQueueDoubleArray(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueValuesDoubleArray + * Signature: (I)[[D + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueValuesDoubleArray + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObjectArray(env, nt::ReadQueueValuesDoubleArray(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDoubleArray + * Signature: (IJ[D)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDoubleArray + (JNIEnv* env, jclass, jint entry, jlong time, jdoubleArray value) +{ + if (!value) { + nullPointerEx.Throw(env, "value cannot be null"); + return false; + } + return nt::SetDoubleArray(entry, CriticalJSpan{env, value}, time); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getDoubleArray + * Signature: (I[D)[D + */ +JNIEXPORT jdoubleArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getDoubleArray + (JNIEnv* env, jclass, jint entry, jdoubleArray defaultValue) +{ + auto val = nt::GetEntryValue(entry); + if (!val || !val.IsDoubleArray()) { + return defaultValue; + } + return MakeJDoubleArray(env, val.GetDoubleArray()); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDefaultDoubleArray + * Signature: (IJ[D)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefaultDoubleArray + (JNIEnv* env, jclass, jint entry, jlong, jdoubleArray defaultValue) +{ + if (!defaultValue) { + nullPointerEx.Throw(env, "defaultValue cannot be null"); + return false; + } + return nt::SetDefaultDoubleArray(entry, CriticalJSpan{env, defaultValue}); +} + + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getAtomicStringArray + * Signature: (I[Ljava/lang/Object;)Ledu/wpi/first/networktables/TimestampedStringArray; + */ +JNIEXPORT jobject JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getAtomicStringArray + (JNIEnv* env, jclass, jint subentry, jobjectArray defaultValue) +{ + return MakeJObject(env, nt::GetAtomicStringArray(subentry, FromJavaStringArray(env, defaultValue))); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueStringArray + * Signature: (I)[Ledu/wpi/first/networktables/TimestampedStringArray; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueStringArray + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObject(env, nt::ReadQueueStringArray(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: readQueueValuesStringArray + * Signature: (I)[[Ljava/lang/Object; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_readQueueValuesStringArray + (JNIEnv* env, jclass, jint subentry) +{ + return MakeJObjectArray(env, nt::ReadQueueValuesStringArray(subentry)); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setStringArray + * Signature: (IJ[Ljava/lang/Object;)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setStringArray + (JNIEnv* env, jclass, jint entry, jlong time, jobjectArray value) +{ + if (!value) { + nullPointerEx.Throw(env, "value cannot be null"); + return false; + } + return nt::SetStringArray(entry, FromJavaStringArray(env, value), time); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getStringArray + * Signature: (I[Ljava/lang/Object;)[Ljava/lang/Object; + */ +JNIEXPORT jobjectArray JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getStringArray + (JNIEnv* env, jclass, jint entry, jobjectArray defaultValue) +{ + auto val = nt::GetEntryValue(entry); + if (!val || !val.IsStringArray()) { + return defaultValue; + } + return MakeJStringArray(env, val.GetStringArray()); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setDefaultStringArray + * Signature: (IJ[Ljava/lang/Object;)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setDefaultStringArray + (JNIEnv* env, jclass, jint entry, jlong, jobjectArray defaultValue) +{ + if (!defaultValue) { + nullPointerEx.Throw(env, "defaultValue cannot be null"); + return false; + } + return nt::SetDefaultStringArray(entry, FromJavaStringArray(env, defaultValue)); +} + + +} // extern "C" diff --git a/ntcore/src/generated/main/native/cpp/ntcore_c_types.cpp b/ntcore/src/generated/main/native/cpp/ntcore_c_types.cpp new file mode 100644 index 00000000000..dcf1a946cbe --- /dev/null +++ b/ntcore/src/generated/main/native/cpp/ntcore_c_types.cpp @@ -0,0 +1,495 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#include "ntcore_c_types.h" + +#include "Value_internal.h" +#include "ntcore_cpp.h" + +using namespace nt; + +template +static inline std::span ConvertFromC(const T* arr, size_t size) { + return {arr, size}; +} + +static inline std::string_view ConvertFromC(const struct WPI_String* str) { + return wpi::to_string_view(str); +} + +static std::vector ConvertFromC(const struct WPI_String* arr, size_t size) { + std::vector v; + v.reserve(size); + for (size_t i = 0; i < size; ++i) { + v.emplace_back(ConvertFromC(arr[i])); + } + return v; +} + + +static void ConvertToC(const nt::TimestampedBoolean& in, NT_TimestampedBoolean* out) { + out->time = in.time; + out->serverTime = in.serverTime; + out->value = in.value; +} + +static void ConvertToC(const nt::TimestampedInteger& in, NT_TimestampedInteger* out) { + out->time = in.time; + out->serverTime = in.serverTime; + out->value = in.value; +} + +static void ConvertToC(const nt::TimestampedFloat& in, NT_TimestampedFloat* out) { + out->time = in.time; + out->serverTime = in.serverTime; + out->value = in.value; +} + +static void ConvertToC(const nt::TimestampedDouble& in, NT_TimestampedDouble* out) { + out->time = in.time; + out->serverTime = in.serverTime; + out->value = in.value; +} + +static void ConvertToC(const nt::TimestampedString& in, NT_TimestampedString* out) { + out->time = in.time; + out->serverTime = in.serverTime; + ConvertToC(in.value, &out->value); +} + +static void ConvertToC(const nt::TimestampedRaw& in, NT_TimestampedRaw* out) { + out->time = in.time; + out->serverTime = in.serverTime; + out->value = ConvertToC(in.value, &out->len); +} + +static void ConvertToC(const nt::TimestampedBooleanArray& in, NT_TimestampedBooleanArray* out) { + out->time = in.time; + out->serverTime = in.serverTime; + out->value = ConvertToC(in.value, &out->len); +} + +static void ConvertToC(const nt::TimestampedIntegerArray& in, NT_TimestampedIntegerArray* out) { + out->time = in.time; + out->serverTime = in.serverTime; + out->value = ConvertToC(in.value, &out->len); +} + +static void ConvertToC(const nt::TimestampedFloatArray& in, NT_TimestampedFloatArray* out) { + out->time = in.time; + out->serverTime = in.serverTime; + out->value = ConvertToC(in.value, &out->len); +} + +static void ConvertToC(const nt::TimestampedDoubleArray& in, NT_TimestampedDoubleArray* out) { + out->time = in.time; + out->serverTime = in.serverTime; + out->value = ConvertToC(in.value, &out->len); +} + +static void ConvertToC(const nt::TimestampedStringArray& in, NT_TimestampedStringArray* out) { + out->time = in.time; + out->serverTime = in.serverTime; + out->value = ConvertToC(in.value, &out->len); +} + + +extern "C" { + +NT_Bool NT_SetBoolean(NT_Handle pubentry, int64_t time, NT_Bool value) { + return nt::SetBoolean(pubentry, value, time); +} + +NT_Bool NT_SetDefaultBoolean(NT_Handle pubentry, NT_Bool defaultValue) { + return nt::SetDefaultBoolean(pubentry, defaultValue); +} + +NT_Bool NT_GetBoolean(NT_Handle subentry, NT_Bool defaultValue) { + return nt::GetBoolean(subentry, defaultValue); +} + +void NT_GetAtomicBoolean(NT_Handle subentry, NT_Bool defaultValue, struct NT_TimestampedBoolean* value) { + auto cppValue = nt::GetAtomicBoolean(subentry, defaultValue); + ConvertToC(cppValue, value); +} + +void NT_DisposeTimestampedBoolean(struct NT_TimestampedBoolean* value) { +} + +struct NT_TimestampedBoolean* NT_ReadQueueBoolean(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueBoolean(subentry); + return ConvertToC(arr, len); +} + +void NT_FreeQueueBoolean(struct NT_TimestampedBoolean* arr, size_t len) { + for (size_t i = 0; i < len; ++i) { + NT_DisposeTimestampedBoolean(&arr[i]); + } + std::free(arr); +} +NT_Bool* NT_ReadQueueValuesBoolean(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueValuesBoolean(subentry); + return ConvertToC(arr, len); +} + + +NT_Bool NT_SetInteger(NT_Handle pubentry, int64_t time, int64_t value) { + return nt::SetInteger(pubentry, value, time); +} + +NT_Bool NT_SetDefaultInteger(NT_Handle pubentry, int64_t defaultValue) { + return nt::SetDefaultInteger(pubentry, defaultValue); +} + +int64_t NT_GetInteger(NT_Handle subentry, int64_t defaultValue) { + return nt::GetInteger(subentry, defaultValue); +} + +void NT_GetAtomicInteger(NT_Handle subentry, int64_t defaultValue, struct NT_TimestampedInteger* value) { + auto cppValue = nt::GetAtomicInteger(subentry, defaultValue); + ConvertToC(cppValue, value); +} + +void NT_DisposeTimestampedInteger(struct NT_TimestampedInteger* value) { +} + +struct NT_TimestampedInteger* NT_ReadQueueInteger(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueInteger(subentry); + return ConvertToC(arr, len); +} + +void NT_FreeQueueInteger(struct NT_TimestampedInteger* arr, size_t len) { + for (size_t i = 0; i < len; ++i) { + NT_DisposeTimestampedInteger(&arr[i]); + } + std::free(arr); +} +int64_t* NT_ReadQueueValuesInteger(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueValuesInteger(subentry); + return ConvertToC(arr, len); +} + + +NT_Bool NT_SetFloat(NT_Handle pubentry, int64_t time, float value) { + return nt::SetFloat(pubentry, value, time); +} + +NT_Bool NT_SetDefaultFloat(NT_Handle pubentry, float defaultValue) { + return nt::SetDefaultFloat(pubentry, defaultValue); +} + +float NT_GetFloat(NT_Handle subentry, float defaultValue) { + return nt::GetFloat(subentry, defaultValue); +} + +void NT_GetAtomicFloat(NT_Handle subentry, float defaultValue, struct NT_TimestampedFloat* value) { + auto cppValue = nt::GetAtomicFloat(subentry, defaultValue); + ConvertToC(cppValue, value); +} + +void NT_DisposeTimestampedFloat(struct NT_TimestampedFloat* value) { +} + +struct NT_TimestampedFloat* NT_ReadQueueFloat(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueFloat(subentry); + return ConvertToC(arr, len); +} + +void NT_FreeQueueFloat(struct NT_TimestampedFloat* arr, size_t len) { + for (size_t i = 0; i < len; ++i) { + NT_DisposeTimestampedFloat(&arr[i]); + } + std::free(arr); +} +float* NT_ReadQueueValuesFloat(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueValuesFloat(subentry); + return ConvertToC(arr, len); +} + + +NT_Bool NT_SetDouble(NT_Handle pubentry, int64_t time, double value) { + return nt::SetDouble(pubentry, value, time); +} + +NT_Bool NT_SetDefaultDouble(NT_Handle pubentry, double defaultValue) { + return nt::SetDefaultDouble(pubentry, defaultValue); +} + +double NT_GetDouble(NT_Handle subentry, double defaultValue) { + return nt::GetDouble(subentry, defaultValue); +} + +void NT_GetAtomicDouble(NT_Handle subentry, double defaultValue, struct NT_TimestampedDouble* value) { + auto cppValue = nt::GetAtomicDouble(subentry, defaultValue); + ConvertToC(cppValue, value); +} + +void NT_DisposeTimestampedDouble(struct NT_TimestampedDouble* value) { +} + +struct NT_TimestampedDouble* NT_ReadQueueDouble(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueDouble(subentry); + return ConvertToC(arr, len); +} + +void NT_FreeQueueDouble(struct NT_TimestampedDouble* arr, size_t len) { + for (size_t i = 0; i < len; ++i) { + NT_DisposeTimestampedDouble(&arr[i]); + } + std::free(arr); +} +double* NT_ReadQueueValuesDouble(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueValuesDouble(subentry); + return ConvertToC(arr, len); +} + + +NT_Bool NT_SetString(NT_Handle pubentry, int64_t time, const struct WPI_String* value) { + return nt::SetString(pubentry, ConvertFromC(value), time); +} + +NT_Bool NT_SetDefaultString(NT_Handle pubentry, const struct WPI_String* defaultValue) { + return nt::SetDefaultString(pubentry, ConvertFromC(defaultValue)); +} + +void NT_GetString(NT_Handle subentry, const struct WPI_String* defaultValue, struct WPI_String* value) { + auto cppValue = nt::GetString(subentry, ConvertFromC(defaultValue)); + ConvertToC(cppValue, value); +} + +void NT_GetAtomicString(NT_Handle subentry, const struct WPI_String* defaultValue, struct NT_TimestampedString* value) { + auto cppValue = nt::GetAtomicString(subentry, ConvertFromC(defaultValue)); + ConvertToC(cppValue, value); +} + +void NT_DisposeTimestampedString(struct NT_TimestampedString* value) { + WPI_FreeString(&value->value); +} + +struct NT_TimestampedString* NT_ReadQueueString(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueString(subentry); + return ConvertToC(arr, len); +} + +void NT_FreeQueueString(struct NT_TimestampedString* arr, size_t len) { + for (size_t i = 0; i < len; ++i) { + NT_DisposeTimestampedString(&arr[i]); + } + std::free(arr); +} + + +NT_Bool NT_SetRaw(NT_Handle pubentry, int64_t time, const uint8_t* value, size_t len) { + return nt::SetRaw(pubentry, ConvertFromC(value, len), time); +} + +NT_Bool NT_SetDefaultRaw(NT_Handle pubentry, const uint8_t* defaultValue, size_t defaultValueLen) { + return nt::SetDefaultRaw(pubentry, ConvertFromC(defaultValue, defaultValueLen)); +} + +uint8_t* NT_GetRaw(NT_Handle subentry, const uint8_t* defaultValue, size_t defaultValueLen, size_t* len) { + auto cppValue = nt::GetRaw(subentry, ConvertFromC(defaultValue, defaultValueLen)); + return ConvertToC(cppValue, len); +} + +void NT_GetAtomicRaw(NT_Handle subentry, const uint8_t* defaultValue, size_t defaultValueLen, struct NT_TimestampedRaw* value) { + auto cppValue = nt::GetAtomicRaw(subentry, ConvertFromC(defaultValue, defaultValueLen)); + ConvertToC(cppValue, value); +} + +void NT_DisposeTimestampedRaw(struct NT_TimestampedRaw* value) { + std::free(value->value); +} + +struct NT_TimestampedRaw* NT_ReadQueueRaw(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueRaw(subentry); + return ConvertToC(arr, len); +} + +void NT_FreeQueueRaw(struct NT_TimestampedRaw* arr, size_t len) { + for (size_t i = 0; i < len; ++i) { + NT_DisposeTimestampedRaw(&arr[i]); + } + std::free(arr); +} + + +NT_Bool NT_SetBooleanArray(NT_Handle pubentry, int64_t time, const NT_Bool* value, size_t len) { + return nt::SetBooleanArray(pubentry, ConvertFromC(value, len), time); +} + +NT_Bool NT_SetDefaultBooleanArray(NT_Handle pubentry, const NT_Bool* defaultValue, size_t defaultValueLen) { + return nt::SetDefaultBooleanArray(pubentry, ConvertFromC(defaultValue, defaultValueLen)); +} + +NT_Bool* NT_GetBooleanArray(NT_Handle subentry, const NT_Bool* defaultValue, size_t defaultValueLen, size_t* len) { + auto cppValue = nt::GetBooleanArray(subentry, ConvertFromC(defaultValue, defaultValueLen)); + return ConvertToC(cppValue, len); +} + +void NT_GetAtomicBooleanArray(NT_Handle subentry, const NT_Bool* defaultValue, size_t defaultValueLen, struct NT_TimestampedBooleanArray* value) { + auto cppValue = nt::GetAtomicBooleanArray(subentry, ConvertFromC(defaultValue, defaultValueLen)); + ConvertToC(cppValue, value); +} + +void NT_DisposeTimestampedBooleanArray(struct NT_TimestampedBooleanArray* value) { + std::free(value->value); +} + +struct NT_TimestampedBooleanArray* NT_ReadQueueBooleanArray(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueBooleanArray(subentry); + return ConvertToC(arr, len); +} + +void NT_FreeQueueBooleanArray(struct NT_TimestampedBooleanArray* arr, size_t len) { + for (size_t i = 0; i < len; ++i) { + NT_DisposeTimestampedBooleanArray(&arr[i]); + } + std::free(arr); +} + + +NT_Bool NT_SetIntegerArray(NT_Handle pubentry, int64_t time, const int64_t* value, size_t len) { + return nt::SetIntegerArray(pubentry, ConvertFromC(value, len), time); +} + +NT_Bool NT_SetDefaultIntegerArray(NT_Handle pubentry, const int64_t* defaultValue, size_t defaultValueLen) { + return nt::SetDefaultIntegerArray(pubentry, ConvertFromC(defaultValue, defaultValueLen)); +} + +int64_t* NT_GetIntegerArray(NT_Handle subentry, const int64_t* defaultValue, size_t defaultValueLen, size_t* len) { + auto cppValue = nt::GetIntegerArray(subentry, ConvertFromC(defaultValue, defaultValueLen)); + return ConvertToC(cppValue, len); +} + +void NT_GetAtomicIntegerArray(NT_Handle subentry, const int64_t* defaultValue, size_t defaultValueLen, struct NT_TimestampedIntegerArray* value) { + auto cppValue = nt::GetAtomicIntegerArray(subentry, ConvertFromC(defaultValue, defaultValueLen)); + ConvertToC(cppValue, value); +} + +void NT_DisposeTimestampedIntegerArray(struct NT_TimestampedIntegerArray* value) { + std::free(value->value); +} + +struct NT_TimestampedIntegerArray* NT_ReadQueueIntegerArray(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueIntegerArray(subentry); + return ConvertToC(arr, len); +} + +void NT_FreeQueueIntegerArray(struct NT_TimestampedIntegerArray* arr, size_t len) { + for (size_t i = 0; i < len; ++i) { + NT_DisposeTimestampedIntegerArray(&arr[i]); + } + std::free(arr); +} + + +NT_Bool NT_SetFloatArray(NT_Handle pubentry, int64_t time, const float* value, size_t len) { + return nt::SetFloatArray(pubentry, ConvertFromC(value, len), time); +} + +NT_Bool NT_SetDefaultFloatArray(NT_Handle pubentry, const float* defaultValue, size_t defaultValueLen) { + return nt::SetDefaultFloatArray(pubentry, ConvertFromC(defaultValue, defaultValueLen)); +} + +float* NT_GetFloatArray(NT_Handle subentry, const float* defaultValue, size_t defaultValueLen, size_t* len) { + auto cppValue = nt::GetFloatArray(subentry, ConvertFromC(defaultValue, defaultValueLen)); + return ConvertToC(cppValue, len); +} + +void NT_GetAtomicFloatArray(NT_Handle subentry, const float* defaultValue, size_t defaultValueLen, struct NT_TimestampedFloatArray* value) { + auto cppValue = nt::GetAtomicFloatArray(subentry, ConvertFromC(defaultValue, defaultValueLen)); + ConvertToC(cppValue, value); +} + +void NT_DisposeTimestampedFloatArray(struct NT_TimestampedFloatArray* value) { + std::free(value->value); +} + +struct NT_TimestampedFloatArray* NT_ReadQueueFloatArray(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueFloatArray(subentry); + return ConvertToC(arr, len); +} + +void NT_FreeQueueFloatArray(struct NT_TimestampedFloatArray* arr, size_t len) { + for (size_t i = 0; i < len; ++i) { + NT_DisposeTimestampedFloatArray(&arr[i]); + } + std::free(arr); +} + + +NT_Bool NT_SetDoubleArray(NT_Handle pubentry, int64_t time, const double* value, size_t len) { + return nt::SetDoubleArray(pubentry, ConvertFromC(value, len), time); +} + +NT_Bool NT_SetDefaultDoubleArray(NT_Handle pubentry, const double* defaultValue, size_t defaultValueLen) { + return nt::SetDefaultDoubleArray(pubentry, ConvertFromC(defaultValue, defaultValueLen)); +} + +double* NT_GetDoubleArray(NT_Handle subentry, const double* defaultValue, size_t defaultValueLen, size_t* len) { + auto cppValue = nt::GetDoubleArray(subentry, ConvertFromC(defaultValue, defaultValueLen)); + return ConvertToC(cppValue, len); +} + +void NT_GetAtomicDoubleArray(NT_Handle subentry, const double* defaultValue, size_t defaultValueLen, struct NT_TimestampedDoubleArray* value) { + auto cppValue = nt::GetAtomicDoubleArray(subentry, ConvertFromC(defaultValue, defaultValueLen)); + ConvertToC(cppValue, value); +} + +void NT_DisposeTimestampedDoubleArray(struct NT_TimestampedDoubleArray* value) { + std::free(value->value); +} + +struct NT_TimestampedDoubleArray* NT_ReadQueueDoubleArray(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueDoubleArray(subentry); + return ConvertToC(arr, len); +} + +void NT_FreeQueueDoubleArray(struct NT_TimestampedDoubleArray* arr, size_t len) { + for (size_t i = 0; i < len; ++i) { + NT_DisposeTimestampedDoubleArray(&arr[i]); + } + std::free(arr); +} + + +NT_Bool NT_SetStringArray(NT_Handle pubentry, int64_t time, const struct WPI_String* value, size_t len) { + return nt::SetStringArray(pubentry, ConvertFromC(value, len), time); +} + +NT_Bool NT_SetDefaultStringArray(NT_Handle pubentry, const struct WPI_String* defaultValue, size_t defaultValueLen) { + return nt::SetDefaultStringArray(pubentry, ConvertFromC(defaultValue, defaultValueLen)); +} + +struct WPI_String* NT_GetStringArray(NT_Handle subentry, const struct WPI_String* defaultValue, size_t defaultValueLen, size_t* len) { + auto cppValue = nt::GetStringArray(subentry, ConvertFromC(defaultValue, defaultValueLen)); + return ConvertToC(cppValue, len); +} + +void NT_GetAtomicStringArray(NT_Handle subentry, const struct WPI_String* defaultValue, size_t defaultValueLen, struct NT_TimestampedStringArray* value) { + auto cppValue = nt::GetAtomicStringArray(subentry, ConvertFromC(defaultValue, defaultValueLen)); + ConvertToC(cppValue, value); +} + +void NT_DisposeTimestampedStringArray(struct NT_TimestampedStringArray* value) { + WPI_FreeStringArray(value->value, value->len); +} + +struct NT_TimestampedStringArray* NT_ReadQueueStringArray(NT_Handle subentry, size_t* len) { + auto arr = nt::ReadQueueStringArray(subentry); + return ConvertToC(arr, len); +} + +void NT_FreeQueueStringArray(struct NT_TimestampedStringArray* arr, size_t len) { + for (size_t i = 0; i < len; ++i) { + NT_DisposeTimestampedStringArray(&arr[i]); + } + std::free(arr); +} + + +} // extern "C" diff --git a/ntcore/src/generated/main/native/cpp/ntcore_cpp_types.cpp b/ntcore/src/generated/main/native/cpp/ntcore_cpp_types.cpp new file mode 100644 index 00000000000..030857e8957 --- /dev/null +++ b/ntcore/src/generated/main/native/cpp/ntcore_cpp_types.cpp @@ -0,0 +1,463 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#include "ntcore_cpp_types.h" + +#include "Handle.h" +#include "InstanceImpl.h" + +namespace { +template +struct ValuesType { + using Vector = + std::vector>::Value>; +}; + +template <> +struct ValuesType { + using Vector = std::vector; +}; +} // namespace + +namespace nt { + +template +static inline bool Set(NT_Handle pubentry, typename TypeInfo::View value, + int64_t time) { + if (auto ii = InstanceImpl::Get(Handle{pubentry}.GetInst())) { + return ii->localStorage.SetEntryValue( + pubentry, MakeValue(value, time == 0 ? Now() : time)); + } else { + return {}; + } +} + +template +static inline bool SetDefault(NT_Handle pubentry, + typename TypeInfo::View defaultValue) { + if (auto ii = InstanceImpl::Get(Handle{pubentry}.GetInst())) { + return ii->localStorage.SetDefaultEntryValue(pubentry, + MakeValue(defaultValue, 1)); + } else { + return {}; + } +} + +template +static inline Timestamped::Value> GetAtomic( + NT_Handle subentry, typename TypeInfo::View defaultValue) { + if (auto ii = InstanceImpl::Get(Handle{subentry}.GetInst())) { + return ii->localStorage.GetAtomic(subentry, defaultValue); + } else { + return {}; + } +} + +template +inline Timestamped::SmallRet> GetAtomic( + NT_Handle subentry, + wpi::SmallVectorImpl::SmallElem>& buf, + typename TypeInfo::View defaultValue) { + if (auto ii = InstanceImpl::Get(Handle{subentry}.GetInst())) { + return ii->localStorage.GetAtomic(subentry, buf, defaultValue); + } else { + return {}; + } +} + +template +static inline std::vector::Value>> ReadQueue( + NT_Handle subentry) { + if (auto ii = InstanceImpl::Get(Handle{subentry}.GetInst())) { + return ii->localStorage.ReadQueue(subentry); + } else { + return {}; + } +} + +template +static inline typename ValuesType::Vector ReadQueueValues( + NT_Handle subentry) { + typename ValuesType::Vector rv; + auto arr = ReadQueue(subentry); + rv.reserve(arr.size()); + for (auto&& elem : arr) { + rv.emplace_back(std::move(elem.value)); + } + return rv; +} + +bool SetBoolean(NT_Handle pubentry, bool value, int64_t time) { + return Set(pubentry, value, time); +} + +bool SetDefaultBoolean(NT_Handle pubentry, bool defaultValue) { + return SetDefault(pubentry, defaultValue); +} + +bool GetBoolean(NT_Handle subentry, bool defaultValue) { + return GetAtomic(subentry, defaultValue).value; +} + +TimestampedBoolean GetAtomicBoolean( + NT_Handle subentry, bool defaultValue) { + return GetAtomic(subentry, defaultValue); +} + +std::vector ReadQueueBoolean(NT_Handle subentry) { + return ReadQueue(subentry); +} + +std::vector ReadQueueValuesBoolean(NT_Handle subentry) { + return ReadQueueValues(subentry); +} + + +bool SetInteger(NT_Handle pubentry, int64_t value, int64_t time) { + return Set(pubentry, value, time); +} + +bool SetDefaultInteger(NT_Handle pubentry, int64_t defaultValue) { + return SetDefault(pubentry, defaultValue); +} + +int64_t GetInteger(NT_Handle subentry, int64_t defaultValue) { + return GetAtomic(subentry, defaultValue).value; +} + +TimestampedInteger GetAtomicInteger( + NT_Handle subentry, int64_t defaultValue) { + return GetAtomic(subentry, defaultValue); +} + +std::vector ReadQueueInteger(NT_Handle subentry) { + return ReadQueue(subentry); +} + +std::vector ReadQueueValuesInteger(NT_Handle subentry) { + return ReadQueueValues(subentry); +} + + +bool SetFloat(NT_Handle pubentry, float value, int64_t time) { + return Set(pubentry, value, time); +} + +bool SetDefaultFloat(NT_Handle pubentry, float defaultValue) { + return SetDefault(pubentry, defaultValue); +} + +float GetFloat(NT_Handle subentry, float defaultValue) { + return GetAtomic(subentry, defaultValue).value; +} + +TimestampedFloat GetAtomicFloat( + NT_Handle subentry, float defaultValue) { + return GetAtomic(subentry, defaultValue); +} + +std::vector ReadQueueFloat(NT_Handle subentry) { + return ReadQueue(subentry); +} + +std::vector ReadQueueValuesFloat(NT_Handle subentry) { + return ReadQueueValues(subentry); +} + + +bool SetDouble(NT_Handle pubentry, double value, int64_t time) { + return Set(pubentry, value, time); +} + +bool SetDefaultDouble(NT_Handle pubentry, double defaultValue) { + return SetDefault(pubentry, defaultValue); +} + +double GetDouble(NT_Handle subentry, double defaultValue) { + return GetAtomic(subentry, defaultValue).value; +} + +TimestampedDouble GetAtomicDouble( + NT_Handle subentry, double defaultValue) { + return GetAtomic(subentry, defaultValue); +} + +std::vector ReadQueueDouble(NT_Handle subentry) { + return ReadQueue(subentry); +} + +std::vector ReadQueueValuesDouble(NT_Handle subentry) { + return ReadQueueValues(subentry); +} + + +bool SetString(NT_Handle pubentry, std::string_view value, int64_t time) { + return Set(pubentry, value, time); +} + +bool SetDefaultString(NT_Handle pubentry, std::string_view defaultValue) { + return SetDefault(pubentry, defaultValue); +} + +std::string GetString(NT_Handle subentry, std::string_view defaultValue) { + return GetAtomic(subentry, defaultValue).value; +} + +TimestampedString GetAtomicString( + NT_Handle subentry, std::string_view defaultValue) { + return GetAtomic(subentry, defaultValue); +} + +std::vector ReadQueueString(NT_Handle subentry) { + return ReadQueue(subentry); +} + +std::vector ReadQueueValuesString(NT_Handle subentry) { + return ReadQueueValues(subentry); +} + +std::string_view GetString( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::string_view defaultValue) { + return GetAtomic(subentry, buf, defaultValue).value; +} + +TimestampedStringView GetAtomicString( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::string_view defaultValue) { + return GetAtomic(subentry, buf, defaultValue); +} + + +bool SetRaw(NT_Handle pubentry, std::span value, int64_t time) { + return Set(pubentry, value, time); +} + +bool SetDefaultRaw(NT_Handle pubentry, std::span defaultValue) { + return SetDefault(pubentry, defaultValue); +} + +std::vector GetRaw(NT_Handle subentry, std::span defaultValue) { + return GetAtomic(subentry, defaultValue).value; +} + +TimestampedRaw GetAtomicRaw( + NT_Handle subentry, std::span defaultValue) { + return GetAtomic(subentry, defaultValue); +} + +std::vector ReadQueueRaw(NT_Handle subentry) { + return ReadQueue(subentry); +} + +std::vector> ReadQueueValuesRaw(NT_Handle subentry) { + return ReadQueueValues(subentry); +} + +std::span GetRaw( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue) { + return GetAtomic(subentry, buf, defaultValue).value; +} + +TimestampedRawView GetAtomicRaw( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue) { + return GetAtomic(subentry, buf, defaultValue); +} + + +bool SetBooleanArray(NT_Handle pubentry, std::span value, int64_t time) { + return Set(pubentry, value, time); +} + +bool SetDefaultBooleanArray(NT_Handle pubentry, std::span defaultValue) { + return SetDefault(pubentry, defaultValue); +} + +std::vector GetBooleanArray(NT_Handle subentry, std::span defaultValue) { + return GetAtomic(subentry, defaultValue).value; +} + +TimestampedBooleanArray GetAtomicBooleanArray( + NT_Handle subentry, std::span defaultValue) { + return GetAtomic(subentry, defaultValue); +} + +std::vector ReadQueueBooleanArray(NT_Handle subentry) { + return ReadQueue(subentry); +} + +std::vector> ReadQueueValuesBooleanArray(NT_Handle subentry) { + return ReadQueueValues(subentry); +} + +std::span GetBooleanArray( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue) { + return GetAtomic(subentry, buf, defaultValue).value; +} + +TimestampedBooleanArrayView GetAtomicBooleanArray( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue) { + return GetAtomic(subentry, buf, defaultValue); +} + + +bool SetIntegerArray(NT_Handle pubentry, std::span value, int64_t time) { + return Set(pubentry, value, time); +} + +bool SetDefaultIntegerArray(NT_Handle pubentry, std::span defaultValue) { + return SetDefault(pubentry, defaultValue); +} + +std::vector GetIntegerArray(NT_Handle subentry, std::span defaultValue) { + return GetAtomic(subentry, defaultValue).value; +} + +TimestampedIntegerArray GetAtomicIntegerArray( + NT_Handle subentry, std::span defaultValue) { + return GetAtomic(subentry, defaultValue); +} + +std::vector ReadQueueIntegerArray(NT_Handle subentry) { + return ReadQueue(subentry); +} + +std::vector> ReadQueueValuesIntegerArray(NT_Handle subentry) { + return ReadQueueValues(subentry); +} + +std::span GetIntegerArray( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue) { + return GetAtomic(subentry, buf, defaultValue).value; +} + +TimestampedIntegerArrayView GetAtomicIntegerArray( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue) { + return GetAtomic(subentry, buf, defaultValue); +} + + +bool SetFloatArray(NT_Handle pubentry, std::span value, int64_t time) { + return Set(pubentry, value, time); +} + +bool SetDefaultFloatArray(NT_Handle pubentry, std::span defaultValue) { + return SetDefault(pubentry, defaultValue); +} + +std::vector GetFloatArray(NT_Handle subentry, std::span defaultValue) { + return GetAtomic(subentry, defaultValue).value; +} + +TimestampedFloatArray GetAtomicFloatArray( + NT_Handle subentry, std::span defaultValue) { + return GetAtomic(subentry, defaultValue); +} + +std::vector ReadQueueFloatArray(NT_Handle subentry) { + return ReadQueue(subentry); +} + +std::vector> ReadQueueValuesFloatArray(NT_Handle subentry) { + return ReadQueueValues(subentry); +} + +std::span GetFloatArray( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue) { + return GetAtomic(subentry, buf, defaultValue).value; +} + +TimestampedFloatArrayView GetAtomicFloatArray( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue) { + return GetAtomic(subentry, buf, defaultValue); +} + + +bool SetDoubleArray(NT_Handle pubentry, std::span value, int64_t time) { + return Set(pubentry, value, time); +} + +bool SetDefaultDoubleArray(NT_Handle pubentry, std::span defaultValue) { + return SetDefault(pubentry, defaultValue); +} + +std::vector GetDoubleArray(NT_Handle subentry, std::span defaultValue) { + return GetAtomic(subentry, defaultValue).value; +} + +TimestampedDoubleArray GetAtomicDoubleArray( + NT_Handle subentry, std::span defaultValue) { + return GetAtomic(subentry, defaultValue); +} + +std::vector ReadQueueDoubleArray(NT_Handle subentry) { + return ReadQueue(subentry); +} + +std::vector> ReadQueueValuesDoubleArray(NT_Handle subentry) { + return ReadQueueValues(subentry); +} + +std::span GetDoubleArray( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue) { + return GetAtomic(subentry, buf, defaultValue).value; +} + +TimestampedDoubleArrayView GetAtomicDoubleArray( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue) { + return GetAtomic(subentry, buf, defaultValue); +} + + +bool SetStringArray(NT_Handle pubentry, std::span value, int64_t time) { + return Set(pubentry, value, time); +} + +bool SetDefaultStringArray(NT_Handle pubentry, std::span defaultValue) { + return SetDefault(pubentry, defaultValue); +} + +std::vector GetStringArray(NT_Handle subentry, std::span defaultValue) { + return GetAtomic(subentry, defaultValue).value; +} + +TimestampedStringArray GetAtomicStringArray( + NT_Handle subentry, std::span defaultValue) { + return GetAtomic(subentry, defaultValue); +} + +std::vector ReadQueueStringArray(NT_Handle subentry) { + return ReadQueue(subentry); +} + +std::vector> ReadQueueValuesStringArray(NT_Handle subentry) { + return ReadQueueValues(subentry); +} + + +} // namespace nt diff --git a/ntcore/src/generated/main/native/include/networktables/BooleanArrayTopic.h b/ntcore/src/generated/main/native/include/networktables/BooleanArrayTopic.h new file mode 100644 index 00000000000..de89f4b2b08 --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/BooleanArrayTopic.h @@ -0,0 +1,426 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include +#include +#include +#include + +#include + +#include "networktables/Topic.h" + +namespace wpi { +template +class SmallVectorImpl; +} // namespace wpi + +namespace nt { + +class BooleanArrayTopic; + +/** + * NetworkTables BooleanArray subscriber. + */ +class BooleanArraySubscriber : public Subscriber { + public: + using TopicType = BooleanArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + using TimestampedValueType = TimestampedBooleanArray; + + using SmallRetType = std::span; + using SmallElemType = int; + using TimestampedValueViewType = TimestampedBooleanArrayView; + + + BooleanArraySubscriber() = default; + + /** + * Construct from a subscriber handle; recommended to use + * BooleanArrayTopic::Subscribe() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + BooleanArraySubscriber(NT_Subscriber handle, ParamType defaultValue); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + ValueType Get() const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + ValueType Get(ParamType defaultValue) const; + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @param buf storage for returned value + * @return value + */ + SmallRetType Get(wpi::SmallVectorImpl& buf) const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param buf storage for returned value + * @param defaultValue default value to return if no value has been published + * @return value + */ + SmallRetType Get(wpi::SmallVectorImpl& buf, ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedValueType GetAtomic() const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueType GetAtomic(ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @param buf storage for returned value + * @return timestamped value + */ + TimestampedValueViewType GetAtomic( + wpi::SmallVectorImpl& buf) const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param buf storage for returned value + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueViewType GetAtomic( + wpi::SmallVectorImpl& buf, + ParamType defaultValue) const; + + /** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + std::vector ReadQueue(); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + private: + ValueType m_defaultValue; +}; + +/** + * NetworkTables BooleanArray publisher. + */ +class BooleanArrayPublisher : public Publisher { + public: + using TopicType = BooleanArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + + using SmallRetType = std::span; + using SmallElemType = int; + + using TimestampedValueType = TimestampedBooleanArray; + + BooleanArrayPublisher() = default; + + /** + * Construct from a publisher handle; recommended to use + * BooleanArrayTopic::Publish() instead. + * + * @param handle Native handle + */ + explicit BooleanArrayPublisher(NT_Publisher handle); + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void Set(ParamType value, int64_t time = 0); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void SetDefault(ParamType value); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; +}; + +/** + * NetworkTables BooleanArray entry. + * + * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. + */ +class BooleanArrayEntry final : public BooleanArraySubscriber, + public BooleanArrayPublisher { + public: + using SubscriberType = BooleanArraySubscriber; + using PublisherType = BooleanArrayPublisher; + using TopicType = BooleanArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + + using SmallRetType = std::span; + using SmallElemType = int; + + using TimestampedValueType = TimestampedBooleanArray; + + BooleanArrayEntry() = default; + + /** + * Construct from an entry handle; recommended to use + * BooleanArrayTopic::GetEntry() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + BooleanArrayEntry(NT_Entry handle, ParamType defaultValue); + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + explicit operator bool() const { return m_subHandle != 0; } + + /** + * Gets the native handle for the entry. + * + * @return Native handle + */ + NT_Entry GetHandle() const { return m_subHandle; } + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + /** + * Stops publishing the entry if it's published. + */ + void Unpublish(); +}; + +/** + * NetworkTables BooleanArray topic. + */ +class BooleanArrayTopic final : public Topic { + public: + using SubscriberType = BooleanArraySubscriber; + using PublisherType = BooleanArrayPublisher; + using EntryType = BooleanArrayEntry; + using ValueType = std::vector; + using ParamType = std::span; + using TimestampedValueType = TimestampedBooleanArray; + /** The default type string for this topic type. */ + static constexpr std::string_view kTypeString = "boolean[]"; + + BooleanArrayTopic() = default; + + /** + * Construct from a topic handle; recommended to use + * NetworkTableInstance::GetBooleanArrayTopic() instead. + * + * @param handle Native handle + */ + explicit BooleanArrayTopic(NT_Topic handle) : Topic{handle} {} + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + explicit BooleanArrayTopic(Topic topic) : Topic{topic} {} + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType Subscribe( + ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new subscriber to the topic, with specific type string. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType SubscribeEx( + std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType Publish(const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic, with type string and initial + * properties. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType PublishEx(std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new entry for the topic. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntry(ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new entry for the topic, with specific type string. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntryEx(std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + +}; + +} // namespace nt + +#include "networktables/BooleanArrayTopic.inc" diff --git a/ntcore/src/generated/main/native/include/networktables/BooleanArrayTopic.inc b/ntcore/src/generated/main/native/include/networktables/BooleanArrayTopic.inc new file mode 100644 index 00000000000..404ec7e23df --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/BooleanArrayTopic.inc @@ -0,0 +1,137 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include "networktables/BooleanArrayTopic.h" +#include "networktables/NetworkTableType.h" +#include "ntcore_cpp.h" + +namespace nt { + +inline BooleanArraySubscriber::BooleanArraySubscriber( + NT_Subscriber handle, std::span defaultValue) + : Subscriber{handle}, + m_defaultValue{defaultValue.begin(), defaultValue.end()} {} + +inline std::vector BooleanArraySubscriber::Get() const { + return Get(m_defaultValue); +} + +inline std::vector BooleanArraySubscriber::Get( + std::span defaultValue) const { + return ::nt::GetBooleanArray(m_subHandle, defaultValue); +} + +inline std::span BooleanArraySubscriber::Get(wpi::SmallVectorImpl& buf) const { + return Get(buf, m_defaultValue); +} + +inline std::span BooleanArraySubscriber::Get(wpi::SmallVectorImpl& buf, std::span defaultValue) const { + return nt::GetBooleanArray(m_subHandle, buf, defaultValue); +} + +inline TimestampedBooleanArray BooleanArraySubscriber::GetAtomic() const { + return GetAtomic(m_defaultValue); +} + +inline TimestampedBooleanArray BooleanArraySubscriber::GetAtomic( + std::span defaultValue) const { + return ::nt::GetAtomicBooleanArray(m_subHandle, defaultValue); +} + +inline TimestampedBooleanArrayView BooleanArraySubscriber::GetAtomic(wpi::SmallVectorImpl& buf) const { + return GetAtomic(buf, m_defaultValue); +} + +inline TimestampedBooleanArrayView BooleanArraySubscriber::GetAtomic(wpi::SmallVectorImpl& buf, std::span defaultValue) const { + return nt::GetAtomicBooleanArray(m_subHandle, buf, defaultValue); +} + +inline std::vector +BooleanArraySubscriber::ReadQueue() { + return ::nt::ReadQueueBooleanArray(m_subHandle); +} + +inline BooleanArrayTopic BooleanArraySubscriber::GetTopic() const { + return BooleanArrayTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline BooleanArrayPublisher::BooleanArrayPublisher(NT_Publisher handle) + : Publisher{handle} {} + +inline void BooleanArrayPublisher::Set(std::span value, + int64_t time) { + ::nt::SetBooleanArray(m_pubHandle, value, time); +} + +inline void BooleanArrayPublisher::SetDefault(std::span value) { + ::nt::SetDefaultBooleanArray(m_pubHandle, value); +} + +inline BooleanArrayTopic BooleanArrayPublisher::GetTopic() const { + return BooleanArrayTopic{::nt::GetTopicFromHandle(m_pubHandle)}; +} + +inline BooleanArrayEntry::BooleanArrayEntry( + NT_Entry handle, std::span defaultValue) + : BooleanArraySubscriber{handle, defaultValue}, + BooleanArrayPublisher{handle} {} + +inline BooleanArrayTopic BooleanArrayEntry::GetTopic() const { + return BooleanArrayTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline void BooleanArrayEntry::Unpublish() { + ::nt::Unpublish(m_pubHandle); +} + +inline BooleanArraySubscriber BooleanArrayTopic::Subscribe( + std::span defaultValue, + const PubSubOptions& options) { + return BooleanArraySubscriber{ + ::nt::Subscribe(m_handle, NT_BOOLEAN_ARRAY, "boolean[]", options), + defaultValue}; +} +inline BooleanArraySubscriber BooleanArrayTopic::SubscribeEx( + std::string_view typeString, std::span defaultValue, + const PubSubOptions& options) { + return BooleanArraySubscriber{ + ::nt::Subscribe(m_handle, NT_BOOLEAN_ARRAY, typeString, options), + defaultValue}; +} + +inline BooleanArrayPublisher BooleanArrayTopic::Publish( + const PubSubOptions& options) { + return BooleanArrayPublisher{ + ::nt::Publish(m_handle, NT_BOOLEAN_ARRAY, "boolean[]", options)}; +} + +inline BooleanArrayPublisher BooleanArrayTopic::PublishEx( + std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options) { + return BooleanArrayPublisher{ + ::nt::PublishEx(m_handle, NT_BOOLEAN_ARRAY, typeString, properties, options)}; +} + +inline BooleanArrayEntry BooleanArrayTopic::GetEntry( + std::span defaultValue, + const PubSubOptions& options) { + return BooleanArrayEntry{ + ::nt::GetEntry(m_handle, NT_BOOLEAN_ARRAY, "boolean[]", options), + defaultValue}; +} +inline BooleanArrayEntry BooleanArrayTopic::GetEntryEx( + std::string_view typeString, std::span defaultValue, + const PubSubOptions& options) { + return BooleanArrayEntry{ + ::nt::GetEntry(m_handle, NT_BOOLEAN_ARRAY, typeString, options), + defaultValue}; +} + +} // namespace nt diff --git a/ntcore/src/generated/main/native/include/networktables/BooleanTopic.h b/ntcore/src/generated/main/native/include/networktables/BooleanTopic.h new file mode 100644 index 00000000000..22db06b9e1d --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/BooleanTopic.h @@ -0,0 +1,373 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + + +#include +#include +#include + +#include + +#include "networktables/Topic.h" + +namespace wpi { +template +class SmallVectorImpl; +} // namespace wpi + +namespace nt { + +class BooleanTopic; + +/** + * NetworkTables Boolean subscriber. + */ +class BooleanSubscriber : public Subscriber { + public: + using TopicType = BooleanTopic; + using ValueType = bool; + using ParamType = bool; + using TimestampedValueType = TimestampedBoolean; + + + BooleanSubscriber() = default; + + /** + * Construct from a subscriber handle; recommended to use + * BooleanTopic::Subscribe() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + BooleanSubscriber(NT_Subscriber handle, ParamType defaultValue); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + ValueType Get() const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + ValueType Get(ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedValueType GetAtomic() const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueType GetAtomic(ParamType defaultValue) const; + + /** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + std::vector ReadQueue(); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + private: + ValueType m_defaultValue; +}; + +/** + * NetworkTables Boolean publisher. + */ +class BooleanPublisher : public Publisher { + public: + using TopicType = BooleanTopic; + using ValueType = bool; + using ParamType = bool; + + using TimestampedValueType = TimestampedBoolean; + + BooleanPublisher() = default; + + /** + * Construct from a publisher handle; recommended to use + * BooleanTopic::Publish() instead. + * + * @param handle Native handle + */ + explicit BooleanPublisher(NT_Publisher handle); + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void Set(ParamType value, int64_t time = 0); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void SetDefault(ParamType value); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; +}; + +/** + * NetworkTables Boolean entry. + * + * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. + */ +class BooleanEntry final : public BooleanSubscriber, + public BooleanPublisher { + public: + using SubscriberType = BooleanSubscriber; + using PublisherType = BooleanPublisher; + using TopicType = BooleanTopic; + using ValueType = bool; + using ParamType = bool; + + using TimestampedValueType = TimestampedBoolean; + + BooleanEntry() = default; + + /** + * Construct from an entry handle; recommended to use + * BooleanTopic::GetEntry() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + BooleanEntry(NT_Entry handle, ParamType defaultValue); + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + explicit operator bool() const { return m_subHandle != 0; } + + /** + * Gets the native handle for the entry. + * + * @return Native handle + */ + NT_Entry GetHandle() const { return m_subHandle; } + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + /** + * Stops publishing the entry if it's published. + */ + void Unpublish(); +}; + +/** + * NetworkTables Boolean topic. + */ +class BooleanTopic final : public Topic { + public: + using SubscriberType = BooleanSubscriber; + using PublisherType = BooleanPublisher; + using EntryType = BooleanEntry; + using ValueType = bool; + using ParamType = bool; + using TimestampedValueType = TimestampedBoolean; + /** The default type string for this topic type. */ + static constexpr std::string_view kTypeString = "boolean"; + + BooleanTopic() = default; + + /** + * Construct from a topic handle; recommended to use + * NetworkTableInstance::GetBooleanTopic() instead. + * + * @param handle Native handle + */ + explicit BooleanTopic(NT_Topic handle) : Topic{handle} {} + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + explicit BooleanTopic(Topic topic) : Topic{topic} {} + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType Subscribe( + ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new subscriber to the topic, with specific type string. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType SubscribeEx( + std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType Publish(const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic, with type string and initial + * properties. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType PublishEx(std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new entry for the topic. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntry(ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new entry for the topic, with specific type string. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntryEx(std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + +}; + +} // namespace nt + +#include "networktables/BooleanTopic.inc" diff --git a/ntcore/src/generated/main/native/include/networktables/BooleanTopic.inc b/ntcore/src/generated/main/native/include/networktables/BooleanTopic.inc new file mode 100644 index 00000000000..2a4d7e61ce4 --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/BooleanTopic.inc @@ -0,0 +1,121 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include "networktables/BooleanTopic.h" +#include "networktables/NetworkTableType.h" +#include "ntcore_cpp.h" + +namespace nt { + +inline BooleanSubscriber::BooleanSubscriber( + NT_Subscriber handle, bool defaultValue) + : Subscriber{handle}, + m_defaultValue{defaultValue} {} + +inline bool BooleanSubscriber::Get() const { + return Get(m_defaultValue); +} + +inline bool BooleanSubscriber::Get( + bool defaultValue) const { + return ::nt::GetBoolean(m_subHandle, defaultValue); +} + +inline TimestampedBoolean BooleanSubscriber::GetAtomic() const { + return GetAtomic(m_defaultValue); +} + +inline TimestampedBoolean BooleanSubscriber::GetAtomic( + bool defaultValue) const { + return ::nt::GetAtomicBoolean(m_subHandle, defaultValue); +} + +inline std::vector +BooleanSubscriber::ReadQueue() { + return ::nt::ReadQueueBoolean(m_subHandle); +} + +inline BooleanTopic BooleanSubscriber::GetTopic() const { + return BooleanTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline BooleanPublisher::BooleanPublisher(NT_Publisher handle) + : Publisher{handle} {} + +inline void BooleanPublisher::Set(bool value, + int64_t time) { + ::nt::SetBoolean(m_pubHandle, value, time); +} + +inline void BooleanPublisher::SetDefault(bool value) { + ::nt::SetDefaultBoolean(m_pubHandle, value); +} + +inline BooleanTopic BooleanPublisher::GetTopic() const { + return BooleanTopic{::nt::GetTopicFromHandle(m_pubHandle)}; +} + +inline BooleanEntry::BooleanEntry( + NT_Entry handle, bool defaultValue) + : BooleanSubscriber{handle, defaultValue}, + BooleanPublisher{handle} {} + +inline BooleanTopic BooleanEntry::GetTopic() const { + return BooleanTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline void BooleanEntry::Unpublish() { + ::nt::Unpublish(m_pubHandle); +} + +inline BooleanSubscriber BooleanTopic::Subscribe( + bool defaultValue, + const PubSubOptions& options) { + return BooleanSubscriber{ + ::nt::Subscribe(m_handle, NT_BOOLEAN, "boolean", options), + defaultValue}; +} +inline BooleanSubscriber BooleanTopic::SubscribeEx( + std::string_view typeString, bool defaultValue, + const PubSubOptions& options) { + return BooleanSubscriber{ + ::nt::Subscribe(m_handle, NT_BOOLEAN, typeString, options), + defaultValue}; +} + +inline BooleanPublisher BooleanTopic::Publish( + const PubSubOptions& options) { + return BooleanPublisher{ + ::nt::Publish(m_handle, NT_BOOLEAN, "boolean", options)}; +} + +inline BooleanPublisher BooleanTopic::PublishEx( + std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options) { + return BooleanPublisher{ + ::nt::PublishEx(m_handle, NT_BOOLEAN, typeString, properties, options)}; +} + +inline BooleanEntry BooleanTopic::GetEntry( + bool defaultValue, + const PubSubOptions& options) { + return BooleanEntry{ + ::nt::GetEntry(m_handle, NT_BOOLEAN, "boolean", options), + defaultValue}; +} +inline BooleanEntry BooleanTopic::GetEntryEx( + std::string_view typeString, bool defaultValue, + const PubSubOptions& options) { + return BooleanEntry{ + ::nt::GetEntry(m_handle, NT_BOOLEAN, typeString, options), + defaultValue}; +} + +} // namespace nt diff --git a/ntcore/src/generated/main/native/include/networktables/DoubleArrayTopic.h b/ntcore/src/generated/main/native/include/networktables/DoubleArrayTopic.h new file mode 100644 index 00000000000..6f64d367f2c --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/DoubleArrayTopic.h @@ -0,0 +1,426 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include +#include +#include +#include + +#include + +#include "networktables/Topic.h" + +namespace wpi { +template +class SmallVectorImpl; +} // namespace wpi + +namespace nt { + +class DoubleArrayTopic; + +/** + * NetworkTables DoubleArray subscriber. + */ +class DoubleArraySubscriber : public Subscriber { + public: + using TopicType = DoubleArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + using TimestampedValueType = TimestampedDoubleArray; + + using SmallRetType = std::span; + using SmallElemType = double; + using TimestampedValueViewType = TimestampedDoubleArrayView; + + + DoubleArraySubscriber() = default; + + /** + * Construct from a subscriber handle; recommended to use + * DoubleArrayTopic::Subscribe() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + DoubleArraySubscriber(NT_Subscriber handle, ParamType defaultValue); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + ValueType Get() const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + ValueType Get(ParamType defaultValue) const; + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @param buf storage for returned value + * @return value + */ + SmallRetType Get(wpi::SmallVectorImpl& buf) const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param buf storage for returned value + * @param defaultValue default value to return if no value has been published + * @return value + */ + SmallRetType Get(wpi::SmallVectorImpl& buf, ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedValueType GetAtomic() const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueType GetAtomic(ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @param buf storage for returned value + * @return timestamped value + */ + TimestampedValueViewType GetAtomic( + wpi::SmallVectorImpl& buf) const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param buf storage for returned value + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueViewType GetAtomic( + wpi::SmallVectorImpl& buf, + ParamType defaultValue) const; + + /** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + std::vector ReadQueue(); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + private: + ValueType m_defaultValue; +}; + +/** + * NetworkTables DoubleArray publisher. + */ +class DoubleArrayPublisher : public Publisher { + public: + using TopicType = DoubleArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + + using SmallRetType = std::span; + using SmallElemType = double; + + using TimestampedValueType = TimestampedDoubleArray; + + DoubleArrayPublisher() = default; + + /** + * Construct from a publisher handle; recommended to use + * DoubleArrayTopic::Publish() instead. + * + * @param handle Native handle + */ + explicit DoubleArrayPublisher(NT_Publisher handle); + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void Set(ParamType value, int64_t time = 0); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void SetDefault(ParamType value); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; +}; + +/** + * NetworkTables DoubleArray entry. + * + * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. + */ +class DoubleArrayEntry final : public DoubleArraySubscriber, + public DoubleArrayPublisher { + public: + using SubscriberType = DoubleArraySubscriber; + using PublisherType = DoubleArrayPublisher; + using TopicType = DoubleArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + + using SmallRetType = std::span; + using SmallElemType = double; + + using TimestampedValueType = TimestampedDoubleArray; + + DoubleArrayEntry() = default; + + /** + * Construct from an entry handle; recommended to use + * DoubleArrayTopic::GetEntry() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + DoubleArrayEntry(NT_Entry handle, ParamType defaultValue); + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + explicit operator bool() const { return m_subHandle != 0; } + + /** + * Gets the native handle for the entry. + * + * @return Native handle + */ + NT_Entry GetHandle() const { return m_subHandle; } + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + /** + * Stops publishing the entry if it's published. + */ + void Unpublish(); +}; + +/** + * NetworkTables DoubleArray topic. + */ +class DoubleArrayTopic final : public Topic { + public: + using SubscriberType = DoubleArraySubscriber; + using PublisherType = DoubleArrayPublisher; + using EntryType = DoubleArrayEntry; + using ValueType = std::vector; + using ParamType = std::span; + using TimestampedValueType = TimestampedDoubleArray; + /** The default type string for this topic type. */ + static constexpr std::string_view kTypeString = "double[]"; + + DoubleArrayTopic() = default; + + /** + * Construct from a topic handle; recommended to use + * NetworkTableInstance::GetDoubleArrayTopic() instead. + * + * @param handle Native handle + */ + explicit DoubleArrayTopic(NT_Topic handle) : Topic{handle} {} + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + explicit DoubleArrayTopic(Topic topic) : Topic{topic} {} + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType Subscribe( + ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new subscriber to the topic, with specific type string. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType SubscribeEx( + std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType Publish(const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic, with type string and initial + * properties. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType PublishEx(std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new entry for the topic. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntry(ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new entry for the topic, with specific type string. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntryEx(std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + +}; + +} // namespace nt + +#include "networktables/DoubleArrayTopic.inc" diff --git a/ntcore/src/generated/main/native/include/networktables/DoubleArrayTopic.inc b/ntcore/src/generated/main/native/include/networktables/DoubleArrayTopic.inc new file mode 100644 index 00000000000..bab8dd0080a --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/DoubleArrayTopic.inc @@ -0,0 +1,137 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include "networktables/DoubleArrayTopic.h" +#include "networktables/NetworkTableType.h" +#include "ntcore_cpp.h" + +namespace nt { + +inline DoubleArraySubscriber::DoubleArraySubscriber( + NT_Subscriber handle, std::span defaultValue) + : Subscriber{handle}, + m_defaultValue{defaultValue.begin(), defaultValue.end()} {} + +inline std::vector DoubleArraySubscriber::Get() const { + return Get(m_defaultValue); +} + +inline std::vector DoubleArraySubscriber::Get( + std::span defaultValue) const { + return ::nt::GetDoubleArray(m_subHandle, defaultValue); +} + +inline std::span DoubleArraySubscriber::Get(wpi::SmallVectorImpl& buf) const { + return Get(buf, m_defaultValue); +} + +inline std::span DoubleArraySubscriber::Get(wpi::SmallVectorImpl& buf, std::span defaultValue) const { + return nt::GetDoubleArray(m_subHandle, buf, defaultValue); +} + +inline TimestampedDoubleArray DoubleArraySubscriber::GetAtomic() const { + return GetAtomic(m_defaultValue); +} + +inline TimestampedDoubleArray DoubleArraySubscriber::GetAtomic( + std::span defaultValue) const { + return ::nt::GetAtomicDoubleArray(m_subHandle, defaultValue); +} + +inline TimestampedDoubleArrayView DoubleArraySubscriber::GetAtomic(wpi::SmallVectorImpl& buf) const { + return GetAtomic(buf, m_defaultValue); +} + +inline TimestampedDoubleArrayView DoubleArraySubscriber::GetAtomic(wpi::SmallVectorImpl& buf, std::span defaultValue) const { + return nt::GetAtomicDoubleArray(m_subHandle, buf, defaultValue); +} + +inline std::vector +DoubleArraySubscriber::ReadQueue() { + return ::nt::ReadQueueDoubleArray(m_subHandle); +} + +inline DoubleArrayTopic DoubleArraySubscriber::GetTopic() const { + return DoubleArrayTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline DoubleArrayPublisher::DoubleArrayPublisher(NT_Publisher handle) + : Publisher{handle} {} + +inline void DoubleArrayPublisher::Set(std::span value, + int64_t time) { + ::nt::SetDoubleArray(m_pubHandle, value, time); +} + +inline void DoubleArrayPublisher::SetDefault(std::span value) { + ::nt::SetDefaultDoubleArray(m_pubHandle, value); +} + +inline DoubleArrayTopic DoubleArrayPublisher::GetTopic() const { + return DoubleArrayTopic{::nt::GetTopicFromHandle(m_pubHandle)}; +} + +inline DoubleArrayEntry::DoubleArrayEntry( + NT_Entry handle, std::span defaultValue) + : DoubleArraySubscriber{handle, defaultValue}, + DoubleArrayPublisher{handle} {} + +inline DoubleArrayTopic DoubleArrayEntry::GetTopic() const { + return DoubleArrayTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline void DoubleArrayEntry::Unpublish() { + ::nt::Unpublish(m_pubHandle); +} + +inline DoubleArraySubscriber DoubleArrayTopic::Subscribe( + std::span defaultValue, + const PubSubOptions& options) { + return DoubleArraySubscriber{ + ::nt::Subscribe(m_handle, NT_DOUBLE_ARRAY, "double[]", options), + defaultValue}; +} +inline DoubleArraySubscriber DoubleArrayTopic::SubscribeEx( + std::string_view typeString, std::span defaultValue, + const PubSubOptions& options) { + return DoubleArraySubscriber{ + ::nt::Subscribe(m_handle, NT_DOUBLE_ARRAY, typeString, options), + defaultValue}; +} + +inline DoubleArrayPublisher DoubleArrayTopic::Publish( + const PubSubOptions& options) { + return DoubleArrayPublisher{ + ::nt::Publish(m_handle, NT_DOUBLE_ARRAY, "double[]", options)}; +} + +inline DoubleArrayPublisher DoubleArrayTopic::PublishEx( + std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options) { + return DoubleArrayPublisher{ + ::nt::PublishEx(m_handle, NT_DOUBLE_ARRAY, typeString, properties, options)}; +} + +inline DoubleArrayEntry DoubleArrayTopic::GetEntry( + std::span defaultValue, + const PubSubOptions& options) { + return DoubleArrayEntry{ + ::nt::GetEntry(m_handle, NT_DOUBLE_ARRAY, "double[]", options), + defaultValue}; +} +inline DoubleArrayEntry DoubleArrayTopic::GetEntryEx( + std::string_view typeString, std::span defaultValue, + const PubSubOptions& options) { + return DoubleArrayEntry{ + ::nt::GetEntry(m_handle, NT_DOUBLE_ARRAY, typeString, options), + defaultValue}; +} + +} // namespace nt diff --git a/ntcore/src/generated/main/native/include/networktables/DoubleTopic.h b/ntcore/src/generated/main/native/include/networktables/DoubleTopic.h new file mode 100644 index 00000000000..bcb1751b404 --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/DoubleTopic.h @@ -0,0 +1,373 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + + +#include +#include +#include + +#include + +#include "networktables/Topic.h" + +namespace wpi { +template +class SmallVectorImpl; +} // namespace wpi + +namespace nt { + +class DoubleTopic; + +/** + * NetworkTables Double subscriber. + */ +class DoubleSubscriber : public Subscriber { + public: + using TopicType = DoubleTopic; + using ValueType = double; + using ParamType = double; + using TimestampedValueType = TimestampedDouble; + + + DoubleSubscriber() = default; + + /** + * Construct from a subscriber handle; recommended to use + * DoubleTopic::Subscribe() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + DoubleSubscriber(NT_Subscriber handle, ParamType defaultValue); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + ValueType Get() const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + ValueType Get(ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedValueType GetAtomic() const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueType GetAtomic(ParamType defaultValue) const; + + /** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + std::vector ReadQueue(); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + private: + ValueType m_defaultValue; +}; + +/** + * NetworkTables Double publisher. + */ +class DoublePublisher : public Publisher { + public: + using TopicType = DoubleTopic; + using ValueType = double; + using ParamType = double; + + using TimestampedValueType = TimestampedDouble; + + DoublePublisher() = default; + + /** + * Construct from a publisher handle; recommended to use + * DoubleTopic::Publish() instead. + * + * @param handle Native handle + */ + explicit DoublePublisher(NT_Publisher handle); + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void Set(ParamType value, int64_t time = 0); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void SetDefault(ParamType value); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; +}; + +/** + * NetworkTables Double entry. + * + * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. + */ +class DoubleEntry final : public DoubleSubscriber, + public DoublePublisher { + public: + using SubscriberType = DoubleSubscriber; + using PublisherType = DoublePublisher; + using TopicType = DoubleTopic; + using ValueType = double; + using ParamType = double; + + using TimestampedValueType = TimestampedDouble; + + DoubleEntry() = default; + + /** + * Construct from an entry handle; recommended to use + * DoubleTopic::GetEntry() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + DoubleEntry(NT_Entry handle, ParamType defaultValue); + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + explicit operator bool() const { return m_subHandle != 0; } + + /** + * Gets the native handle for the entry. + * + * @return Native handle + */ + NT_Entry GetHandle() const { return m_subHandle; } + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + /** + * Stops publishing the entry if it's published. + */ + void Unpublish(); +}; + +/** + * NetworkTables Double topic. + */ +class DoubleTopic final : public Topic { + public: + using SubscriberType = DoubleSubscriber; + using PublisherType = DoublePublisher; + using EntryType = DoubleEntry; + using ValueType = double; + using ParamType = double; + using TimestampedValueType = TimestampedDouble; + /** The default type string for this topic type. */ + static constexpr std::string_view kTypeString = "double"; + + DoubleTopic() = default; + + /** + * Construct from a topic handle; recommended to use + * NetworkTableInstance::GetDoubleTopic() instead. + * + * @param handle Native handle + */ + explicit DoubleTopic(NT_Topic handle) : Topic{handle} {} + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + explicit DoubleTopic(Topic topic) : Topic{topic} {} + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType Subscribe( + ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new subscriber to the topic, with specific type string. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType SubscribeEx( + std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType Publish(const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic, with type string and initial + * properties. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType PublishEx(std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new entry for the topic. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntry(ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new entry for the topic, with specific type string. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntryEx(std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + +}; + +} // namespace nt + +#include "networktables/DoubleTopic.inc" diff --git a/ntcore/src/generated/main/native/include/networktables/DoubleTopic.inc b/ntcore/src/generated/main/native/include/networktables/DoubleTopic.inc new file mode 100644 index 00000000000..49b1c4c8b55 --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/DoubleTopic.inc @@ -0,0 +1,121 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include "networktables/DoubleTopic.h" +#include "networktables/NetworkTableType.h" +#include "ntcore_cpp.h" + +namespace nt { + +inline DoubleSubscriber::DoubleSubscriber( + NT_Subscriber handle, double defaultValue) + : Subscriber{handle}, + m_defaultValue{defaultValue} {} + +inline double DoubleSubscriber::Get() const { + return Get(m_defaultValue); +} + +inline double DoubleSubscriber::Get( + double defaultValue) const { + return ::nt::GetDouble(m_subHandle, defaultValue); +} + +inline TimestampedDouble DoubleSubscriber::GetAtomic() const { + return GetAtomic(m_defaultValue); +} + +inline TimestampedDouble DoubleSubscriber::GetAtomic( + double defaultValue) const { + return ::nt::GetAtomicDouble(m_subHandle, defaultValue); +} + +inline std::vector +DoubleSubscriber::ReadQueue() { + return ::nt::ReadQueueDouble(m_subHandle); +} + +inline DoubleTopic DoubleSubscriber::GetTopic() const { + return DoubleTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline DoublePublisher::DoublePublisher(NT_Publisher handle) + : Publisher{handle} {} + +inline void DoublePublisher::Set(double value, + int64_t time) { + ::nt::SetDouble(m_pubHandle, value, time); +} + +inline void DoublePublisher::SetDefault(double value) { + ::nt::SetDefaultDouble(m_pubHandle, value); +} + +inline DoubleTopic DoublePublisher::GetTopic() const { + return DoubleTopic{::nt::GetTopicFromHandle(m_pubHandle)}; +} + +inline DoubleEntry::DoubleEntry( + NT_Entry handle, double defaultValue) + : DoubleSubscriber{handle, defaultValue}, + DoublePublisher{handle} {} + +inline DoubleTopic DoubleEntry::GetTopic() const { + return DoubleTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline void DoubleEntry::Unpublish() { + ::nt::Unpublish(m_pubHandle); +} + +inline DoubleSubscriber DoubleTopic::Subscribe( + double defaultValue, + const PubSubOptions& options) { + return DoubleSubscriber{ + ::nt::Subscribe(m_handle, NT_DOUBLE, "double", options), + defaultValue}; +} +inline DoubleSubscriber DoubleTopic::SubscribeEx( + std::string_view typeString, double defaultValue, + const PubSubOptions& options) { + return DoubleSubscriber{ + ::nt::Subscribe(m_handle, NT_DOUBLE, typeString, options), + defaultValue}; +} + +inline DoublePublisher DoubleTopic::Publish( + const PubSubOptions& options) { + return DoublePublisher{ + ::nt::Publish(m_handle, NT_DOUBLE, "double", options)}; +} + +inline DoublePublisher DoubleTopic::PublishEx( + std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options) { + return DoublePublisher{ + ::nt::PublishEx(m_handle, NT_DOUBLE, typeString, properties, options)}; +} + +inline DoubleEntry DoubleTopic::GetEntry( + double defaultValue, + const PubSubOptions& options) { + return DoubleEntry{ + ::nt::GetEntry(m_handle, NT_DOUBLE, "double", options), + defaultValue}; +} +inline DoubleEntry DoubleTopic::GetEntryEx( + std::string_view typeString, double defaultValue, + const PubSubOptions& options) { + return DoubleEntry{ + ::nt::GetEntry(m_handle, NT_DOUBLE, typeString, options), + defaultValue}; +} + +} // namespace nt diff --git a/ntcore/src/generated/main/native/include/networktables/FloatArrayTopic.h b/ntcore/src/generated/main/native/include/networktables/FloatArrayTopic.h new file mode 100644 index 00000000000..a0d2b66b33e --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/FloatArrayTopic.h @@ -0,0 +1,426 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include +#include +#include +#include + +#include + +#include "networktables/Topic.h" + +namespace wpi { +template +class SmallVectorImpl; +} // namespace wpi + +namespace nt { + +class FloatArrayTopic; + +/** + * NetworkTables FloatArray subscriber. + */ +class FloatArraySubscriber : public Subscriber { + public: + using TopicType = FloatArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + using TimestampedValueType = TimestampedFloatArray; + + using SmallRetType = std::span; + using SmallElemType = float; + using TimestampedValueViewType = TimestampedFloatArrayView; + + + FloatArraySubscriber() = default; + + /** + * Construct from a subscriber handle; recommended to use + * FloatArrayTopic::Subscribe() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + FloatArraySubscriber(NT_Subscriber handle, ParamType defaultValue); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + ValueType Get() const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + ValueType Get(ParamType defaultValue) const; + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @param buf storage for returned value + * @return value + */ + SmallRetType Get(wpi::SmallVectorImpl& buf) const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param buf storage for returned value + * @param defaultValue default value to return if no value has been published + * @return value + */ + SmallRetType Get(wpi::SmallVectorImpl& buf, ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedValueType GetAtomic() const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueType GetAtomic(ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @param buf storage for returned value + * @return timestamped value + */ + TimestampedValueViewType GetAtomic( + wpi::SmallVectorImpl& buf) const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param buf storage for returned value + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueViewType GetAtomic( + wpi::SmallVectorImpl& buf, + ParamType defaultValue) const; + + /** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + std::vector ReadQueue(); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + private: + ValueType m_defaultValue; +}; + +/** + * NetworkTables FloatArray publisher. + */ +class FloatArrayPublisher : public Publisher { + public: + using TopicType = FloatArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + + using SmallRetType = std::span; + using SmallElemType = float; + + using TimestampedValueType = TimestampedFloatArray; + + FloatArrayPublisher() = default; + + /** + * Construct from a publisher handle; recommended to use + * FloatArrayTopic::Publish() instead. + * + * @param handle Native handle + */ + explicit FloatArrayPublisher(NT_Publisher handle); + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void Set(ParamType value, int64_t time = 0); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void SetDefault(ParamType value); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; +}; + +/** + * NetworkTables FloatArray entry. + * + * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. + */ +class FloatArrayEntry final : public FloatArraySubscriber, + public FloatArrayPublisher { + public: + using SubscriberType = FloatArraySubscriber; + using PublisherType = FloatArrayPublisher; + using TopicType = FloatArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + + using SmallRetType = std::span; + using SmallElemType = float; + + using TimestampedValueType = TimestampedFloatArray; + + FloatArrayEntry() = default; + + /** + * Construct from an entry handle; recommended to use + * FloatArrayTopic::GetEntry() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + FloatArrayEntry(NT_Entry handle, ParamType defaultValue); + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + explicit operator bool() const { return m_subHandle != 0; } + + /** + * Gets the native handle for the entry. + * + * @return Native handle + */ + NT_Entry GetHandle() const { return m_subHandle; } + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + /** + * Stops publishing the entry if it's published. + */ + void Unpublish(); +}; + +/** + * NetworkTables FloatArray topic. + */ +class FloatArrayTopic final : public Topic { + public: + using SubscriberType = FloatArraySubscriber; + using PublisherType = FloatArrayPublisher; + using EntryType = FloatArrayEntry; + using ValueType = std::vector; + using ParamType = std::span; + using TimestampedValueType = TimestampedFloatArray; + /** The default type string for this topic type. */ + static constexpr std::string_view kTypeString = "float[]"; + + FloatArrayTopic() = default; + + /** + * Construct from a topic handle; recommended to use + * NetworkTableInstance::GetFloatArrayTopic() instead. + * + * @param handle Native handle + */ + explicit FloatArrayTopic(NT_Topic handle) : Topic{handle} {} + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + explicit FloatArrayTopic(Topic topic) : Topic{topic} {} + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType Subscribe( + ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new subscriber to the topic, with specific type string. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType SubscribeEx( + std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType Publish(const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic, with type string and initial + * properties. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType PublishEx(std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new entry for the topic. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntry(ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new entry for the topic, with specific type string. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntryEx(std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + +}; + +} // namespace nt + +#include "networktables/FloatArrayTopic.inc" diff --git a/ntcore/src/generated/main/native/include/networktables/FloatArrayTopic.inc b/ntcore/src/generated/main/native/include/networktables/FloatArrayTopic.inc new file mode 100644 index 00000000000..93570765e12 --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/FloatArrayTopic.inc @@ -0,0 +1,137 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include "networktables/FloatArrayTopic.h" +#include "networktables/NetworkTableType.h" +#include "ntcore_cpp.h" + +namespace nt { + +inline FloatArraySubscriber::FloatArraySubscriber( + NT_Subscriber handle, std::span defaultValue) + : Subscriber{handle}, + m_defaultValue{defaultValue.begin(), defaultValue.end()} {} + +inline std::vector FloatArraySubscriber::Get() const { + return Get(m_defaultValue); +} + +inline std::vector FloatArraySubscriber::Get( + std::span defaultValue) const { + return ::nt::GetFloatArray(m_subHandle, defaultValue); +} + +inline std::span FloatArraySubscriber::Get(wpi::SmallVectorImpl& buf) const { + return Get(buf, m_defaultValue); +} + +inline std::span FloatArraySubscriber::Get(wpi::SmallVectorImpl& buf, std::span defaultValue) const { + return nt::GetFloatArray(m_subHandle, buf, defaultValue); +} + +inline TimestampedFloatArray FloatArraySubscriber::GetAtomic() const { + return GetAtomic(m_defaultValue); +} + +inline TimestampedFloatArray FloatArraySubscriber::GetAtomic( + std::span defaultValue) const { + return ::nt::GetAtomicFloatArray(m_subHandle, defaultValue); +} + +inline TimestampedFloatArrayView FloatArraySubscriber::GetAtomic(wpi::SmallVectorImpl& buf) const { + return GetAtomic(buf, m_defaultValue); +} + +inline TimestampedFloatArrayView FloatArraySubscriber::GetAtomic(wpi::SmallVectorImpl& buf, std::span defaultValue) const { + return nt::GetAtomicFloatArray(m_subHandle, buf, defaultValue); +} + +inline std::vector +FloatArraySubscriber::ReadQueue() { + return ::nt::ReadQueueFloatArray(m_subHandle); +} + +inline FloatArrayTopic FloatArraySubscriber::GetTopic() const { + return FloatArrayTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline FloatArrayPublisher::FloatArrayPublisher(NT_Publisher handle) + : Publisher{handle} {} + +inline void FloatArrayPublisher::Set(std::span value, + int64_t time) { + ::nt::SetFloatArray(m_pubHandle, value, time); +} + +inline void FloatArrayPublisher::SetDefault(std::span value) { + ::nt::SetDefaultFloatArray(m_pubHandle, value); +} + +inline FloatArrayTopic FloatArrayPublisher::GetTopic() const { + return FloatArrayTopic{::nt::GetTopicFromHandle(m_pubHandle)}; +} + +inline FloatArrayEntry::FloatArrayEntry( + NT_Entry handle, std::span defaultValue) + : FloatArraySubscriber{handle, defaultValue}, + FloatArrayPublisher{handle} {} + +inline FloatArrayTopic FloatArrayEntry::GetTopic() const { + return FloatArrayTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline void FloatArrayEntry::Unpublish() { + ::nt::Unpublish(m_pubHandle); +} + +inline FloatArraySubscriber FloatArrayTopic::Subscribe( + std::span defaultValue, + const PubSubOptions& options) { + return FloatArraySubscriber{ + ::nt::Subscribe(m_handle, NT_FLOAT_ARRAY, "float[]", options), + defaultValue}; +} +inline FloatArraySubscriber FloatArrayTopic::SubscribeEx( + std::string_view typeString, std::span defaultValue, + const PubSubOptions& options) { + return FloatArraySubscriber{ + ::nt::Subscribe(m_handle, NT_FLOAT_ARRAY, typeString, options), + defaultValue}; +} + +inline FloatArrayPublisher FloatArrayTopic::Publish( + const PubSubOptions& options) { + return FloatArrayPublisher{ + ::nt::Publish(m_handle, NT_FLOAT_ARRAY, "float[]", options)}; +} + +inline FloatArrayPublisher FloatArrayTopic::PublishEx( + std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options) { + return FloatArrayPublisher{ + ::nt::PublishEx(m_handle, NT_FLOAT_ARRAY, typeString, properties, options)}; +} + +inline FloatArrayEntry FloatArrayTopic::GetEntry( + std::span defaultValue, + const PubSubOptions& options) { + return FloatArrayEntry{ + ::nt::GetEntry(m_handle, NT_FLOAT_ARRAY, "float[]", options), + defaultValue}; +} +inline FloatArrayEntry FloatArrayTopic::GetEntryEx( + std::string_view typeString, std::span defaultValue, + const PubSubOptions& options) { + return FloatArrayEntry{ + ::nt::GetEntry(m_handle, NT_FLOAT_ARRAY, typeString, options), + defaultValue}; +} + +} // namespace nt diff --git a/ntcore/src/generated/main/native/include/networktables/FloatTopic.h b/ntcore/src/generated/main/native/include/networktables/FloatTopic.h new file mode 100644 index 00000000000..9a838348765 --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/FloatTopic.h @@ -0,0 +1,373 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + + +#include +#include +#include + +#include + +#include "networktables/Topic.h" + +namespace wpi { +template +class SmallVectorImpl; +} // namespace wpi + +namespace nt { + +class FloatTopic; + +/** + * NetworkTables Float subscriber. + */ +class FloatSubscriber : public Subscriber { + public: + using TopicType = FloatTopic; + using ValueType = float; + using ParamType = float; + using TimestampedValueType = TimestampedFloat; + + + FloatSubscriber() = default; + + /** + * Construct from a subscriber handle; recommended to use + * FloatTopic::Subscribe() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + FloatSubscriber(NT_Subscriber handle, ParamType defaultValue); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + ValueType Get() const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + ValueType Get(ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedValueType GetAtomic() const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueType GetAtomic(ParamType defaultValue) const; + + /** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + std::vector ReadQueue(); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + private: + ValueType m_defaultValue; +}; + +/** + * NetworkTables Float publisher. + */ +class FloatPublisher : public Publisher { + public: + using TopicType = FloatTopic; + using ValueType = float; + using ParamType = float; + + using TimestampedValueType = TimestampedFloat; + + FloatPublisher() = default; + + /** + * Construct from a publisher handle; recommended to use + * FloatTopic::Publish() instead. + * + * @param handle Native handle + */ + explicit FloatPublisher(NT_Publisher handle); + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void Set(ParamType value, int64_t time = 0); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void SetDefault(ParamType value); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; +}; + +/** + * NetworkTables Float entry. + * + * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. + */ +class FloatEntry final : public FloatSubscriber, + public FloatPublisher { + public: + using SubscriberType = FloatSubscriber; + using PublisherType = FloatPublisher; + using TopicType = FloatTopic; + using ValueType = float; + using ParamType = float; + + using TimestampedValueType = TimestampedFloat; + + FloatEntry() = default; + + /** + * Construct from an entry handle; recommended to use + * FloatTopic::GetEntry() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + FloatEntry(NT_Entry handle, ParamType defaultValue); + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + explicit operator bool() const { return m_subHandle != 0; } + + /** + * Gets the native handle for the entry. + * + * @return Native handle + */ + NT_Entry GetHandle() const { return m_subHandle; } + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + /** + * Stops publishing the entry if it's published. + */ + void Unpublish(); +}; + +/** + * NetworkTables Float topic. + */ +class FloatTopic final : public Topic { + public: + using SubscriberType = FloatSubscriber; + using PublisherType = FloatPublisher; + using EntryType = FloatEntry; + using ValueType = float; + using ParamType = float; + using TimestampedValueType = TimestampedFloat; + /** The default type string for this topic type. */ + static constexpr std::string_view kTypeString = "float"; + + FloatTopic() = default; + + /** + * Construct from a topic handle; recommended to use + * NetworkTableInstance::GetFloatTopic() instead. + * + * @param handle Native handle + */ + explicit FloatTopic(NT_Topic handle) : Topic{handle} {} + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + explicit FloatTopic(Topic topic) : Topic{topic} {} + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType Subscribe( + ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new subscriber to the topic, with specific type string. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType SubscribeEx( + std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType Publish(const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic, with type string and initial + * properties. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType PublishEx(std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new entry for the topic. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntry(ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new entry for the topic, with specific type string. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntryEx(std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + +}; + +} // namespace nt + +#include "networktables/FloatTopic.inc" diff --git a/ntcore/src/generated/main/native/include/networktables/FloatTopic.inc b/ntcore/src/generated/main/native/include/networktables/FloatTopic.inc new file mode 100644 index 00000000000..9df0f793ed2 --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/FloatTopic.inc @@ -0,0 +1,121 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include "networktables/FloatTopic.h" +#include "networktables/NetworkTableType.h" +#include "ntcore_cpp.h" + +namespace nt { + +inline FloatSubscriber::FloatSubscriber( + NT_Subscriber handle, float defaultValue) + : Subscriber{handle}, + m_defaultValue{defaultValue} {} + +inline float FloatSubscriber::Get() const { + return Get(m_defaultValue); +} + +inline float FloatSubscriber::Get( + float defaultValue) const { + return ::nt::GetFloat(m_subHandle, defaultValue); +} + +inline TimestampedFloat FloatSubscriber::GetAtomic() const { + return GetAtomic(m_defaultValue); +} + +inline TimestampedFloat FloatSubscriber::GetAtomic( + float defaultValue) const { + return ::nt::GetAtomicFloat(m_subHandle, defaultValue); +} + +inline std::vector +FloatSubscriber::ReadQueue() { + return ::nt::ReadQueueFloat(m_subHandle); +} + +inline FloatTopic FloatSubscriber::GetTopic() const { + return FloatTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline FloatPublisher::FloatPublisher(NT_Publisher handle) + : Publisher{handle} {} + +inline void FloatPublisher::Set(float value, + int64_t time) { + ::nt::SetFloat(m_pubHandle, value, time); +} + +inline void FloatPublisher::SetDefault(float value) { + ::nt::SetDefaultFloat(m_pubHandle, value); +} + +inline FloatTopic FloatPublisher::GetTopic() const { + return FloatTopic{::nt::GetTopicFromHandle(m_pubHandle)}; +} + +inline FloatEntry::FloatEntry( + NT_Entry handle, float defaultValue) + : FloatSubscriber{handle, defaultValue}, + FloatPublisher{handle} {} + +inline FloatTopic FloatEntry::GetTopic() const { + return FloatTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline void FloatEntry::Unpublish() { + ::nt::Unpublish(m_pubHandle); +} + +inline FloatSubscriber FloatTopic::Subscribe( + float defaultValue, + const PubSubOptions& options) { + return FloatSubscriber{ + ::nt::Subscribe(m_handle, NT_FLOAT, "float", options), + defaultValue}; +} +inline FloatSubscriber FloatTopic::SubscribeEx( + std::string_view typeString, float defaultValue, + const PubSubOptions& options) { + return FloatSubscriber{ + ::nt::Subscribe(m_handle, NT_FLOAT, typeString, options), + defaultValue}; +} + +inline FloatPublisher FloatTopic::Publish( + const PubSubOptions& options) { + return FloatPublisher{ + ::nt::Publish(m_handle, NT_FLOAT, "float", options)}; +} + +inline FloatPublisher FloatTopic::PublishEx( + std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options) { + return FloatPublisher{ + ::nt::PublishEx(m_handle, NT_FLOAT, typeString, properties, options)}; +} + +inline FloatEntry FloatTopic::GetEntry( + float defaultValue, + const PubSubOptions& options) { + return FloatEntry{ + ::nt::GetEntry(m_handle, NT_FLOAT, "float", options), + defaultValue}; +} +inline FloatEntry FloatTopic::GetEntryEx( + std::string_view typeString, float defaultValue, + const PubSubOptions& options) { + return FloatEntry{ + ::nt::GetEntry(m_handle, NT_FLOAT, typeString, options), + defaultValue}; +} + +} // namespace nt diff --git a/ntcore/src/generated/main/native/include/networktables/IntegerArrayTopic.h b/ntcore/src/generated/main/native/include/networktables/IntegerArrayTopic.h new file mode 100644 index 00000000000..a99823acd8c --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/IntegerArrayTopic.h @@ -0,0 +1,426 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include +#include +#include +#include + +#include + +#include "networktables/Topic.h" + +namespace wpi { +template +class SmallVectorImpl; +} // namespace wpi + +namespace nt { + +class IntegerArrayTopic; + +/** + * NetworkTables IntegerArray subscriber. + */ +class IntegerArraySubscriber : public Subscriber { + public: + using TopicType = IntegerArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + using TimestampedValueType = TimestampedIntegerArray; + + using SmallRetType = std::span; + using SmallElemType = int64_t; + using TimestampedValueViewType = TimestampedIntegerArrayView; + + + IntegerArraySubscriber() = default; + + /** + * Construct from a subscriber handle; recommended to use + * IntegerArrayTopic::Subscribe() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + IntegerArraySubscriber(NT_Subscriber handle, ParamType defaultValue); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + ValueType Get() const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + ValueType Get(ParamType defaultValue) const; + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @param buf storage for returned value + * @return value + */ + SmallRetType Get(wpi::SmallVectorImpl& buf) const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param buf storage for returned value + * @param defaultValue default value to return if no value has been published + * @return value + */ + SmallRetType Get(wpi::SmallVectorImpl& buf, ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedValueType GetAtomic() const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueType GetAtomic(ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @param buf storage for returned value + * @return timestamped value + */ + TimestampedValueViewType GetAtomic( + wpi::SmallVectorImpl& buf) const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param buf storage for returned value + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueViewType GetAtomic( + wpi::SmallVectorImpl& buf, + ParamType defaultValue) const; + + /** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + std::vector ReadQueue(); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + private: + ValueType m_defaultValue; +}; + +/** + * NetworkTables IntegerArray publisher. + */ +class IntegerArrayPublisher : public Publisher { + public: + using TopicType = IntegerArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + + using SmallRetType = std::span; + using SmallElemType = int64_t; + + using TimestampedValueType = TimestampedIntegerArray; + + IntegerArrayPublisher() = default; + + /** + * Construct from a publisher handle; recommended to use + * IntegerArrayTopic::Publish() instead. + * + * @param handle Native handle + */ + explicit IntegerArrayPublisher(NT_Publisher handle); + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void Set(ParamType value, int64_t time = 0); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void SetDefault(ParamType value); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; +}; + +/** + * NetworkTables IntegerArray entry. + * + * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. + */ +class IntegerArrayEntry final : public IntegerArraySubscriber, + public IntegerArrayPublisher { + public: + using SubscriberType = IntegerArraySubscriber; + using PublisherType = IntegerArrayPublisher; + using TopicType = IntegerArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + + using SmallRetType = std::span; + using SmallElemType = int64_t; + + using TimestampedValueType = TimestampedIntegerArray; + + IntegerArrayEntry() = default; + + /** + * Construct from an entry handle; recommended to use + * IntegerArrayTopic::GetEntry() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + IntegerArrayEntry(NT_Entry handle, ParamType defaultValue); + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + explicit operator bool() const { return m_subHandle != 0; } + + /** + * Gets the native handle for the entry. + * + * @return Native handle + */ + NT_Entry GetHandle() const { return m_subHandle; } + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + /** + * Stops publishing the entry if it's published. + */ + void Unpublish(); +}; + +/** + * NetworkTables IntegerArray topic. + */ +class IntegerArrayTopic final : public Topic { + public: + using SubscriberType = IntegerArraySubscriber; + using PublisherType = IntegerArrayPublisher; + using EntryType = IntegerArrayEntry; + using ValueType = std::vector; + using ParamType = std::span; + using TimestampedValueType = TimestampedIntegerArray; + /** The default type string for this topic type. */ + static constexpr std::string_view kTypeString = "int[]"; + + IntegerArrayTopic() = default; + + /** + * Construct from a topic handle; recommended to use + * NetworkTableInstance::GetIntegerArrayTopic() instead. + * + * @param handle Native handle + */ + explicit IntegerArrayTopic(NT_Topic handle) : Topic{handle} {} + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + explicit IntegerArrayTopic(Topic topic) : Topic{topic} {} + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType Subscribe( + ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new subscriber to the topic, with specific type string. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType SubscribeEx( + std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType Publish(const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic, with type string and initial + * properties. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType PublishEx(std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new entry for the topic. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntry(ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new entry for the topic, with specific type string. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntryEx(std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + +}; + +} // namespace nt + +#include "networktables/IntegerArrayTopic.inc" diff --git a/ntcore/src/generated/main/native/include/networktables/IntegerArrayTopic.inc b/ntcore/src/generated/main/native/include/networktables/IntegerArrayTopic.inc new file mode 100644 index 00000000000..ba3d00d1d25 --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/IntegerArrayTopic.inc @@ -0,0 +1,137 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include "networktables/IntegerArrayTopic.h" +#include "networktables/NetworkTableType.h" +#include "ntcore_cpp.h" + +namespace nt { + +inline IntegerArraySubscriber::IntegerArraySubscriber( + NT_Subscriber handle, std::span defaultValue) + : Subscriber{handle}, + m_defaultValue{defaultValue.begin(), defaultValue.end()} {} + +inline std::vector IntegerArraySubscriber::Get() const { + return Get(m_defaultValue); +} + +inline std::vector IntegerArraySubscriber::Get( + std::span defaultValue) const { + return ::nt::GetIntegerArray(m_subHandle, defaultValue); +} + +inline std::span IntegerArraySubscriber::Get(wpi::SmallVectorImpl& buf) const { + return Get(buf, m_defaultValue); +} + +inline std::span IntegerArraySubscriber::Get(wpi::SmallVectorImpl& buf, std::span defaultValue) const { + return nt::GetIntegerArray(m_subHandle, buf, defaultValue); +} + +inline TimestampedIntegerArray IntegerArraySubscriber::GetAtomic() const { + return GetAtomic(m_defaultValue); +} + +inline TimestampedIntegerArray IntegerArraySubscriber::GetAtomic( + std::span defaultValue) const { + return ::nt::GetAtomicIntegerArray(m_subHandle, defaultValue); +} + +inline TimestampedIntegerArrayView IntegerArraySubscriber::GetAtomic(wpi::SmallVectorImpl& buf) const { + return GetAtomic(buf, m_defaultValue); +} + +inline TimestampedIntegerArrayView IntegerArraySubscriber::GetAtomic(wpi::SmallVectorImpl& buf, std::span defaultValue) const { + return nt::GetAtomicIntegerArray(m_subHandle, buf, defaultValue); +} + +inline std::vector +IntegerArraySubscriber::ReadQueue() { + return ::nt::ReadQueueIntegerArray(m_subHandle); +} + +inline IntegerArrayTopic IntegerArraySubscriber::GetTopic() const { + return IntegerArrayTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline IntegerArrayPublisher::IntegerArrayPublisher(NT_Publisher handle) + : Publisher{handle} {} + +inline void IntegerArrayPublisher::Set(std::span value, + int64_t time) { + ::nt::SetIntegerArray(m_pubHandle, value, time); +} + +inline void IntegerArrayPublisher::SetDefault(std::span value) { + ::nt::SetDefaultIntegerArray(m_pubHandle, value); +} + +inline IntegerArrayTopic IntegerArrayPublisher::GetTopic() const { + return IntegerArrayTopic{::nt::GetTopicFromHandle(m_pubHandle)}; +} + +inline IntegerArrayEntry::IntegerArrayEntry( + NT_Entry handle, std::span defaultValue) + : IntegerArraySubscriber{handle, defaultValue}, + IntegerArrayPublisher{handle} {} + +inline IntegerArrayTopic IntegerArrayEntry::GetTopic() const { + return IntegerArrayTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline void IntegerArrayEntry::Unpublish() { + ::nt::Unpublish(m_pubHandle); +} + +inline IntegerArraySubscriber IntegerArrayTopic::Subscribe( + std::span defaultValue, + const PubSubOptions& options) { + return IntegerArraySubscriber{ + ::nt::Subscribe(m_handle, NT_INTEGER_ARRAY, "int[]", options), + defaultValue}; +} +inline IntegerArraySubscriber IntegerArrayTopic::SubscribeEx( + std::string_view typeString, std::span defaultValue, + const PubSubOptions& options) { + return IntegerArraySubscriber{ + ::nt::Subscribe(m_handle, NT_INTEGER_ARRAY, typeString, options), + defaultValue}; +} + +inline IntegerArrayPublisher IntegerArrayTopic::Publish( + const PubSubOptions& options) { + return IntegerArrayPublisher{ + ::nt::Publish(m_handle, NT_INTEGER_ARRAY, "int[]", options)}; +} + +inline IntegerArrayPublisher IntegerArrayTopic::PublishEx( + std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options) { + return IntegerArrayPublisher{ + ::nt::PublishEx(m_handle, NT_INTEGER_ARRAY, typeString, properties, options)}; +} + +inline IntegerArrayEntry IntegerArrayTopic::GetEntry( + std::span defaultValue, + const PubSubOptions& options) { + return IntegerArrayEntry{ + ::nt::GetEntry(m_handle, NT_INTEGER_ARRAY, "int[]", options), + defaultValue}; +} +inline IntegerArrayEntry IntegerArrayTopic::GetEntryEx( + std::string_view typeString, std::span defaultValue, + const PubSubOptions& options) { + return IntegerArrayEntry{ + ::nt::GetEntry(m_handle, NT_INTEGER_ARRAY, typeString, options), + defaultValue}; +} + +} // namespace nt diff --git a/ntcore/src/generated/main/native/include/networktables/IntegerTopic.h b/ntcore/src/generated/main/native/include/networktables/IntegerTopic.h new file mode 100644 index 00000000000..0d5ab21492c --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/IntegerTopic.h @@ -0,0 +1,373 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + + +#include +#include +#include + +#include + +#include "networktables/Topic.h" + +namespace wpi { +template +class SmallVectorImpl; +} // namespace wpi + +namespace nt { + +class IntegerTopic; + +/** + * NetworkTables Integer subscriber. + */ +class IntegerSubscriber : public Subscriber { + public: + using TopicType = IntegerTopic; + using ValueType = int64_t; + using ParamType = int64_t; + using TimestampedValueType = TimestampedInteger; + + + IntegerSubscriber() = default; + + /** + * Construct from a subscriber handle; recommended to use + * IntegerTopic::Subscribe() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + IntegerSubscriber(NT_Subscriber handle, ParamType defaultValue); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + ValueType Get() const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + ValueType Get(ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedValueType GetAtomic() const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueType GetAtomic(ParamType defaultValue) const; + + /** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + std::vector ReadQueue(); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + private: + ValueType m_defaultValue; +}; + +/** + * NetworkTables Integer publisher. + */ +class IntegerPublisher : public Publisher { + public: + using TopicType = IntegerTopic; + using ValueType = int64_t; + using ParamType = int64_t; + + using TimestampedValueType = TimestampedInteger; + + IntegerPublisher() = default; + + /** + * Construct from a publisher handle; recommended to use + * IntegerTopic::Publish() instead. + * + * @param handle Native handle + */ + explicit IntegerPublisher(NT_Publisher handle); + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void Set(ParamType value, int64_t time = 0); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void SetDefault(ParamType value); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; +}; + +/** + * NetworkTables Integer entry. + * + * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. + */ +class IntegerEntry final : public IntegerSubscriber, + public IntegerPublisher { + public: + using SubscriberType = IntegerSubscriber; + using PublisherType = IntegerPublisher; + using TopicType = IntegerTopic; + using ValueType = int64_t; + using ParamType = int64_t; + + using TimestampedValueType = TimestampedInteger; + + IntegerEntry() = default; + + /** + * Construct from an entry handle; recommended to use + * IntegerTopic::GetEntry() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + IntegerEntry(NT_Entry handle, ParamType defaultValue); + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + explicit operator bool() const { return m_subHandle != 0; } + + /** + * Gets the native handle for the entry. + * + * @return Native handle + */ + NT_Entry GetHandle() const { return m_subHandle; } + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + /** + * Stops publishing the entry if it's published. + */ + void Unpublish(); +}; + +/** + * NetworkTables Integer topic. + */ +class IntegerTopic final : public Topic { + public: + using SubscriberType = IntegerSubscriber; + using PublisherType = IntegerPublisher; + using EntryType = IntegerEntry; + using ValueType = int64_t; + using ParamType = int64_t; + using TimestampedValueType = TimestampedInteger; + /** The default type string for this topic type. */ + static constexpr std::string_view kTypeString = "int"; + + IntegerTopic() = default; + + /** + * Construct from a topic handle; recommended to use + * NetworkTableInstance::GetIntegerTopic() instead. + * + * @param handle Native handle + */ + explicit IntegerTopic(NT_Topic handle) : Topic{handle} {} + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + explicit IntegerTopic(Topic topic) : Topic{topic} {} + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType Subscribe( + ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new subscriber to the topic, with specific type string. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType SubscribeEx( + std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType Publish(const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic, with type string and initial + * properties. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType PublishEx(std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new entry for the topic. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntry(ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new entry for the topic, with specific type string. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntryEx(std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + +}; + +} // namespace nt + +#include "networktables/IntegerTopic.inc" diff --git a/ntcore/src/generated/main/native/include/networktables/IntegerTopic.inc b/ntcore/src/generated/main/native/include/networktables/IntegerTopic.inc new file mode 100644 index 00000000000..2ca31e53e17 --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/IntegerTopic.inc @@ -0,0 +1,121 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include "networktables/IntegerTopic.h" +#include "networktables/NetworkTableType.h" +#include "ntcore_cpp.h" + +namespace nt { + +inline IntegerSubscriber::IntegerSubscriber( + NT_Subscriber handle, int64_t defaultValue) + : Subscriber{handle}, + m_defaultValue{defaultValue} {} + +inline int64_t IntegerSubscriber::Get() const { + return Get(m_defaultValue); +} + +inline int64_t IntegerSubscriber::Get( + int64_t defaultValue) const { + return ::nt::GetInteger(m_subHandle, defaultValue); +} + +inline TimestampedInteger IntegerSubscriber::GetAtomic() const { + return GetAtomic(m_defaultValue); +} + +inline TimestampedInteger IntegerSubscriber::GetAtomic( + int64_t defaultValue) const { + return ::nt::GetAtomicInteger(m_subHandle, defaultValue); +} + +inline std::vector +IntegerSubscriber::ReadQueue() { + return ::nt::ReadQueueInteger(m_subHandle); +} + +inline IntegerTopic IntegerSubscriber::GetTopic() const { + return IntegerTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline IntegerPublisher::IntegerPublisher(NT_Publisher handle) + : Publisher{handle} {} + +inline void IntegerPublisher::Set(int64_t value, + int64_t time) { + ::nt::SetInteger(m_pubHandle, value, time); +} + +inline void IntegerPublisher::SetDefault(int64_t value) { + ::nt::SetDefaultInteger(m_pubHandle, value); +} + +inline IntegerTopic IntegerPublisher::GetTopic() const { + return IntegerTopic{::nt::GetTopicFromHandle(m_pubHandle)}; +} + +inline IntegerEntry::IntegerEntry( + NT_Entry handle, int64_t defaultValue) + : IntegerSubscriber{handle, defaultValue}, + IntegerPublisher{handle} {} + +inline IntegerTopic IntegerEntry::GetTopic() const { + return IntegerTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline void IntegerEntry::Unpublish() { + ::nt::Unpublish(m_pubHandle); +} + +inline IntegerSubscriber IntegerTopic::Subscribe( + int64_t defaultValue, + const PubSubOptions& options) { + return IntegerSubscriber{ + ::nt::Subscribe(m_handle, NT_INTEGER, "int", options), + defaultValue}; +} +inline IntegerSubscriber IntegerTopic::SubscribeEx( + std::string_view typeString, int64_t defaultValue, + const PubSubOptions& options) { + return IntegerSubscriber{ + ::nt::Subscribe(m_handle, NT_INTEGER, typeString, options), + defaultValue}; +} + +inline IntegerPublisher IntegerTopic::Publish( + const PubSubOptions& options) { + return IntegerPublisher{ + ::nt::Publish(m_handle, NT_INTEGER, "int", options)}; +} + +inline IntegerPublisher IntegerTopic::PublishEx( + std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options) { + return IntegerPublisher{ + ::nt::PublishEx(m_handle, NT_INTEGER, typeString, properties, options)}; +} + +inline IntegerEntry IntegerTopic::GetEntry( + int64_t defaultValue, + const PubSubOptions& options) { + return IntegerEntry{ + ::nt::GetEntry(m_handle, NT_INTEGER, "int", options), + defaultValue}; +} +inline IntegerEntry IntegerTopic::GetEntryEx( + std::string_view typeString, int64_t defaultValue, + const PubSubOptions& options) { + return IntegerEntry{ + ::nt::GetEntry(m_handle, NT_INTEGER, typeString, options), + defaultValue}; +} + +} // namespace nt diff --git a/ntcore/src/generated/main/native/include/networktables/RawTopic.h b/ntcore/src/generated/main/native/include/networktables/RawTopic.h new file mode 100644 index 00000000000..e124fe1db68 --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/RawTopic.h @@ -0,0 +1,384 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include +#include +#include +#include + +#include + +#include "networktables/Topic.h" + +namespace wpi { +template +class SmallVectorImpl; +} // namespace wpi + +namespace nt { + +class RawTopic; + +/** + * NetworkTables Raw subscriber. + */ +class RawSubscriber : public Subscriber { + public: + using TopicType = RawTopic; + using ValueType = std::vector; + using ParamType = std::span; + using TimestampedValueType = TimestampedRaw; + + using SmallRetType = std::span; + using SmallElemType = uint8_t; + using TimestampedValueViewType = TimestampedRawView; + + + RawSubscriber() = default; + + /** + * Construct from a subscriber handle; recommended to use + * RawTopic::Subscribe() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + RawSubscriber(NT_Subscriber handle, ParamType defaultValue); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + ValueType Get() const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + ValueType Get(ParamType defaultValue) const; + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @param buf storage for returned value + * @return value + */ + SmallRetType Get(wpi::SmallVectorImpl& buf) const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param buf storage for returned value + * @param defaultValue default value to return if no value has been published + * @return value + */ + SmallRetType Get(wpi::SmallVectorImpl& buf, ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedValueType GetAtomic() const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueType GetAtomic(ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @param buf storage for returned value + * @return timestamped value + */ + TimestampedValueViewType GetAtomic( + wpi::SmallVectorImpl& buf) const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param buf storage for returned value + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueViewType GetAtomic( + wpi::SmallVectorImpl& buf, + ParamType defaultValue) const; + + /** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + std::vector ReadQueue(); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + private: + ValueType m_defaultValue; +}; + +/** + * NetworkTables Raw publisher. + */ +class RawPublisher : public Publisher { + public: + using TopicType = RawTopic; + using ValueType = std::vector; + using ParamType = std::span; + + using SmallRetType = std::span; + using SmallElemType = uint8_t; + + using TimestampedValueType = TimestampedRaw; + + RawPublisher() = default; + + /** + * Construct from a publisher handle; recommended to use + * RawTopic::Publish() instead. + * + * @param handle Native handle + */ + explicit RawPublisher(NT_Publisher handle); + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void Set(ParamType value, int64_t time = 0); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void SetDefault(ParamType value); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; +}; + +/** + * NetworkTables Raw entry. + * + * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. + */ +class RawEntry final : public RawSubscriber, + public RawPublisher { + public: + using SubscriberType = RawSubscriber; + using PublisherType = RawPublisher; + using TopicType = RawTopic; + using ValueType = std::vector; + using ParamType = std::span; + + using SmallRetType = std::span; + using SmallElemType = uint8_t; + + using TimestampedValueType = TimestampedRaw; + + RawEntry() = default; + + /** + * Construct from an entry handle; recommended to use + * RawTopic::GetEntry() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + RawEntry(NT_Entry handle, ParamType defaultValue); + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + explicit operator bool() const { return m_subHandle != 0; } + + /** + * Gets the native handle for the entry. + * + * @return Native handle + */ + NT_Entry GetHandle() const { return m_subHandle; } + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + /** + * Stops publishing the entry if it's published. + */ + void Unpublish(); +}; + +/** + * NetworkTables Raw topic. + */ +class RawTopic final : public Topic { + public: + using SubscriberType = RawSubscriber; + using PublisherType = RawPublisher; + using EntryType = RawEntry; + using ValueType = std::vector; + using ParamType = std::span; + using TimestampedValueType = TimestampedRaw; + + RawTopic() = default; + + /** + * Construct from a topic handle; recommended to use + * NetworkTableInstance::GetRawTopic() instead. + * + * @param handle Native handle + */ + explicit RawTopic(NT_Topic handle) : Topic{handle} {} + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + explicit RawTopic(Topic topic) : Topic{topic} {} + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType Subscribe( + std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new publisher to the topic. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType Publish(std::string_view typeString, const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic, with type string and initial + * properties. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType PublishEx(std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new entry for the topic. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntry(std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); +}; + +} // namespace nt + +#include "networktables/RawTopic.inc" diff --git a/ntcore/src/generated/main/native/include/networktables/RawTopic.inc b/ntcore/src/generated/main/native/include/networktables/RawTopic.inc new file mode 100644 index 00000000000..b31ebcb1f7c --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/RawTopic.inc @@ -0,0 +1,121 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include "networktables/RawTopic.h" +#include "networktables/NetworkTableType.h" +#include "ntcore_cpp.h" + +namespace nt { + +inline RawSubscriber::RawSubscriber( + NT_Subscriber handle, std::span defaultValue) + : Subscriber{handle}, + m_defaultValue{defaultValue.begin(), defaultValue.end()} {} + +inline std::vector RawSubscriber::Get() const { + return Get(m_defaultValue); +} + +inline std::vector RawSubscriber::Get( + std::span defaultValue) const { + return ::nt::GetRaw(m_subHandle, defaultValue); +} + +inline std::span RawSubscriber::Get(wpi::SmallVectorImpl& buf) const { + return Get(buf, m_defaultValue); +} + +inline std::span RawSubscriber::Get(wpi::SmallVectorImpl& buf, std::span defaultValue) const { + return nt::GetRaw(m_subHandle, buf, defaultValue); +} + +inline TimestampedRaw RawSubscriber::GetAtomic() const { + return GetAtomic(m_defaultValue); +} + +inline TimestampedRaw RawSubscriber::GetAtomic( + std::span defaultValue) const { + return ::nt::GetAtomicRaw(m_subHandle, defaultValue); +} + +inline TimestampedRawView RawSubscriber::GetAtomic(wpi::SmallVectorImpl& buf) const { + return GetAtomic(buf, m_defaultValue); +} + +inline TimestampedRawView RawSubscriber::GetAtomic(wpi::SmallVectorImpl& buf, std::span defaultValue) const { + return nt::GetAtomicRaw(m_subHandle, buf, defaultValue); +} + +inline std::vector +RawSubscriber::ReadQueue() { + return ::nt::ReadQueueRaw(m_subHandle); +} + +inline RawTopic RawSubscriber::GetTopic() const { + return RawTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline RawPublisher::RawPublisher(NT_Publisher handle) + : Publisher{handle} {} + +inline void RawPublisher::Set(std::span value, + int64_t time) { + ::nt::SetRaw(m_pubHandle, value, time); +} + +inline void RawPublisher::SetDefault(std::span value) { + ::nt::SetDefaultRaw(m_pubHandle, value); +} + +inline RawTopic RawPublisher::GetTopic() const { + return RawTopic{::nt::GetTopicFromHandle(m_pubHandle)}; +} + +inline RawEntry::RawEntry( + NT_Entry handle, std::span defaultValue) + : RawSubscriber{handle, defaultValue}, + RawPublisher{handle} {} + +inline RawTopic RawEntry::GetTopic() const { + return RawTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline void RawEntry::Unpublish() { + ::nt::Unpublish(m_pubHandle); +} + +inline RawSubscriber RawTopic::Subscribe( + std::string_view typeString, std::span defaultValue, + const PubSubOptions& options) { + return RawSubscriber{ + ::nt::Subscribe(m_handle, NT_RAW, typeString, options), + defaultValue}; +} +inline RawPublisher RawTopic::Publish( + std::string_view typeString, const PubSubOptions& options) { + return RawPublisher{ + ::nt::Publish(m_handle, NT_RAW, typeString, options)}; +} + +inline RawPublisher RawTopic::PublishEx( + std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options) { + return RawPublisher{ + ::nt::PublishEx(m_handle, NT_RAW, typeString, properties, options)}; +} + +inline RawEntry RawTopic::GetEntry( + std::string_view typeString, std::span defaultValue, + const PubSubOptions& options) { + return RawEntry{ + ::nt::GetEntry(m_handle, NT_RAW, typeString, options), + defaultValue}; +} +} // namespace nt diff --git a/ntcore/src/generated/main/native/include/networktables/StringArrayTopic.h b/ntcore/src/generated/main/native/include/networktables/StringArrayTopic.h new file mode 100644 index 00000000000..9339521002c --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/StringArrayTopic.h @@ -0,0 +1,373 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include +#include +#include +#include + +#include + +#include "networktables/Topic.h" + +namespace wpi { +template +class SmallVectorImpl; +} // namespace wpi + +namespace nt { + +class StringArrayTopic; + +/** + * NetworkTables StringArray subscriber. + */ +class StringArraySubscriber : public Subscriber { + public: + using TopicType = StringArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + using TimestampedValueType = TimestampedStringArray; + + + StringArraySubscriber() = default; + + /** + * Construct from a subscriber handle; recommended to use + * StringArrayTopic::Subscribe() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + StringArraySubscriber(NT_Subscriber handle, ParamType defaultValue); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + ValueType Get() const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + ValueType Get(ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedValueType GetAtomic() const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueType GetAtomic(ParamType defaultValue) const; + + /** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + std::vector ReadQueue(); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + private: + ValueType m_defaultValue; +}; + +/** + * NetworkTables StringArray publisher. + */ +class StringArrayPublisher : public Publisher { + public: + using TopicType = StringArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + + using TimestampedValueType = TimestampedStringArray; + + StringArrayPublisher() = default; + + /** + * Construct from a publisher handle; recommended to use + * StringArrayTopic::Publish() instead. + * + * @param handle Native handle + */ + explicit StringArrayPublisher(NT_Publisher handle); + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void Set(ParamType value, int64_t time = 0); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void SetDefault(ParamType value); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; +}; + +/** + * NetworkTables StringArray entry. + * + * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. + */ +class StringArrayEntry final : public StringArraySubscriber, + public StringArrayPublisher { + public: + using SubscriberType = StringArraySubscriber; + using PublisherType = StringArrayPublisher; + using TopicType = StringArrayTopic; + using ValueType = std::vector; + using ParamType = std::span; + + using TimestampedValueType = TimestampedStringArray; + + StringArrayEntry() = default; + + /** + * Construct from an entry handle; recommended to use + * StringArrayTopic::GetEntry() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + StringArrayEntry(NT_Entry handle, ParamType defaultValue); + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + explicit operator bool() const { return m_subHandle != 0; } + + /** + * Gets the native handle for the entry. + * + * @return Native handle + */ + NT_Entry GetHandle() const { return m_subHandle; } + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + /** + * Stops publishing the entry if it's published. + */ + void Unpublish(); +}; + +/** + * NetworkTables StringArray topic. + */ +class StringArrayTopic final : public Topic { + public: + using SubscriberType = StringArraySubscriber; + using PublisherType = StringArrayPublisher; + using EntryType = StringArrayEntry; + using ValueType = std::vector; + using ParamType = std::span; + using TimestampedValueType = TimestampedStringArray; + /** The default type string for this topic type. */ + static constexpr std::string_view kTypeString = "string[]"; + + StringArrayTopic() = default; + + /** + * Construct from a topic handle; recommended to use + * NetworkTableInstance::GetStringArrayTopic() instead. + * + * @param handle Native handle + */ + explicit StringArrayTopic(NT_Topic handle) : Topic{handle} {} + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + explicit StringArrayTopic(Topic topic) : Topic{topic} {} + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType Subscribe( + ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new subscriber to the topic, with specific type string. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType SubscribeEx( + std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType Publish(const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic, with type string and initial + * properties. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType PublishEx(std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new entry for the topic. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntry(ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new entry for the topic, with specific type string. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntryEx(std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + +}; + +} // namespace nt + +#include "networktables/StringArrayTopic.inc" diff --git a/ntcore/src/generated/main/native/include/networktables/StringArrayTopic.inc b/ntcore/src/generated/main/native/include/networktables/StringArrayTopic.inc new file mode 100644 index 00000000000..f003ff00c5d --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/StringArrayTopic.inc @@ -0,0 +1,121 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include "networktables/StringArrayTopic.h" +#include "networktables/NetworkTableType.h" +#include "ntcore_cpp.h" + +namespace nt { + +inline StringArraySubscriber::StringArraySubscriber( + NT_Subscriber handle, std::span defaultValue) + : Subscriber{handle}, + m_defaultValue{defaultValue.begin(), defaultValue.end()} {} + +inline std::vector StringArraySubscriber::Get() const { + return Get(m_defaultValue); +} + +inline std::vector StringArraySubscriber::Get( + std::span defaultValue) const { + return ::nt::GetStringArray(m_subHandle, defaultValue); +} + +inline TimestampedStringArray StringArraySubscriber::GetAtomic() const { + return GetAtomic(m_defaultValue); +} + +inline TimestampedStringArray StringArraySubscriber::GetAtomic( + std::span defaultValue) const { + return ::nt::GetAtomicStringArray(m_subHandle, defaultValue); +} + +inline std::vector +StringArraySubscriber::ReadQueue() { + return ::nt::ReadQueueStringArray(m_subHandle); +} + +inline StringArrayTopic StringArraySubscriber::GetTopic() const { + return StringArrayTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline StringArrayPublisher::StringArrayPublisher(NT_Publisher handle) + : Publisher{handle} {} + +inline void StringArrayPublisher::Set(std::span value, + int64_t time) { + ::nt::SetStringArray(m_pubHandle, value, time); +} + +inline void StringArrayPublisher::SetDefault(std::span value) { + ::nt::SetDefaultStringArray(m_pubHandle, value); +} + +inline StringArrayTopic StringArrayPublisher::GetTopic() const { + return StringArrayTopic{::nt::GetTopicFromHandle(m_pubHandle)}; +} + +inline StringArrayEntry::StringArrayEntry( + NT_Entry handle, std::span defaultValue) + : StringArraySubscriber{handle, defaultValue}, + StringArrayPublisher{handle} {} + +inline StringArrayTopic StringArrayEntry::GetTopic() const { + return StringArrayTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline void StringArrayEntry::Unpublish() { + ::nt::Unpublish(m_pubHandle); +} + +inline StringArraySubscriber StringArrayTopic::Subscribe( + std::span defaultValue, + const PubSubOptions& options) { + return StringArraySubscriber{ + ::nt::Subscribe(m_handle, NT_STRING_ARRAY, "string[]", options), + defaultValue}; +} +inline StringArraySubscriber StringArrayTopic::SubscribeEx( + std::string_view typeString, std::span defaultValue, + const PubSubOptions& options) { + return StringArraySubscriber{ + ::nt::Subscribe(m_handle, NT_STRING_ARRAY, typeString, options), + defaultValue}; +} + +inline StringArrayPublisher StringArrayTopic::Publish( + const PubSubOptions& options) { + return StringArrayPublisher{ + ::nt::Publish(m_handle, NT_STRING_ARRAY, "string[]", options)}; +} + +inline StringArrayPublisher StringArrayTopic::PublishEx( + std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options) { + return StringArrayPublisher{ + ::nt::PublishEx(m_handle, NT_STRING_ARRAY, typeString, properties, options)}; +} + +inline StringArrayEntry StringArrayTopic::GetEntry( + std::span defaultValue, + const PubSubOptions& options) { + return StringArrayEntry{ + ::nt::GetEntry(m_handle, NT_STRING_ARRAY, "string[]", options), + defaultValue}; +} +inline StringArrayEntry StringArrayTopic::GetEntryEx( + std::string_view typeString, std::span defaultValue, + const PubSubOptions& options) { + return StringArrayEntry{ + ::nt::GetEntry(m_handle, NT_STRING_ARRAY, typeString, options), + defaultValue}; +} + +} // namespace nt diff --git a/ntcore/src/generated/main/native/include/networktables/StringTopic.h b/ntcore/src/generated/main/native/include/networktables/StringTopic.h new file mode 100644 index 00000000000..3e0ff87545b --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/StringTopic.h @@ -0,0 +1,428 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include "networktables/Topic.h" + +namespace wpi { +template +class SmallVectorImpl; +} // namespace wpi + +namespace nt { + +class StringTopic; + +/** + * NetworkTables String subscriber. + */ +class StringSubscriber : public Subscriber { + public: + using TopicType = StringTopic; + using ValueType = std::string; + using ParamType = std::string_view; + using TimestampedValueType = TimestampedString; + + using SmallRetType = std::string_view; + using SmallElemType = char; + using TimestampedValueViewType = TimestampedStringView; + + + StringSubscriber() = default; + + /** + * Construct from a subscriber handle; recommended to use + * StringTopic::Subscribe() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + StringSubscriber(NT_Subscriber handle, ParamType defaultValue); + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @return value + */ + ValueType Get() const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param defaultValue default value to return if no value has been published + * @return value + */ + ValueType Get(ParamType defaultValue) const; + + /** + * Get the last published value. + * If no value has been published, returns the stored default value. + * + * @param buf storage for returned value + * @return value + */ + SmallRetType Get(wpi::SmallVectorImpl& buf) const; + + /** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param buf storage for returned value + * @param defaultValue default value to return if no value has been published + * @return value + */ + SmallRetType Get(wpi::SmallVectorImpl& buf, ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @return timestamped value + */ + TimestampedValueType GetAtomic() const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueType GetAtomic(ParamType defaultValue) const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the stored default value and a + * timestamp of 0. + * + * @param buf storage for returned value + * @return timestamped value + */ + TimestampedValueViewType GetAtomic( + wpi::SmallVectorImpl& buf) const; + + /** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param buf storage for returned value + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ + TimestampedValueViewType GetAtomic( + wpi::SmallVectorImpl& buf, + ParamType defaultValue) const; + + /** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ + std::vector ReadQueue(); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + private: + ValueType m_defaultValue; +}; + +/** + * NetworkTables String publisher. + */ +class StringPublisher : public Publisher { + public: + using TopicType = StringTopic; + using ValueType = std::string; + using ParamType = std::string_view; + + using SmallRetType = std::string_view; + using SmallElemType = char; + + using TimestampedValueType = TimestampedString; + + StringPublisher() = default; + + /** + * Construct from a publisher handle; recommended to use + * StringTopic::Publish() instead. + * + * @param handle Native handle + */ + explicit StringPublisher(NT_Publisher handle); + + /** + * Publish a new value. + * + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ + void Set(ParamType value, int64_t time = 0); + + /** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param value value + */ + void SetDefault(ParamType value); + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; +}; + +/** + * NetworkTables String entry. + * + * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. + */ +class StringEntry final : public StringSubscriber, + public StringPublisher { + public: + using SubscriberType = StringSubscriber; + using PublisherType = StringPublisher; + using TopicType = StringTopic; + using ValueType = std::string; + using ParamType = std::string_view; + + using SmallRetType = std::string_view; + using SmallElemType = char; + + using TimestampedValueType = TimestampedString; + + StringEntry() = default; + + /** + * Construct from an entry handle; recommended to use + * StringTopic::GetEntry() instead. + * + * @param handle Native handle + * @param defaultValue Default value + */ + StringEntry(NT_Entry handle, ParamType defaultValue); + + /** + * Determines if the native handle is valid. + * + * @return True if the native handle is valid, false otherwise. + */ + explicit operator bool() const { return m_subHandle != 0; } + + /** + * Gets the native handle for the entry. + * + * @return Native handle + */ + NT_Entry GetHandle() const { return m_subHandle; } + + /** + * Get the corresponding topic. + * + * @return Topic + */ + TopicType GetTopic() const; + + /** + * Stops publishing the entry if it's published. + */ + void Unpublish(); +}; + +/** + * NetworkTables String topic. + */ +class StringTopic final : public Topic { + public: + using SubscriberType = StringSubscriber; + using PublisherType = StringPublisher; + using EntryType = StringEntry; + using ValueType = std::string; + using ParamType = std::string_view; + using TimestampedValueType = TimestampedString; + /** The default type string for this topic type. */ + static constexpr std::string_view kTypeString = "string"; + + StringTopic() = default; + + /** + * Construct from a topic handle; recommended to use + * NetworkTableInstance::GetStringTopic() instead. + * + * @param handle Native handle + */ + explicit StringTopic(NT_Topic handle) : Topic{handle} {} + + /** + * Construct from a generic topic. + * + * @param topic Topic + */ + explicit StringTopic(Topic topic) : Topic{topic} {} + + /** + * Create a new subscriber to the topic. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType Subscribe( + ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new subscriber to the topic, with specific type string. + * + *

The subscriber is only active as long as the returned object + * is not destroyed. + * + * @note Subscribers that do not match the published data type do not return + * any values. To determine if the data type matches, use the appropriate + * Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options subscribe options + * @return subscriber + */ + [[nodiscard]] + SubscriberType SubscribeEx( + std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType Publish(const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new publisher to the topic, with type string and initial + * properties. + * + * The publisher is only active as long as the returned object + * is not destroyed. + * + * @note It is not possible to publish two different data types to the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored). To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param properties JSON properties + * @param options publish options + * @return publisher + */ + [[nodiscard]] + PublisherType PublishEx(std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions); + + /** + * Create a new entry for the topic. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntry(ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + /** + * Create a new entry for the topic, with specific type string. + * + * Entries act as a combination of a subscriber and a weak publisher. The + * subscriber is active as long as the entry is not destroyed. The publisher + * is created when the entry is first written to, and remains active until + * either Unpublish() is called or the entry is destroyed. + * + * @note It is not possible to use two different data types with the same + * topic. Conflicts between publishers are typically resolved by the + * server on a first-come, first-served basis. Any published values that + * do not match the topic's data type are dropped (ignored), and the entry + * will show no new values if the data type does not match. To determine + * if the data type matches, use the appropriate Topic functions. + * + * @param typeString type string + * @param defaultValue default value used when a default is not provided to a + * getter function + * @param options publish and/or subscribe options + * @return entry + */ + [[nodiscard]] + EntryType GetEntryEx(std::string_view typeString, ParamType defaultValue, + const PubSubOptions& options = kDefaultPubSubOptions); + +}; + +} // namespace nt + +#include "networktables/StringTopic.inc" diff --git a/ntcore/src/generated/main/native/include/networktables/StringTopic.inc b/ntcore/src/generated/main/native/include/networktables/StringTopic.inc new file mode 100644 index 00000000000..a1934e4cfd5 --- /dev/null +++ b/ntcore/src/generated/main/native/include/networktables/StringTopic.inc @@ -0,0 +1,137 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include "networktables/StringTopic.h" +#include "networktables/NetworkTableType.h" +#include "ntcore_cpp.h" + +namespace nt { + +inline StringSubscriber::StringSubscriber( + NT_Subscriber handle, std::string_view defaultValue) + : Subscriber{handle}, + m_defaultValue{defaultValue} {} + +inline std::string StringSubscriber::Get() const { + return Get(m_defaultValue); +} + +inline std::string StringSubscriber::Get( + std::string_view defaultValue) const { + return ::nt::GetString(m_subHandle, defaultValue); +} + +inline std::string_view StringSubscriber::Get(wpi::SmallVectorImpl& buf) const { + return Get(buf, m_defaultValue); +} + +inline std::string_view StringSubscriber::Get(wpi::SmallVectorImpl& buf, std::string_view defaultValue) const { + return nt::GetString(m_subHandle, buf, defaultValue); +} + +inline TimestampedString StringSubscriber::GetAtomic() const { + return GetAtomic(m_defaultValue); +} + +inline TimestampedString StringSubscriber::GetAtomic( + std::string_view defaultValue) const { + return ::nt::GetAtomicString(m_subHandle, defaultValue); +} + +inline TimestampedStringView StringSubscriber::GetAtomic(wpi::SmallVectorImpl& buf) const { + return GetAtomic(buf, m_defaultValue); +} + +inline TimestampedStringView StringSubscriber::GetAtomic(wpi::SmallVectorImpl& buf, std::string_view defaultValue) const { + return nt::GetAtomicString(m_subHandle, buf, defaultValue); +} + +inline std::vector +StringSubscriber::ReadQueue() { + return ::nt::ReadQueueString(m_subHandle); +} + +inline StringTopic StringSubscriber::GetTopic() const { + return StringTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline StringPublisher::StringPublisher(NT_Publisher handle) + : Publisher{handle} {} + +inline void StringPublisher::Set(std::string_view value, + int64_t time) { + ::nt::SetString(m_pubHandle, value, time); +} + +inline void StringPublisher::SetDefault(std::string_view value) { + ::nt::SetDefaultString(m_pubHandle, value); +} + +inline StringTopic StringPublisher::GetTopic() const { + return StringTopic{::nt::GetTopicFromHandle(m_pubHandle)}; +} + +inline StringEntry::StringEntry( + NT_Entry handle, std::string_view defaultValue) + : StringSubscriber{handle, defaultValue}, + StringPublisher{handle} {} + +inline StringTopic StringEntry::GetTopic() const { + return StringTopic{::nt::GetTopicFromHandle(m_subHandle)}; +} + +inline void StringEntry::Unpublish() { + ::nt::Unpublish(m_pubHandle); +} + +inline StringSubscriber StringTopic::Subscribe( + std::string_view defaultValue, + const PubSubOptions& options) { + return StringSubscriber{ + ::nt::Subscribe(m_handle, NT_STRING, "string", options), + defaultValue}; +} +inline StringSubscriber StringTopic::SubscribeEx( + std::string_view typeString, std::string_view defaultValue, + const PubSubOptions& options) { + return StringSubscriber{ + ::nt::Subscribe(m_handle, NT_STRING, typeString, options), + defaultValue}; +} + +inline StringPublisher StringTopic::Publish( + const PubSubOptions& options) { + return StringPublisher{ + ::nt::Publish(m_handle, NT_STRING, "string", options)}; +} + +inline StringPublisher StringTopic::PublishEx( + std::string_view typeString, + const wpi::json& properties, const PubSubOptions& options) { + return StringPublisher{ + ::nt::PublishEx(m_handle, NT_STRING, typeString, properties, options)}; +} + +inline StringEntry StringTopic::GetEntry( + std::string_view defaultValue, + const PubSubOptions& options) { + return StringEntry{ + ::nt::GetEntry(m_handle, NT_STRING, "string", options), + defaultValue}; +} +inline StringEntry StringTopic::GetEntryEx( + std::string_view typeString, std::string_view defaultValue, + const PubSubOptions& options) { + return StringEntry{ + ::nt::GetEntry(m_handle, NT_STRING, typeString, options), + defaultValue}; +} + +} // namespace nt diff --git a/ntcore/src/generated/main/native/include/ntcore_c_types.h b/ntcore/src/generated/main/native/include/ntcore_c_types.h new file mode 100644 index 00000000000..a9a57117c1a --- /dev/null +++ b/ntcore/src/generated/main/native/include/ntcore_c_types.h @@ -0,0 +1,1232 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include "ntcore_c.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * Timestamped Boolean. + * @ingroup ntcore_c_api + */ +struct NT_TimestampedBoolean { + /** + * Time in local time base. + */ + int64_t time; + + /** + * Time in server time base. May be 0 or 1 for locally set values. + */ + int64_t serverTime; + + /** + * Value. + */ + NT_Bool value; +}; + +/** + * @defgroup ntcore_Boolean_cfunc Boolean Functions + * @ingroup ntcore_c_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param time timestamp; 0 indicates current NT time should be used + * @param value value to publish + */ +NT_Bool NT_SetBoolean(NT_Handle pubentry, int64_t time, NT_Bool value); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +NT_Bool NT_SetDefaultBoolean(NT_Handle pubentry, NT_Bool defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +NT_Bool NT_GetBoolean(NT_Handle subentry, NT_Bool defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param value timestamped value (output) + */ +void NT_GetAtomicBoolean(NT_Handle subentry, NT_Bool defaultValue, struct NT_TimestampedBoolean* value); + +/** + * Disposes a timestamped value (as returned by NT_GetAtomicBoolean). + * + * @param value timestamped value + */ +void NT_DisposeTimestampedBoolean(struct NT_TimestampedBoolean* value); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of timestamped values; NULL if no new changes have + * been published since the previous call. + */ +struct NT_TimestampedBoolean* NT_ReadQueueBoolean(NT_Handle subentry, size_t* len); + +/** + * Frees a timestamped array of values (as returned by NT_ReadQueueBoolean). + * + * @param arr array + * @param len length of array + */ +void NT_FreeQueueBoolean(struct NT_TimestampedBoolean* arr, size_t len); +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of values; NULL if no new changes have + * been published since the previous call. + */ +NT_Bool* NT_ReadQueueValuesBoolean(NT_Handle subentry, size_t* len); + +/** @} */ + +/** + * Timestamped Integer. + * @ingroup ntcore_c_api + */ +struct NT_TimestampedInteger { + /** + * Time in local time base. + */ + int64_t time; + + /** + * Time in server time base. May be 0 or 1 for locally set values. + */ + int64_t serverTime; + + /** + * Value. + */ + int64_t value; +}; + +/** + * @defgroup ntcore_Integer_cfunc Integer Functions + * @ingroup ntcore_c_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param time timestamp; 0 indicates current NT time should be used + * @param value value to publish + */ +NT_Bool NT_SetInteger(NT_Handle pubentry, int64_t time, int64_t value); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +NT_Bool NT_SetDefaultInteger(NT_Handle pubentry, int64_t defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +int64_t NT_GetInteger(NT_Handle subentry, int64_t defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param value timestamped value (output) + */ +void NT_GetAtomicInteger(NT_Handle subentry, int64_t defaultValue, struct NT_TimestampedInteger* value); + +/** + * Disposes a timestamped value (as returned by NT_GetAtomicInteger). + * + * @param value timestamped value + */ +void NT_DisposeTimestampedInteger(struct NT_TimestampedInteger* value); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of timestamped values; NULL if no new changes have + * been published since the previous call. + */ +struct NT_TimestampedInteger* NT_ReadQueueInteger(NT_Handle subentry, size_t* len); + +/** + * Frees a timestamped array of values (as returned by NT_ReadQueueInteger). + * + * @param arr array + * @param len length of array + */ +void NT_FreeQueueInteger(struct NT_TimestampedInteger* arr, size_t len); +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of values; NULL if no new changes have + * been published since the previous call. + */ +int64_t* NT_ReadQueueValuesInteger(NT_Handle subentry, size_t* len); + +/** @} */ + +/** + * Timestamped Float. + * @ingroup ntcore_c_api + */ +struct NT_TimestampedFloat { + /** + * Time in local time base. + */ + int64_t time; + + /** + * Time in server time base. May be 0 or 1 for locally set values. + */ + int64_t serverTime; + + /** + * Value. + */ + float value; +}; + +/** + * @defgroup ntcore_Float_cfunc Float Functions + * @ingroup ntcore_c_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param time timestamp; 0 indicates current NT time should be used + * @param value value to publish + */ +NT_Bool NT_SetFloat(NT_Handle pubentry, int64_t time, float value); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +NT_Bool NT_SetDefaultFloat(NT_Handle pubentry, float defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +float NT_GetFloat(NT_Handle subentry, float defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param value timestamped value (output) + */ +void NT_GetAtomicFloat(NT_Handle subentry, float defaultValue, struct NT_TimestampedFloat* value); + +/** + * Disposes a timestamped value (as returned by NT_GetAtomicFloat). + * + * @param value timestamped value + */ +void NT_DisposeTimestampedFloat(struct NT_TimestampedFloat* value); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of timestamped values; NULL if no new changes have + * been published since the previous call. + */ +struct NT_TimestampedFloat* NT_ReadQueueFloat(NT_Handle subentry, size_t* len); + +/** + * Frees a timestamped array of values (as returned by NT_ReadQueueFloat). + * + * @param arr array + * @param len length of array + */ +void NT_FreeQueueFloat(struct NT_TimestampedFloat* arr, size_t len); +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of values; NULL if no new changes have + * been published since the previous call. + */ +float* NT_ReadQueueValuesFloat(NT_Handle subentry, size_t* len); + +/** @} */ + +/** + * Timestamped Double. + * @ingroup ntcore_c_api + */ +struct NT_TimestampedDouble { + /** + * Time in local time base. + */ + int64_t time; + + /** + * Time in server time base. May be 0 or 1 for locally set values. + */ + int64_t serverTime; + + /** + * Value. + */ + double value; +}; + +/** + * @defgroup ntcore_Double_cfunc Double Functions + * @ingroup ntcore_c_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param time timestamp; 0 indicates current NT time should be used + * @param value value to publish + */ +NT_Bool NT_SetDouble(NT_Handle pubentry, int64_t time, double value); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +NT_Bool NT_SetDefaultDouble(NT_Handle pubentry, double defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +double NT_GetDouble(NT_Handle subentry, double defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param value timestamped value (output) + */ +void NT_GetAtomicDouble(NT_Handle subentry, double defaultValue, struct NT_TimestampedDouble* value); + +/** + * Disposes a timestamped value (as returned by NT_GetAtomicDouble). + * + * @param value timestamped value + */ +void NT_DisposeTimestampedDouble(struct NT_TimestampedDouble* value); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of timestamped values; NULL if no new changes have + * been published since the previous call. + */ +struct NT_TimestampedDouble* NT_ReadQueueDouble(NT_Handle subentry, size_t* len); + +/** + * Frees a timestamped array of values (as returned by NT_ReadQueueDouble). + * + * @param arr array + * @param len length of array + */ +void NT_FreeQueueDouble(struct NT_TimestampedDouble* arr, size_t len); +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of values; NULL if no new changes have + * been published since the previous call. + */ +double* NT_ReadQueueValuesDouble(NT_Handle subentry, size_t* len); + +/** @} */ + +/** + * Timestamped String. + * @ingroup ntcore_c_api + */ +struct NT_TimestampedString { + /** + * Time in local time base. + */ + int64_t time; + + /** + * Time in server time base. May be 0 or 1 for locally set values. + */ + int64_t serverTime; + + /** + * Value. + */ + struct WPI_String value; +}; + +/** + * @defgroup ntcore_String_cfunc String Functions + * @ingroup ntcore_c_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param time timestamp; 0 indicates current NT time should be used + * @param value value to publish + */ +NT_Bool NT_SetString(NT_Handle pubentry, int64_t time, const struct WPI_String* value); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +NT_Bool NT_SetDefaultString(NT_Handle pubentry, const struct WPI_String* defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param value returned value (output) + + */ +void NT_GetString(NT_Handle subentry, const struct WPI_String* defaultValue, struct WPI_String* value); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param value timestamped value (output) + */ +void NT_GetAtomicString(NT_Handle subentry, const struct WPI_String* defaultValue, struct NT_TimestampedString* value); + +/** + * Disposes a timestamped value (as returned by NT_GetAtomicString). + * + * @param value timestamped value + */ +void NT_DisposeTimestampedString(struct NT_TimestampedString* value); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of timestamped values; NULL if no new changes have + * been published since the previous call. + */ +struct NT_TimestampedString* NT_ReadQueueString(NT_Handle subentry, size_t* len); + +/** + * Frees a timestamped array of values (as returned by NT_ReadQueueString). + * + * @param arr array + * @param len length of array + */ +void NT_FreeQueueString(struct NT_TimestampedString* arr, size_t len); + +/** @} */ + +/** + * Timestamped Raw. + * @ingroup ntcore_c_api + */ +struct NT_TimestampedRaw { + /** + * Time in local time base. + */ + int64_t time; + + /** + * Time in server time base. May be 0 or 1 for locally set values. + */ + int64_t serverTime; + + /** + * Value. + */ + uint8_t* value; + /** + * Value length. + */ + size_t len; + +}; + +/** + * @defgroup ntcore_Raw_cfunc Raw Functions + * @ingroup ntcore_c_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param time timestamp; 0 indicates current NT time should be used + * @param value value to publish + * @param len length of value + + */ +NT_Bool NT_SetRaw(NT_Handle pubentry, int64_t time, const uint8_t* value, size_t len); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + * @param defaultValueLen length of default value + + */ +NT_Bool NT_SetDefaultRaw(NT_Handle pubentry, const uint8_t* defaultValue, size_t defaultValueLen); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param defaultValueLen length of default value + * @param len length of returned value (output) + + * @return value + */ +uint8_t* NT_GetRaw(NT_Handle subentry, const uint8_t* defaultValue, size_t defaultValueLen, size_t* len); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param defaultValueLen length of default value + + * @param value timestamped value (output) + */ +void NT_GetAtomicRaw(NT_Handle subentry, const uint8_t* defaultValue, size_t defaultValueLen, struct NT_TimestampedRaw* value); + +/** + * Disposes a timestamped value (as returned by NT_GetAtomicRaw). + * + * @param value timestamped value + */ +void NT_DisposeTimestampedRaw(struct NT_TimestampedRaw* value); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of timestamped values; NULL if no new changes have + * been published since the previous call. + */ +struct NT_TimestampedRaw* NT_ReadQueueRaw(NT_Handle subentry, size_t* len); + +/** + * Frees a timestamped array of values (as returned by NT_ReadQueueRaw). + * + * @param arr array + * @param len length of array + */ +void NT_FreeQueueRaw(struct NT_TimestampedRaw* arr, size_t len); + +/** @} */ + +/** + * Timestamped BooleanArray. + * @ingroup ntcore_c_api + */ +struct NT_TimestampedBooleanArray { + /** + * Time in local time base. + */ + int64_t time; + + /** + * Time in server time base. May be 0 or 1 for locally set values. + */ + int64_t serverTime; + + /** + * Value. + */ + NT_Bool* value; + /** + * Value length. + */ + size_t len; + +}; + +/** + * @defgroup ntcore_BooleanArray_cfunc BooleanArray Functions + * @ingroup ntcore_c_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param time timestamp; 0 indicates current NT time should be used + * @param value value to publish + * @param len length of value + + */ +NT_Bool NT_SetBooleanArray(NT_Handle pubentry, int64_t time, const NT_Bool* value, size_t len); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + * @param defaultValueLen length of default value + + */ +NT_Bool NT_SetDefaultBooleanArray(NT_Handle pubentry, const NT_Bool* defaultValue, size_t defaultValueLen); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param defaultValueLen length of default value + * @param len length of returned value (output) + + * @return value + */ +NT_Bool* NT_GetBooleanArray(NT_Handle subentry, const NT_Bool* defaultValue, size_t defaultValueLen, size_t* len); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param defaultValueLen length of default value + + * @param value timestamped value (output) + */ +void NT_GetAtomicBooleanArray(NT_Handle subentry, const NT_Bool* defaultValue, size_t defaultValueLen, struct NT_TimestampedBooleanArray* value); + +/** + * Disposes a timestamped value (as returned by NT_GetAtomicBooleanArray). + * + * @param value timestamped value + */ +void NT_DisposeTimestampedBooleanArray(struct NT_TimestampedBooleanArray* value); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of timestamped values; NULL if no new changes have + * been published since the previous call. + */ +struct NT_TimestampedBooleanArray* NT_ReadQueueBooleanArray(NT_Handle subentry, size_t* len); + +/** + * Frees a timestamped array of values (as returned by NT_ReadQueueBooleanArray). + * + * @param arr array + * @param len length of array + */ +void NT_FreeQueueBooleanArray(struct NT_TimestampedBooleanArray* arr, size_t len); + +/** @} */ + +/** + * Timestamped IntegerArray. + * @ingroup ntcore_c_api + */ +struct NT_TimestampedIntegerArray { + /** + * Time in local time base. + */ + int64_t time; + + /** + * Time in server time base. May be 0 or 1 for locally set values. + */ + int64_t serverTime; + + /** + * Value. + */ + int64_t* value; + /** + * Value length. + */ + size_t len; + +}; + +/** + * @defgroup ntcore_IntegerArray_cfunc IntegerArray Functions + * @ingroup ntcore_c_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param time timestamp; 0 indicates current NT time should be used + * @param value value to publish + * @param len length of value + + */ +NT_Bool NT_SetIntegerArray(NT_Handle pubentry, int64_t time, const int64_t* value, size_t len); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + * @param defaultValueLen length of default value + + */ +NT_Bool NT_SetDefaultIntegerArray(NT_Handle pubentry, const int64_t* defaultValue, size_t defaultValueLen); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param defaultValueLen length of default value + * @param len length of returned value (output) + + * @return value + */ +int64_t* NT_GetIntegerArray(NT_Handle subentry, const int64_t* defaultValue, size_t defaultValueLen, size_t* len); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param defaultValueLen length of default value + + * @param value timestamped value (output) + */ +void NT_GetAtomicIntegerArray(NT_Handle subentry, const int64_t* defaultValue, size_t defaultValueLen, struct NT_TimestampedIntegerArray* value); + +/** + * Disposes a timestamped value (as returned by NT_GetAtomicIntegerArray). + * + * @param value timestamped value + */ +void NT_DisposeTimestampedIntegerArray(struct NT_TimestampedIntegerArray* value); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of timestamped values; NULL if no new changes have + * been published since the previous call. + */ +struct NT_TimestampedIntegerArray* NT_ReadQueueIntegerArray(NT_Handle subentry, size_t* len); + +/** + * Frees a timestamped array of values (as returned by NT_ReadQueueIntegerArray). + * + * @param arr array + * @param len length of array + */ +void NT_FreeQueueIntegerArray(struct NT_TimestampedIntegerArray* arr, size_t len); + +/** @} */ + +/** + * Timestamped FloatArray. + * @ingroup ntcore_c_api + */ +struct NT_TimestampedFloatArray { + /** + * Time in local time base. + */ + int64_t time; + + /** + * Time in server time base. May be 0 or 1 for locally set values. + */ + int64_t serverTime; + + /** + * Value. + */ + float* value; + /** + * Value length. + */ + size_t len; + +}; + +/** + * @defgroup ntcore_FloatArray_cfunc FloatArray Functions + * @ingroup ntcore_c_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param time timestamp; 0 indicates current NT time should be used + * @param value value to publish + * @param len length of value + + */ +NT_Bool NT_SetFloatArray(NT_Handle pubentry, int64_t time, const float* value, size_t len); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + * @param defaultValueLen length of default value + + */ +NT_Bool NT_SetDefaultFloatArray(NT_Handle pubentry, const float* defaultValue, size_t defaultValueLen); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param defaultValueLen length of default value + * @param len length of returned value (output) + + * @return value + */ +float* NT_GetFloatArray(NT_Handle subentry, const float* defaultValue, size_t defaultValueLen, size_t* len); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param defaultValueLen length of default value + + * @param value timestamped value (output) + */ +void NT_GetAtomicFloatArray(NT_Handle subentry, const float* defaultValue, size_t defaultValueLen, struct NT_TimestampedFloatArray* value); + +/** + * Disposes a timestamped value (as returned by NT_GetAtomicFloatArray). + * + * @param value timestamped value + */ +void NT_DisposeTimestampedFloatArray(struct NT_TimestampedFloatArray* value); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of timestamped values; NULL if no new changes have + * been published since the previous call. + */ +struct NT_TimestampedFloatArray* NT_ReadQueueFloatArray(NT_Handle subentry, size_t* len); + +/** + * Frees a timestamped array of values (as returned by NT_ReadQueueFloatArray). + * + * @param arr array + * @param len length of array + */ +void NT_FreeQueueFloatArray(struct NT_TimestampedFloatArray* arr, size_t len); + +/** @} */ + +/** + * Timestamped DoubleArray. + * @ingroup ntcore_c_api + */ +struct NT_TimestampedDoubleArray { + /** + * Time in local time base. + */ + int64_t time; + + /** + * Time in server time base. May be 0 or 1 for locally set values. + */ + int64_t serverTime; + + /** + * Value. + */ + double* value; + /** + * Value length. + */ + size_t len; + +}; + +/** + * @defgroup ntcore_DoubleArray_cfunc DoubleArray Functions + * @ingroup ntcore_c_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param time timestamp; 0 indicates current NT time should be used + * @param value value to publish + * @param len length of value + + */ +NT_Bool NT_SetDoubleArray(NT_Handle pubentry, int64_t time, const double* value, size_t len); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + * @param defaultValueLen length of default value + + */ +NT_Bool NT_SetDefaultDoubleArray(NT_Handle pubentry, const double* defaultValue, size_t defaultValueLen); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param defaultValueLen length of default value + * @param len length of returned value (output) + + * @return value + */ +double* NT_GetDoubleArray(NT_Handle subentry, const double* defaultValue, size_t defaultValueLen, size_t* len); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param defaultValueLen length of default value + + * @param value timestamped value (output) + */ +void NT_GetAtomicDoubleArray(NT_Handle subentry, const double* defaultValue, size_t defaultValueLen, struct NT_TimestampedDoubleArray* value); + +/** + * Disposes a timestamped value (as returned by NT_GetAtomicDoubleArray). + * + * @param value timestamped value + */ +void NT_DisposeTimestampedDoubleArray(struct NT_TimestampedDoubleArray* value); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of timestamped values; NULL if no new changes have + * been published since the previous call. + */ +struct NT_TimestampedDoubleArray* NT_ReadQueueDoubleArray(NT_Handle subentry, size_t* len); + +/** + * Frees a timestamped array of values (as returned by NT_ReadQueueDoubleArray). + * + * @param arr array + * @param len length of array + */ +void NT_FreeQueueDoubleArray(struct NT_TimestampedDoubleArray* arr, size_t len); + +/** @} */ + +/** + * Timestamped StringArray. + * @ingroup ntcore_c_api + */ +struct NT_TimestampedStringArray { + /** + * Time in local time base. + */ + int64_t time; + + /** + * Time in server time base. May be 0 or 1 for locally set values. + */ + int64_t serverTime; + + /** + * Value. + */ + struct WPI_String* value; + /** + * Value length. + */ + size_t len; + +}; + +/** + * @defgroup ntcore_StringArray_cfunc StringArray Functions + * @ingroup ntcore_c_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param time timestamp; 0 indicates current NT time should be used + * @param value value to publish + * @param len length of value + + */ +NT_Bool NT_SetStringArray(NT_Handle pubentry, int64_t time, const struct WPI_String* value, size_t len); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + * @param defaultValueLen length of default value + + */ +NT_Bool NT_SetDefaultStringArray(NT_Handle pubentry, const struct WPI_String* defaultValue, size_t defaultValueLen); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param defaultValueLen length of default value + * @param len length of returned value (output) + + * @return value + */ +struct WPI_String* NT_GetStringArray(NT_Handle subentry, const struct WPI_String* defaultValue, size_t defaultValueLen, size_t* len); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @param defaultValueLen length of default value + + * @param value timestamped value (output) + */ +void NT_GetAtomicStringArray(NT_Handle subentry, const struct WPI_String* defaultValue, size_t defaultValueLen, struct NT_TimestampedStringArray* value); + +/** + * Disposes a timestamped value (as returned by NT_GetAtomicStringArray). + * + * @param value timestamped value + */ +void NT_DisposeTimestampedStringArray(struct NT_TimestampedStringArray* value); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @param len length of returned array (output) + * @return Array of timestamped values; NULL if no new changes have + * been published since the previous call. + */ +struct NT_TimestampedStringArray* NT_ReadQueueStringArray(NT_Handle subentry, size_t* len); + +/** + * Frees a timestamped array of values (as returned by NT_ReadQueueStringArray). + * + * @param arr array + * @param len length of array + */ +void NT_FreeQueueStringArray(struct NT_TimestampedStringArray* arr, size_t len); + +/** @} */ + + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/ntcore/src/generated/main/native/include/ntcore_cpp_types.h b/ntcore/src/generated/main/native/include/ntcore_cpp_types.h new file mode 100644 index 00000000000..c0cac5e5a51 --- /dev/null +++ b/ntcore/src/generated/main/native/include/ntcore_cpp_types.h @@ -0,0 +1,998 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./ntcore/generate_topics.py. DO NOT MODIFY + +#pragma once + +#include + +#include +#include +#include +#include +#include + +#include "ntcore_c.h" + +namespace wpi { +template +class SmallVectorImpl; +} // namespace wpi + +namespace nt { +/** + * Timestamped value. + * @ingroup ntcore_cpp_handle_api + */ +template +struct Timestamped { + Timestamped() = default; + Timestamped(int64_t time, int64_t serverTime, T value) + : time{time}, serverTime{serverTime}, value{std::move(value)} {} + + /** + * Time in local time base. + */ + int64_t time = 0; + + /** + * Time in server time base. May be 0 or 1 for locally set values. + */ + int64_t serverTime = 0; + + /** + * Value. + */ + T value = {}; +}; + +/** + * Timestamped Boolean. + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedBoolean = Timestamped; + +/** + * @defgroup ntcore_Boolean_func Boolean Functions + * @ingroup ntcore_cpp_handle_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ +bool SetBoolean(NT_Handle pubentry, bool value, int64_t time = 0); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +bool SetDefaultBoolean(NT_Handle pubentry, bool defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +bool GetBoolean(NT_Handle subentry, bool defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ +TimestampedBoolean GetAtomicBoolean(NT_Handle subentry, bool defaultValue); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueBoolean(NT_Handle subentry); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueValuesBoolean(NT_Handle subentry); + +/** @} */ + +/** + * Timestamped Integer. + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedInteger = Timestamped; + +/** + * @defgroup ntcore_Integer_func Integer Functions + * @ingroup ntcore_cpp_handle_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ +bool SetInteger(NT_Handle pubentry, int64_t value, int64_t time = 0); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +bool SetDefaultInteger(NT_Handle pubentry, int64_t defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +int64_t GetInteger(NT_Handle subentry, int64_t defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ +TimestampedInteger GetAtomicInteger(NT_Handle subentry, int64_t defaultValue); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueInteger(NT_Handle subentry); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueValuesInteger(NT_Handle subentry); + +/** @} */ + +/** + * Timestamped Float. + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedFloat = Timestamped; + +/** + * @defgroup ntcore_Float_func Float Functions + * @ingroup ntcore_cpp_handle_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ +bool SetFloat(NT_Handle pubentry, float value, int64_t time = 0); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +bool SetDefaultFloat(NT_Handle pubentry, float defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +float GetFloat(NT_Handle subentry, float defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ +TimestampedFloat GetAtomicFloat(NT_Handle subentry, float defaultValue); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueFloat(NT_Handle subentry); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueValuesFloat(NT_Handle subentry); + +/** @} */ + +/** + * Timestamped Double. + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedDouble = Timestamped; + +/** + * @defgroup ntcore_Double_func Double Functions + * @ingroup ntcore_cpp_handle_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ +bool SetDouble(NT_Handle pubentry, double value, int64_t time = 0); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +bool SetDefaultDouble(NT_Handle pubentry, double defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +double GetDouble(NT_Handle subentry, double defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ +TimestampedDouble GetAtomicDouble(NT_Handle subentry, double defaultValue); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueDouble(NT_Handle subentry); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueValuesDouble(NT_Handle subentry); + +/** @} */ + +/** + * Timestamped String. + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedString = Timestamped; + +/** + * Timestamped String view (for SmallVector-taking functions). + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedStringView = Timestamped; + +/** + * @defgroup ntcore_String_func String Functions + * @ingroup ntcore_cpp_handle_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ +bool SetString(NT_Handle pubentry, std::string_view value, int64_t time = 0); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +bool SetDefaultString(NT_Handle pubentry, std::string_view defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +std::string GetString(NT_Handle subentry, std::string_view defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ +TimestampedString GetAtomicString(NT_Handle subentry, std::string_view defaultValue); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueString(NT_Handle subentry); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueValuesString(NT_Handle subentry); + +std::string_view GetString(NT_Handle subentry, wpi::SmallVectorImpl& buf, std::string_view defaultValue); + +TimestampedStringView GetAtomicString( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::string_view defaultValue); + +/** @} */ + +/** + * Timestamped Raw. + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedRaw = Timestamped>; + +/** + * Timestamped Raw view (for SmallVector-taking functions). + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedRawView = Timestamped>; + +/** + * @defgroup ntcore_Raw_func Raw Functions + * @ingroup ntcore_cpp_handle_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ +bool SetRaw(NT_Handle pubentry, std::span value, int64_t time = 0); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +bool SetDefaultRaw(NT_Handle pubentry, std::span defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +std::vector GetRaw(NT_Handle subentry, std::span defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ +TimestampedRaw GetAtomicRaw(NT_Handle subentry, std::span defaultValue); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueRaw(NT_Handle subentry); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of values; empty array if no new changes have + * been published since the previous call. + */ +std::vector> ReadQueueValuesRaw(NT_Handle subentry); + +std::span GetRaw(NT_Handle subentry, wpi::SmallVectorImpl& buf, std::span defaultValue); + +TimestampedRawView GetAtomicRaw( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue); + +/** @} */ + +/** + * Timestamped BooleanArray. + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedBooleanArray = Timestamped>; + +/** + * Timestamped BooleanArray view (for SmallVector-taking functions). + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedBooleanArrayView = Timestamped>; + +/** + * @defgroup ntcore_BooleanArray_func BooleanArray Functions + * @ingroup ntcore_cpp_handle_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ +bool SetBooleanArray(NT_Handle pubentry, std::span value, int64_t time = 0); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +bool SetDefaultBooleanArray(NT_Handle pubentry, std::span defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +std::vector GetBooleanArray(NT_Handle subentry, std::span defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ +TimestampedBooleanArray GetAtomicBooleanArray(NT_Handle subentry, std::span defaultValue); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueBooleanArray(NT_Handle subentry); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of values; empty array if no new changes have + * been published since the previous call. + */ +std::vector> ReadQueueValuesBooleanArray(NT_Handle subentry); + +std::span GetBooleanArray(NT_Handle subentry, wpi::SmallVectorImpl& buf, std::span defaultValue); + +TimestampedBooleanArrayView GetAtomicBooleanArray( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue); + +/** @} */ + +/** + * Timestamped IntegerArray. + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedIntegerArray = Timestamped>; + +/** + * Timestamped IntegerArray view (for SmallVector-taking functions). + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedIntegerArrayView = Timestamped>; + +/** + * @defgroup ntcore_IntegerArray_func IntegerArray Functions + * @ingroup ntcore_cpp_handle_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ +bool SetIntegerArray(NT_Handle pubentry, std::span value, int64_t time = 0); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +bool SetDefaultIntegerArray(NT_Handle pubentry, std::span defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +std::vector GetIntegerArray(NT_Handle subentry, std::span defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ +TimestampedIntegerArray GetAtomicIntegerArray(NT_Handle subentry, std::span defaultValue); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueIntegerArray(NT_Handle subentry); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of values; empty array if no new changes have + * been published since the previous call. + */ +std::vector> ReadQueueValuesIntegerArray(NT_Handle subentry); + +std::span GetIntegerArray(NT_Handle subentry, wpi::SmallVectorImpl& buf, std::span defaultValue); + +TimestampedIntegerArrayView GetAtomicIntegerArray( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue); + +/** @} */ + +/** + * Timestamped FloatArray. + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedFloatArray = Timestamped>; + +/** + * Timestamped FloatArray view (for SmallVector-taking functions). + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedFloatArrayView = Timestamped>; + +/** + * @defgroup ntcore_FloatArray_func FloatArray Functions + * @ingroup ntcore_cpp_handle_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ +bool SetFloatArray(NT_Handle pubentry, std::span value, int64_t time = 0); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +bool SetDefaultFloatArray(NT_Handle pubentry, std::span defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +std::vector GetFloatArray(NT_Handle subentry, std::span defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ +TimestampedFloatArray GetAtomicFloatArray(NT_Handle subentry, std::span defaultValue); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueFloatArray(NT_Handle subentry); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of values; empty array if no new changes have + * been published since the previous call. + */ +std::vector> ReadQueueValuesFloatArray(NT_Handle subentry); + +std::span GetFloatArray(NT_Handle subentry, wpi::SmallVectorImpl& buf, std::span defaultValue); + +TimestampedFloatArrayView GetAtomicFloatArray( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue); + +/** @} */ + +/** + * Timestamped DoubleArray. + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedDoubleArray = Timestamped>; + +/** + * Timestamped DoubleArray view (for SmallVector-taking functions). + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedDoubleArrayView = Timestamped>; + +/** + * @defgroup ntcore_DoubleArray_func DoubleArray Functions + * @ingroup ntcore_cpp_handle_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ +bool SetDoubleArray(NT_Handle pubentry, std::span value, int64_t time = 0); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +bool SetDefaultDoubleArray(NT_Handle pubentry, std::span defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +std::vector GetDoubleArray(NT_Handle subentry, std::span defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ +TimestampedDoubleArray GetAtomicDoubleArray(NT_Handle subentry, std::span defaultValue); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueDoubleArray(NT_Handle subentry); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of values; empty array if no new changes have + * been published since the previous call. + */ +std::vector> ReadQueueValuesDoubleArray(NT_Handle subentry); + +std::span GetDoubleArray(NT_Handle subentry, wpi::SmallVectorImpl& buf, std::span defaultValue); + +TimestampedDoubleArrayView GetAtomicDoubleArray( + NT_Handle subentry, + wpi::SmallVectorImpl& buf, + std::span defaultValue); + +/** @} */ + +/** + * Timestamped StringArray. + * @ingroup ntcore_cpp_handle_api + */ +using TimestampedStringArray = Timestamped>; + +/** + * @defgroup ntcore_StringArray_func StringArray Functions + * @ingroup ntcore_cpp_handle_api + * @{ + */ + +/** + * Publish a new value. + * + * @param pubentry publisher or entry handle + * @param value value to publish + * @param time timestamp; 0 indicates current NT time should be used + */ +bool SetStringArray(NT_Handle pubentry, std::span value, int64_t time = 0); + +/** + * Publish a default value. + * On reconnect, a default value will never be used in preference to a + * published value. + * + * @param pubentry publisher or entry handle + * @param defaultValue default value + */ +bool SetDefaultStringArray(NT_Handle pubentry, std::span defaultValue); + +/** + * Get the last published value. + * If no value has been published, returns the passed defaultValue. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return value + */ +std::vector GetStringArray(NT_Handle subentry, std::span defaultValue); + +/** + * Get the last published value along with its timestamp. + * If no value has been published, returns the passed defaultValue and a + * timestamp of 0. + * + * @param subentry subscriber or entry handle + * @param defaultValue default value to return if no value has been published + * @return timestamped value + */ +TimestampedStringArray GetAtomicStringArray(NT_Handle subentry, std::span defaultValue); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * Also provides a timestamp for each value. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of timestamped values; empty array if no new changes have + * been published since the previous call. + */ +std::vector ReadQueueStringArray(NT_Handle subentry); + +/** + * Get an array of all value changes since the last call to ReadQueue. + * + * @note The "poll storage" subscribe option can be used to set the queue + * depth. + * + * @param subentry subscriber or entry handle + * @return Array of values; empty array if no new changes have + * been published since the previous call. + */ +std::vector> ReadQueueValuesStringArray(NT_Handle subentry); + +/** @} */ + +} // namespace nt diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/EntryBase.java b/ntcore/src/main/java/edu/wpi/first/networktables/EntryBase.java index 48d4a9c3627..2083423d930 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/EntryBase.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/EntryBase.java @@ -40,5 +40,6 @@ public long getLastChange() { return NetworkTablesJNI.getEntryLastChange(m_handle); } + /** NetworkTables handle. */ protected int m_handle; } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/LogMessage.java b/ntcore/src/main/java/edu/wpi/first/networktables/LogMessage.java index fd090afff0c..3f268405b63 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/LogMessage.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/LogMessage.java @@ -7,16 +7,31 @@ /** NetworkTables log message. */ @SuppressWarnings("MemberName") public final class LogMessage { - /** Logging levels. */ + /** Critical logging level. */ public static final int kCritical = 50; + /** Error logging level. */ public static final int kError = 40; + + /** Warning log level. */ public static final int kWarning = 30; + + /** Info log level. */ public static final int kInfo = 20; + + /** Debug log level. */ public static final int kDebug = 10; + + /** Debug log level 1. */ public static final int kDebug1 = 9; + + /** Debug log level 2. */ public static final int kDebug2 = 8; + + /** Debug log level 3. */ public static final int kDebug3 = 7; + + /** Debug log level 4. */ public static final int kDebug4 = 6; /** Log level of the message. */ diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/NTSendableBuilder.java b/ntcore/src/main/java/edu/wpi/first/networktables/NTSendableBuilder.java index 4d5e6a5330d..ce09d693de1 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/NTSendableBuilder.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/NTSendableBuilder.java @@ -6,6 +6,7 @@ import edu.wpi.first.util.sendable.SendableBuilder; +/** Helper class for building Sendable dashboard representations for NetworkTables. */ public interface NTSendableBuilder extends SendableBuilder { /** * Set the function that should be called to update the network table for things other than diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTable.java b/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTable.java index 3c6593809b3..a9768ff7e89 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTable.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTable.java @@ -330,7 +330,7 @@ public NetworkTable getSubTable(String key) { * @return true if the table as a value assigned to the given key */ public boolean containsKey(String key) { - return !("".equals(key)) && getTopic(key).exists(); + return !"".equals(key) && getTopic(key).exists(); } /** @@ -574,7 +574,7 @@ public int addSubTableListener(SubTableListener listener) { return m_inst.addListener( new String[] {m_pathWithSep}, EnumSet.of(NetworkTableEvent.Kind.kPublish, NetworkTableEvent.Kind.kImmediate), - new Consumer() { + new Consumer<>() { final Set m_notifiedTables = new HashSet<>(); @Override diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTableEvent.java b/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTableEvent.java index 97883c8c390..55f040c96a8 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTableEvent.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTableEvent.java @@ -12,6 +12,7 @@ */ @SuppressWarnings("MemberName") public final class NetworkTableEvent { + /** NetworkTable event kind. */ public enum Kind { /** * Initial listener addition. Set this to receive immediate notification of matches to other @@ -61,6 +62,11 @@ public enum Kind { this.value = value; } + /** + * Returns the NetworkTable event kind value. + * + * @return The NetworkTable event kind value. + */ public int getValue() { return value; } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTableType.java b/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTableType.java index 2350b49bba6..89a5413b1cd 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTableType.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/NetworkTableType.java @@ -6,17 +6,29 @@ /** Network table data types. */ public enum NetworkTableType { + /** Unassigned data type. */ kUnassigned(0, ""), + /** Boolean data type. */ kBoolean(0x01, "boolean"), + /** Double precision floating-point data type. */ kDouble(0x02, "double"), + /** String data type. */ kString(0x04, "string"), + /** Raw data type. */ kRaw(0x08, "raw"), + /** Boolean array data type. */ kBooleanArray(0x10, "boolean[]"), + /** Double precision floating-point array data type. */ kDoubleArray(0x20, "double[]"), + /** String array data type. */ kStringArray(0x40, "string[]"), + /** Integer data type. */ kInteger(0x100, "int"), + /** Single precision floating-point data type. */ kFloat(0x200, "float"), + /** Integer array data type. */ kIntegerArray(0x400, "int[]"), + /** Single precision floating-point array data type. */ kFloatArray(0x800, "float[]"); private final int m_value; @@ -27,10 +39,20 @@ public enum NetworkTableType { m_valueStr = valueStr; } + /** + * Returns the NetworkTable type value. + * + * @return The NetworkTable type value. + */ public int getValue() { return m_value; } + /** + * Returns the NetworkTable type value as as string. + * + * @return The NetworkTable type value as a string. + */ public String getValueStr() { return m_valueStr; } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufEntryImpl.java b/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufEntryImpl.java index b4359eaf030..6d891c45169 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufEntryImpl.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufEntryImpl.java @@ -190,14 +190,14 @@ private T fromRaw(byte[] raw, T defaultValue) { private TimestampedObject fromRaw(TimestampedRaw raw, T defaultValue) { if (raw.value.length == 0) { - return new TimestampedObject(0, 0, defaultValue); + return new TimestampedObject<>(0, 0, defaultValue); } try { synchronized (m_buf) { - return new TimestampedObject(raw.timestamp, raw.serverTime, m_buf.read(raw.value)); + return new TimestampedObject<>(raw.timestamp, raw.serverTime, m_buf.read(raw.value)); } } catch (IOException e) { - return new TimestampedObject(0, 0, defaultValue); + return new TimestampedObject<>(0, 0, defaultValue); } } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufTopic.java b/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufTopic.java index c3dad133a58..eb9a489d75c 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufTopic.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/ProtobufTopic.java @@ -32,7 +32,7 @@ private ProtobufTopic(NetworkTableInstance inst, int handle, Protobuf prot * @return ProtobufTopic for value class */ public static ProtobufTopic wrap(Topic topic, Protobuf proto) { - return new ProtobufTopic(topic, proto); + return new ProtobufTopic<>(topic, proto); } /** @@ -47,7 +47,7 @@ public static ProtobufTopic wrap(Topic topic, Protobuf proto) { */ public static ProtobufTopic wrap( NetworkTableInstance inst, int handle, Protobuf proto) { - return new ProtobufTopic(inst, handle, proto); + return new ProtobufTopic<>(inst, handle, proto); } /** @@ -63,7 +63,7 @@ public static ProtobufTopic wrap( * @return subscriber */ public ProtobufSubscriber subscribe(T defaultValue, PubSubOption... options) { - return new ProtobufEntryImpl( + return new ProtobufEntryImpl<>( this, ProtobufBuffer.create(m_proto), NetworkTablesJNI.subscribe( @@ -87,7 +87,7 @@ public ProtobufSubscriber subscribe(T defaultValue, PubSubOption... options) */ public ProtobufPublisher publish(PubSubOption... options) { m_inst.addSchema(m_proto); - return new ProtobufEntryImpl( + return new ProtobufEntryImpl<>( this, ProtobufBuffer.create(m_proto), NetworkTablesJNI.publish( @@ -113,7 +113,7 @@ public ProtobufPublisher publish(PubSubOption... options) { */ public ProtobufPublisher publishEx(String properties, PubSubOption... options) { m_inst.addSchema(m_proto); - return new ProtobufEntryImpl( + return new ProtobufEntryImpl<>( this, ProtobufBuffer.create(m_proto), NetworkTablesJNI.publishEx( @@ -144,7 +144,7 @@ public ProtobufPublisher publishEx(String properties, PubSubOption... options * @return entry */ public ProtobufEntry getEntry(T defaultValue, PubSubOption... options) { - return new ProtobufEntryImpl( + return new ProtobufEntryImpl<>( this, ProtobufBuffer.create(m_proto), NetworkTablesJNI.getEntry( @@ -153,6 +153,11 @@ public ProtobufEntry getEntry(T defaultValue, PubSubOption... options) { false); } + /** + * Returns the protobuf. + * + * @return The protobuf. + */ public Protobuf getProto() { return m_proto; } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/PubSubOption.java b/ntcore/src/main/java/edu/wpi/first/networktables/PubSubOption.java index dd96eec8efd..b9d885533ee 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/PubSubOption.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/PubSubOption.java @@ -15,7 +15,8 @@ enum Kind { disableRemote, disableLocal, excludePublisher, - excludeSelf + excludeSelf, + hidden } PubSubOption(Kind kind, boolean value) { @@ -149,6 +150,18 @@ public static PubSubOption excludeSelf(boolean enabled) { return new PubSubOption(Kind.excludeSelf, enabled); } + /** + * For subscriptions, don't share the existence of the subscription with the network. Note this + * means updates will not be received from the network unless another subscription overlaps with + * this one, and the subscription will not appear in metatopics. + * + * @param enabled True to enable, false to disable + * @return option + */ + public static PubSubOption hidden(boolean enabled) { + return new PubSubOption(Kind.hidden, enabled); + } + final Kind m_kind; final boolean m_bValue; final int m_iValue; diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/PubSubOptions.java b/ntcore/src/main/java/edu/wpi/first/networktables/PubSubOptions.java index 18557b93db4..ec9158af392 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/PubSubOptions.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/PubSubOptions.java @@ -42,6 +42,9 @@ public PubSubOptions(PubSubOption... options) { case excludeSelf: excludeSelf = option.m_bValue; break; + case hidden: + hidden = option.m_bValue; + break; default: break; } @@ -58,7 +61,8 @@ public PubSubOptions(PubSubOption... options) { boolean prefixMatch, boolean disableRemote, boolean disableLocal, - boolean excludeSelf) { + boolean excludeSelf, + boolean hidden) { this.pollStorage = pollStorage; this.periodic = periodic; this.excludePublisher = excludePublisher; @@ -69,6 +73,7 @@ public PubSubOptions(PubSubOption... options) { this.disableRemote = disableRemote; this.disableLocal = disableLocal; this.excludeSelf = excludeSelf; + this.hidden = hidden; } /** Default value of periodic. */ @@ -123,4 +128,11 @@ public PubSubOptions(PubSubOption... options) { /** For entries, don't queue (for readQueue) value updates for the entry's internal publisher. */ public boolean excludeSelf; + + /** + * For subscriptions, don't share the existence of the subscription with the network. Note this + * means updates will not be received from the network unless another subscription overlaps with + * this one, and the subscription will not appear in metatopics. + */ + public boolean hidden; } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayEntryImpl.java b/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayEntryImpl.java index 4e8a4a0495a..1e6b69ec0fd 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayEntryImpl.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayEntryImpl.java @@ -177,15 +177,14 @@ private T[] fromRaw(byte[] raw, T[] defaultValue) { @SuppressWarnings("PMD.AvoidCatchingGenericException") private TimestampedObject fromRaw(TimestampedRaw raw, T[] defaultValue) { if (raw.value.length == 0) { - return new TimestampedObject(0, 0, defaultValue); + return new TimestampedObject<>(0, 0, defaultValue); } try { synchronized (m_buf) { - return new TimestampedObject( - raw.timestamp, raw.serverTime, m_buf.readArray(raw.value)); + return new TimestampedObject<>(raw.timestamp, raw.serverTime, m_buf.readArray(raw.value)); } } catch (RuntimeException e) { - return new TimestampedObject(0, 0, defaultValue); + return new TimestampedObject<>(0, 0, defaultValue); } } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayTopic.java b/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayTopic.java index 247501bbfa0..6f22179258a 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayTopic.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/StructArrayTopic.java @@ -32,7 +32,7 @@ private StructArrayTopic(NetworkTableInstance inst, int handle, Struct struct * @return StructArrayTopic for value class */ public static StructArrayTopic wrap(Topic topic, Struct struct) { - return new StructArrayTopic(topic, struct); + return new StructArrayTopic<>(topic, struct); } /** @@ -47,7 +47,7 @@ public static StructArrayTopic wrap(Topic topic, Struct struct) { */ public static StructArrayTopic wrap( NetworkTableInstance inst, int handle, Struct struct) { - return new StructArrayTopic(inst, handle, struct); + return new StructArrayTopic<>(inst, handle, struct); } /** @@ -63,7 +63,7 @@ public static StructArrayTopic wrap( * @return subscriber */ public StructArraySubscriber subscribe(T[] defaultValue, PubSubOption... options) { - return new StructArrayEntryImpl( + return new StructArrayEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.subscribe( @@ -87,7 +87,7 @@ public StructArraySubscriber subscribe(T[] defaultValue, PubSubOption... opti */ public StructArrayPublisher publish(PubSubOption... options) { m_inst.addSchema(m_struct); - return new StructArrayEntryImpl( + return new StructArrayEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.publish( @@ -113,7 +113,7 @@ public StructArrayPublisher publish(PubSubOption... options) { */ public StructArrayPublisher publishEx(String properties, PubSubOption... options) { m_inst.addSchema(m_struct); - return new StructArrayEntryImpl( + return new StructArrayEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.publishEx( @@ -144,7 +144,7 @@ public StructArrayPublisher publishEx(String properties, PubSubOption... opti * @return entry */ public StructArrayEntry getEntry(T[] defaultValue, PubSubOption... options) { - return new StructArrayEntryImpl( + return new StructArrayEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.getEntry( @@ -153,6 +153,11 @@ public StructArrayEntry getEntry(T[] defaultValue, PubSubOption... options) { false); } + /** + * Returns the struct. + * + * @return The struct. + */ public Struct getStruct() { return m_struct; } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/StructEntryImpl.java b/ntcore/src/main/java/edu/wpi/first/networktables/StructEntryImpl.java index bd02d27fe5d..5d377657075 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/StructEntryImpl.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/StructEntryImpl.java @@ -188,14 +188,14 @@ private T fromRaw(byte[] raw, T defaultValue) { @SuppressWarnings("PMD.AvoidCatchingGenericException") private TimestampedObject fromRaw(TimestampedRaw raw, T defaultValue) { if (raw.value.length == 0) { - return new TimestampedObject(0, 0, defaultValue); + return new TimestampedObject<>(0, 0, defaultValue); } try { synchronized (m_buf) { - return new TimestampedObject(raw.timestamp, raw.serverTime, m_buf.read(raw.value)); + return new TimestampedObject<>(raw.timestamp, raw.serverTime, m_buf.read(raw.value)); } } catch (RuntimeException e) { - return new TimestampedObject(0, 0, defaultValue); + return new TimestampedObject<>(0, 0, defaultValue); } } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/StructTopic.java b/ntcore/src/main/java/edu/wpi/first/networktables/StructTopic.java index b1ff0264f3c..1212ead7003 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/StructTopic.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/StructTopic.java @@ -32,7 +32,7 @@ private StructTopic(NetworkTableInstance inst, int handle, Struct struct) { * @return StructTopic for value class */ public static StructTopic wrap(Topic topic, Struct struct) { - return new StructTopic(topic, struct); + return new StructTopic<>(topic, struct); } /** @@ -46,7 +46,7 @@ public static StructTopic wrap(Topic topic, Struct struct) { * @return StructTopic for value class */ public static StructTopic wrap(NetworkTableInstance inst, int handle, Struct struct) { - return new StructTopic(inst, handle, struct); + return new StructTopic<>(inst, handle, struct); } /** @@ -62,7 +62,7 @@ public static StructTopic wrap(NetworkTableInstance inst, int handle, Str * @return subscriber */ public StructSubscriber subscribe(T defaultValue, PubSubOption... options) { - return new StructEntryImpl( + return new StructEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.subscribe( @@ -86,7 +86,7 @@ public StructSubscriber subscribe(T defaultValue, PubSubOption... options) { */ public StructPublisher publish(PubSubOption... options) { m_inst.addSchema(m_struct); - return new StructEntryImpl( + return new StructEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.publish( @@ -112,7 +112,7 @@ public StructPublisher publish(PubSubOption... options) { */ public StructPublisher publishEx(String properties, PubSubOption... options) { m_inst.addSchema(m_struct); - return new StructEntryImpl( + return new StructEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.publishEx( @@ -143,7 +143,7 @@ public StructPublisher publishEx(String properties, PubSubOption... options) * @return entry */ public StructEntry getEntry(T defaultValue, PubSubOption... options) { - return new StructEntryImpl( + return new StructEntryImpl<>( this, StructBuffer.create(m_struct), NetworkTablesJNI.getEntry( @@ -152,6 +152,11 @@ public StructEntry getEntry(T defaultValue, PubSubOption... options) { false); } + /** + * Returns the struct. + * + * @return The struct. + */ public Struct getStruct() { return m_struct; } diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/TimestampedObject.java b/ntcore/src/main/java/edu/wpi/first/networktables/TimestampedObject.java index 37c15447936..896ec795a3b 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/TimestampedObject.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/TimestampedObject.java @@ -4,7 +4,11 @@ package edu.wpi.first.networktables; -/** NetworkTables timestamped object. */ +/** + * NetworkTables timestamped object. + * + * @param Value type. + */ public final class TimestampedObject { /** * Create a timestamped value. diff --git a/ntcore/src/main/java/edu/wpi/first/networktables/Topic.java b/ntcore/src/main/java/edu/wpi/first/networktables/Topic.java index db08a344d28..358814c4c21 100644 --- a/ntcore/src/main/java/edu/wpi/first/networktables/Topic.java +++ b/ntcore/src/main/java/edu/wpi/first/networktables/Topic.java @@ -117,6 +117,25 @@ public boolean isRetained() { return NetworkTablesJNI.getTopicRetained(m_handle); } + /** + * Allow storage of the topic's last value, allowing the value to be read (and not just accessed + * through event queues and listeners). + * + * @param cached True for cached, false for not cached. + */ + public void setCached(boolean cached) { + NetworkTablesJNI.setTopicCached(m_handle, cached); + } + + /** + * Returns whether the topic's last value is stored. + * + * @return True if the topic is cached. + */ + public boolean isCached() { + return NetworkTablesJNI.getTopicCached(m_handle); + } + /** * Determines if the topic is currently being published. * @@ -317,6 +336,9 @@ public int hashCode() { return m_handle; } + /** NetworkTables instance. */ protected NetworkTableInstance m_inst; + + /** NetworkTables handle. */ protected int m_handle; } diff --git a/ntcore/src/main/native/cpp/LocalStorage.cpp b/ntcore/src/main/native/cpp/LocalStorage.cpp index 4591ff55b0b..7d1c3e4dc0d 100644 --- a/ntcore/src/main/native/cpp/LocalStorage.cpp +++ b/ntcore/src/main/native/cpp/LocalStorage.cpp @@ -46,10 +46,17 @@ bool LocalStorage::MultiSubscriberData::Matches(std::string_view name, } int LocalStorage::DataLoggerData::Start(TopicData* topic, int64_t time) { + std::string_view typeStr = topic->typeStr; + // NT and DataLog use different standard representations for int and int[] + if (typeStr == "int") { + typeStr = "int64"; + } else if (typeStr == "int[]") { + typeStr = "int64[]"; + } return log.Start(fmt::format("{}{}", logPrefix, wpi::drop_front(topic->name, prefix.size())), - topic->typeStr == "int" ? "int64" : topic->typeStr, - DataLoggerEntry::MakeMetadata(topic->propertiesStr), time); + typeStr, DataLoggerEntry::MakeMetadata(topic->propertiesStr), + time); } void LocalStorage::DataLoggerEntry::Append(const Value& v) { @@ -175,22 +182,26 @@ void LocalStorage::Impl::CheckReset(TopicData* topic) { } bool LocalStorage::Impl::SetValue(TopicData* topic, const Value& value, - unsigned int eventFlags, bool isDuplicate, + unsigned int eventFlags, bool suppressIfDuplicate, const PublisherData* publisher) { + const bool isDuplicate = topic->IsCached() && topic->lastValue == value; DEBUG4("SetValue({}, {}, {}, {})", topic->name, value.time(), eventFlags, isDuplicate); if (topic->type != NT_UNASSIGNED && topic->type != value.type()) { return false; } + // Make sure value isn't older than last value if (!topic->lastValue || topic->lastValue.time() == 0 || value.time() >= topic->lastValue.time()) { // TODO: notify option even if older value if (!(suppressIfDuplicate && isDuplicate)) { topic->type = value.type(); - topic->lastValue = value; - topic->lastValueFromNetwork = false; - NotifyValue(topic, eventFlags, isDuplicate, publisher); + if (topic->IsCached()) { + topic->lastValue = value; + topic->lastValueFromNetwork = false; + } + NotifyValue(topic, value, eventFlags, isDuplicate, publisher); if (topic->datalogType == value.type()) { for (auto&& datalog : topic->datalogs) { datalog.Append(value); @@ -202,8 +213,8 @@ bool LocalStorage::Impl::SetValue(TopicData* topic, const Value& value, return true; } -void LocalStorage::Impl::NotifyValue(TopicData* topic, unsigned int eventFlags, - bool isDuplicate, +void LocalStorage::Impl::NotifyValue(TopicData* topic, const Value& value, + unsigned int eventFlags, bool isDuplicate, const PublisherData* publisher) { bool isNetwork = (eventFlags & NT_EVENT_VALUE_REMOTE) != 0; for (auto&& subscriber : topic->localSubscribers) { @@ -213,11 +224,11 @@ void LocalStorage::Impl::NotifyValue(TopicData* topic, unsigned int eventFlags, (!isNetwork && !subscriber->config.disableLocal)) && (!publisher || (publisher && (subscriber->config.excludePublisher != publisher->handle)))) { - subscriber->pollStorage.emplace_back(topic->lastValue); + subscriber->pollStorage.emplace_back(value); subscriber->handle.Set(); if (!subscriber->valueListeners.empty()) { m_listenerStorage.Notify(subscriber->valueListeners, eventFlags, - topic->handle, 0, topic->lastValue); + topic->handle, 0, value); } } } @@ -227,7 +238,7 @@ void LocalStorage::Impl::NotifyValue(TopicData* topic, unsigned int eventFlags, subscriber->handle.Set(); if (!subscriber->valueListeners.empty()) { m_listenerStorage.Notify(subscriber->valueListeners, eventFlags, - topic->handle, 0, topic->lastValue); + topic->handle, 0, value); } } } @@ -249,6 +260,22 @@ void LocalStorage::Impl::SetFlags(TopicData* topic, unsigned int flags) { topic->properties.erase("retained"); update["retained"] = wpi::json(); } + if ((flags & NT_UNCACHED) != 0) { + topic->properties["cached"] = false; + update["cached"] = false; + } else { + topic->properties.erase("cached"); + update["cached"] = wpi::json(); + } + if ((flags & NT_UNCACHED) != 0) { + topic->lastValue = {}; + topic->lastValueNetwork = {}; + topic->lastValueFromNetwork = false; + } + if ((flags & NT_UNCACHED) != 0 && (flags & NT_PERSISTENT) != 0) { + WARN("topic {}: disabling cached property disables persistent storage", + topic->name); + } topic->flags = flags; if (!update.empty()) { PropertiesUpdated(topic, update, NT_EVENT_NONE, true, false); @@ -283,6 +310,20 @@ void LocalStorage::Impl::SetRetained(TopicData* topic, bool value) { PropertiesUpdated(topic, update, NT_EVENT_NONE, true, false); } +void LocalStorage::Impl::SetCached(TopicData* topic, bool value) { + wpi::json update = wpi::json::object(); + if (value) { + topic->flags &= ~NT_UNCACHED; + topic->properties.erase("cached"); + update["cached"] = wpi::json(); + } else { + topic->flags |= NT_UNCACHED; + topic->properties["cached"] = false; + update["cached"] = false; + } + PropertiesUpdated(topic, update, NT_EVENT_NONE, true, false); +} + void LocalStorage::Impl::SetProperties(TopicData* topic, const wpi::json& update, bool sendNetwork) { @@ -328,6 +369,28 @@ void LocalStorage::Impl::PropertiesUpdated(TopicData* topic, } } } + it = topic->properties.find("cached"); + if (it != topic->properties.end()) { + if (auto val = it->get_ptr()) { + if (*val) { + topic->flags &= ~NT_UNCACHED; + } else { + topic->flags |= NT_UNCACHED; + } + } + } + + if ((topic->flags & NT_UNCACHED) != 0) { + topic->lastValue = {}; + topic->lastValueNetwork = {}; + topic->lastValueFromNetwork = false; + } + + if ((topic->flags & NT_UNCACHED) != 0 && + (topic->flags & NT_PERSISTENT) != 0) { + WARN("topic {}: disabling cached property disables persistent storage", + topic->name); + } } topic->propertiesStr = topic->properties.dump(); @@ -548,7 +611,7 @@ LocalStorage::SubscriberData* LocalStorage::Impl::AddLocalSubscriber( "published as '{}')", topic->name, config.typeStr, topic->typeStr); } - if (m_network) { + if (m_network && !subscriber->config.hidden) { DEBUG4("-> NetworkSubscribe({})", topic->name); m_network->Subscribe(subscriber->handle, {{topic->name}}, config); } @@ -577,7 +640,7 @@ LocalStorage::Impl::RemoveLocalSubscriber(NT_Subscriber subHandle) { listener.getSecond()->subscriber = nullptr; } } - if (m_network) { + if (m_network && !subscriber->config.hidden) { m_network->Unsubscribe(subscriber->handle); } } @@ -613,7 +676,7 @@ LocalStorage::MultiSubscriberData* LocalStorage::Impl::AddMultiSubscriber( } } } - if (m_network) { + if (m_network && !subscriber->options.hidden) { DEBUG4("-> NetworkSubscribe"); m_network->Subscribe(subscriber->handle, subscriber->prefixes, subscriber->options); @@ -633,7 +696,7 @@ LocalStorage::Impl::RemoveMultiSubscriber(NT_MultiSubscriber subHandle) { listener.getSecond()->multiSubscriber = nullptr; } } - if (m_network) { + if (m_network && !subscriber->options.hidden) { m_network->Unsubscribe(subscriber->handle); } } @@ -895,20 +958,22 @@ bool LocalStorage::Impl::PublishLocalValue(PublisherData* publisher, return false; } if (publisher->active) { - bool isDuplicate, isNetworkDuplicate, suppressDuplicates; + bool isNetworkDuplicate, suppressDuplicates; if (force || publisher->config.keepDuplicates) { suppressDuplicates = false; isNetworkDuplicate = false; } else { suppressDuplicates = true; - isNetworkDuplicate = (publisher->topic->lastValueNetwork == value); + isNetworkDuplicate = publisher->topic->IsCached() && + (publisher->topic->lastValueNetwork == value); } - isDuplicate = (publisher->topic->lastValue == value); if (!isNetworkDuplicate && m_network) { - publisher->topic->lastValueNetwork = value; + if (publisher->topic->IsCached()) { + publisher->topic->lastValueNetwork = value; + } m_network->SetValue(publisher->handle, value); } - return SetValue(publisher->topic, value, NT_EVENT_VALUE_LOCAL, isDuplicate, + return SetValue(publisher->topic, value, NT_EVENT_VALUE_LOCAL, suppressDuplicates, publisher); } else { return false; @@ -940,6 +1005,10 @@ bool LocalStorage::Impl::SetDefaultEntryValue(NT_Handle pubsubentryHandle, return false; } if (auto topic = GetTopic(pubsubentryHandle)) { + if (!topic->IsCached()) { + WARN("ignoring default value on non-cached topic '{}'", topic->name); + return false; + } if (!topic->lastValue && (topic->type == NT_UNASSIGNED || topic->type == value.type() || IsNumericCompatible(topic->type, value.type()))) { @@ -1026,10 +1095,11 @@ void LocalStorage::NetworkPropertiesUpdate(std::string_view name, void LocalStorage::NetworkSetValue(NT_Topic topicHandle, const Value& value) { std::scoped_lock lock{m_mutex}; if (auto topic = m_impl.m_topics.Get(topicHandle)) { - if (m_impl.SetValue(topic, value, NT_EVENT_VALUE_REMOTE, - value == topic->lastValue, false, nullptr)) { - topic->lastValueNetwork = value; - topic->lastValueFromNetwork = true; + if (m_impl.SetValue(topic, value, NT_EVENT_VALUE_REMOTE, false, nullptr)) { + if (topic->IsCached()) { + topic->lastValueNetwork = value; + topic->lastValueFromNetwork = true; + } } } } @@ -1058,12 +1128,16 @@ void LocalStorage::Impl::StartNetwork(net::NetworkInterface* network) { } } for (auto&& subscriber : m_subscribers) { - network->Subscribe(subscriber->handle, {{subscriber->topic->name}}, - subscriber->config); + if (!subscriber->config.hidden) { + network->Subscribe(subscriber->handle, {{subscriber->topic->name}}, + subscriber->config); + } } for (auto&& subscriber : m_multiSubscribers) { - network->Subscribe(subscriber->handle, subscriber->prefixes, - subscriber->options); + if (!subscriber->options.hidden) { + network->Subscribe(subscriber->handle, subscriber->prefixes, + subscriber->options); + } } } diff --git a/ntcore/src/main/native/cpp/LocalStorage.h b/ntcore/src/main/native/cpp/LocalStorage.h index af2b4debe04..44951137e61 100644 --- a/ntcore/src/main/native/cpp/LocalStorage.h +++ b/ntcore/src/main/native/cpp/LocalStorage.h @@ -136,6 +136,22 @@ class LocalStorage final : public net::ILocalStorage { } } + void SetTopicCached(NT_Topic topicHandle, bool value) { + std::scoped_lock lock{m_mutex}; + if (auto topic = m_impl.m_topics.Get(topicHandle)) { + m_impl.SetCached(topic, value); + } + } + + bool GetTopicCached(NT_Topic topicHandle) { + std::scoped_lock lock{m_mutex}; + if (auto topic = m_impl.m_topics.Get(topicHandle)) { + return (topic->flags & NT_UNCACHED) == 0; + } else { + return false; + } + } + bool GetTopicExists(NT_Handle handle) { std::scoped_lock lock{m_mutex}; TopicData* topic = m_impl.GetTopic(handle); @@ -238,13 +254,13 @@ class LocalStorage final : public net::ILocalStorage { wpi::SmallVectorImpl::SmallElem>& buf, typename TypeInfo::View defaultValue); - std::vector ReadQueueValue(NT_Handle subentry) { + std::vector ReadQueueValue(NT_Handle subentry, unsigned int types) { std::scoped_lock lock{m_mutex}; auto subscriber = m_impl.GetSubEntry(subentry); if (!subscriber) { return {}; } - return subscriber->pollStorage.ReadValue(); + return subscriber->pollStorage.ReadValue(types); } template @@ -361,6 +377,8 @@ class LocalStorage final : public net::ILocalStorage { bool Exists() const { return onNetwork || !localPublishers.empty(); } + bool IsCached() const { return (flags & NT_UNCACHED) == 0; } + TopicInfo GetTopicInfo() const; // invariants @@ -565,14 +583,15 @@ class LocalStorage final : public net::ILocalStorage { void CheckReset(TopicData* topic); bool SetValue(TopicData* topic, const Value& value, unsigned int eventFlags, - bool isDuplicate, bool suppressIfDuplicate, - const PublisherData* publisher); - void NotifyValue(TopicData* topic, unsigned int eventFlags, - bool isDuplicate, const PublisherData* publisher); + bool suppressIfDuplicate, const PublisherData* publisher); + void NotifyValue(TopicData* topic, const Value& value, + unsigned int eventFlags, bool isDuplicate, + const PublisherData* publisher); void SetFlags(TopicData* topic, unsigned int flags); void SetPersistent(TopicData* topic, bool value); void SetRetained(TopicData* topic, bool value); + void SetCached(TopicData* topic, bool value); void SetProperties(TopicData* topic, const wpi::json& update, bool sendNetwork); void PropertiesUpdated(TopicData* topic, const wpi::json& update, diff --git a/ntcore/src/main/native/cpp/LoggerImpl.cpp b/ntcore/src/main/native/cpp/LoggerImpl.cpp index f5742d5d982..4e49070b3d4 100644 --- a/ntcore/src/main/native/cpp/LoggerImpl.cpp +++ b/ntcore/src/main/native/cpp/LoggerImpl.cpp @@ -4,10 +4,10 @@ #include "LoggerImpl.h" -#include #include #include #include +#include #include "IListenerStorage.h" @@ -16,7 +16,7 @@ using namespace nt; static void DefaultLogger(unsigned int level, const char* file, unsigned int line, const char* msg) { if (level == wpi::WPI_LOG_INFO) { - fmt::print(stderr, "NT: {}\n", msg); + wpi::print(stderr, "NT: {}\n", msg); return; } @@ -30,7 +30,7 @@ static void DefaultLogger(unsigned int level, const char* file, } else { return; } - fmt::print(stderr, "NT: {}: {} ({}:{})\n", levelmsg, msg, file, line); + wpi::print(stderr, "NT: {}: {} ({}:{})\n", levelmsg, msg, file, line); } static constexpr unsigned int kFlagCritical = 1u << 16; diff --git a/ntcore/src/main/native/cpp/NetworkClient.cpp b/ntcore/src/main/native/cpp/NetworkClient.cpp index 7634be988b9..477ade1a72d 100644 --- a/ntcore/src/main/native/cpp/NetworkClient.cpp +++ b/ntcore/src/main/native/cpp/NetworkClient.cpp @@ -206,7 +206,9 @@ void NetworkClient3::TcpConnected(uv::Tcp& tcp) { auto clientImpl = std::make_shared( m_loop.Now().count(), m_inst, *wire, m_logger, [this](uint32_t repeatMs) { DEBUG4("Setting periodic timer to {}", repeatMs); - if (m_sendOutgoingTimer) { + if (m_sendOutgoingTimer && + (!m_sendOutgoingTimer->IsActive() || + uv::Timer::Time{repeatMs} != m_sendOutgoingTimer->GetRepeat())) { m_sendOutgoingTimer->Start(uv::Timer::Time{repeatMs}, uv::Timer::Time{repeatMs}); } @@ -360,6 +362,7 @@ void NetworkClient::HandleLocal() { } void NetworkClient::TcpConnected(uv::Tcp& tcp) { + tcp.SetLogger(&m_logger); tcp.SetNoDelay(true); // Start the WS client if (m_logger.min_level() >= wpi::WPI_LOG_DEBUG4) { @@ -399,14 +402,15 @@ void NetworkClient::WsConnected(wpi::WebSocket& ws, uv::Tcp& tcp, INFO("CONNECTED NT4 to {} port {}", connInfo.remote_ip, connInfo.remote_port); m_connHandle = m_connList.AddConnection(connInfo); - m_wire = - std::make_shared(ws, connInfo.protocol_version); - m_wire->Start(); + m_wire = std::make_shared( + ws, connInfo.protocol_version, m_logger); m_clientImpl = std::make_unique( m_loop.Now().count(), m_inst, *m_wire, m_logger, m_timeSyncUpdated, [this](uint32_t repeatMs) { DEBUG4("Setting periodic timer to {}", repeatMs); - if (m_sendOutgoingTimer) { + if (m_sendOutgoingTimer && + (!m_sendOutgoingTimer->IsActive() || + uv::Timer::Time{repeatMs} != m_sendOutgoingTimer->GetRepeat())) { m_sendOutgoingTimer->Start(uv::Timer::Time{repeatMs}, uv::Timer::Time{repeatMs}); } diff --git a/ntcore/src/main/native/cpp/NetworkServer.cpp b/ntcore/src/main/native/cpp/NetworkServer.cpp index 9062c7fec50..26dd9408297 100644 --- a/ntcore/src/main/native/cpp/NetworkServer.cpp +++ b/ntcore/src/main/native/cpp/NetworkServer.cpp @@ -112,7 +112,8 @@ void NetworkServer::ServerConnection::UpdateOutgoingTimer(uint32_t repeatMs) { DEBUG4("Setting periodic timer to {}", repeatMs); if (repeatMs == UINT32_MAX) { m_outgoingTimer->Stop(); - } else { + } else if (!m_outgoingTimer->IsActive() || + uv::Timer::Time{repeatMs} != m_outgoingTimer->GetRepeat()) { m_outgoingTimer->Start(uv::Timer::Time{repeatMs}, uv::Timer::Time{repeatMs}); } @@ -241,7 +242,7 @@ void NetworkServer::ServerConnection4::ProcessWsUpgrade() { m_info.protocol_version = protocol == "v4.1.networktables.first.wpi.edu" ? 0x0401 : 0x0400; m_wire = std::make_shared( - *m_websocket, m_info.protocol_version); + *m_websocket, m_info.protocol_version, m_logger); if (protocol == "rtt.networktables.first.wpi.edu") { INFO("CONNECTED RTT client (from {})", m_connInfo); @@ -280,7 +281,6 @@ void NetworkServer::ServerConnection4::ProcessWsUpgrade() { INFO("CONNECTED NT4 client '{}' (from {})", dedupName, m_connInfo); m_info.remote_id = dedupName; m_server.AddConnection(this, m_info); - m_wire->Start(); m_websocket->closed.connect([this](uint16_t, std::string_view reason) { auto realReason = m_wire->GetDisconnectReason(); INFO("DISCONNECTED NT4 client '{}' (from {}): {}", m_info.remote_id, @@ -323,8 +323,7 @@ NetworkServer::NetworkServer(std::string_view persistentFilename, HandleLocal(); // load persistent file first, then initialize - uv::QueueWork( - m_loop, [this] { LoadPersistent(); }, [this] { Init(); }); + uv::QueueWork(m_loop, [this] { LoadPersistent(); }, [this] { Init(); }); }); } @@ -360,6 +359,9 @@ void NetworkServer::LoadPersistent() { "could not open persistent file '{}': {} " "(this can be ignored if you aren't expecting persistent values)", m_persistentFilename, ec.message()); + // backup file + fs::copy_file(m_persistentFilename, m_persistentFilename + ".bak", + std::filesystem::copy_options::overwrite_existing, ec); // try to write an empty file so it doesn't happen again wpi::raw_fd_ostream os{m_persistentFilename, ec, fs::F_Text}; if (ec.value() == 0) { @@ -499,6 +501,7 @@ void NetworkServer::Init() { if (!tcp) { return; } + tcp->SetLogger(&m_logger); tcp->error.connect([logger = &m_logger](uv::Error err) { WPI_INFO(*logger, "NT4 socket error: {}", err.str()); }); diff --git a/ntcore/src/main/native/cpp/Value.cpp b/ntcore/src/main/native/cpp/Value.cpp index 09ba775b899..28765487ae2 100644 --- a/ntcore/src/main/native/cpp/Value.cpp +++ b/ntcore/src/main/native/cpp/Value.cpp @@ -32,7 +32,7 @@ struct StringArrayStorage { size_t EstimateSize() const { return sizeof(StringArrayStorage) + strings.capacity() * sizeof(std::string) + - ntStrings.capacity() * sizeof(NT_String) + + ntStrings.capacity() * sizeof(WPI_String) + std::accumulate(strings.begin(), strings.end(), 0, [](const auto& sum, const auto& val) { return sum + val.capacity(); @@ -40,7 +40,7 @@ struct StringArrayStorage { } std::vector strings; - std::vector ntStrings; + std::vector ntStrings; }; template @@ -58,11 +58,11 @@ inline std::shared_ptr AllocateArray(size_t nelem) { } // namespace void StringArrayStorage::InitNtStrings() { - // point NT_String's to the contents in the vector. + // point WPI_String's to the contents in the vector. ntStrings.reserve(strings.size()); for (const auto& str : strings) { ntStrings.emplace_back( - NT_String{const_cast(str.c_str()), str.size()}); + WPI_String{const_cast(str.c_str()), str.size()}); } } @@ -250,8 +250,7 @@ void nt::ConvertToC(const Value& in, NT_Value* out) { } case NT_STRING_ARRAY: { auto v = in.GetStringArray(); - out->data.arr_string.arr = static_cast( - wpi::safe_malloc(v.size() * sizeof(NT_String))); + out->data.arr_string.arr = WPI_AllocateStringArray(v.size()); for (size_t i = 0; i < v.size(); ++i) { ConvertToC(std::string_view{v[i]}, &out->data.arr_string.arr[i]); } @@ -263,18 +262,14 @@ void nt::ConvertToC(const Value& in, NT_Value* out) { } } -size_t nt::ConvertToC(std::string_view in, char** out) { - *out = static_cast(wpi::safe_malloc(in.size() + 1)); - std::memmove(*out, in.data(), in.size()); // NOLINT - (*out)[in.size()] = '\0'; - return in.size(); -} - -void nt::ConvertToC(std::string_view in, NT_String* out) { - out->len = in.size(); - out->str = static_cast(wpi::safe_malloc(in.size() + 1)); - std::memcpy(out->str, in.data(), in.size()); - out->str[in.size()] = '\0'; +void nt::ConvertToC(std::string_view in, WPI_String* out) { + if (in.empty()) { + out->len = 0; + out->str = nullptr; + return; + } + auto write = WPI_AllocateString(out, in.size()); + std::memcpy(write, in.data(), in.size()); } Value nt::ConvertFromC(const NT_Value& value) { diff --git a/ntcore/src/main/native/cpp/ValueCircularBuffer.cpp b/ntcore/src/main/native/cpp/ValueCircularBuffer.cpp index f611a335d98..55c2968616e 100644 --- a/ntcore/src/main/native/cpp/ValueCircularBuffer.cpp +++ b/ntcore/src/main/native/cpp/ValueCircularBuffer.cpp @@ -6,10 +6,13 @@ using namespace nt; -std::vector ValueCircularBuffer::ReadValue() { +std::vector ValueCircularBuffer::ReadValue(unsigned int types) { std::vector rv; rv.reserve(m_storage.size()); for (auto&& val : m_storage) { + if (types != 0 && (types & val.type()) == 0) { + continue; + } rv.emplace_back(std::move(val)); } m_storage.reset(); diff --git a/ntcore/src/main/native/cpp/ValueCircularBuffer.h b/ntcore/src/main/native/cpp/ValueCircularBuffer.h index b80b5db6bbb..9ea01718a77 100644 --- a/ntcore/src/main/native/cpp/ValueCircularBuffer.h +++ b/ntcore/src/main/native/cpp/ValueCircularBuffer.h @@ -24,7 +24,7 @@ class ValueCircularBuffer { m_storage.emplace_back(std::forward(args...)); } - std::vector ReadValue(); + std::vector ReadValue(unsigned int types); template std::vector::Value>> Read(); diff --git a/ntcore/src/main/native/cpp/Value_internal.h b/ntcore/src/main/native/cpp/Value_internal.h index 8f2c8fb1382..fd633f13005 100644 --- a/ntcore/src/main/native/cpp/Value_internal.h +++ b/ntcore/src/main/native/cpp/Value_internal.h @@ -420,8 +420,8 @@ inline void ConvertToC(const T& in, T* out) { void ConvertToC(const Value& in, NT_Value* out); Value ConvertFromC(const NT_Value& value); size_t ConvertToC(std::string_view in, char** out); -void ConvertToC(std::string_view in, NT_String* out); -inline std::string_view ConvertFromC(const NT_String& str) { +void ConvertToC(std::string_view in, WPI_String* out); +inline std::string_view ConvertFromC(const WPI_String& str) { return {str.str, str.len}; } diff --git a/ntcore/src/main/native/cpp/jni/NetworkTablesJNI.cpp b/ntcore/src/main/native/cpp/jni/NetworkTablesJNI.cpp index 14b5df16749..ae10656bb99 100644 --- a/ntcore/src/main/native/cpp/jni/NetworkTablesJNI.cpp +++ b/ntcore/src/main/native/cpp/jni/NetworkTablesJNI.cpp @@ -139,6 +139,7 @@ static nt::PubSubOptions FromJavaPubSubOptions(JNIEnv* env, jobject joptions) { FIELD(disableRemote, "Z"); FIELD(disableLocal, "Z"); FIELD(excludeSelf, "Z"); + FIELD(hidden, "Z"); #undef FIELD @@ -154,7 +155,8 @@ static nt::PubSubOptions FromJavaPubSubOptions(JNIEnv* env, jobject joptions) { FIELD(bool, Boolean, prefixMatch), FIELD(bool, Boolean, disableRemote), FIELD(bool, Boolean, disableLocal), - FIELD(bool, Boolean, excludeSelf)}; + FIELD(bool, Boolean, excludeSelf), + FIELD(bool, Boolean, hidden)}; #undef GET #undef FIELD @@ -671,6 +673,30 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_getTopicRetained return nt::GetTopicRetained(topic); } +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: setTopicCached + * Signature: (IZ)V + */ +JNIEXPORT void JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_setTopicCached + (JNIEnv*, jclass, jint topic, jboolean value) +{ + nt::SetTopicCached(topic, value); +} + +/* + * Class: edu_wpi_first_networktables_NetworkTablesJNI + * Method: getTopicCached + * Signature: (I)Z + */ +JNIEXPORT jboolean JNICALL +Java_edu_wpi_first_networktables_NetworkTablesJNI_getTopicCached + (JNIEnv*, jclass, jint topic) +{ + return nt::GetTopicCached(topic); +} + /* * Class: edu_wpi_first_networktables_NetworkTablesJNI * Method: getTopicTypeString diff --git a/ntcore/src/main/native/cpp/net/ClientImpl.cpp b/ntcore/src/main/native/cpp/net/ClientImpl.cpp index 309b01a0d05..96a6be76410 100644 --- a/ntcore/src/main/native/cpp/net/ClientImpl.cpp +++ b/ntcore/src/main/native/cpp/net/ClientImpl.cpp @@ -20,7 +20,6 @@ #include "NetworkInterface.h" #include "WireConnection.h" #include "WireEncoder.h" -#include "net/NetworkOutgoingQueue.h" #include "networktables/NetworkTableValue.h" using namespace nt; @@ -68,26 +67,28 @@ void ClientImpl::ProcessIncomingBinary(uint64_t curTimeMs, DEBUG4("BinaryMessage({})", id); // handle RTT ping response (only use first one) - if (!m_haveTimeOffset && id == -1) { - if (!value.IsInteger()) { - WARN("RTT ping response with non-integer type {}", - static_cast(value.type())); - continue; - } - DEBUG4("RTT ping response time {} value {}", value.time(), - value.GetInteger()); - if (m_wire.GetVersion() < 0x0401) { - m_pongTimeMs = curTimeMs; - } - int64_t now = wpi::Now(); - int64_t rtt2 = (now - value.GetInteger()) / 2; - if (rtt2 < m_rtt2Us) { - m_rtt2Us = rtt2; - int64_t serverTimeOffsetUs = value.server_time() + rtt2 - now; - DEBUG3("Time offset: {}", serverTimeOffsetUs); - m_outgoing.SetTimeOffset(serverTimeOffsetUs); - m_haveTimeOffset = true; - m_timeSyncUpdated(serverTimeOffsetUs, m_rtt2Us, true); + if (id == -1) { + if (!m_haveTimeOffset) { + if (!value.IsInteger()) { + WARN("RTT ping response with non-integer type {}", + static_cast(value.type())); + continue; + } + DEBUG4("RTT ping response time {} value {}", value.time(), + value.GetInteger()); + if (m_wire.GetVersion() < 0x0401) { + m_pongTimeMs = curTimeMs; + } + int64_t now = wpi::Now(); + int64_t rtt2 = (now - value.GetInteger()) / 2; + if (rtt2 < m_rtt2Us) { + m_rtt2Us = rtt2; + int64_t serverTimeOffsetUs = value.server_time() + rtt2 - now; + DEBUG3("Time offset: {}", serverTimeOffsetUs); + m_outgoing.SetTimeOffset(serverTimeOffsetUs); + m_haveTimeOffset = true; + m_timeSyncUpdated(serverTimeOffsetUs, m_rtt2Us, true); + } } continue; } diff --git a/ntcore/src/main/native/cpp/net/NetworkPing.cpp b/ntcore/src/main/native/cpp/net/NetworkPing.cpp index fdbd26c132a..e3d55a2b31b 100644 --- a/ntcore/src/main/native/cpp/net/NetworkPing.cpp +++ b/ntcore/src/main/native/cpp/net/NetworkPing.cpp @@ -12,14 +12,15 @@ bool NetworkPing::Send(uint64_t curTimeMs) { if (curTimeMs < m_nextPingTimeMs) { return true; } - // if we didn't receive a timely response to our last ping, disconnect - uint64_t lastPing = m_wire.GetLastPingResponse(); + // if we haven't received data in a while, disconnect + // (we should at least be getting PONG responses) + uint64_t lastData = m_wire.GetLastReceivedTime(); // DEBUG4("WS ping: lastPing={} curTime={} pongTimeMs={}\n", lastPing, // curTimeMs, m_pongTimeMs); - if (lastPing == 0) { - lastPing = m_pongTimeMs; + if (lastData == 0) { + lastData = m_pongTimeMs; } - if (m_pongTimeMs != 0 && curTimeMs > (lastPing + kPingTimeoutMs)) { + if (m_pongTimeMs != 0 && curTimeMs > (lastData + kPingTimeoutMs)) { m_wire.Disconnect("connection timed out"); return false; } diff --git a/ntcore/src/main/native/cpp/net/ServerImpl.cpp b/ntcore/src/main/native/cpp/net/ServerImpl.cpp index 111980918a7..0a9071dd9d7 100644 --- a/ntcore/src/main/native/cpp/net/ServerImpl.cpp +++ b/ntcore/src/main/native/cpp/net/ServerImpl.cpp @@ -917,6 +917,7 @@ void ServerImpl::ClientData3::EntryAssign(std::string_view name, auto typeStr = TypeToString(value.type()); wpi::json properties = wpi::json::object(); properties["retained"] = true; // treat all NT3 published topics as retained + properties["cached"] = true; // treat all NT3 published topics as cached if ((flags & NT_PERSISTENT) != 0) { properties["persistent"] = true; } @@ -1095,6 +1096,7 @@ bool ServerImpl::TopicData::SetProperties(const wpi::json& update) { void ServerImpl::TopicData::RefreshProperties() { persistent = false; retained = false; + cached = true; auto persistentIt = properties.find("persistent"); if (persistentIt != properties.end()) { @@ -1109,6 +1111,23 @@ void ServerImpl::TopicData::RefreshProperties() { retained = *val; } } + + auto cachedIt = properties.find("cached"); + if (cachedIt != properties.end()) { + if (auto val = cachedIt->get_ptr()) { + cached = *val; + } + } + + if (!cached) { + lastValue = {}; + lastValueClient = nullptr; + } + + if (!cached && persistent) { + WARN("topic {}: disabling cached property disables persistent storage", + name); + } } bool ServerImpl::TopicData::SetFlags(unsigned int flags_) { @@ -1122,6 +1141,30 @@ bool ServerImpl::TopicData::SetFlags(unsigned int flags_) { persistent = false; properties.erase("persistent"); } + if ((flags_ & NT_RETAINED) != 0) { + updated |= !retained; + retained = true; + properties["retained"] = true; + } else { + updated |= retained; + retained = false; + properties.erase("retained"); + } + if ((flags_ & NT_UNCACHED) != 0) { + updated |= cached; + cached = false; + properties["cached"] = false; + lastValue = {}; + lastValueClient = nullptr; + } else { + updated |= !cached; + cached = true; + properties.erase("cached"); + } + if (!cached && persistent) { + WARN("topic {}: disabling cached property disables persistent storage", + name); + } return updated; } @@ -1642,7 +1685,7 @@ ServerImpl::TopicData* ServerImpl::CreateTopic(ClientData* client, } else { // new topic unsigned int id = m_topics.emplace_back( - std::make_unique(name, typeStr, properties)); + std::make_unique(m_logger, name, typeStr, properties)); topic = m_topics[id].get(); topic->id = id; topic->special = special; @@ -1663,8 +1706,14 @@ ServerImpl::TopicData* ServerImpl::CreateTopic(ClientData* client, } auto& tcd = topic->clients[aClient.get()]; + bool added = false; for (auto subscriber : subscribers) { - tcd.AddSubscriber(subscriber); + if (tcd.AddSubscriber(subscriber)) { + added = true; + } + } + if (added) { + aClient->UpdatePeriod(tcd, topic); } if (aClient.get() == client) { @@ -1707,6 +1756,7 @@ void ServerImpl::DeleteTopic(TopicData* topic) { // unannounce to all subscribers for (auto&& tcd : topic->clients) { if (!tcd.second.subscribers.empty()) { + tcd.first->UpdatePeriod(tcd.second, topic); tcd.first->SendUnannounce(topic); } } @@ -1751,8 +1801,9 @@ void ServerImpl::SetFlags(ClientData* client, TopicData* topic, void ServerImpl::SetValue(ClientData* client, TopicData* topic, const Value& value) { // update retained value if from same client or timestamp newer - if (!topic->lastValue || topic->lastValueClient == client || - topic->lastValue.time() == 0 || value.time() >= topic->lastValue.time()) { + if (topic->cached && (!topic->lastValue || topic->lastValueClient == client || + topic->lastValue.time() == 0 || + value.time() >= topic->lastValue.time())) { DEBUG4("updating '{}' last value (time was {} is {})", topic->name, topic->lastValue.time(), value.time()); topic->lastValue = value; @@ -1765,7 +1816,8 @@ void ServerImpl::SetValue(ClientData* client, TopicData* topic, } for (auto&& tcd : topic->clients) { - if (tcd.second.sendMode != ValueSendMode::kDisabled) { + if (tcd.first != client && + tcd.second.sendMode != ValueSendMode::kDisabled) { tcd.first->SendValue(topic, value, tcd.second.sendMode); } } diff --git a/ntcore/src/main/native/cpp/net/ServerImpl.h b/ntcore/src/main/native/cpp/net/ServerImpl.h index 3ea5a82a2bf..d84a06ce299 100644 --- a/ntcore/src/main/native/cpp/net/ServerImpl.h +++ b/ntcore/src/main/native/cpp/net/ServerImpl.h @@ -98,11 +98,15 @@ class ServerImpl final { struct SubscriberData; struct TopicData { - TopicData(std::string_view name, std::string_view typeStr) - : name{name}, typeStr{typeStr} {} - TopicData(std::string_view name, std::string_view typeStr, - wpi::json properties) - : name{name}, typeStr{typeStr}, properties(std::move(properties)) { + TopicData(wpi::Logger& logger, std::string_view name, + std::string_view typeStr) + : m_logger{logger}, name{name}, typeStr{typeStr} {} + TopicData(wpi::Logger& logger, std::string_view name, + std::string_view typeStr, wpi::json properties) + : m_logger{logger}, + name{name}, + typeStr{typeStr}, + properties(std::move(properties)) { RefreshProperties(); } @@ -117,6 +121,7 @@ class ServerImpl final { NT_Handle GetIdHandle() const { return Handle(0, id, Handle::kTopic); } + wpi::Logger& m_logger; // Must be m_logger for WARN macro to work std::string name; unsigned int id; Value lastValue; @@ -126,6 +131,7 @@ class ServerImpl final { unsigned int publisherCount{0}; bool persistent{false}; bool retained{false}; + bool cached{true}; bool special{false}; NT_Topic localHandle{0}; @@ -148,10 +154,12 @@ class ServerImpl final { bool AddSubscriber(SubscriberData* sub) { bool added = subscribers.insert(sub).second; - if (!sub->options.topicsOnly && sendMode == ValueSendMode::kDisabled) { - sendMode = ValueSendMode::kNormal; - } else if (sub->options.sendAll) { - sendMode = ValueSendMode::kAll; + if (!sub->options.topicsOnly) { + if (sub->options.sendAll) { + sendMode = ValueSendMode::kAll; + } else if (sendMode == ValueSendMode::kDisabled) { + sendMode = ValueSendMode::kNormal; + } } return added; } @@ -200,9 +208,10 @@ class ServerImpl final { std::string_view GetName() const { return m_name; } int GetId() const { return m_id; } - protected: - virtual void UpdatePeriodic(TopicData* topic) {} + virtual void UpdatePeriod(TopicData::TopicClientData& tcd, + TopicData* topic) {} + protected: std::string m_name; std::string m_connInfo; bool m_local; // local to machine @@ -245,9 +254,6 @@ class ServerImpl final { void ClientSetValue(int64_t pubuid, const Value& value); - virtual void UpdatePeriod(TopicData::TopicClientData& tcd, - TopicData* topic) {} - wpi::DenseMap m_announceSent; }; diff --git a/ntcore/src/main/native/cpp/net/WebSocketConnection.cpp b/ntcore/src/main/native/cpp/net/WebSocketConnection.cpp index dcfbabe240d..595e724e0a1 100644 --- a/ntcore/src/main/native/cpp/net/WebSocketConnection.cpp +++ b/ntcore/src/main/native/cpp/net/WebSocketConnection.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -52,10 +53,20 @@ class WebSocketConnection::Stream final : public wpi::raw_ostream { void WebSocketConnection::Stream::write_impl(const char* data, size_t len) { if (data == m_conn.m_bufs.back().base) { // flush_nonempty() case + size_t amt = len - m_conn.m_bufs.back().len; + WPI_DEBUG4(m_conn.m_logger, "conn: writing {} bytes (nonempty)", amt); m_conn.m_bufs.back().len = len; + m_conn.m_framePos += amt; + m_conn.m_written += amt; if (!m_disableAlloc) { +#ifdef NT_ENABLE_WS_FRAG m_conn.m_frames.back().opcode &= ~wpi::WebSocket::kFlagFin; m_conn.StartFrame(wpi::WebSocket::Frame::kFragment); +#else + m_conn.m_bufs.emplace_back(m_conn.AllocBuf()); + m_conn.m_bufs.back().len = 0; + ++m_conn.m_frames.back().end; +#endif SetBuffer(m_conn.m_bufs.back().base, kAllocSize); } return; @@ -68,6 +79,7 @@ void WebSocketConnection::Stream::write_impl(const char* data, size_t len) { size_t amt = (std::min)(static_cast(kAllocSize - buf.len), static_cast(len)); if (amt > 0) { + WPI_DEBUG4(m_conn.m_logger, "conn: writing {} bytes", amt); std::memcpy(buf.base + buf.len, data, amt); buf.len += amt; m_conn.m_framePos += amt; @@ -76,9 +88,15 @@ void WebSocketConnection::Stream::write_impl(const char* data, size_t len) { len -= amt; } if (buf.len >= kAllocSize && (len > 0 || !m_disableAlloc)) { +#ifdef NT_ENABLE_WS_FRAG // fragment the current frame and start a new one m_conn.m_frames.back().opcode &= ~wpi::WebSocket::kFlagFin; m_conn.StartFrame(wpi::WebSocket::Frame::kFragment); +#else + m_conn.m_bufs.emplace_back(m_conn.AllocBuf()); + m_conn.m_bufs.back().len = 0; + ++m_conn.m_frames.back().end; +#endif updateBuffer = true; } } @@ -89,8 +107,9 @@ void WebSocketConnection::Stream::write_impl(const char* data, size_t len) { } WebSocketConnection::WebSocketConnection(wpi::WebSocket& ws, - unsigned int version) - : m_ws{ws}, m_version{version} {} + unsigned int version, + wpi::Logger& logger) + : m_ws{ws}, m_logger{logger}, m_version{version} {} WebSocketConnection::~WebSocketConnection() { for (auto&& buf : m_bufs) { @@ -101,22 +120,11 @@ WebSocketConnection::~WebSocketConnection() { } } -void WebSocketConnection::Start() { - m_ws.pong.connect([selfweak = weak_from_this()](auto data) { - if (data.size() != 8) { - return; - } - if (auto self = selfweak.lock()) { - self->m_lastPingResponse = - wpi::support::endian::read64(data.data()); - } - }); -} - void WebSocketConnection::SendPing(uint64_t time) { + WPI_DEBUG4(m_logger, "conn: sending ping {}", time); auto buf = AllocBuf(); buf.len = 8; - wpi::support::endian::write64(buf.base, time); + wpi::support::endian::write64(buf.base, time); m_ws.SendPing({buf}, [selfweak = weak_from_this()](auto bufs, auto err) { if (auto self = selfweak.lock()) { self->m_err = err; @@ -130,6 +138,8 @@ void WebSocketConnection::SendPing(uint64_t time) { } void WebSocketConnection::StartFrame(uint8_t opcode) { + WPI_DEBUG4(m_logger, "conn: starting frame {}", + static_cast(opcode)); m_frames.emplace_back(opcode, m_bufs.size(), m_bufs.size() + 1); m_bufs.emplace_back(AllocBuf()); m_bufs.back().len = 0; @@ -165,6 +175,7 @@ int WebSocketConnection::Write( if (kind == kText) { os << (first ? '[' : ','); } + WPI_DEBUG4(m_logger, "writing"); writer(os); } ++m_frames.back().count; @@ -176,6 +187,7 @@ int WebSocketConnection::Write( } int WebSocketConnection::Flush() { + WPI_DEBUG4(m_logger, "conn: flushing"); m_lastFlushTime = wpi::Now(); if (m_state == kEmpty) { return 0; @@ -221,6 +233,8 @@ int WebSocketConnection::Flush() { int count = 0; for (auto&& frame : wpi::take_back(std::span{m_frames}, unsentFrames.size())) { + ReleaseBufs( + std::span{m_bufs}.subspan(frame.start, frame.end - frame.start)); count += frame.count; } m_frames.clear(); @@ -240,6 +254,7 @@ void WebSocketConnection::Send( os << ']'; } wpi::WebSocket::Frame frame{opcode, os.bufs()}; + WPI_DEBUG4(m_logger, "Send({})", static_cast(opcode)); m_ws.SendFrames({{frame}}, [selfweak = weak_from_this()](auto bufs, auto) { if (auto self = selfweak.lock()) { self->ReleaseBufs(bufs); @@ -253,7 +268,7 @@ void WebSocketConnection::Send( void WebSocketConnection::Disconnect(std::string_view reason) { m_reason = reason; - m_ws.Fail(1005, reason); + m_ws.Fail(1001, reason); } wpi::uv::Buffer WebSocketConnection::AllocBuf() { diff --git a/ntcore/src/main/native/cpp/net/WebSocketConnection.h b/ntcore/src/main/native/cpp/net/WebSocketConnection.h index 4398451532a..fc5cfe98330 100644 --- a/ntcore/src/main/native/cpp/net/WebSocketConnection.h +++ b/ntcore/src/main/native/cpp/net/WebSocketConnection.h @@ -15,19 +15,22 @@ #include "WireConnection.h" +namespace wpi { +class Logger; +} // namespace wpi + namespace nt::net { class WebSocketConnection final : public WireConnection, public std::enable_shared_from_this { public: - WebSocketConnection(wpi::WebSocket& ws, unsigned int version); + WebSocketConnection(wpi::WebSocket& ws, unsigned int version, + wpi::Logger& logger); ~WebSocketConnection() override; WebSocketConnection(const WebSocketConnection&) = delete; WebSocketConnection& operator=(const WebSocketConnection&) = delete; - void Start(); - unsigned int GetVersion() const final { return m_version; } void SendPing(uint64_t time) final; @@ -51,7 +54,9 @@ class WebSocketConnection final uint64_t GetLastFlushTime() const final { return m_lastFlushTime; } - uint64_t GetLastPingResponse() const final { return m_lastPingResponse; } + uint64_t GetLastReceivedTime() const final { + return m_ws.GetLastReceivedTime(); + } void Disconnect(std::string_view reason) final; @@ -70,6 +75,7 @@ class WebSocketConnection final void ReleaseBufs(std::span bufs); wpi::WebSocket& m_ws; + wpi::Logger& m_logger; class Stream; @@ -92,7 +98,6 @@ class WebSocketConnection final State m_state = kEmpty; std::string m_reason; uint64_t m_lastFlushTime = 0; - uint64_t m_lastPingResponse = 0; unsigned int m_version; }; diff --git a/ntcore/src/main/native/cpp/net/WireConnection.h b/ntcore/src/main/native/cpp/net/WireConnection.h index 2c876cc29f3..c1efaff2f8c 100644 --- a/ntcore/src/main/native/cpp/net/WireConnection.h +++ b/ntcore/src/main/native/cpp/net/WireConnection.h @@ -51,8 +51,8 @@ class WireConnection { virtual uint64_t GetLastFlushTime() const = 0; // in microseconds - // Gets the timestamp of the last ping we got a reply to - virtual uint64_t GetLastPingResponse() const = 0; // in microseconds + // Gets the timestamp of the last incoming data + virtual uint64_t GetLastReceivedTime() const = 0; // in microseconds virtual void Disconnect(std::string_view reason) = 0; }; diff --git a/ntcore/src/main/native/cpp/networktables/NetworkTableInstance.cpp b/ntcore/src/main/native/cpp/networktables/NetworkTableInstance.cpp index 251e211d581..d2cac1ce6a3 100644 --- a/ntcore/src/main/native/cpp/networktables/NetworkTableInstance.cpp +++ b/ntcore/src/main/native/cpp/networktables/NetworkTableInstance.cpp @@ -4,8 +4,8 @@ #include "networktables/NetworkTableInstance.h" -#include #include +#include #include "networktables/BooleanArrayTopic.h" #include "networktables/BooleanTopic.h" @@ -105,7 +105,7 @@ NT_Listener NetworkTableInstance::AddListener(Topic topic, unsigned int eventMask, ListenerCallback listener) { if (::nt::GetInstanceFromHandle(topic.GetHandle()) != m_handle) { - fmt::print(stderr, "AddListener: topic is not from this instance\n"); + wpi::print(stderr, "AddListener: topic is not from this instance\n"); return 0; } return ::nt::AddListener(topic.GetHandle(), eventMask, std::move(listener)); @@ -115,7 +115,7 @@ NT_Listener NetworkTableInstance::AddListener(Subscriber& subscriber, unsigned int eventMask, ListenerCallback listener) { if (::nt::GetInstanceFromHandle(subscriber.GetHandle()) != m_handle) { - fmt::print(stderr, "AddListener: subscriber is not from this instance\n"); + wpi::print(stderr, "AddListener: subscriber is not from this instance\n"); return 0; } return ::nt::AddListener(subscriber.GetHandle(), eventMask, @@ -126,7 +126,7 @@ NT_Listener NetworkTableInstance::AddListener(const NetworkTableEntry& entry, int eventMask, ListenerCallback listener) { if (::nt::GetInstanceFromHandle(entry.GetHandle()) != m_handle) { - fmt::print(stderr, "AddListener: entry is not from this instance\n"); + wpi::print(stderr, "AddListener: entry is not from this instance\n"); return 0; } return ::nt::AddListener(entry.GetHandle(), eventMask, std::move(listener)); @@ -136,7 +136,7 @@ NT_Listener NetworkTableInstance::AddListener(MultiSubscriber& subscriber, int eventMask, ListenerCallback listener) { if (::nt::GetInstanceFromHandle(subscriber.GetHandle()) != m_handle) { - fmt::print(stderr, "AddListener: subscriber is not from this instance\n"); + wpi::print(stderr, "AddListener: subscriber is not from this instance\n"); return 0; } return ::nt::AddListener(subscriber.GetHandle(), eventMask, diff --git a/ntcore/src/main/native/cpp/ntcore_c.cpp b/ntcore/src/main/native/cpp/ntcore_c.cpp index b4326646fdc..ee8b45eeb1e 100644 --- a/ntcore/src/main/native/cpp/ntcore_c.cpp +++ b/ntcore/src/main/native/cpp/ntcore_c.cpp @@ -87,19 +87,19 @@ static void ConvertToC(const Event& in, NT_Event* out) { } static void DisposeConnectionInfo(NT_ConnectionInfo* info) { - std::free(info->remote_id.str); - std::free(info->remote_ip.str); + WPI_FreeString(&info->remote_id); + WPI_FreeString(&info->remote_ip); } static void DisposeTopicInfo(NT_TopicInfo* info) { - std::free(info->name.str); - std::free(info->type_str.str); - std::free(info->properties.str); + WPI_FreeString(&info->name); + WPI_FreeString(&info->type_str); + WPI_FreeString(&info->properties); } static void DisposeLogMessage(NT_LogMessage* msg) { - std::free(msg->filename); - std::free(msg->message); + WPI_FreeString(&msg->filename); + WPI_FreeString(&msg->message); } static void DisposeEvent(NT_Event* event) { @@ -126,6 +126,7 @@ static PubSubOptions ConvertToCpp(const NT_PubSubOptions* in) { out.disableRemote = in->disableRemote; out.disableLocal = in->disableLocal; out.excludeSelf = in->excludeSelf; + out.hidden = in->hidden; return out; } @@ -155,15 +156,12 @@ NT_Inst NT_GetInstanceFromHandle(NT_Handle handle) { * Table Functions */ -NT_Entry NT_GetEntry(NT_Inst inst, const char* name, size_t name_len) { - return nt::GetEntry(inst, {name, name_len}); +NT_Entry NT_GetEntry(NT_Inst inst, const struct WPI_String* name) { + return nt::GetEntry(inst, wpi::to_string_view(name)); } -char* NT_GetEntryName(NT_Entry entry, size_t* name_len) { - struct NT_String v_name; - nt::ConvertToC(nt::GetEntryName(entry), &v_name); - *name_len = v_name.len; - return v_name.str; +void NT_GetEntryName(NT_Entry entry, struct WPI_String* name) { + nt::ConvertToC(nt::GetEntryName(entry), name); } enum NT_Type NT_GetEntryType(NT_Entry entry) { @@ -175,11 +173,19 @@ uint64_t NT_GetEntryLastChange(NT_Entry entry) { } void NT_GetEntryValue(NT_Entry entry, struct NT_Value* value) { + NT_GetEntryValueType(entry, 0, value); +} + +void NT_GetEntryValueType(NT_Entry entry, unsigned int types, + struct NT_Value* value) { NT_InitValue(value); auto v = nt::GetEntryValue(entry); if (!v) { return; } + if (types != 0 && (types & v.type()) == 0) { + return; + } ConvertToC(v, value); } @@ -204,41 +210,46 @@ struct NT_Value* NT_ReadQueueValue(NT_Handle subentry, size_t* count) { return ConvertToC(nt::ReadQueueValue(subentry), count); } -NT_Topic* NT_GetTopics(NT_Inst inst, const char* prefix, size_t prefix_len, +struct NT_Value* NT_ReadQueueValueType(NT_Handle subentry, unsigned int types, + size_t* count) { + return ConvertToC(nt::ReadQueueValue(subentry, types), count); +} + +NT_Topic* NT_GetTopics(NT_Inst inst, const struct WPI_String* prefix, unsigned int types, size_t* count) { - auto info_v = nt::GetTopics(inst, {prefix, prefix_len}, types); + auto info_v = nt::GetTopics(inst, wpi::to_string_view(prefix), types); return ConvertToC(info_v, count); } -NT_Topic* NT_GetTopicsStr(NT_Inst inst, const char* prefix, size_t prefix_len, - const char* const* types, size_t types_len, +NT_Topic* NT_GetTopicsStr(NT_Inst inst, const struct WPI_String* prefix, + const struct WPI_String* types, size_t types_len, size_t* count) { wpi::SmallVector typesCpp; typesCpp.reserve(types_len); for (size_t i = 0; i < types_len; ++i) { - typesCpp.emplace_back(types[i]); + typesCpp.emplace_back(wpi::to_string_view(&types[i])); } - auto info_v = nt::GetTopics(inst, {prefix, prefix_len}, typesCpp); + auto info_v = nt::GetTopics(inst, wpi::to_string_view(prefix), typesCpp); return ConvertToC(info_v, count); } -struct NT_TopicInfo* NT_GetTopicInfos(NT_Inst inst, const char* prefix, - size_t prefix_len, unsigned int types, - size_t* count) { - auto info_v = nt::GetTopicInfo(inst, {prefix, prefix_len}, types); +struct NT_TopicInfo* NT_GetTopicInfos(NT_Inst inst, + const struct WPI_String* prefix, + unsigned int types, size_t* count) { + auto info_v = nt::GetTopicInfo(inst, wpi::to_string_view(prefix), types); return ConvertToC(info_v, count); } -struct NT_TopicInfo* NT_GetTopicInfosStr(NT_Inst inst, const char* prefix, - size_t prefix_len, - const char* const* types, +struct NT_TopicInfo* NT_GetTopicInfosStr(NT_Inst inst, + const struct WPI_String* prefix, + const struct WPI_String* types, size_t types_len, size_t* count) { wpi::SmallVector typesCpp; typesCpp.reserve(types_len); for (size_t i = 0; i < types_len; ++i) { - typesCpp.emplace_back(types[i]); + typesCpp.emplace_back(wpi::to_string_view(&types[i])); } - auto info_v = nt::GetTopicInfo(inst, {prefix, prefix_len}, typesCpp); + auto info_v = nt::GetTopicInfo(inst, wpi::to_string_view(prefix), typesCpp); return ConvertToC(info_v, count); } @@ -251,32 +262,20 @@ NT_Bool NT_GetTopicInfo(NT_Topic topic, struct NT_TopicInfo* info) { return true; } -NT_Topic NT_GetTopic(NT_Inst inst, const char* name, size_t name_len) { - return nt::GetTopic(inst, std::string_view{name, name_len}); +NT_Topic NT_GetTopic(NT_Inst inst, const struct WPI_String* name) { + return nt::GetTopic(inst, wpi::to_string_view(name)); } -char* NT_GetTopicName(NT_Topic topic, size_t* name_len) { - auto name = nt::GetTopicName(topic); - if (name.empty()) { - *name_len = 0; - return nullptr; - } - struct NT_String v_name; - nt::ConvertToC(name, &v_name); - *name_len = v_name.len; - return v_name.str; +void NT_GetTopicName(NT_Topic topic, struct WPI_String* name) { + nt::ConvertToC(nt::GetTopicName(topic), name); } NT_Type NT_GetTopicType(NT_Topic topic) { return nt::GetTopicType(topic); } -char* NT_GetTopicTypeString(NT_Topic topic, size_t* type_len) { - auto type = nt::GetTopicTypeString(topic); - struct NT_String v_type; - nt::ConvertToC(type, &v_type); - *type_len = v_type.len; - return v_type.str; +void NT_GetTopicTypeString(NT_Topic topic, struct WPI_String* type) { + nt::ConvertToC(nt::GetTopicTypeString(topic), type); } void NT_SetTopicPersistent(NT_Topic topic, NT_Bool value) { @@ -295,91 +294,103 @@ NT_Bool NT_GetTopicRetained(NT_Topic topic) { return nt::GetTopicRetained(topic); } +void NT_SetTopicCached(NT_Topic topic, NT_Bool value) { + nt::SetTopicCached(topic, value); +} + +NT_Bool NT_GetTopicCached(NT_Topic topic) { + return nt::GetTopicCached(topic); +} + NT_Bool NT_GetTopicExists(NT_Handle handle) { return nt::GetTopicExists(handle); } -char* NT_GetTopicProperty(NT_Topic topic, const char* name, size_t* len) { - wpi::json j = nt::GetTopicProperty(topic, name); - struct NT_String v; - nt::ConvertToC(j.dump(), &v); - *len = v.len; - return v.str; +void NT_GetTopicProperty(NT_Topic topic, const struct WPI_String* name, + struct WPI_String* prop) { + wpi::json j = nt::GetTopicProperty(topic, wpi::to_string_view(name)); + nt::ConvertToC(j.dump(), prop); } -NT_Bool NT_SetTopicProperty(NT_Topic topic, const char* name, - const char* value) { +NT_Bool NT_SetTopicProperty(NT_Topic topic, const struct WPI_String* name, + const struct WPI_String* value) { wpi::json j; try { - j = wpi::json::parse(value); + j = wpi::json::parse(wpi::to_string_view(value)); } catch (wpi::json::parse_error&) { return false; } - nt::SetTopicProperty(topic, name, j); + nt::SetTopicProperty(topic, wpi::to_string_view(name), j); return true; } -void NT_DeleteTopicProperty(NT_Topic topic, const char* name) { - nt::DeleteTopicProperty(topic, name); +void NT_DeleteTopicProperty(NT_Topic topic, const struct WPI_String* name) { + nt::DeleteTopicProperty(topic, wpi::to_string_view(name)); } -char* NT_GetTopicProperties(NT_Topic topic, size_t* len) { +void NT_GetTopicProperties(NT_Topic topic, struct WPI_String* property) { wpi::json j = nt::GetTopicProperties(topic); - struct NT_String v; - nt::ConvertToC(j.dump(), &v); - *len = v.len; - return v.str; + nt::ConvertToC(j.dump(), property); } -NT_Bool NT_SetTopicProperties(NT_Topic topic, const char* properties) { +NT_Bool NT_SetTopicProperties(NT_Topic topic, + const struct WPI_String* properties) { wpi::json j; try { - j = wpi::json::parse(properties); + j = wpi::json::parse(wpi::to_string_view(properties)); } catch (wpi::json::parse_error&) { return false; } return nt::SetTopicProperties(topic, j); } -NT_Subscriber NT_Subscribe(NT_Topic topic, NT_Type type, const char* typeStr, +NT_Subscriber NT_Subscribe(NT_Topic topic, NT_Type type, + const struct WPI_String* typeStr, const struct NT_PubSubOptions* options) { - return nt::Subscribe(topic, type, typeStr, ConvertToCpp(options)); + return nt::Subscribe(topic, type, wpi::to_string_view(typeStr), + ConvertToCpp(options)); } void NT_Unsubscribe(NT_Subscriber sub) { return nt::Unsubscribe(sub); } -NT_Publisher NT_Publish(NT_Topic topic, NT_Type type, const char* typeStr, +NT_Publisher NT_Publish(NT_Topic topic, NT_Type type, + const struct WPI_String* typeStr, const struct NT_PubSubOptions* options) { - return nt::Publish(topic, type, typeStr, ConvertToCpp(options)); + return nt::Publish(topic, type, wpi::to_string_view(typeStr), + ConvertToCpp(options)); } -NT_Publisher NT_PublishEx(NT_Topic topic, NT_Type type, const char* typeStr, - const char* properties, +NT_Publisher NT_PublishEx(NT_Topic topic, NT_Type type, + const struct WPI_String* typeStr, + const struct WPI_String* properties, const struct NT_PubSubOptions* options) { wpi::json j; - if (properties[0] == '\0') { + if (properties->len == 0) { // gracefully handle empty string j = wpi::json::object(); } else { try { - j = wpi::json::parse(properties); + j = wpi::json::parse(wpi::to_string_view(properties)); } catch (wpi::json::parse_error&) { return {}; } } - return nt::PublishEx(topic, type, typeStr, j, ConvertToCpp(options)); + return nt::PublishEx(topic, type, wpi::to_string_view(typeStr), j, + ConvertToCpp(options)); } void NT_Unpublish(NT_Handle pubentry) { return nt::Unpublish(pubentry); } -NT_Entry NT_GetEntryEx(NT_Topic topic, NT_Type type, const char* typeStr, +NT_Entry NT_GetEntryEx(NT_Topic topic, NT_Type type, + const struct WPI_String* typeStr, const struct NT_PubSubOptions* options) { - return nt::GetEntry(topic, type, typeStr, ConvertToCpp(options)); + return nt::GetEntry(topic, type, wpi::to_string_view(typeStr), + ConvertToCpp(options)); } void NT_ReleaseEntry(NT_Entry entry) { @@ -419,10 +430,10 @@ NT_Bool NT_WaitForListenerQueue(NT_Handle handle, double timeout) { return nt::WaitForListenerQueue(handle, timeout); } -NT_Listener NT_AddListenerSingle(NT_Inst inst, const char* prefix, - size_t prefix_len, unsigned int mask, - void* data, NT_ListenerCallback callback) { - std::string_view p{prefix, prefix_len}; +NT_Listener NT_AddListenerSingle(NT_Inst inst, const struct WPI_String* prefix, + unsigned int mask, void* data, + NT_ListenerCallback callback) { + std::string_view p = wpi::to_string_view(prefix); return nt::AddListener(inst, {{p}}, mask, [=](auto& event) { NT_Event event_c; ConvertToC(event, &event_c); @@ -431,7 +442,8 @@ NT_Listener NT_AddListenerSingle(NT_Inst inst, const char* prefix, }); } -NT_Listener NT_AddListenerMultiple(NT_Inst inst, const NT_String* prefixes, +NT_Listener NT_AddListenerMultiple(NT_Inst inst, + const struct WPI_String* prefixes, size_t prefixes_len, unsigned int mask, void* data, NT_ListenerCallback callback) { wpi::SmallVector p; @@ -458,14 +470,14 @@ NT_Listener NT_AddListener(NT_Topic topic, unsigned int mask, void* data, } NT_Listener NT_AddPolledListenerSingle(NT_ListenerPoller poller, - const char* prefix, size_t prefix_len, + const struct WPI_String* prefix, unsigned int mask) { - std::string_view p{prefix, prefix_len}; + std::string_view p = wpi::to_string_view(prefix); return nt::AddPolledListener(poller, {{p}}, mask); } NT_Listener NT_AddPolledListenerMultiple(NT_ListenerPoller poller, - const NT_String* prefixes, + const struct WPI_String* prefixes, size_t prefixes_len, unsigned int mask) { wpi::SmallVector p; @@ -497,38 +509,42 @@ void NT_StopLocal(NT_Inst inst) { nt::StopLocal(inst); } -void NT_StartServer(NT_Inst inst, const char* persist_filename, - const char* listen_address, unsigned int port3, +void NT_StartServer(NT_Inst inst, const struct WPI_String* persist_filename, + const struct WPI_String* listen_address, unsigned int port3, unsigned int port4) { - nt::StartServer(inst, persist_filename, listen_address, port3, port4); + nt::StartServer(inst, wpi::to_string_view(persist_filename), + wpi::to_string_view(listen_address), port3, port4); } void NT_StopServer(NT_Inst inst) { nt::StopServer(inst); } -void NT_StartClient3(NT_Inst inst, const char* identity) { - nt::StartClient3(inst, identity); +void NT_StartClient3(NT_Inst inst, const struct WPI_String* identity) { + nt::StartClient3(inst, wpi::to_string_view(identity)); } -void NT_StartClient4(NT_Inst inst, const char* identity) { - nt::StartClient4(inst, identity); +void NT_StartClient4(NT_Inst inst, const struct WPI_String* identity) { + nt::StartClient4(inst, wpi::to_string_view(identity)); } void NT_StopClient(NT_Inst inst) { nt::StopClient(inst); } -void NT_SetServer(NT_Inst inst, const char* server_name, unsigned int port) { - nt::SetServer(inst, server_name, port); +void NT_SetServer(NT_Inst inst, const struct WPI_String* server_name, + unsigned int port) { + nt::SetServer(inst, wpi::to_string_view(server_name), port); } -void NT_SetServerMulti(NT_Inst inst, size_t count, const char** server_names, +void NT_SetServerMulti(NT_Inst inst, size_t count, + const struct WPI_String* server_names, const unsigned int* ports) { std::vector> servers; servers.reserve(count); for (size_t i = 0; i < count; ++i) { - servers.emplace_back(std::make_pair(server_names[i], ports[i])); + servers.emplace_back( + std::make_pair(wpi::to_string_view(&server_names[i]), ports[i])); } nt::SetServer(inst, servers); } @@ -589,20 +605,22 @@ void NT_SetNow(int64_t timestamp) { } NT_DataLogger NT_StartEntryDataLog(NT_Inst inst, struct WPI_DataLog* log, - const char* prefix, const char* logPrefix) { + const struct WPI_String* prefix, + const struct WPI_String* logPrefix) { return nt::StartEntryDataLog(inst, *reinterpret_cast(log), - prefix, logPrefix); + wpi::to_string_view(prefix), + wpi::to_string_view(logPrefix)); } void NT_StopEntryDataLog(NT_DataLogger logger) { nt::StopEntryDataLog(logger); } -NT_ConnectionDataLogger NT_StartConnectionDataLog(NT_Inst inst, - struct WPI_DataLog* log, - const char* name) { - return nt::StartConnectionDataLog( - inst, *reinterpret_cast(log), name); +NT_ConnectionDataLogger NT_StartConnectionDataLog( + NT_Inst inst, struct WPI_DataLog* log, const struct WPI_String* name) { + return nt::StartConnectionDataLog(inst, + *reinterpret_cast(log), + wpi::to_string_view(name)); } void NT_StopConnectionDataLog(NT_ConnectionDataLogger logger) { @@ -625,13 +643,15 @@ NT_Listener NT_AddPolledLogger(NT_ListenerPoller poller, unsigned int min_level, return nt::AddPolledLogger(poller, min_level, max_level); } -NT_Bool NT_HasSchema(NT_Inst inst, const char* name) { - return nt::HasSchema(inst, name); +NT_Bool NT_HasSchema(NT_Inst inst, const struct WPI_String* name) { + return nt::HasSchema(inst, wpi::to_string_view(name)); } -void NT_AddSchema(NT_Inst inst, const char* name, const char* type, - const uint8_t* schema, size_t schemaSize) { - nt::AddSchema(inst, name, type, {schema, schemaSize}); +void NT_AddSchema(NT_Inst inst, const struct WPI_String* name, + const struct WPI_String* type, const uint8_t* schema, + size_t schemaSize) { + nt::AddSchema(inst, wpi::to_string_view(name), wpi::to_string_view(type), + {schema, schemaSize}); } void NT_DisposeValue(NT_Value* value) { @@ -643,7 +663,7 @@ void NT_DisposeValue(NT_Value* value) { case NT_DOUBLE: break; case NT_STRING: - std::free(value->data.v_string.str); + WPI_FreeString(&value->data.v_string); break; case NT_RAW: std::free(value->data.v_raw.data); @@ -662,7 +682,7 @@ void NT_DisposeValue(NT_Value* value) { break; case NT_STRING_ARRAY: { for (size_t i = 0; i < value->data.arr_string.size; i++) { - std::free(value->data.arr_string.arr[i].str); + WPI_FreeString(&value->data.arr_string.arr[i]); } std::free(value->data.arr_string.arr); break; @@ -681,17 +701,6 @@ void NT_InitValue(NT_Value* value) { value->server_time = 0; } -void NT_DisposeString(NT_String* str) { - std::free(str->str); - str->str = nullptr; - str->len = 0; -} - -void NT_InitString(NT_String* str) { - str->str = nullptr; - str->len = 0; -} - void NT_DisposeValueArray(struct NT_Value* arr, size_t count) { for (size_t i = 0; i < count; ++i) { NT_DisposeValue(&arr[i]); @@ -759,12 +768,6 @@ double* NT_AllocateDoubleArray(size_t size) { return retVal; } -struct NT_String* NT_AllocateStringArray(size_t size) { - NT_String* retVal = - static_cast(wpi::safe_malloc(size * sizeof(NT_String))); - return retVal; -} - void NT_FreeCharArray(char* v_char) { std::free(v_char); } @@ -780,12 +783,6 @@ void NT_FreeFloatArray(float* v_float) { void NT_FreeDoubleArray(double* v_double) { std::free(v_double); } -void NT_FreeStringArray(struct NT_String* v_string, size_t arr_size) { - for (size_t i = 0; i < arr_size; ++i) { - std::free(v_string[i].str); - } - std::free(v_string); -} enum NT_Type NT_GetValueType(const struct NT_Value* value) { if (!value) { @@ -916,20 +913,19 @@ double* NT_GetValueDoubleArray(const struct NT_Value* value, return arr; } -NT_String* NT_GetValueStringArray(const struct NT_Value* value, - uint64_t* last_change, size_t* arr_size) { +struct WPI_String* NT_GetValueStringArray(const struct NT_Value* value, + uint64_t* last_change, + size_t* arr_size) { if (!value || value->type != NT_Type::NT_STRING_ARRAY) { return nullptr; } *last_change = value->last_change; *arr_size = value->data.arr_string.size; - NT_String* arr = static_cast( - wpi::safe_malloc(value->data.arr_string.size * sizeof(NT_String))); + struct WPI_String* arr = WPI_AllocateStringArray(value->data.arr_string.size); for (size_t i = 0; i < value->data.arr_string.size; ++i) { size_t len = value->data.arr_string.arr[i].len; - arr[i].len = len; - arr[i].str = static_cast(wpi::safe_malloc(len + 1)); - std::memcpy(arr[i].str, value->data.arr_string.arr[i].str, len + 1); + auto write = WPI_AllocateString(&arr[i], len); + std::memcpy(write, value->data.arr_string.arr[i].str, len); } return arr; } diff --git a/ntcore/src/main/native/cpp/ntcore_cpp.cpp b/ntcore/src/main/native/cpp/ntcore_cpp.cpp index 4b48f050df2..75f20a6db5c 100644 --- a/ntcore/src/main/native/cpp/ntcore_cpp.cpp +++ b/ntcore/src/main/native/cpp/ntcore_cpp.cpp @@ -144,8 +144,12 @@ unsigned int GetEntryFlags(NT_Entry entry) { } std::vector ReadQueueValue(NT_Handle subentry) { + return ReadQueueValue(subentry, 0); +} + +std::vector ReadQueueValue(NT_Handle subentry, unsigned int types) { if (auto ii = InstanceImpl::GetHandle(subentry)) { - return ii->localStorage.ReadQueueValue(subentry); + return ii->localStorage.ReadQueueValue(subentry, types); } else { return {}; } @@ -263,6 +267,22 @@ bool GetTopicRetained(NT_Topic topic) { } } +void SetTopicCached(NT_Topic topic, bool value) { + if (auto ii = InstanceImpl::GetTyped(topic, Handle::kTopic)) { + ii->localStorage.SetTopicCached(topic, value); + } else { + return; + } +} + +bool GetTopicCached(NT_Topic topic) { + if (auto ii = InstanceImpl::GetTyped(topic, Handle::kTopic)) { + return ii->localStorage.GetTopicCached(topic); + } else { + return {}; + } +} + bool GetTopicExists(NT_Handle handle) { if (auto ii = InstanceImpl::GetHandle(handle)) { return ii->localStorage.GetTopicExists(handle); @@ -610,7 +630,7 @@ void StopLocal(NT_Inst inst) { } void StartServer(NT_Inst inst, std::string_view persist_filename, - const char* listen_address, unsigned int port3, + std::string_view listen_address, unsigned int port3, unsigned int port4) { if (auto ii = InstanceImpl::GetTyped(inst, Handle::kInstance)) { ii->StartServer(persist_filename, listen_address, port3, port4); @@ -641,7 +661,7 @@ void StopClient(NT_Inst inst) { } } -void SetServer(NT_Inst inst, const char* server_name, unsigned int port) { +void SetServer(NT_Inst inst, std::string_view server_name, unsigned int port) { SetServer(inst, {{{server_name, port}}}); } diff --git a/ntcore/src/main/native/cpp/ntcore_meta_c.cpp b/ntcore/src/main/native/cpp/ntcore_meta_c.cpp index 889254e1b70..6c6c026ecb1 100644 --- a/ntcore/src/main/native/cpp/ntcore_meta_c.cpp +++ b/ntcore/src/main/native/cpp/ntcore_meta_c.cpp @@ -40,7 +40,7 @@ static void ConvertToC(const ClientPublisher& in, static void ConvertToC(const ClientSubscriber& in, NT_Meta_ClientSubscriber* out) { out->uid = in.uid; - out->topics = ConvertToC(in.topics, &out->topicsCount); + out->topics = ConvertToC(in.topics, &out->topicsCount); ConvertToC(in.options, &out->options); } @@ -98,7 +98,7 @@ struct NT_Meta_Client* NT_Meta_DecodeClients(const uint8_t* data, size_t size, void NT_Meta_FreeTopicPublishers(struct NT_Meta_TopicPublisher* arr, size_t count) { for (size_t i = 0; i < count; ++i) { - std::free(arr[i].client.str); + WPI_FreeString(&arr[i].client); } std::free(arr); } @@ -106,7 +106,7 @@ void NT_Meta_FreeTopicPublishers(struct NT_Meta_TopicPublisher* arr, void NT_Meta_FreeTopicSubscribers(struct NT_Meta_TopicSubscriber* arr, size_t count) { for (size_t i = 0; i < count; ++i) { - std::free(arr[i].client.str); + WPI_FreeString(&arr[i].client); } std::free(arr); } @@ -114,7 +114,7 @@ void NT_Meta_FreeTopicSubscribers(struct NT_Meta_TopicSubscriber* arr, void NT_Meta_FreeClientPublishers(struct NT_Meta_ClientPublisher* arr, size_t count) { for (size_t i = 0; i < count; ++i) { - std::free(arr[i].topic.str); + WPI_FreeString(&arr[i].topic); } std::free(arr); } @@ -122,15 +122,15 @@ void NT_Meta_FreeClientPublishers(struct NT_Meta_ClientPublisher* arr, void NT_Meta_FreeClientSubscribers(struct NT_Meta_ClientSubscriber* arr, size_t count) { for (size_t i = 0; i < count; ++i) { - NT_FreeStringArray(arr[i].topics, arr[i].topicsCount); + WPI_FreeStringArray(arr[i].topics, arr[i].topicsCount); } std::free(arr); } void NT_Meta_FreeClients(struct NT_Meta_Client* arr, size_t count) { for (size_t i = 0; i < count; ++i) { - std::free(arr[i].id.str); - std::free(arr[i].conn.str); + WPI_FreeString(&arr[i].id); + WPI_FreeString(&arr[i].conn); } std::free(arr); } diff --git a/ntcore/src/main/native/cpp/ntcore_test.cpp b/ntcore/src/main/native/cpp/ntcore_test.cpp index 2a07867e95d..43643706687 100644 --- a/ntcore/src/main/native/cpp/ntcore_test.cpp +++ b/ntcore/src/main/native/cpp/ntcore_test.cpp @@ -11,11 +11,11 @@ #include "Value_internal.h" extern "C" { -struct NT_String* NT_GetStringForTesting(const char* str, int* struct_size) { - struct NT_String* strout = - static_cast(wpi::safe_calloc(1, sizeof(NT_String))); +struct WPI_String* NT_GetStringForTesting(const char* str, int* struct_size) { + struct WPI_String* strout = + static_cast(wpi::safe_calloc(1, sizeof(WPI_String))); nt::ConvertToC(str, strout); - *struct_size = sizeof(NT_String); + *struct_size = sizeof(WPI_String); return strout; } @@ -33,8 +33,9 @@ struct NT_TopicInfo* NT_GetTopicInfoForTesting(const char* name, } void NT_FreeTopicInfoForTesting(struct NT_TopicInfo* info) { - std::free(info->name.str); - std::free(info->type_str.str); + WPI_FreeString(&info->name); + WPI_FreeString(&info->type_str); + WPI_FreeString(&info->properties); std::free(info); } @@ -53,8 +54,8 @@ struct NT_ConnectionInfo* NT_GetConnectionInfoForTesting( } void NT_FreeConnectionInfoForTesting(struct NT_ConnectionInfo* info) { - std::free(info->remote_id.str); - std::free(info->remote_ip.str); + WPI_FreeString(&info->remote_id); + WPI_FreeString(&info->remote_ip); std::free(info); } @@ -136,21 +137,19 @@ struct NT_Value* NT_GetValueDoubleArrayForTesting(uint64_t last_change, } struct NT_Value* NT_GetValueStringArrayForTesting(uint64_t last_change, - const struct NT_String* arr, + const struct WPI_String* arr, size_t array_len, int* struct_size) { struct NT_Value* value = static_cast(wpi::safe_calloc(1, sizeof(NT_Value))); value->type = NT_BOOLEAN; value->last_change = last_change; - value->data.arr_string.arr = NT_AllocateStringArray(array_len); + value->data.arr_string.arr = WPI_AllocateStringArray(array_len); value->data.arr_string.size = array_len; for (size_t i = 0; i < value->data.arr_string.size; ++i) { size_t len = arr[i].len; - value->data.arr_string.arr[i].len = len; - value->data.arr_string.arr[i].str = - static_cast(wpi::safe_malloc(len + 1)); - std::memcpy(value->data.arr_string.arr[i].str, arr[i].str, len + 1); + auto write = WPI_AllocateString(&value->data.arr_string.arr[i], len); + std::memcpy(write, arr[i].str, len); } *struct_size = sizeof(NT_Value); return value; diff --git a/ntcore/src/main/native/include/networktables/NTSendableBuilder.h b/ntcore/src/main/native/include/networktables/NTSendableBuilder.h index 01ce6cc6aa6..3c6fe0e3f05 100644 --- a/ntcore/src/main/native/include/networktables/NTSendableBuilder.h +++ b/ntcore/src/main/native/include/networktables/NTSendableBuilder.h @@ -15,6 +15,10 @@ namespace nt { +/** + * Helper class for building Sendable dashboard representations for + * NetworkTables. + */ class NTSendableBuilder : public wpi::SendableBuilder { public: /** diff --git a/ntcore/src/main/native/include/networktables/NetworkTable.h b/ntcore/src/main/native/include/networktables/NetworkTable.h index e03ea9e99ad..10088591715 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTable.h +++ b/ntcore/src/main/native/include/networktables/NetworkTable.h @@ -37,9 +37,11 @@ class ProtobufTopic; class RawTopic; class StringArrayTopic; class StringTopic; -template +template + requires wpi::StructSerializable class StructArrayTopic; -template +template + requires wpi::StructSerializable class StructTopic; class Topic; @@ -244,22 +246,27 @@ class NetworkTable final { * Gets a raw struct serialized value topic. * * @param name topic name + * @param info optional struct type info * @return Topic */ - template - StructTopic GetStructTopic(std::string_view name) const { - return StructTopic{GetTopic(name)}; + template + requires wpi::StructSerializable + StructTopic GetStructTopic(std::string_view name, I... info) const { + return StructTopic{GetTopic(name), std::move(info)...}; } /** * Gets a raw struct serialized array topic. * * @param name topic name + * @param info optional struct type info * @return Topic */ - template - StructArrayTopic GetStructArrayTopic(std::string_view name) const { - return StructArrayTopic{GetTopic(name)}; + template + requires wpi::StructSerializable + StructArrayTopic GetStructArrayTopic(std::string_view name, + I... info) const { + return StructArrayTopic{GetTopic(name), std::move(info)...}; } /** diff --git a/ntcore/src/main/native/include/networktables/NetworkTableEntry.h b/ntcore/src/main/native/include/networktables/NetworkTableEntry.h index 31fe9a68bdc..6eec8964f36 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTableEntry.h +++ b/ntcore/src/main/native/include/networktables/NetworkTableEntry.h @@ -33,12 +33,6 @@ class Topic; */ class NetworkTableEntry final { public: - /** - * Flag values (as returned by GetFlags()). - * @deprecated Use IsPersistent() instead. - */ - enum Flags { kPersistent = NT_PERSISTENT }; - /** * Construct invalid instance. */ @@ -93,15 +87,6 @@ class NetworkTableEntry final { */ NetworkTableType GetType() const; - /** - * Returns the flags. - * - * @return the flags (bitmask) - * @deprecated Use IsPersistent() or topic properties instead - */ - [[deprecated("Use IsPersistent() or topic properties instead")]] - unsigned int GetFlags() const; - /** * Gets the last time the entry's value was changed. * @@ -460,24 +445,6 @@ class NetworkTableEntry final { */ bool SetStringArray(std::span value, int64_t time = 0); - /** - * Sets flags. - * - * @param flags the flags to set (bitmask) - * @deprecated Use SetPersistent() or topic properties instead - */ - [[deprecated("Use SetPersistent() or topic properties instead")]] - void SetFlags(unsigned int flags); - - /** - * Clears flags. - * - * @param flags the flags to clear (bitmask) - * @deprecated Use SetPersistent() or topic properties instead - */ - [[deprecated("Use SetPersistent() or topic properties instead")]] - void ClearFlags(unsigned int flags); - /** * Make value persistent through program restarts. */ @@ -500,13 +467,6 @@ class NetworkTableEntry final { */ void Unpublish(); - /** - * Deletes the entry. - * @deprecated Use Unpublish() instead. - */ - [[deprecated("Use Unpublish() instead")]] - void Delete(); - /** * Gets the entry's topic. * diff --git a/ntcore/src/main/native/include/networktables/NetworkTableEntry.inc b/ntcore/src/main/native/include/networktables/NetworkTableEntry.inc index 0b4f628f4aa..0f18e2d445d 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTableEntry.inc +++ b/ntcore/src/main/native/include/networktables/NetworkTableEntry.inc @@ -36,10 +36,6 @@ inline NetworkTableType NetworkTableEntry::GetType() const { return static_cast(GetEntryType(m_handle)); } -inline unsigned int NetworkTableEntry::GetFlags() const { - return GetEntryFlags(m_handle); -} - inline int64_t NetworkTableEntry::GetLastChange() const { return GetEntryLastChange(m_handle); } @@ -216,14 +212,6 @@ inline bool NetworkTableEntry::SetStringArray( return nt::SetStringArray(m_handle, value, time); } -inline void NetworkTableEntry::SetFlags(unsigned int flags) { - SetEntryFlags(m_handle, GetEntryFlags(m_handle) | flags); -} - -inline void NetworkTableEntry::ClearFlags(unsigned int flags) { - SetEntryFlags(m_handle, GetEntryFlags(m_handle) & ~flags); -} - inline void NetworkTableEntry::SetPersistent() { nt::SetTopicPersistent(nt::GetTopicFromHandle(m_handle), true); } @@ -240,8 +228,4 @@ inline void NetworkTableEntry::Unpublish() { return nt::Unpublish(m_handle); } -inline void NetworkTableEntry::Delete() { - Unpublish(); -} - } // namespace nt diff --git a/ntcore/src/main/native/include/networktables/NetworkTableInstance.h b/ntcore/src/main/native/include/networktables/NetworkTableInstance.h index 06e2cd6483c..60cf7841de8 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTableInstance.h +++ b/ntcore/src/main/native/include/networktables/NetworkTableInstance.h @@ -37,9 +37,11 @@ class ProtobufTopic; class RawTopic; class StringArrayTopic; class StringTopic; -template +template + requires wpi::StructSerializable class StructArrayTopic; -template +template + requires wpi::StructSerializable class StructTopic; class Subscriber; class Topic; @@ -260,19 +262,24 @@ class NetworkTableInstance final { * Gets a raw struct serialized value topic. * * @param name topic name + * @param info optional struct type info * @return Topic */ - template - StructTopic GetStructTopic(std::string_view name) const; + template + requires wpi::StructSerializable + StructTopic GetStructTopic(std::string_view name, I... info) const; /** * Gets a raw struct serialized array topic. * * @param name topic name + * @param info optional struct type info * @return Topic */ - template - StructArrayTopic GetStructArrayTopic(std::string_view name) const; + template + requires wpi::StructSerializable + StructArrayTopic GetStructArrayTopic(std::string_view name, + I... info) const; /** * Get Published Topics. @@ -589,10 +596,10 @@ class NetworkTableInstance final { /** * Sets server address and port for client (without restarting client). * - * @param server_name server name (UTF-8 string, null terminated) + * @param server_name server name (UTF-8 string) * @param port port to communicate over (0 = default) */ - void SetServer(const char* server_name, unsigned int port = 0); + void SetServer(std::string_view server_name, unsigned int port = 0); /** * Sets server addresses and ports for client (without restarting client). @@ -818,10 +825,12 @@ class NetworkTableInstance final { * Registers a struct schema. Duplicate calls to this function with the same * name are silently ignored. * - * @param T struct serializable type + * @tparam T struct serializable type + * @param info optional struct type info */ - template - void AddStructSchema(); + template + requires wpi::StructSerializable + void AddStructSchema(const I&... info); /** * Equality operator. Returns true if both instances refer to the same diff --git a/ntcore/src/main/native/include/networktables/NetworkTableInstance.inc b/ntcore/src/main/native/include/networktables/NetworkTableInstance.inc index fdd517e2010..20b5c0b58ae 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTableInstance.inc +++ b/ntcore/src/main/native/include/networktables/NetworkTableInstance.inc @@ -44,16 +44,18 @@ inline ProtobufTopic NetworkTableInstance::GetProtobufTopic( return ProtobufTopic{GetTopic(name)}; } -template -inline StructTopic NetworkTableInstance::GetStructTopic( - std::string_view name) const { - return StructTopic{GetTopic(name)}; +template + requires wpi::StructSerializable +inline StructTopic NetworkTableInstance::GetStructTopic( + std::string_view name, I... info) const { + return StructTopic{GetTopic(name), std::move(info)...}; } -template -inline StructArrayTopic NetworkTableInstance::GetStructArrayTopic( - std::string_view name) const { - return StructArrayTopic{GetTopic(name)}; +template + requires wpi::StructSerializable +inline StructArrayTopic NetworkTableInstance::GetStructArrayTopic( + std::string_view name, I... info) const { + return StructArrayTopic{GetTopic(name), std::move(info)...}; } inline std::vector NetworkTableInstance::GetTopics() { @@ -166,7 +168,7 @@ inline void NetworkTableInstance::StopClient() { ::nt::StopClient(m_handle); } -inline void NetworkTableInstance::SetServer(const char* server_name, +inline void NetworkTableInstance::SetServer(std::string_view server_name, unsigned int port) { ::nt::SetServer(m_handle, server_name, port); } @@ -257,6 +259,12 @@ inline void NetworkTableInstance::AddSchema(std::string_view name, ::nt::AddSchema(m_handle, name, type, schema); } +// Suppress unused-lambda-capture warning on AddSchema() call +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-lambda-capture" +#endif + template void NetworkTableInstance::AddProtobufSchema(wpi::ProtobufMessage& msg) { msg.ForEachProtobufDescriptor( @@ -266,11 +274,18 @@ void NetworkTableInstance::AddProtobufSchema(wpi::ProtobufMessage& msg) { }); } -template -void NetworkTableInstance::AddStructSchema() { - wpi::ForEachStructSchema([this](auto typeString, auto schema) { - AddSchema(typeString, "structschema", schema); - }); +template + requires wpi::StructSerializable +void NetworkTableInstance::AddStructSchema(const I&... info) { + wpi::ForEachStructSchema( + [this](auto typeString, auto schema) { + AddSchema(typeString, "structschema", schema); + }, + info...); } +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + } // namespace nt diff --git a/ntcore/src/main/native/include/networktables/NetworkTableType.h b/ntcore/src/main/native/include/networktables/NetworkTableType.h index 4b604543654..3b3e0861552 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTableType.h +++ b/ntcore/src/main/native/include/networktables/NetworkTableType.h @@ -13,17 +13,29 @@ namespace nt { * @ingroup ntcore_cpp_api */ enum class NetworkTableType { + /// Unassigned data type. kUnassigned = NT_UNASSIGNED, + /// Boolean data type. kBoolean = NT_BOOLEAN, + /// Double precision floating-point data type. kDouble = NT_DOUBLE, + /// String data type. kString = NT_STRING, + /// Raw data type. kRaw = NT_RAW, + /// Boolean array data type. kBooleanArray = NT_BOOLEAN_ARRAY, + /// Double precision floating-point array data type. kDoubleArray = NT_DOUBLE_ARRAY, + /// String array data type. kStringArray = NT_STRING_ARRAY, + /// Integer data type. kInteger = NT_INTEGER, + /// Single precision floating-point data type. kFloat = NT_FLOAT, + /// Integer array data type. kIntegerArray = NT_INTEGER_ARRAY, + /// Single precision floating-point array data type. kFloatArray = NT_FLOAT_ARRAY }; diff --git a/ntcore/src/main/native/include/networktables/ProtobufTopic.h b/ntcore/src/main/native/include/networktables/ProtobufTopic.h index eba6bf0caa1..7a56759f673 100644 --- a/ntcore/src/main/native/include/networktables/ProtobufTopic.h +++ b/ntcore/src/main/native/include/networktables/ProtobufTopic.h @@ -212,10 +212,9 @@ class ProtobufPublisher : public Publisher { ProtobufPublisher& operator=(ProtobufPublisher&& rhs) { Publisher::operator=(std::move(rhs)); m_msg = std::move(rhs.m_msg); - m_schemaPublished.clear(); - if (rhs.m_schemaPublished.test()) { - m_schemaPublished.test_and_set(); - } + m_schemaPublished.store( + rhs.m_schemaPublished.load(std::memory_order_relaxed), + std::memory_order_relaxed); return *this; } @@ -229,7 +228,7 @@ class ProtobufPublisher : public Publisher { wpi::SmallVector buf; { std::scoped_lock lock{m_mutex}; - if (!m_schemaPublished.test_and_set()) { + if (!m_schemaPublished.exchange(true, std::memory_order_relaxed)) { GetTopic().GetInstance().template AddProtobufSchema(m_msg); } m_msg.Pack(buf, value); @@ -248,7 +247,7 @@ class ProtobufPublisher : public Publisher { wpi::SmallVector buf; { std::scoped_lock lock{m_mutex}; - if (!m_schemaPublished.test_and_set()) { + if (!m_schemaPublished.exchange(true, std::memory_order_relaxed)) { GetTopic().GetInstance().template AddProtobufSchema(m_msg); } m_msg.Pack(buf, value); @@ -268,7 +267,7 @@ class ProtobufPublisher : public Publisher { private: wpi::mutex m_mutex; wpi::ProtobufMessage m_msg; - std::atomic_flag m_schemaPublished = ATOMIC_FLAG_INIT; + std::atomic_bool m_schemaPublished{false}; }; /** diff --git a/ntcore/src/main/native/include/networktables/StructArrayTopic.h b/ntcore/src/main/native/include/networktables/StructArrayTopic.h index e27b8e462dd..009524a8bf5 100644 --- a/ntcore/src/main/native/include/networktables/StructArrayTopic.h +++ b/ntcore/src/main/native/include/networktables/StructArrayTopic.h @@ -7,9 +7,11 @@ #include #include +#include +#include #include #include -#include +#include #include #include @@ -24,18 +26,20 @@ namespace nt { -template +template + requires wpi::StructSerializable class StructArrayTopic; /** * NetworkTables struct-encoded value array subscriber. */ -template +template + requires wpi::StructSerializable class StructArraySubscriber : public Subscriber { - using S = wpi::Struct; + using S = wpi::Struct; public: - using TopicType = StructArrayTopic; + using TopicType = StructArrayTopic; using ValueType = std::vector; using ParamType = std::span; using TimestampedValueType = Timestamped; @@ -48,15 +52,17 @@ class StructArraySubscriber : public Subscriber { * * @param handle Native handle * @param defaultValue Default value + * @param info optional struct type info */ template #if __cpp_lib_ranges >= 201911L requires std::ranges::range && std::convertible_to, T> #endif - StructArraySubscriber(NT_Subscriber handle, U&& defaultValue) + StructArraySubscriber(NT_Subscriber handle, U&& defaultValue, I... info) : Subscriber{handle}, - m_defaultValue{defaultValue.begin(), defaultValue.end()} { + m_defaultValue{defaultValue.begin(), defaultValue.end()}, + m_info{std::move(info)...} { } /** @@ -121,16 +127,21 @@ class StructArraySubscriber : public Subscriber { #endif TimestampedValueType GetAtomic(U&& defaultValue) const { wpi::SmallVector buf; + size_t size = std::apply(S::GetSize, m_info); TimestampedRawView view = ::nt::GetAtomicRaw(m_subHandle, buf, {}); - if (view.value.size() == 0 || (view.value.size() % S::kSize) != 0) { + if (view.value.size() == 0 || (view.value.size() % size) != 0) { return {0, 0, std::forward(defaultValue)}; } TimestampedValueType rv{view.time, view.serverTime, {}}; - rv.value.reserve(view.value.size() / S::kSize); + rv.value.reserve(view.value.size() / size); for (auto in = view.value.begin(), end = view.value.end(); in != end; - in += S::kSize) { - rv.value.emplace_back( - S::Unpack(std::span{in, in + S::kSize})); + in += size) { + std::apply( + [&](const I&... info) { + rv.value.emplace_back(S::Unpack( + std::span{std::to_address(in), size}, info...)); + }, + m_info); } return rv; } @@ -145,16 +156,21 @@ class StructArraySubscriber : public Subscriber { */ TimestampedValueType GetAtomic(std::span defaultValue) const { wpi::SmallVector buf; + size_t size = std::apply(S::GetSize, m_info); TimestampedRawView view = ::nt::GetAtomicRaw(m_subHandle, buf, {}); - if (view.value.size() == 0 || (view.value.size() % S::kSize) != 0) { + if (view.value.size() == 0 || (view.value.size() % size) != 0) { return {0, 0, {defaultValue.begin(), defaultValue.end()}}; } TimestampedValueType rv{view.time, view.serverTime, {}}; - rv.value.reserve(view.value.size() / S::kSize); + rv.value.reserve(view.value.size() / size); for (auto in = view.value.begin(), end = view.value.end(); in != end; - in += S::kSize) { - rv.value.emplace_back( - S::Unpack(std::span{in, in + S::kSize})); + in += size) { + std::apply( + [&](const I&... info) { + rv.value.emplace_back(S::Unpack( + std::span{std::to_address(in), size}, info...)); + }, + m_info); } return rv; } @@ -174,16 +190,22 @@ class StructArraySubscriber : public Subscriber { auto raw = ::nt::ReadQueueRaw(m_subHandle); std::vector rv; rv.reserve(raw.size()); + size_t size = std::apply(S::GetSize, m_info); for (auto&& r : raw) { - if (r.value.size() == 0 || (r.value.size() % S::kSize) != 0) { + if (r.value.size() == 0 || (r.value.size() % size) != 0) { continue; } std::vector values; - values.reserve(r.value.size() / S::kSize); + values.reserve(r.value.size() / size); for (auto in = r.value.begin(), end = r.value.end(); in != end; - in += S::kSize) { - values.emplace_back( - S::Unpack(std::span{in, in + S::kSize})); + in += size) { + std::apply( + [&](const I&... info) { + values.emplace_back( + S::Unpack(std::span{std::to_address(in), size}, + info...)); + }, + m_info); } rv.emplace_back(r.time, r.serverTime, std::move(values)); } @@ -196,22 +218,30 @@ class StructArraySubscriber : public Subscriber { * @return Topic */ TopicType GetTopic() const { - return StructArrayTopic{::nt::GetTopicFromHandle(m_subHandle)}; + return std::apply( + [&](const I&... info) { + return StructArrayTopic{ + ::nt::GetTopicFromHandle(m_subHandle), info...}; + }, + m_info); } private: ValueType m_defaultValue; + [[no_unique_address]] + std::tuple m_info; }; /** * NetworkTables struct-encoded value array publisher. */ -template +template + requires wpi::StructSerializable class StructArrayPublisher : public Publisher { - using S = wpi::Struct; + using S = wpi::Struct; public: - using TopicType = StructArrayTopic; + using TopicType = StructArrayTopic; using ValueType = std::vector; using ParamType = std::span; @@ -224,8 +254,10 @@ class StructArrayPublisher : public Publisher { * StructTopic::Publish() instead. * * @param handle Native handle + * @param info optional struct type info */ - explicit StructArrayPublisher(NT_Publisher handle) : Publisher{handle} {} + explicit StructArrayPublisher(NT_Publisher handle, I... info) + : Publisher{handle}, m_info{std::move(info)...} {} StructArrayPublisher(const StructArrayPublisher&) = delete; StructArrayPublisher& operator=(const StructArrayPublisher&) = delete; @@ -233,15 +265,17 @@ class StructArrayPublisher : public Publisher { StructArrayPublisher(StructArrayPublisher&& rhs) : Publisher{std::move(rhs)}, m_buf{std::move(rhs.m_buf)}, - m_schemaPublished{rhs.m_schemaPublished} {} + m_schemaPublished{ + rhs.m_schemaPublished.load(std::memory_order_relaxed)}, + m_info{std::move(rhs.m_info)} {} StructArrayPublisher& operator=(StructArrayPublisher&& rhs) { Publisher::operator=(std::move(rhs)); m_buf = std::move(rhs.m_buf); - m_schemaPublished.clear(); - if (rhs.m_schemaPublished.test()) { - m_schemaPublished.test_and_set(); - } + m_schemaPublished.store( + rhs.m_schemaPublished.load(std::memory_order_relaxed), + std::memory_order_relaxed); + m_info = std::move(rhs.m_info); return *this; } @@ -257,11 +291,17 @@ class StructArrayPublisher : public Publisher { std::convertible_to, T> #endif void Set(U&& value, int64_t time = 0) { - if (!m_schemaPublished.test_and_set()) { - GetTopic().GetInstance().template AddStructSchema(); - } - m_buf.Write(std::forward(value), - [&](auto bytes) { ::nt::SetRaw(m_pubHandle, bytes, time); }); + std::apply( + [&](const I&... info) { + if (!m_schemaPublished.exchange(true, std::memory_order_relaxed)) { + GetTopic().GetInstance().template AddStructSchema(info...); + } + m_buf.Write( + std::forward(value), + [&](auto bytes) { ::nt::SetRaw(m_pubHandle, bytes, time); }, + info...); + }, + m_info); } /** @@ -271,8 +311,17 @@ class StructArrayPublisher : public Publisher { * @param time timestamp; 0 indicates current NT time should be used */ void Set(std::span value, int64_t time = 0) { - m_buf.Write(value, - [&](auto bytes) { ::nt::SetRaw(m_pubHandle, bytes, time); }); + std::apply( + [&](const I&... info) { + if (!m_schemaPublished.exchange(true, std::memory_order_relaxed)) { + GetTopic().GetInstance().template AddStructSchema(info...); + } + m_buf.Write( + value, + [&](auto bytes) { ::nt::SetRaw(m_pubHandle, bytes, time); }, + info...); + }, + m_info); } /** @@ -288,11 +337,17 @@ class StructArrayPublisher : public Publisher { std::convertible_to, T> #endif void SetDefault(U&& value) { - if (!m_schemaPublished.test_and_set()) { - GetTopic().GetInstance().template AddStructSchema(); - } - m_buf.Write(std::forward(value), - [&](auto bytes) { ::nt::SetDefaultRaw(m_pubHandle, bytes); }); + std::apply( + [&](const I&... info) { + if (!m_schemaPublished.exchange(true, std::memory_order_relaxed)) { + GetTopic().GetInstance().template AddStructSchema(info...); + } + m_buf.Write( + std::forward(value), + [&](auto bytes) { ::nt::SetDefaultRaw(m_pubHandle, bytes); }, + info...); + }, + m_info); } /** @@ -303,8 +358,17 @@ class StructArrayPublisher : public Publisher { * @param value value */ void SetDefault(std::span value) { - m_buf.Write(value, - [&](auto bytes) { ::nt::SetDefaultRaw(m_pubHandle, bytes); }); + std::apply( + [&](const I&... info) { + if (!m_schemaPublished.exchange(true, std::memory_order_relaxed)) { + GetTopic().GetInstance().template AddStructSchema(info...); + } + m_buf.Write( + value, + [&](auto bytes) { ::nt::SetDefaultRaw(m_pubHandle, bytes); }, + info...); + }, + m_info); } /** @@ -313,12 +377,19 @@ class StructArrayPublisher : public Publisher { * @return Topic */ TopicType GetTopic() const { - return StructArrayTopic{::nt::GetTopicFromHandle(m_pubHandle)}; + return std::apply( + [&](const I&... info) { + return StructArrayTopic{ + ::nt::GetTopicFromHandle(m_pubHandle), info...}; + }, + m_info); } private: - wpi::StructArrayBuffer m_buf; - std::atomic_flag m_schemaPublished = ATOMIC_FLAG_INIT; + wpi::StructArrayBuffer m_buf; + std::atomic_bool m_schemaPublished{false}; + [[no_unique_address]] + std::tuple m_info; }; /** @@ -326,13 +397,14 @@ class StructArrayPublisher : public Publisher { * * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. */ -template -class StructArrayEntry final : public StructArraySubscriber, - public StructArrayPublisher { +template + requires wpi::StructSerializable +class StructArrayEntry final : public StructArraySubscriber, + public StructArrayPublisher { public: - using SubscriberType = StructArraySubscriber; - using PublisherType = StructArrayPublisher; - using TopicType = StructArrayTopic; + using SubscriberType = StructArraySubscriber; + using PublisherType = StructArrayPublisher; + using TopicType = StructArrayTopic; using ValueType = std::vector; using ParamType = std::span; @@ -346,15 +418,16 @@ class StructArrayEntry final : public StructArraySubscriber, * * @param handle Native handle * @param defaultValue Default value + * @param info optional struct type info */ template #if __cpp_lib_ranges >= 201911L requires std::ranges::range && std::convertible_to, T> #endif - StructArrayEntry(NT_Entry handle, U&& defaultValue) - : StructArraySubscriber{handle, defaultValue}, - StructArrayPublisher{handle} { + StructArrayEntry(NT_Entry handle, U&& defaultValue, const I&... info) + : StructArraySubscriber{handle, defaultValue, info...}, + StructArrayPublisher{handle, info...} { } /** @@ -377,7 +450,7 @@ class StructArrayEntry final : public StructArraySubscriber, * @return Topic */ TopicType GetTopic() const { - return StructArrayTopic{::nt::GetTopicFromHandle(this->m_subHandle)}; + return StructArraySubscriber::GetTopic(); } /** @@ -389,12 +462,13 @@ class StructArrayEntry final : public StructArraySubscriber, /** * NetworkTables struct-encoded value array topic. */ -template +template + requires wpi::StructSerializable class StructArrayTopic final : public Topic { public: - using SubscriberType = StructArraySubscriber; - using PublisherType = StructArrayPublisher; - using EntryType = StructArrayEntry; + using SubscriberType = StructArraySubscriber; + using PublisherType = StructArrayPublisher; + using EntryType = StructArrayEntry; using ValueType = std::vector; using ParamType = std::span; using TimestampedValueType = Timestamped; @@ -406,15 +480,19 @@ class StructArrayTopic final : public Topic { * NetworkTableInstance::GetStructTopic() instead. * * @param handle Native handle + * @param info optional struct type info */ - explicit StructArrayTopic(NT_Topic handle) : Topic{handle} {} + explicit StructArrayTopic(NT_Topic handle, I... info) + : Topic{handle}, m_info{std::move(info)...} {} /** * Construct from a generic topic. * * @param topic Topic + * @param info optional struct type info */ - explicit StructArrayTopic(Topic topic) : Topic{topic} {} + explicit StructArrayTopic(Topic topic, I... info) + : Topic{topic}, m_info{std::move(info)...} {} /** * Create a new subscriber to the topic. @@ -439,11 +517,17 @@ class StructArrayTopic final : public Topic { [[nodiscard]] SubscriberType Subscribe( U&& defaultValue, const PubSubOptions& options = kDefaultPubSubOptions) { - return StructArraySubscriber{ - ::nt::Subscribe( - m_handle, NT_RAW, - wpi::MakeStructArrayTypeString(), options), - defaultValue}; + return std::apply( + [&](const I&... info) { + return StructArraySubscriber{ + ::nt::Subscribe( + m_handle, NT_RAW, + wpi::MakeStructArrayTypeString( + info...), + options), + defaultValue, info...}; + }, + m_info); } /** @@ -465,11 +549,17 @@ class StructArrayTopic final : public Topic { SubscriberType Subscribe( std::span defaultValue, const PubSubOptions& options = kDefaultPubSubOptions) { - return StructArraySubscriber{ - ::nt::Subscribe( - m_handle, NT_RAW, - wpi::MakeStructArrayTypeString(), options), - defaultValue}; + return std::apply( + [&](const I&... info) { + return StructArraySubscriber{ + ::nt::Subscribe( + m_handle, NT_RAW, + wpi::MakeStructArrayTypeString( + info...), + options), + defaultValue, info...}; + }, + m_info); } /** @@ -489,9 +579,17 @@ class StructArrayTopic final : public Topic { */ [[nodiscard]] PublisherType Publish(const PubSubOptions& options = kDefaultPubSubOptions) { - return StructArrayPublisher{::nt::Publish( - m_handle, NT_RAW, - wpi::MakeStructArrayTypeString(), options)}; + return std::apply( + [&](const I&... info) { + return StructArrayPublisher{ + ::nt::Publish( + m_handle, NT_RAW, + wpi::MakeStructArrayTypeString( + info...), + options), + info...}; + }, + m_info); } /** @@ -515,10 +613,17 @@ class StructArrayTopic final : public Topic { PublisherType PublishEx( const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions) { - return StructArrayPublisher{::nt::PublishEx( - m_handle, NT_RAW, - wpi::MakeStructArrayTypeString(), properties, - options)}; + return std::apply( + [&](const I&... info) { + return StructArrayPublisher{ + ::nt::PublishEx( + m_handle, NT_RAW, + wpi::MakeStructArrayTypeString( + info...), + properties, options), + info...}; + }, + m_info); } /** @@ -549,11 +654,17 @@ class StructArrayTopic final : public Topic { [[nodiscard]] EntryType GetEntry(U&& defaultValue, const PubSubOptions& options = kDefaultPubSubOptions) { - return StructArrayEntry{ - ::nt::GetEntry(m_handle, NT_RAW, - wpi::MakeStructArrayTypeString(), - options), - defaultValue}; + return std::apply( + [&](const I&... info) { + return StructArrayEntry{ + ::nt::GetEntry( + m_handle, NT_RAW, + wpi::MakeStructArrayTypeString( + info...), + options), + defaultValue, info...}; + }, + m_info); } /** @@ -579,12 +690,22 @@ class StructArrayTopic final : public Topic { [[nodiscard]] EntryType GetEntry(std::span defaultValue, const PubSubOptions& options = kDefaultPubSubOptions) { - return StructArrayEntry{ - ::nt::GetEntry(m_handle, NT_RAW, - wpi::MakeStructArrayTypeString(), - options), - defaultValue}; + return std::apply( + [&](const I&... info) { + return StructArrayEntry{ + ::nt::GetEntry( + m_handle, NT_RAW, + wpi::MakeStructArrayTypeString( + info...), + options), + defaultValue, info...}; + }, + m_info); } + + private: + [[no_unique_address]] + std::tuple m_info; }; } // namespace nt diff --git a/ntcore/src/main/native/include/networktables/StructTopic.h b/ntcore/src/main/native/include/networktables/StructTopic.h index 619f94fa5ab..7097dbc1327 100644 --- a/ntcore/src/main/native/include/networktables/StructTopic.h +++ b/ntcore/src/main/native/include/networktables/StructTopic.h @@ -8,8 +8,10 @@ #include #include +#include #include #include +#include #include #include @@ -23,18 +25,20 @@ namespace nt { -template +template + requires wpi::StructSerializable class StructTopic; /** * NetworkTables struct-encoded value subscriber. */ -template +template + requires wpi::StructSerializable class StructSubscriber : public Subscriber { - using S = wpi::Struct; + using S = wpi::Struct; public: - using TopicType = StructTopic; + using TopicType = StructTopic; using ValueType = T; using ParamType = const T&; using TimestampedValueType = Timestamped; @@ -47,9 +51,12 @@ class StructSubscriber : public Subscriber { * * @param handle Native handle * @param defaultValue Default value + * @param info optional struct type info */ - StructSubscriber(NT_Subscriber handle, T defaultValue) - : Subscriber{handle}, m_defaultValue{std::move(defaultValue)} {} + StructSubscriber(NT_Subscriber handle, T defaultValue, I... info) + : Subscriber{handle}, + m_defaultValue{std::move(defaultValue)}, + m_info{std::move(info)...} {} /** * Get the last published value. @@ -81,12 +88,16 @@ class StructSubscriber : public Subscriber { * @return true if successful */ bool GetInto(T* out) { - wpi::SmallVector buf; + wpi::SmallVector buf; TimestampedRawView view = ::nt::GetAtomicRaw(m_subHandle, buf, {}); - if (view.value.size() < S::kSize) { + if (view.value.size() < std::apply(S::GetSize, m_info)) { return false; } else { - wpi::UnpackStructInto(out, view.value.subspan<0, S::kSize>()); + std::apply( + [&](const I&... info) { + wpi::UnpackStructInto(out, view.value, info...); + }, + m_info); return true; } } @@ -109,13 +120,16 @@ class StructSubscriber : public Subscriber { * @return timestamped value */ TimestampedValueType GetAtomic(const T& defaultValue) const { - wpi::SmallVector buf; + wpi::SmallVector buf; TimestampedRawView view = ::nt::GetAtomicRaw(m_subHandle, buf, {}); - if (view.value.size() < S::kSize) { + if (view.value.size() < std::apply(S::GetSize, m_info)) { return {0, 0, defaultValue}; } else { - return {view.time, view.serverTime, - S::Unpack(view.value.subspan<0, S::kSize>())}; + return { + view.time, view.serverTime, + std::apply( + [&](const I&... info) { return S::Unpack(view.value, info...); }, + m_info)}; } } @@ -135,13 +149,16 @@ class StructSubscriber : public Subscriber { std::vector rv; rv.reserve(raw.size()); for (auto&& r : raw) { - if (r.value.size() < S::kSize) { + if (r.value.size() < std::apply(S::GetSize, m_info)) { continue; } else { - rv.emplace_back( - r.time, r.serverTime, - S::Unpack( - std::span(r.value).subspan<0, S::kSize>())); + std::apply( + [&](const I&... info) { + rv.emplace_back( + r.time, r.serverTime, + S::Unpack(std::span(r.value), info...)); + }, + m_info); } } return rv; @@ -153,22 +170,30 @@ class StructSubscriber : public Subscriber { * @return Topic */ TopicType GetTopic() const { - return StructTopic{::nt::GetTopicFromHandle(m_subHandle)}; + return std::apply( + [&](const I&... info) { + return StructTopic{::nt::GetTopicFromHandle(m_subHandle), + info...}; + }, + m_info); } private: ValueType m_defaultValue; + [[no_unique_address]] + std::tuple m_info; }; /** * NetworkTables struct-encoded value publisher. */ -template +template + requires wpi::StructSerializable class StructPublisher : public Publisher { - using S = wpi::Struct; + using S = wpi::Struct; public: - using TopicType = StructTopic; + using TopicType = StructTopic; using ValueType = T; using ParamType = const T&; @@ -180,14 +205,17 @@ class StructPublisher : public Publisher { StructPublisher& operator=(const StructPublisher&) = delete; StructPublisher(StructPublisher&& rhs) - : Publisher{std::move(rhs)}, m_schemaPublished{rhs.m_schemaPublished} {} + : Publisher{std::move(rhs)}, + m_schemaPublished{ + rhs.m_schemaPublished.load(std::memory_order_relaxed)}, + m_info{std::move(rhs.m_info)} {} StructPublisher& operator=(StructPublisher&& rhs) { Publisher::operator=(std::move(rhs)); - m_schemaPublished.clear(); - if (rhs.m_schemaPublished.test()) { - m_schemaPublished.test_and_set(); - } + m_schemaPublished.store( + rhs.m_schemaPublished.load(std::memory_order_relaxed), + std::memory_order_relaxed); + m_info = std::move(rhs.m_info); return *this; } @@ -196,8 +224,10 @@ class StructPublisher : public Publisher { * StructTopic::Publish() instead. * * @param handle Native handle + * @param info optional struct type info */ - explicit StructPublisher(NT_Publisher handle) : Publisher{handle} {} + explicit StructPublisher(NT_Publisher handle, I... info) + : Publisher{handle}, m_info{std::move(info)...} {} /** * Publish a new value. @@ -206,11 +236,24 @@ class StructPublisher : public Publisher { * @param time timestamp; 0 indicates current NT time should be used */ void Set(const T& value, int64_t time = 0) { - if (!m_schemaPublished.test_and_set()) { - GetTopic().GetInstance().template AddStructSchema(); + if (!m_schemaPublished.exchange(true, std::memory_order_relaxed)) { + std::apply( + [&](const I&... info) { + GetTopic().GetInstance().template AddStructSchema(info...); + }, + m_info); + } + if constexpr (sizeof...(I) == 0) { + if constexpr (wpi::is_constexpr([] { S::GetSize(); })) { + uint8_t buf[S::GetSize()]; + S::Pack(buf, value); + ::nt::SetRaw(m_pubHandle, buf, time); + return; + } } - uint8_t buf[S::kSize]; - S::Pack(buf, value); + wpi::SmallVector buf; + buf.resize_for_overwrite(std::apply(S::GetSize, m_info)); + std::apply([&](const I&... info) { S::Pack(buf, value, info...); }, m_info); ::nt::SetRaw(m_pubHandle, buf, time); } @@ -222,11 +265,24 @@ class StructPublisher : public Publisher { * @param value value */ void SetDefault(const T& value) { - if (!m_schemaPublished.test_and_set()) { - GetTopic().GetInstance().template AddStructSchema(); + if (!m_schemaPublished.exchange(true, std::memory_order_relaxed)) { + std::apply( + [&](const I&... info) { + GetTopic().GetInstance().template AddStructSchema(info...); + }, + m_info); + } + if constexpr (sizeof...(I) == 0) { + if constexpr (wpi::is_constexpr([] { S::GetSize(); })) { + uint8_t buf[S::GetSize()]; + S::Pack(buf, value); + ::nt::SetDefaultRaw(m_pubHandle, buf); + return; + } } - uint8_t buf[S::kSize]; - S::Pack(buf, value); + wpi::SmallVector buf; + buf.resize_for_overwrite(std::apply(S::GetSize, m_info)); + std::apply([&](const I&... info) { S::Pack(buf, value, info...); }, m_info); ::nt::SetDefaultRaw(m_pubHandle, buf); } @@ -236,11 +292,18 @@ class StructPublisher : public Publisher { * @return Topic */ TopicType GetTopic() const { - return StructTopic{::nt::GetTopicFromHandle(m_pubHandle)}; + return std::apply( + [&](const I&... info) { + return StructTopic{::nt::GetTopicFromHandle(m_pubHandle), + info...}; + }, + m_info); } private: - std::atomic_flag m_schemaPublished = ATOMIC_FLAG_INIT; + std::atomic_bool m_schemaPublished{false}; + [[no_unique_address]] + std::tuple m_info; }; /** @@ -248,13 +311,14 @@ class StructPublisher : public Publisher { * * @note Unlike NetworkTableEntry, the entry goes away when this is destroyed. */ -template -class StructEntry final : public StructSubscriber, - public StructPublisher { +template + requires wpi::StructSerializable +class StructEntry final : public StructSubscriber, + public StructPublisher { public: - using SubscriberType = StructSubscriber; - using PublisherType = StructPublisher; - using TopicType = StructTopic; + using SubscriberType = StructSubscriber; + using PublisherType = StructPublisher; + using TopicType = StructTopic; using ValueType = T; using ParamType = const T&; @@ -268,10 +332,11 @@ class StructEntry final : public StructSubscriber, * * @param handle Native handle * @param defaultValue Default value + * @param info optional struct type info */ - StructEntry(NT_Entry handle, T defaultValue) - : StructSubscriber{handle, std::move(defaultValue)}, - StructPublisher{handle} {} + StructEntry(NT_Entry handle, T defaultValue, const I&... info) + : StructSubscriber{handle, std::move(defaultValue), info...}, + StructPublisher{handle, info...} {} /** * Determines if the native handle is valid. @@ -292,9 +357,7 @@ class StructEntry final : public StructSubscriber, * * @return Topic */ - TopicType GetTopic() const { - return StructTopic{::nt::GetTopicFromHandle(this->m_subHandle)}; - } + TopicType GetTopic() const { return StructSubscriber::GetTopic(); } /** * Stops publishing the entry if it's published. @@ -305,12 +368,13 @@ class StructEntry final : public StructSubscriber, /** * NetworkTables struct-encoded value topic. */ -template +template + requires wpi::StructSerializable class StructTopic final : public Topic { public: - using SubscriberType = StructSubscriber; - using PublisherType = StructPublisher; - using EntryType = StructEntry; + using SubscriberType = StructSubscriber; + using PublisherType = StructPublisher; + using EntryType = StructEntry; using ValueType = T; using ParamType = const T&; using TimestampedValueType = Timestamped; @@ -322,15 +386,19 @@ class StructTopic final : public Topic { * NetworkTableInstance::GetStructTopic() instead. * * @param handle Native handle + * @param info optional struct type info */ - explicit StructTopic(NT_Topic handle) : Topic{handle} {} + explicit StructTopic(NT_Topic handle, I... info) + : Topic{handle}, m_info{std::move(info)...} {} /** * Construct from a generic topic. * * @param topic Topic + * @param info optional struct type info */ - explicit StructTopic(Topic topic) : Topic{topic} {} + explicit StructTopic(Topic topic, I... info) + : Topic{topic}, m_info{std::move(info)...} {} /** * Create a new subscriber to the topic. @@ -350,10 +418,15 @@ class StructTopic final : public Topic { [[nodiscard]] SubscriberType Subscribe( T defaultValue, const PubSubOptions& options = kDefaultPubSubOptions) { - return StructSubscriber{ - ::nt::Subscribe(m_handle, NT_RAW, wpi::GetStructTypeString(), - options), - std::move(defaultValue)}; + return std::apply( + [&](const I&... info) { + return StructSubscriber{ + ::nt::Subscribe(m_handle, NT_RAW, + wpi::GetStructTypeString(info...), + options), + std::move(defaultValue), info...}; + }, + m_info); } /** @@ -373,8 +446,15 @@ class StructTopic final : public Topic { */ [[nodiscard]] PublisherType Publish(const PubSubOptions& options = kDefaultPubSubOptions) { - return StructPublisher{::nt::Publish( - m_handle, NT_RAW, wpi::GetStructTypeString(), options)}; + return std::apply( + [&](const I&... info) { + return StructPublisher{ + ::nt::Publish(m_handle, NT_RAW, + wpi::GetStructTypeString(info...), + options), + info...}; + }, + m_info); } /** @@ -398,8 +478,15 @@ class StructTopic final : public Topic { PublisherType PublishEx( const wpi::json& properties, const PubSubOptions& options = kDefaultPubSubOptions) { - return StructPublisher{::nt::PublishEx( - m_handle, NT_RAW, wpi::GetStructTypeString(), properties, options)}; + return std::apply( + [&](const I&... info) { + return StructPublisher{ + ::nt::PublishEx(m_handle, NT_RAW, + wpi::GetStructTypeString(info...), + properties, options), + info...}; + }, + m_info); } /** @@ -425,11 +512,20 @@ class StructTopic final : public Topic { [[nodiscard]] EntryType GetEntry(T defaultValue, const PubSubOptions& options = kDefaultPubSubOptions) { - return StructEntry{ - ::nt::GetEntry(m_handle, NT_RAW, wpi::GetStructTypeString(), - options), - std::move(defaultValue)}; + return std::apply( + [&](const I&... info) { + return StructEntry{ + ::nt::GetEntry(m_handle, NT_RAW, + wpi::GetStructTypeString(info...), + options), + std::move(defaultValue), info...}; + }, + m_info); } + + private: + [[no_unique_address]] + std::tuple m_info; }; } // namespace nt diff --git a/ntcore/src/main/native/include/networktables/Topic.h b/ntcore/src/main/native/include/networktables/Topic.h index d623fbdc342..e34d7facc1c 100644 --- a/ntcore/src/main/native/include/networktables/Topic.h +++ b/ntcore/src/main/native/include/networktables/Topic.h @@ -102,6 +102,21 @@ class Topic { */ bool IsRetained() const; + /** + * Allow storage of the topic's last value, allowing the value to be read (and + * not just accessed through event queues and listeners). + * + * @param cached True for cached, false for not cached. + */ + void SetCached(bool cached); + + /** + * Returns whether the topic's last value is stored. + * + * @return True if the topic is cached. + */ + bool IsCached() const; + /** * Determines if the topic is currently being published. * @@ -381,6 +396,7 @@ class Publisher { Publisher() = default; explicit Publisher(NT_Publisher handle) : m_pubHandle{handle} {} + /// NetworkTables handle. NT_Publisher m_pubHandle{0}; }; diff --git a/ntcore/src/main/native/include/networktables/Topic.inc b/ntcore/src/main/native/include/networktables/Topic.inc index 166dc6d7a12..605f9d8d10d 100644 --- a/ntcore/src/main/native/include/networktables/Topic.inc +++ b/ntcore/src/main/native/include/networktables/Topic.inc @@ -41,6 +41,14 @@ inline bool Topic::IsRetained() const { return ::nt::GetTopicRetained(m_handle); } +inline void Topic::SetCached(bool cached) { + ::nt::SetTopicCached(m_handle, cached); +} + +inline bool Topic::IsCached() const { + return ::nt::GetTopicCached(m_handle); +} + inline bool Topic::Exists() const { return nt::GetTopicExists(m_handle); } diff --git a/ntcore/src/main/native/include/ntcore_c.h b/ntcore/src/main/native/include/ntcore_c.h index 1af0e6623bb..e918aaafa05 100644 --- a/ntcore/src/main/native/include/ntcore_c.h +++ b/ntcore/src/main/native/include/ntcore_c.h @@ -6,6 +6,8 @@ #include +#include + #ifdef __cplusplus #include #else @@ -65,7 +67,11 @@ enum NT_Type { }; /** NetworkTables entry flags. */ -enum NT_EntryFlags { NT_PERSISTENT = 0x01, NT_RETAINED = 0x02 }; +enum NT_EntryFlags { + NT_PERSISTENT = 0x01, + NT_RETAINED = 0x02, + NT_UNCACHED = 0x04 +}; /** NetworkTables logging levels. */ enum NT_LogLevel { @@ -125,23 +131,6 @@ enum NT_EventFlags { * Structures */ -/** A NetworkTables string. */ -struct NT_String { - /** - * String contents (UTF-8). - * The string is NOT required to be zero-terminated. - * When returned by the library, this is zero-terminated and allocated with - * std::malloc(). - */ - char* str; - - /** - * Length of the string in bytes. If the string happens to be zero - * terminated, this does not include the zero-termination. - */ - size_t len; -}; - /** NetworkTables Entry Value. Note this is a typed union. */ struct NT_Value { enum NT_Type type; @@ -152,7 +141,7 @@ struct NT_Value { int64_t v_int; float v_float; double v_double; - struct NT_String v_string; + struct WPI_String v_string; struct { uint8_t* data; size_t size; @@ -174,7 +163,7 @@ struct NT_Value { size_t size; } arr_int; struct { - struct NT_String* arr; + struct WPI_String* arr; size_t size; } arr_string; } data; @@ -186,16 +175,16 @@ struct NT_TopicInfo { NT_Topic topic; /** Topic name */ - struct NT_String name; + struct WPI_String name; /** Topic type */ enum NT_Type type; /** Topic type string */ - struct NT_String type_str; + struct WPI_String type_str; /** Topic properties JSON string */ - struct NT_String properties; + struct WPI_String properties; }; /** NetworkTables Connection Information */ @@ -203,10 +192,10 @@ struct NT_ConnectionInfo { /** * The remote identifier (as set on the remote node by NT_StartClient4(). */ - struct NT_String remote_id; + struct WPI_String remote_id; /** The IP address of the remote node. */ - struct NT_String remote_ip; + struct WPI_String remote_ip; /** The port number of the remote node. */ unsigned int remote_port; @@ -242,13 +231,13 @@ struct NT_LogMessage { unsigned int level; /** The filename of the source file that generated the message. */ - char* filename; + struct WPI_String filename; /** The line number in the source file that generated the message. */ unsigned int line; /** The message. */ - char* message; + struct WPI_String message; }; /** NetworkTables time sync event data. */ @@ -363,6 +352,14 @@ struct NT_PubSubOptions { * internal publisher. */ NT_Bool excludeSelf; + + /** + * For subscriptions, don't share the existence of the subscription with the + * network. Note this means updates will not be received from the network + * unless another subscription overlaps with this one, and the subscription + * will not appear in metatopics. + */ + NT_Bool hidden; }; /** @@ -413,20 +410,18 @@ NT_Inst NT_GetInstanceFromHandle(NT_Handle handle); * * @param inst instance handle * @param name entry name (UTF-8 string) - * @param name_len length of name in bytes * @return entry handle */ -NT_Entry NT_GetEntry(NT_Inst inst, const char* name, size_t name_len); +NT_Entry NT_GetEntry(NT_Inst inst, const struct WPI_String* name); /** * Gets the name of the specified entry. * Returns an empty string if the handle is invalid. * * @param entry entry handle - * @param name_len length of the returned string (output parameter) - * @return Entry name + * @param name entry name (output parameter) */ -char* NT_GetEntryName(NT_Entry entry, size_t* name_len); +void NT_GetEntryName(NT_Entry entry, struct WPI_String* name); /** * Gets the type for the specified key, or unassigned if non existent. @@ -460,6 +455,24 @@ uint64_t NT_GetEntryLastChange(NT_Entry entry); */ void NT_GetEntryValue(NT_Entry entry, struct NT_Value* value); +/** + * Get Entry Value. + * + * Returns copy of current entry value. + * Note that one of the type options is "unassigned". + * + * @param entry entry handle + * @param types bitmask of NT_Type values; 0 is treated specially + * as a "don't care" + * @param value storage for returned entry value + * + * It is the caller's responsibility to free value once it's no longer + * needed (the utility function NT_DisposeValue() is useful for this + * purpose). + */ +void NT_GetEntryValueType(NT_Entry entry, unsigned int types, + struct NT_Value* value); + /** * Set Default Entry Value. * @@ -514,6 +527,21 @@ unsigned int NT_GetEntryFlags(NT_Entry entry); */ struct NT_Value* NT_ReadQueueValue(NT_Handle subentry, size_t* count); +/** + * Read Entry Queue. + * + * Returns new entry values since last call. The returned array must be freed + * using NT_DisposeValueArray(). + * + * @param subentry subscriber or entry handle + * @param types bitmask of NT_Type values; 0 is treated specially + * as a "don't care" + * @param count count of items in returned array (output) + * @return entry value array; returns NULL and count=0 if no new values + */ +struct NT_Value* NT_ReadQueueValueType(NT_Handle subentry, unsigned int types, + size_t* count); + /** @} */ /** @@ -531,13 +559,12 @@ struct NT_Value* NT_ReadQueueValue(NT_Handle subentry, size_t* count); * @param inst instance handle * @param prefix name required prefix; only topics whose name * starts with this string are returned - * @param prefix_len length of prefix in bytes * @param types bitmask of NT_Type values; 0 is treated specially * as a "don't care" * @param count output parameter; set to length of returned array * @return Array of topic handles. */ -NT_Topic* NT_GetTopics(NT_Inst inst, const char* prefix, size_t prefix_len, +NT_Topic* NT_GetTopics(NT_Inst inst, const struct WPI_String* prefix, unsigned int types, size_t* count); /** @@ -550,14 +577,13 @@ NT_Topic* NT_GetTopics(NT_Inst inst, const char* prefix, size_t prefix_len, * @param inst instance handle * @param prefix name required prefix; only topics whose name * starts with this string are returned - * @param prefix_len length of prefix in bytes * @param types array of type strings * @param types_len number of elements in types array * @param count output parameter; set to length of returned array * @return Array of topic handles. */ -NT_Topic* NT_GetTopicsStr(NT_Inst inst, const char* prefix, size_t prefix_len, - const char* const* types, size_t types_len, +NT_Topic* NT_GetTopicsStr(NT_Inst inst, const struct WPI_String* prefix, + const struct WPI_String* types, size_t types_len, size_t* count); /** @@ -570,15 +596,14 @@ NT_Topic* NT_GetTopicsStr(NT_Inst inst, const char* prefix, size_t prefix_len, * @param inst instance handle * @param prefix name required prefix; only topics whose name * starts with this string are returned - * @param prefix_len length of prefix in bytes * @param types bitmask of NT_Type values; 0 is treated specially * as a "don't care" * @param count output parameter; set to length of returned array * @return Array of topic information. */ -struct NT_TopicInfo* NT_GetTopicInfos(NT_Inst inst, const char* prefix, - size_t prefix_len, unsigned int types, - size_t* count); +struct NT_TopicInfo* NT_GetTopicInfos(NT_Inst inst, + const struct WPI_String* prefix, + unsigned int types, size_t* count); /** * Get Topics. @@ -590,15 +615,14 @@ struct NT_TopicInfo* NT_GetTopicInfos(NT_Inst inst, const char* prefix, * @param inst instance handle * @param prefix name required prefix; only topics whose name * starts with this string are returned - * @param prefix_len length of prefix in bytes * @param types array of type strings * @param types_len number of elements in types array * @param count output parameter; set to length of returned array * @return Array of topic information. */ -struct NT_TopicInfo* NT_GetTopicInfosStr(NT_Inst inst, const char* prefix, - size_t prefix_len, - const char* const* types, +struct NT_TopicInfo* NT_GetTopicInfosStr(NT_Inst inst, + const struct WPI_String* prefix, + const struct WPI_String* types, size_t types_len, size_t* count); /** @@ -619,19 +643,18 @@ NT_Bool NT_GetTopicInfo(NT_Topic topic, struct NT_TopicInfo* info); * * @param inst instance handle * @param name topic name - * @param name_len length of topic name in bytes * @return Topic handle. */ -NT_Topic NT_GetTopic(NT_Inst inst, const char* name, size_t name_len); +NT_Topic NT_GetTopic(NT_Inst inst, const struct WPI_String* name); /** * Gets the name of the specified topic. * * @param topic topic handle - * @param name_len length of topic name (output) - * @return Topic name; returns NULL and name_len=0 if the handle is invalid. + * @param name topic name (output); return length of 0 and nullptr if + * handle is invalid. */ -char* NT_GetTopicName(NT_Topic topic, size_t* name_len); +void NT_GetTopicName(NT_Topic topic, struct WPI_String* name); /** * Gets the type for the specified topic, or unassigned if non existent. @@ -645,11 +668,10 @@ enum NT_Type NT_GetTopicType(NT_Topic topic); * Gets the type string for the specified topic. This may have more information * than the numeric type (especially for raw values). * - * @param topic topic handle - * @param type_len length of type string (output) - * @return Topic type string; returns NULL if non-existent + * @param topic topic handle + * @param type topic type string (output) */ -char* NT_GetTopicTypeString(NT_Topic topic, size_t* type_len); +void NT_GetTopicTypeString(NT_Topic topic, struct WPI_String* type); /** * Sets the persistent property of a topic. If true, the stored value is @@ -685,6 +707,24 @@ void NT_SetTopicRetained(NT_Topic topic, NT_Bool value); */ NT_Bool NT_GetTopicRetained(NT_Topic topic); +/** + * Sets the cached property of a topic. If true, the server and clients will + * store the latest value, allowing the value to be read (and not just accessed + * through event queues and listeners). + * + * @param topic topic handle + * @param value True for cached, false for not cached + */ +void NT_SetTopicCached(NT_Topic topic, NT_Bool value); + +/** + * Gets the cached property of a topic. + * + * @param topic topic handle + * @return cached property value + */ +NT_Bool NT_GetTopicCached(NT_Topic topic); + /** * Determine if topic exists (e.g. has at least one publisher). * @@ -698,10 +738,10 @@ NT_Bool NT_GetTopicExists(NT_Handle handle); * * @param topic topic handle * @param name property name - * @param len length of returned string (output) - * @return JSON string; empty string if the property does not exist. + * @param property JSON string (output) */ -char* NT_GetTopicProperty(NT_Topic topic, const char* name, size_t* len); +void NT_GetTopicProperty(NT_Topic topic, const struct WPI_String* name, + struct WPI_String* property); /** * Sets a property value. @@ -710,8 +750,8 @@ char* NT_GetTopicProperty(NT_Topic topic, const char* name, size_t* len); * @param name property name * @param value property value (JSON string) */ -NT_Bool NT_SetTopicProperty(NT_Topic topic, const char* name, - const char* value); +NT_Bool NT_SetTopicProperty(NT_Topic topic, const struct WPI_String* name, + const struct WPI_String* value); /** * Deletes a property. Has no effect if the property does not exist. @@ -719,17 +759,16 @@ NT_Bool NT_SetTopicProperty(NT_Topic topic, const char* name, * @param topic topic handle * @param name property name */ -void NT_DeleteTopicProperty(NT_Topic topic, const char* name); +void NT_DeleteTopicProperty(NT_Topic topic, const struct WPI_String* name); /** * Gets all topic properties as a JSON string. Each key in the object * is the property name, and the corresponding value is the property value. * * @param topic topic handle - * @param len length of returned string (output) - * @return JSON string + * @param properties JSON string (output) */ -char* NT_GetTopicProperties(NT_Topic topic, size_t* len); +void NT_GetTopicProperties(NT_Topic topic, struct WPI_String* properties); /** * Updates multiple topic properties. Each key in the passed-in JSON object is @@ -741,7 +780,8 @@ char* NT_GetTopicProperties(NT_Topic topic, size_t* len); * @param properties JSON object string with keys to add/update/delete * @return False if properties are not a valid JSON object */ -NT_Bool NT_SetTopicProperties(NT_Topic topic, const char* properties); +NT_Bool NT_SetTopicProperties(NT_Topic topic, + const struct WPI_String* properties); /** * Creates a new subscriber to value changes on a topic. @@ -753,7 +793,7 @@ NT_Bool NT_SetTopicProperties(NT_Topic topic, const char* properties); * @return Subscriber handle */ NT_Subscriber NT_Subscribe(NT_Topic topic, enum NT_Type type, - const char* typeStr, + const struct WPI_String* typeStr, const struct NT_PubSubOptions* options); /** @@ -772,7 +812,8 @@ void NT_Unsubscribe(NT_Subscriber sub); * @param options publish options * @return Publisher handle */ -NT_Publisher NT_Publish(NT_Topic topic, enum NT_Type type, const char* typeStr, +NT_Publisher NT_Publish(NT_Topic topic, enum NT_Type type, + const struct WPI_String* typeStr, const struct NT_PubSubOptions* options); /** @@ -786,7 +827,8 @@ NT_Publisher NT_Publish(NT_Topic topic, enum NT_Type type, const char* typeStr, * @return Publisher handle */ NT_Publisher NT_PublishEx(NT_Topic topic, enum NT_Type type, - const char* typeStr, const char* properties, + const struct WPI_String* typeStr, + const struct WPI_String* properties, const struct NT_PubSubOptions* options); /** @@ -805,7 +847,8 @@ void NT_Unpublish(NT_Handle pubentry); * @param options publish options * @return Entry handle */ -NT_Entry NT_GetEntryEx(NT_Topic topic, enum NT_Type type, const char* typeStr, +NT_Entry NT_GetEntryEx(NT_Topic topic, enum NT_Type type, + const struct WPI_String* typeStr, const struct NT_PubSubOptions* options); /** @@ -849,7 +892,7 @@ NT_Topic NT_GetTopicFromHandle(NT_Handle pubsubentry); * @return subscriber handle */ NT_MultiSubscriber NT_SubscribeMultiple(NT_Inst inst, - const struct NT_String* prefixes, + const struct WPI_String* prefixes, size_t prefixes_len, const struct NT_PubSubOptions* options); @@ -933,16 +976,15 @@ NT_Bool NT_WaitForListenerQueue(NT_Handle handle, double timeout); * * @param inst Instance handle * @param prefix Topic name string prefix - * @param prefix_len Length of topic name string prefix * @param mask Bitmask of NT_EventFlags values (only topic and value events will * be generated) * @param data Data passed to callback function * @param callback Listener function * @return Listener handle */ -NT_Listener NT_AddListenerSingle(NT_Inst inst, const char* prefix, - size_t prefix_len, unsigned int mask, - void* data, NT_ListenerCallback callback); +NT_Listener NT_AddListenerSingle(NT_Inst inst, const struct WPI_String* prefix, + unsigned int mask, void* data, + NT_ListenerCallback callback); /** * Create a listener for changes to topics with names that start with any of @@ -959,7 +1001,7 @@ NT_Listener NT_AddListenerSingle(NT_Inst inst, const char* prefix, * @return Listener handle */ NT_Listener NT_AddListenerMultiple(NT_Inst inst, - const struct NT_String* prefixes, + const struct WPI_String* prefixes, size_t prefixes_len, unsigned int mask, void* data, NT_ListenerCallback callback); @@ -993,13 +1035,12 @@ NT_Listener NT_AddListener(NT_Handle handle, unsigned int mask, void* data, * * @param poller poller handle * @param prefix UTF-8 string prefix - * @param prefix_len Length of UTF-8 string prefix * @param mask NT_EventFlags bitmask (only topic and value events * will be generated) * @return Listener handle */ NT_Listener NT_AddPolledListenerSingle(NT_ListenerPoller poller, - const char* prefix, size_t prefix_len, + const struct WPI_String* prefix, unsigned int mask); /** @@ -1015,7 +1056,7 @@ NT_Listener NT_AddPolledListenerSingle(NT_ListenerPoller poller, * @return Listener handle */ NT_Listener NT_AddPolledListenerMultiple(NT_ListenerPoller poller, - const struct NT_String* prefixes, + const struct WPI_String* prefixes, size_t prefixes_len, unsigned int mask); @@ -1081,8 +1122,8 @@ void NT_StopLocal(NT_Inst inst); * @param port3 port to communicate over (NT3) * @param port4 port to communicate over (NT4) */ -void NT_StartServer(NT_Inst inst, const char* persist_filename, - const char* listen_address, unsigned int port3, +void NT_StartServer(NT_Inst inst, const struct WPI_String* persist_filename, + const struct WPI_String* listen_address, unsigned int port3, unsigned int port4); /** @@ -1099,7 +1140,7 @@ void NT_StopServer(NT_Inst inst); * @param inst instance handle * @param identity network identity to advertise (cannot be empty string) */ -void NT_StartClient3(NT_Inst inst, const char* identity); +void NT_StartClient3(NT_Inst inst, const struct WPI_String* identity); /** * Starts a NT4 client. Use NT_SetServer or NT_SetServerTeam to set the server @@ -1108,7 +1149,7 @@ void NT_StartClient3(NT_Inst inst, const char* identity); * @param inst instance handle * @param identity network identity to advertise (cannot be empty string) */ -void NT_StartClient4(NT_Inst inst, const char* identity); +void NT_StartClient4(NT_Inst inst, const struct WPI_String* identity); /** * Stops the client if it is running. @@ -1124,7 +1165,8 @@ void NT_StopClient(NT_Inst inst); * @param server_name server name (UTF-8 string, null terminated) * @param port port to communicate over */ -void NT_SetServer(NT_Inst inst, const char* server_name, unsigned int port); +void NT_SetServer(NT_Inst inst, const struct WPI_String* server_name, + unsigned int port); /** * Sets server addresses for client (without restarting client). @@ -1136,7 +1178,8 @@ void NT_SetServer(NT_Inst inst, const char* server_name, unsigned int port); * terminated) * @param ports array of ports to communicate over (one for each server) */ -void NT_SetServerMulti(NT_Inst inst, size_t count, const char** server_names, +void NT_SetServerMulti(NT_Inst inst, size_t count, + const struct WPI_String* server_names, const unsigned int* ports); /** @@ -1260,21 +1303,6 @@ void NT_DisposeValue(struct NT_Value* value); */ void NT_InitValue(struct NT_Value* value); -/** - * Frees string memory. - * - * @param str string to free - */ -void NT_DisposeString(struct NT_String* str); - -/** - * Initializes a NT_String. - * Sets length to zero and pointer to null. - * - * @param str string to initialize - */ -void NT_InitString(struct NT_String* str); - /** * Frees an array of NT_Values. * @@ -1366,7 +1394,8 @@ void NT_SetNow(int64_t timestamp); * @return Data logger handle */ NT_DataLogger NT_StartEntryDataLog(NT_Inst inst, struct WPI_DataLog* log, - const char* prefix, const char* logPrefix); + const struct WPI_String* prefix, + const struct WPI_String* logPrefix); /** * Stops logging entry changes to a DataLog. @@ -1384,9 +1413,8 @@ void NT_StopEntryDataLog(NT_DataLogger logger); * @param name data log entry name * @return Data logger handle */ -NT_ConnectionDataLogger NT_StartConnectionDataLog(NT_Inst inst, - struct WPI_DataLog* log, - const char* name); +NT_ConnectionDataLogger NT_StartConnectionDataLog( + NT_Inst inst, struct WPI_DataLog* log, const struct WPI_String* name); /** * Stops logging connection changes to a DataLog. @@ -1450,7 +1478,7 @@ NT_Listener NT_AddPolledLogger(NT_ListenerPoller poller, unsigned int min_level, * schema) * @return True if schema already registered */ -NT_Bool NT_HasSchema(NT_Inst inst, const char* name); +NT_Bool NT_HasSchema(NT_Inst inst, const struct WPI_String* name); /** * Registers a data schema. Data schemas provide information for how a @@ -1468,8 +1496,9 @@ NT_Bool NT_HasSchema(NT_Inst inst, const char* name); * @param schema Schema data * @param schemaSize Size of schema data */ -void NT_AddSchema(NT_Inst inst, const char* name, const char* type, - const uint8_t* schema, size_t schemaSize); +void NT_AddSchema(NT_Inst inst, const struct WPI_String* name, + const struct WPI_String* type, const uint8_t* schema, + size_t schemaSize); /** @} */ @@ -1548,19 +1577,6 @@ float* NT_AllocateFloatArray(size_t size); */ double* NT_AllocateDoubleArray(size_t size); -/** - * Allocates an array of NT_Strings. - * Note that the size is the number of elements, and not the - * specific number of bytes to allocate. That is calculated internally. - * - * @param size the number of elements the array will contain - * @return the allocated NT_String array - * - * After use, the array should be freed using the NT_FreeStringArray() - * function. - */ -struct NT_String* NT_AllocateStringArray(size_t size); - /** * Frees an array of chars. * @@ -1596,18 +1612,6 @@ void NT_FreeFloatArray(float* v_float); */ void NT_FreeDoubleArray(double* v_double); -/** - * Frees an array of NT_Strings. - * - * @param v_string pointer to the string array to free - * @param arr_size size of the string array to free - * - * Note that the individual NT_Strings in the array should NOT be - * freed before calling this. This function will free all the strings - * individually. - */ -void NT_FreeStringArray(struct NT_String* v_string, size_t arr_size); - /** @} */ /** @@ -1775,24 +1779,24 @@ double* NT_GetValueDoubleArray(const struct NT_Value* value, uint64_t* last_change, size_t* arr_size); /** - * Returns a copy of the NT_String array from the NT_Value. + * Returns a copy of the struct WPI_String array from the NT_Value. * If the NT_Value is null, or is assigned to a different type, returns null. * - * @param value NT_Value struct to get the NT_String array from + * @param value NT_Value struct to get the struct WPI_String array from * @param last_change returns time in ms since the last change in the value * @param arr_size returns the number of elements in the array - * @return pointer to the NT_String array, or null if error + * @return pointer to the struct WPI_String array, or null if error * * It is the caller's responsibility to free the array once its no longer - * needed. The NT_FreeStringArray() function is useful for this purpose. + * needed. The WPI_FreeStringArray() function is useful for this purpose. * The returned array is a copy of the array in the value, and must be - * freed separately. Note that the individual NT_Strings should not be freed, - * but the entire array should be freed at once. The NT_FreeStringArray() - * function will free all the NT_Strings. + * freed separately. Note that the individual struct WPI_Strings should not be + * freed, but the entire array should be freed at once. The + * WPI_FreeStringArray() function will free all the struct WPI_Strings. */ -struct NT_String* NT_GetValueStringArray(const struct NT_Value* value, - uint64_t* last_change, - size_t* arr_size); +struct WPI_String* NT_GetValueStringArray(const struct NT_Value* value, + uint64_t* last_change, + size_t* arr_size); /** @} */ /** @} */ @@ -1821,7 +1825,7 @@ struct NT_Meta_SubscriberOptions { * Topic publisher (as published via `$pub$`). */ struct NT_Meta_TopicPublisher { - struct NT_String client; + struct WPI_String client; uint64_t pubuid; }; @@ -1829,7 +1833,7 @@ struct NT_Meta_TopicPublisher { * Topic subscriber (as published via `$sub$`). */ struct NT_Meta_TopicSubscriber { - struct NT_String client; + struct WPI_String client; uint64_t subuid; struct NT_Meta_SubscriberOptions options; }; @@ -1839,7 +1843,7 @@ struct NT_Meta_TopicSubscriber { */ struct NT_Meta_ClientPublisher { int64_t uid; - struct NT_String topic; + struct WPI_String topic; }; /** @@ -1848,7 +1852,7 @@ struct NT_Meta_ClientPublisher { struct NT_Meta_ClientSubscriber { int64_t uid; size_t topicsCount; - struct NT_String* topics; + struct WPI_String* topics; struct NT_Meta_SubscriberOptions options; }; @@ -1856,8 +1860,8 @@ struct NT_Meta_ClientSubscriber { * Client (as published via `$clients`). */ struct NT_Meta_Client { - struct NT_String id; - struct NT_String conn; + struct WPI_String id; + struct WPI_String conn; uint16_t version; }; diff --git a/ntcore/src/main/native/include/ntcore_cpp.h b/ntcore/src/main/native/include/ntcore_cpp.h index 482d1e3a9cf..226669927c0 100644 --- a/ntcore/src/main/native/include/ntcore_cpp.h +++ b/ntcore/src/main/native/include/ntcore_cpp.h @@ -374,6 +374,14 @@ struct PubSubOptions { * internal publisher. */ bool excludeSelf = false; + + /** + * For subscriptions, don't share the existence of the subscription with the + * network. Note this means updates will not be received from the network + * unless another subscription overlaps with this one, and the subscription + * will not appear in metatopics. + */ + bool hidden = false; }; /** @@ -528,6 +536,18 @@ unsigned int GetEntryFlags(NT_Entry entry); */ std::vector ReadQueueValue(NT_Handle subentry); +/** + * Read Entry Queue. + * + * Returns new entry values since last call. + * + * @param subentry subscriber or entry handle + * @param types bitmask of NT_Type values; 0 is treated specially + * as a "don't care" + * @return entry value array + */ +std::vector ReadQueueValue(NT_Handle subentry, unsigned int types); + /** @} */ /** @@ -681,6 +701,24 @@ void SetTopicRetained(NT_Topic topic, bool value); */ bool GetTopicRetained(NT_Topic topic); +/** + * Sets the cached property of a topic. If true, the server and clients will + * store the latest value, allowing the value to be read (and not just accessed + * through event queues and listeners). + * + * @param topic topic handle + * @param value True for cached, false for not cached + */ +void SetTopicCached(NT_Topic topic, bool value); + +/** + * Gets the cached property of a topic. + * + * @param topic topic handle + * @return cached property value + */ +bool GetTopicCached(NT_Topic topic); + /** * Determine if topic exists (e.g. has at least one publisher). * @@ -1018,12 +1056,12 @@ void StopLocal(NT_Inst inst); * @param persist_filename the name of the persist file to use (UTF-8 string, * null terminated) * @param listen_address the address to listen on, or null to listen on any - * address. (UTF-8 string, null terminated) + * address. (UTF-8 string) * @param port3 port to communicate over (NT3) * @param port4 port to communicate over (NT4) */ void StartServer(NT_Inst inst, std::string_view persist_filename, - const char* listen_address, unsigned int port3, + std::string_view listen_address, unsigned int port3, unsigned int port4); /** @@ -1065,7 +1103,7 @@ void StopClient(NT_Inst inst); * @param server_name server name (UTF-8 string, null terminated) * @param port port to communicate over */ -void SetServer(NT_Inst inst, const char* server_name, unsigned int port); +void SetServer(NT_Inst inst, std::string_view server_name, unsigned int port); /** * Sets server addresses for client (without restarting client). diff --git a/ntcore/src/main/native/include/ntcore_test.h b/ntcore/src/main/native/include/ntcore_test.h index 7e0244682a8..bc17b6d6aa7 100644 --- a/ntcore/src/main/native/include/ntcore_test.h +++ b/ntcore/src/main/native/include/ntcore_test.h @@ -14,7 +14,7 @@ extern "C" { #endif -struct NT_String* NT_GetStringForTesting(const char* str, int* struct_size); +struct WPI_String* NT_GetStringForTesting(const char* str, int* struct_size); // No need for free as one already exists in main library struct NT_EntryInfo* NT_GetEntryInfoForTesting(const char* name, @@ -54,7 +54,7 @@ struct NT_Value* NT_GetValueDoubleArrayForTesting(uint64_t last_change, int* struct_size); struct NT_Value* NT_GetValueStringArrayForTesting(uint64_t last_change, - const struct NT_String* arr, + const struct WPI_String* arr, size_t array_len, int* struct_size); // No need for free as one already exists in the main library diff --git a/ntcore/src/test/java/edu/wpi/first/networktables/NetworkTableTest.java b/ntcore/src/test/java/edu/wpi/first/networktables/NetworkTableTest.java index 4c431afbdc9..bca694b9903 100644 --- a/ntcore/src/test/java/edu/wpi/first/networktables/NetworkTableTest.java +++ b/ntcore/src/test/java/edu/wpi/first/networktables/NetworkTableTest.java @@ -6,7 +6,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; @@ -61,8 +60,8 @@ private static Stream getHierarchyArguments() { return Stream.of( Arguments.of(Collections.singletonList("/"), ""), Arguments.of(Collections.singletonList("/"), "/"), - Arguments.of(Arrays.asList("/", "/foo", "/foo/bar", "/foo/bar/baz"), "/foo/bar/baz"), - Arguments.of(Arrays.asList("/", "/foo", "/foo/bar", "/foo/bar/"), "/foo/bar/")); + Arguments.of(List.of("/", "/foo", "/foo/bar", "/foo/bar/baz"), "/foo/bar/baz"), + Arguments.of(List.of("/", "/foo", "/foo/bar", "/foo/bar/"), "/foo/bar/")); } @ParameterizedTest diff --git a/ntcore/src/test/java/edu/wpi/first/networktables/RawTest.java b/ntcore/src/test/java/edu/wpi/first/networktables/RawTest.java index 73d5efb3e7c..293d4437bdd 100644 --- a/ntcore/src/test/java/edu/wpi/first/networktables/RawTest.java +++ b/ntcore/src/test/java/edu/wpi/first/networktables/RawTest.java @@ -4,11 +4,10 @@ package edu.wpi.first.networktables; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.ByteBuffer; -import java.util.Arrays; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,9 +30,9 @@ void tearDown() { void testGenericByteArray() { GenericEntry entry = m_inst.getTopic("test").getGenericEntry("raw"); entry.setRaw(new byte[] {5}, 10); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {5})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {5}); entry.setRaw(new byte[] {5, 6, 7}, 1, 2, 15); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6, 7})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6, 7}); assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(new byte[] {5}, -1, 2, 20)); assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(new byte[] {5}, 1, -2, 20)); assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(new byte[] {5}, 1, 1, 20)); @@ -43,9 +42,9 @@ void testGenericByteArray() { void testRawByteArray() { RawEntry entry = m_inst.getRawTopic("test").getEntry("raw", new byte[] {}); entry.set(new byte[] {5}, 10); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {5})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {5}); entry.set(new byte[] {5, 6, 7}, 1, 2, 15); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6, 7})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {6, 7}); assertThrows(IndexOutOfBoundsException.class, () -> entry.set(new byte[] {5}, -1, 1, 20)); assertThrows(IndexOutOfBoundsException.class, () -> entry.set(new byte[] {5}, 1, -1, 20)); assertThrows(IndexOutOfBoundsException.class, () -> entry.set(new byte[] {5}, 1, 1, 20)); @@ -55,15 +54,15 @@ void testRawByteArray() { void testGenericByteBuffer() { GenericEntry entry = m_inst.getTopic("test").getGenericEntry("raw"); entry.setRaw(ByteBuffer.wrap(new byte[] {5}), 10); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {5})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {5}); entry.setRaw(ByteBuffer.wrap(new byte[] {5, 6, 7}).position(1), 15); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6, 7})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6, 7}); entry.setRaw(ByteBuffer.wrap(new byte[] {5, 6, 7}).position(1).limit(2), 16); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6}); entry.setRaw(ByteBuffer.wrap(new byte[] {8, 9, 0}), 1, 2, 20); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {9, 0})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {9, 0}); entry.setRaw(ByteBuffer.wrap(new byte[] {1, 2, 3}).position(2), 0, 2, 25); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {1, 2})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {1, 2}); assertThrows( IndexOutOfBoundsException.class, () -> entry.setRaw(ByteBuffer.wrap(new byte[] {5}), -1, 1, 30)); @@ -79,15 +78,15 @@ void testGenericByteBuffer() { void testRawByteBuffer() { RawEntry entry = m_inst.getRawTopic("test").getEntry("raw", new byte[] {}); entry.set(ByteBuffer.wrap(new byte[] {5}), 10); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {5})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {5}); entry.set(ByteBuffer.wrap(new byte[] {5, 6, 7}).position(1), 15); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6, 7})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {6, 7}); entry.set(ByteBuffer.wrap(new byte[] {5, 6, 7}).position(1).limit(2), 16); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {6}); entry.set(ByteBuffer.wrap(new byte[] {8, 9, 0}), 1, 2, 20); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {9, 0})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {9, 0}); entry.set(ByteBuffer.wrap(new byte[] {1, 2, 3}).position(2), 0, 2, 25); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {1, 2})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {1, 2}); assertThrows( IndexOutOfBoundsException.class, () -> entry.set(ByteBuffer.wrap(new byte[] {5}), -1, 1, 30)); @@ -105,13 +104,13 @@ void testGenericNativeByteBuffer() { ByteBuffer bb = ByteBuffer.allocateDirect(3); bb.put(new byte[] {5, 6, 7}); entry.setRaw(bb.position(1), 15); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6, 7})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6, 7}); entry.setRaw(bb.limit(2), 16); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {6})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {6}); bb.clear(); bb.put(new byte[] {8, 9, 0}); entry.setRaw(bb, 1, 2, 20); - assertTrue(Arrays.equals(entry.getRaw(new byte[] {}), new byte[] {9, 0})); + assertArrayEquals(entry.getRaw(new byte[] {}), new byte[] {9, 0}); assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(bb, -1, 1, 25)); assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(bb, 1, -1, 25)); assertThrows(IndexOutOfBoundsException.class, () -> entry.setRaw(bb, 2, 2, 25)); @@ -123,13 +122,13 @@ void testRawNativeByteBuffer() { ByteBuffer bb = ByteBuffer.allocateDirect(3); bb.put(new byte[] {5, 6, 7}); entry.set(bb.position(1), 15); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6, 7})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {6, 7}); entry.set(bb.limit(2), 16); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {6})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {6}); bb.clear(); bb.put(new byte[] {8, 9, 0}); entry.set(bb, 1, 2, 20); - assertTrue(Arrays.equals(entry.get(new byte[] {}), new byte[] {9, 0})); + assertArrayEquals(entry.get(new byte[] {}), new byte[] {9, 0}); assertThrows(IndexOutOfBoundsException.class, () -> entry.set(bb, -1, 1, 25)); assertThrows(IndexOutOfBoundsException.class, () -> entry.set(bb, 1, -1, 25)); assertThrows(IndexOutOfBoundsException.class, () -> entry.set(bb, 2, 2, 25)); diff --git a/ntcore/src/test/native/cpp/LocalStorageTest.cpp b/ntcore/src/test/native/cpp/LocalStorageTest.cpp index eb57913a01a..cdb52727d8e 100644 --- a/ntcore/src/test/native/cpp/LocalStorageTest.cpp +++ b/ntcore/src/test/native/cpp/LocalStorageTest.cpp @@ -101,6 +101,17 @@ TEST_F(LocalStorageTest, GetTopicInfoUnpublished) { EXPECT_FALSE(storage.GetTopicExists(fooTopic)); } +TEST_F(LocalStorageTest, DefaultProps) { + EXPECT_CALL(network, Publish(_, fooTopic, std::string_view{"foo"}, + std::string_view{"boolean"}, wpi::json::object(), + IsDefaultPubSubOptions())); + storage.Publish(fooTopic, NT_BOOLEAN, "boolean", wpi::json::object(), {}); + + EXPECT_FALSE(storage.GetTopicPersistent(fooTopic)); + EXPECT_FALSE(storage.GetTopicRetained(fooTopic)); + EXPECT_TRUE(storage.GetTopicCached(fooTopic)); +} + TEST_F(LocalStorageTest, PublishNewNoProps) { EXPECT_CALL(network, Publish(_, fooTopic, std::string_view{"foo"}, std::string_view{"boolean"}, wpi::json::object(), diff --git a/ntcore/src/test/native/cpp/StructTest.cpp b/ntcore/src/test/native/cpp/StructTest.cpp new file mode 100644 index 00000000000..55b6a906c36 --- /dev/null +++ b/ntcore/src/test/native/cpp/StructTest.cpp @@ -0,0 +1,450 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include +#include +#include + +#include "networktables/NetworkTableInstance.h" +#include "networktables/StructArrayTopic.h" +#include "networktables/StructTopic.h" + +namespace { +struct Inner { + int a = 0; + int b = 0; +}; + +struct Outer { + Inner inner; + int c = 0; +}; + +struct Inner2 { + int a = 0; + int b = 0; +}; + +struct Outer2 { + Inner2 inner; + int c = 0; +}; + +struct ThingA { + int x = 0; +}; + +struct ThingB { + int x = 0; +}; + +struct Info1 { + int info = 0; +}; +} // namespace + +template <> +struct wpi::Struct { + static constexpr std::string_view GetTypeString() { return "struct:Inner"; } + static constexpr size_t GetSize() { return 8; } + static constexpr std::string_view GetSchema() { return "int32 a; int32 b"; } + + static Inner Unpack(std::span data) { + return {wpi::UnpackStruct(data), + wpi::UnpackStruct(data)}; + } + static void Pack(std::span data, const Inner& value) { + wpi::PackStruct<0>(data, value.a); + wpi::PackStruct<4>(data, value.b); + } +}; + +template <> +struct wpi::Struct { + static constexpr std::string_view GetTypeString() { return "struct:Outer"; } + static constexpr size_t GetSize() { return wpi::GetStructSize() + 4; } + static constexpr std::string_view GetSchema() { + return "Inner inner; int32 c"; + } + + static Outer Unpack(std::span data) { + constexpr size_t innerSize = wpi::GetStructSize(); + return {wpi::UnpackStruct(data), + wpi::UnpackStruct(data)}; + } + static void Pack(std::span data, const Outer& value) { + constexpr size_t innerSize = wpi::GetStructSize(); + wpi::PackStruct<0>(data, value.inner); + wpi::PackStruct(data, value.c); + } + static void ForEachNested( + std::invocable auto fn) { + wpi::ForEachStructSchema(fn); + } +}; + +template <> +struct wpi::Struct { + static std::string_view GetTypeString() { return "struct:Inner2"; } + static size_t GetSize() { return 8; } + static std::string_view GetSchema() { return "int32 a; int32 b"; } + + static Inner2 Unpack(std::span data) { + return {wpi::UnpackStruct(data), + wpi::UnpackStruct(data)}; + } + static void Pack(std::span data, const Inner2& value) { + wpi::PackStruct<0>(data, value.a); + wpi::PackStruct<4>(data, value.b); + } +}; + +template <> +struct wpi::Struct { + static std::string_view GetTypeString() { return "struct:Outer2"; } + static size_t GetSize() { return wpi::GetStructSize() + 4; } + static std::string_view GetSchema() { return "Inner2 inner; int32 c"; } + + static Outer2 Unpack(std::span data) { + size_t innerSize = wpi::GetStructSize(); + return {wpi::UnpackStruct(data), + wpi::UnpackStruct(data.subspan(innerSize))}; + } + static void Pack(std::span data, const Outer2& value) { + size_t innerSize = wpi::GetStructSize(); + wpi::PackStruct<0>(data, value.inner); + wpi::PackStruct(data.subspan(innerSize), value.c); + } + static void ForEachNested( + std::invocable auto fn) { + wpi::ForEachStructSchema(fn); + } +}; + +template <> +struct wpi::Struct { + static constexpr std::string_view GetTypeString() { return "struct:ThingA"; } + static constexpr size_t GetSize() { return 1; } + static constexpr std::string_view GetSchema() { return "uint8 value"; } + static ThingA Unpack(std::span data) { + return ThingA{.x = data[0]}; + } + static void Pack(std::span data, const ThingA& value) { + data[0] = value.x; + } +}; + +template <> +struct wpi::Struct { + static constexpr std::string_view GetTypeString(const Info1&) { + return "struct:ThingB"; + } + static constexpr size_t GetSize(const Info1&) { return 1; } + static constexpr std::string_view GetSchema(const Info1&) { + return "uint8 value"; + } + static ThingB Unpack(std::span data, const Info1&) { + return ThingB{.x = data[0]}; + } + static void Pack(std::span data, const ThingB& value, const Info1&) { + data[0] = value.x; + } +}; + +namespace nt { + +class StructTest : public ::testing::Test { + public: + StructTest() { inst = nt::NetworkTableInstance::Create(); } + ~StructTest() { nt::NetworkTableInstance::Destroy(inst); } + + nt::NetworkTableInstance inst; +}; + +TEST_F(StructTest, InnerConstexpr) { + nt::StructTopic topic = inst.GetStructTopic("inner"); + nt::StructPublisher pub = topic.Publish(); + nt::StructSubscriber sub = topic.Subscribe({}); + + ASSERT_EQ(topic.GetTypeString(), "struct:Inner"); + + pub.SetDefault({0, 1}); + Inner val = sub.Get(); + ASSERT_EQ(val.a, 0); + ASSERT_EQ(val.b, 1); + + pub.Set({1, 2}); + auto atomicVal = sub.GetAtomic(); + ASSERT_EQ(atomicVal.value.a, 1); + ASSERT_EQ(atomicVal.value.b, 2); + + Inner val2; + sub.GetInto(&val2); + ASSERT_EQ(val2.a, 1); + ASSERT_EQ(val2.b, 2); + + auto vals = sub.ReadQueue(); + ASSERT_EQ(vals.size(), 1u); + ASSERT_EQ(vals[0].value.a, 1); + ASSERT_EQ(vals[0].value.b, 2); +} + +TEST_F(StructTest, InnerNonconstexpr) { + nt::StructTopic topic = inst.GetStructTopic("inner2"); + nt::StructPublisher pub = topic.Publish(); + nt::StructSubscriber sub = topic.Subscribe({}); + + ASSERT_EQ(topic.GetTypeString(), "struct:Inner2"); + + pub.SetDefault({0, 1}); + Inner2 val = sub.Get(); + ASSERT_EQ(val.a, 0); + ASSERT_EQ(val.b, 1); + + pub.Set({1, 2}); + auto atomicVal = sub.GetAtomic(); + ASSERT_EQ(atomicVal.value.a, 1); + ASSERT_EQ(atomicVal.value.b, 2); + + Inner2 val2; + sub.GetInto(&val2); + ASSERT_EQ(val2.a, 1); + ASSERT_EQ(val2.b, 2); + + auto vals = sub.ReadQueue(); + ASSERT_EQ(vals.size(), 1u); + ASSERT_EQ(vals[0].value.a, 1); + ASSERT_EQ(vals[0].value.b, 2); +} + +TEST_F(StructTest, OuterConstexpr) { + nt::StructTopic topic = inst.GetStructTopic("outer"); + nt::StructPublisher pub = topic.Publish(); + nt::StructSubscriber sub = topic.Subscribe({}); + + ASSERT_EQ(topic.GetTypeString(), "struct:Outer"); + + pub.SetDefault({{0, 1}, 2}); + Outer val = sub.Get(); + ASSERT_EQ(val.inner.a, 0); + ASSERT_EQ(val.inner.b, 1); + ASSERT_EQ(val.c, 2); + + pub.Set({{1, 2}, 3}); + auto atomicVal = sub.GetAtomic(); + ASSERT_EQ(atomicVal.value.inner.a, 1); + ASSERT_EQ(atomicVal.value.inner.b, 2); + ASSERT_EQ(atomicVal.value.c, 3); + + Outer val2; + sub.GetInto(&val2); + ASSERT_EQ(val2.inner.a, 1); + ASSERT_EQ(val2.inner.b, 2); + ASSERT_EQ(val2.c, 3); + + auto vals = sub.ReadQueue(); + ASSERT_EQ(vals.size(), 1u); + ASSERT_EQ(vals[0].value.inner.a, 1); + ASSERT_EQ(vals[0].value.inner.b, 2); + ASSERT_EQ(vals[0].value.c, 3); +} + +TEST_F(StructTest, OuterNonconstexpr) { + nt::StructTopic topic = inst.GetStructTopic("outer2"); + nt::StructPublisher pub = topic.Publish(); + nt::StructSubscriber sub = topic.Subscribe({}); + + ASSERT_EQ(topic.GetTypeString(), "struct:Outer2"); + + pub.SetDefault({{0, 1}, 2}); + Outer2 val = sub.Get(); + ASSERT_EQ(val.inner.a, 0); + ASSERT_EQ(val.inner.b, 1); + ASSERT_EQ(val.c, 2); + + pub.Set({{1, 2}, 3}); + auto atomicVal = sub.GetAtomic(); + ASSERT_EQ(atomicVal.value.inner.a, 1); + ASSERT_EQ(atomicVal.value.inner.b, 2); + ASSERT_EQ(atomicVal.value.c, 3); + + Outer2 val2; + sub.GetInto(&val2); + ASSERT_EQ(val2.inner.a, 1); + ASSERT_EQ(val2.inner.b, 2); + ASSERT_EQ(val2.c, 3); + + auto vals = sub.ReadQueue(); + ASSERT_EQ(vals.size(), 1u); + ASSERT_EQ(vals[0].value.inner.a, 1); + ASSERT_EQ(vals[0].value.inner.b, 2); + ASSERT_EQ(vals[0].value.c, 3); +} + +TEST_F(StructTest, InnerArrayConstexpr) { + nt::StructArrayTopic topic = inst.GetStructArrayTopic("innerA"); + nt::StructArrayPublisher pub = topic.Publish(); + nt::StructArraySubscriber sub = topic.Subscribe({}); + + ASSERT_EQ(topic.GetTypeString(), "struct:Inner[]"); + + pub.SetDefault({{{0, 1}}}); + auto val = sub.Get(); + ASSERT_EQ(val.size(), 1u); + ASSERT_EQ(val[0].a, 0); + ASSERT_EQ(val[0].b, 1); + + pub.Set({{{1, 2}}}); + auto atomicVal = sub.GetAtomic(); + ASSERT_EQ(atomicVal.value.size(), 1u); + ASSERT_EQ(atomicVal.value[0].a, 1); + ASSERT_EQ(atomicVal.value[0].b, 2); + + auto vals = sub.ReadQueue(); + ASSERT_EQ(vals.size(), 1u); + ASSERT_EQ(vals[0].value.size(), 1u); + ASSERT_EQ(vals[0].value[0].a, 1); + ASSERT_EQ(vals[0].value[0].b, 2); +} + +TEST_F(StructTest, InnerArrayNonconstexpr) { + nt::StructArrayTopic topic = + inst.GetStructArrayTopic("innerA2"); + nt::StructArrayPublisher pub = topic.Publish(); + nt::StructArraySubscriber sub = topic.Subscribe({}); + + ASSERT_EQ(topic.GetTypeString(), "struct:Inner2[]"); + + pub.SetDefault({{{0, 1}}}); + auto val = sub.Get(); + ASSERT_EQ(val.size(), 1u); + ASSERT_EQ(val[0].a, 0); + ASSERT_EQ(val[0].b, 1); + + pub.Set({{{1, 2}}}); + auto atomicVal = sub.GetAtomic(); + ASSERT_EQ(atomicVal.value.size(), 1u); + ASSERT_EQ(atomicVal.value[0].a, 1); + ASSERT_EQ(atomicVal.value[0].b, 2); + + auto vals = sub.ReadQueue(); + ASSERT_EQ(vals.size(), 1u); + ASSERT_EQ(vals[0].value.size(), 1u); + ASSERT_EQ(vals[0].value[0].a, 1); + ASSERT_EQ(vals[0].value[0].b, 2); +} + +TEST_F(StructTest, StructA) { + nt::StructTopic topic = inst.GetStructTopic("a"); + nt::StructPublisher pub = topic.Publish(); + nt::StructPublisher pub2 = topic.PublishEx({{}}); + nt::StructSubscriber sub = topic.Subscribe({}); + nt::StructEntry entry = topic.GetEntry({}); + pub.SetDefault({}); + pub.Set({}, 5); + sub.Get(); + sub.Get({}); + sub.GetAtomic(); + sub.GetAtomic({}); + entry.SetDefault({}); + entry.Set({}, 6); + entry.Get({}); +} + +TEST_F(StructTest, StructArrayA) { + nt::StructArrayTopic topic = inst.GetStructArrayTopic("a"); + nt::StructArrayPublisher pub = topic.Publish(); + nt::StructArrayPublisher pub2 = topic.PublishEx({{}}); + nt::StructArraySubscriber sub = topic.Subscribe({}); + nt::StructArrayEntry entry = topic.GetEntry({}); + pub.SetDefault({{ThingA{}, ThingA{}}}); + pub.Set({{ThingA{}, ThingA{}}}, 5); + sub.Get(); + sub.Get({}); + sub.GetAtomic(); + sub.GetAtomic({}); + entry.SetDefault({{ThingA{}, ThingA{}}}); + entry.Set({{ThingA{}, ThingA{}}}, 6); + entry.Get({}); +} + +TEST_F(StructTest, StructFixedArrayA) { + nt::StructTopic> topic = + inst.GetStructTopic>("a"); + nt::StructPublisher> pub = topic.Publish(); + nt::StructPublisher> pub2 = topic.PublishEx({{}}); + nt::StructSubscriber> sub = topic.Subscribe({}); + nt::StructEntry> entry = topic.GetEntry({}); + std::array arr; + pub.SetDefault(arr); + pub.Set(arr, 5); + sub.Get(); + sub.Get(arr); + sub.GetAtomic(); + sub.GetAtomic(arr); + entry.SetDefault(arr); + entry.Set(arr, 6); + entry.Get(arr); +} + +TEST_F(StructTest, StructB) { + Info1 info; + nt::StructTopic topic = + inst.GetStructTopic("b", info); + nt::StructPublisher pub = topic.Publish(); + nt::StructPublisher pub2 = topic.PublishEx({{}}); + nt::StructSubscriber sub = topic.Subscribe({}); + nt::StructEntry entry = topic.GetEntry({}); + pub.SetDefault({}); + pub.Set({}, 5); + sub.Get(); + sub.Get({}); + sub.GetAtomic(); + sub.GetAtomic({}); + entry.SetDefault({}); + entry.Set({}, 6); + entry.Get({}); +} + +TEST_F(StructTest, StructArrayB) { + Info1 info; + nt::StructArrayTopic topic = + inst.GetStructArrayTopic("b", info); + nt::StructArrayPublisher pub = topic.Publish(); + nt::StructArrayPublisher pub2 = topic.PublishEx({{}}); + nt::StructArraySubscriber sub = topic.Subscribe({}); + nt::StructArrayEntry entry = topic.GetEntry({}); + pub.SetDefault({{ThingB{}, ThingB{}}}); + pub.Set({{ThingB{}, ThingB{}}}, 5); + sub.Get(); + sub.Get({}); + sub.GetAtomic(); + sub.GetAtomic({}); + entry.SetDefault({{ThingB{}, ThingB{}}}); + entry.Set({{ThingB{}, ThingB{}}}, 6); + entry.Get({}); +} + +TEST_F(StructTest, StructFixedArrayB) { + Info1 info; + nt::StructTopic, Info1> topic = + inst.GetStructTopic, Info1>("b", info); + nt::StructPublisher, Info1> pub = topic.Publish(); + nt::StructPublisher, Info1> pub2 = + topic.PublishEx({{}}); + nt::StructSubscriber, Info1> sub = topic.Subscribe({}); + nt::StructEntry, Info1> entry = topic.GetEntry({}); + std::array arr; + pub.SetDefault(arr); + pub.Set(arr, 5); + sub.Get(); + sub.Get(arr); + sub.GetAtomic(); + sub.GetAtomic(arr); + entry.SetDefault(arr); + entry.Set(arr, 6); + entry.Get(arr); +} + +} // namespace nt diff --git a/ntcore/src/test/native/cpp/ValueTest.cpp b/ntcore/src/test/native/cpp/ValueTest.cpp index ba99782ff67..abb0dd5ece9 100644 --- a/ntcore/src/test/native/cpp/ValueTest.cpp +++ b/ntcore/src/test/native/cpp/ValueTest.cpp @@ -84,7 +84,7 @@ TEST_F(ValueTest, String) { NT_InitValue(&cv); ConvertToC(v, &cv); ASSERT_EQ(NT_STRING, cv.type); - ASSERT_EQ("hello"sv, cv.data.v_string.str); + ASSERT_EQ("hello"sv, wpi::to_string_view(&cv.data.v_string)); ASSERT_EQ(5u, cv.data.v_string.len); v = Value::MakeString("goodbye"); @@ -93,7 +93,7 @@ TEST_F(ValueTest, String) { NT_DisposeValue(&cv); ConvertToC(v, &cv); ASSERT_EQ(NT_STRING, cv.type); - ASSERT_EQ("goodbye"sv, cv.data.v_string.str); + ASSERT_EQ("goodbye"sv, wpi::to_string_view(&cv.data.v_string)); ASSERT_EQ(7u, cv.data.v_string.len); NT_DisposeValue(&cv); @@ -226,9 +226,9 @@ TEST_F(ValueTest, StringArray) { ConvertToC(v, &cv); ASSERT_EQ(NT_STRING_ARRAY, cv.type); ASSERT_EQ(3u, cv.data.arr_string.size); - ASSERT_EQ("hello"sv, cv.data.arr_string.arr[0].str); - ASSERT_EQ("goodbye"sv, cv.data.arr_string.arr[1].str); - ASSERT_EQ("string"sv, cv.data.arr_string.arr[2].str); + ASSERT_EQ("hello"sv, wpi::to_string_view(&cv.data.arr_string.arr[0])); + ASSERT_EQ("goodbye"sv, wpi::to_string_view(&cv.data.arr_string.arr[1])); + ASSERT_EQ("string"sv, wpi::to_string_view(&cv.data.arr_string.arr[2])); // assign with same size vec.clear(); @@ -245,9 +245,9 @@ TEST_F(ValueTest, StringArray) { ConvertToC(v, &cv); ASSERT_EQ(NT_STRING_ARRAY, cv.type); ASSERT_EQ(3u, cv.data.arr_string.size); - ASSERT_EQ("s1"sv, cv.data.arr_string.arr[0].str); - ASSERT_EQ("str2"sv, cv.data.arr_string.arr[1].str); - ASSERT_EQ("string3"sv, cv.data.arr_string.arr[2].str); + ASSERT_EQ("s1"sv, wpi::to_string_view(&cv.data.arr_string.arr[0])); + ASSERT_EQ("str2"sv, wpi::to_string_view(&cv.data.arr_string.arr[1])); + ASSERT_EQ("string3"sv, wpi::to_string_view(&cv.data.arr_string.arr[2])); // assign with different size vec.clear(); @@ -262,8 +262,8 @@ TEST_F(ValueTest, StringArray) { ConvertToC(v, &cv); ASSERT_EQ(NT_STRING_ARRAY, cv.type); ASSERT_EQ(2u, cv.data.arr_string.size); - ASSERT_EQ("short"sv, cv.data.arr_string.arr[0].str); - ASSERT_EQ("er"sv, cv.data.arr_string.arr[1].str); + ASSERT_EQ("short"sv, wpi::to_string_view(&cv.data.arr_string.arr[0])); + ASSERT_EQ("er"sv, wpi::to_string_view(&cv.data.arr_string.arr[1])); NT_DisposeValue(&cv); } diff --git a/ntcore/src/test/native/cpp/main.cpp b/ntcore/src/test/native/cpp/main.cpp index 0f060b0e92d..20bd583d2d4 100644 --- a/ntcore/src/test/native/cpp/main.cpp +++ b/ntcore/src/test/native/cpp/main.cpp @@ -10,7 +10,7 @@ #include "ntcore.h" int main(int argc, char** argv) { - wpi::impl::SetupNowRio(); + wpi::impl::SetupNowDefaultOnRio(); nt::AddLogger(nt::GetDefaultInstance(), 0, UINT_MAX, [](auto& event) { if (auto msg = event.GetLogMessage()) { std::fputs(msg->message.c_str(), stderr); diff --git a/ntcore/src/test/native/cpp/net/MockWireConnection.h b/ntcore/src/test/native/cpp/net/MockWireConnection.h index 797ca253b7d..cc2d19b1715 100644 --- a/ntcore/src/test/native/cpp/net/MockWireConnection.h +++ b/ntcore/src/test/native/cpp/net/MockWireConnection.h @@ -63,7 +63,7 @@ class MockWireConnection : public WireConnection { MOCK_METHOD(int, Flush, (), (override)); MOCK_METHOD(uint64_t, GetLastFlushTime, (), (const, override)); - MOCK_METHOD(uint64_t, GetLastPingResponse, (), (const, override)); + MOCK_METHOD(uint64_t, GetLastReceivedTime, (), (const, override)); MOCK_METHOD(void, Disconnect, (std::string_view reason), (override)); }; diff --git a/ntcore/src/test/native/cpp/net/ServerImplTest.cpp b/ntcore/src/test/native/cpp/net/ServerImplTest.cpp index 64238111eed..b1fac0518c5 100644 --- a/ntcore/src/test/native/cpp/net/ServerImplTest.cpp +++ b/ntcore/src/test/native/cpp/net/ServerImplTest.cpp @@ -181,7 +181,7 @@ TEST_F(ServerImplTest, PublishLocal) { // EXPECT_CALL(wire, Flush()).WillOnce(Return(0)); // AddClient() EXPECT_CALL(setPeriodic, Call(100)); // ClientSubscribe() // EXPECT_CALL(wire, Flush()).WillOnce(Return(0)); // ClientSubscribe() - EXPECT_CALL(wire, GetLastPingResponse()).WillOnce(Return(0)); + EXPECT_CALL(wire, GetLastReceivedTime()).WillOnce(Return(0)); EXPECT_CALL(wire, SendPing(100)); EXPECT_CALL(wire, Ready()).WillOnce(Return(true)); // SendControl() EXPECT_CALL( @@ -258,7 +258,7 @@ TEST_F(ServerImplTest, ClientSubTopicOnlyThenValue) { // EXPECT_CALL(wire, Flush()).WillOnce(Return(0)); // AddClient() EXPECT_CALL(setPeriodic, Call(100)); // ClientSubscribe() // EXPECT_CALL(wire, Flush()).WillOnce(Return(0)); // ClientSubscribe() - EXPECT_CALL(wire, GetLastPingResponse()).WillOnce(Return(0)); + EXPECT_CALL(wire, GetLastReceivedTime()).WillOnce(Return(0)); EXPECT_CALL(wire, SendPing(100)); EXPECT_CALL(wire, Ready()).WillOnce(Return(true)); // SendValues() EXPECT_CALL( diff --git a/ntcoreffi/src/main/native/cpp/DataLogManager.cpp b/ntcoreffi/src/main/native/cpp/DataLogManager.cpp index d007f4f064c..2692b8781b0 100644 --- a/ntcoreffi/src/main/native/cpp/DataLogManager.cpp +++ b/ntcoreffi/src/main/native/cpp/DataLogManager.cpp @@ -7,14 +7,17 @@ #include #include #include +#include +#include #include #include #include -#include +#include #include #include #include +#include #include #ifdef __FRC_ROBORIO__ @@ -192,7 +195,7 @@ struct Thread final : public wpi::SafeThread { std::string m_logDir; bool m_filenameOverride; - wpi::log::DataLog m_log; + wpi::log::DataLogBackgroundWriter m_log; bool m_ntLoggerEnabled = false; NT_DataLogger m_ntEntryLogger = 0; NT_ConnectionDataLogger m_ntConnLogger = 0; @@ -217,12 +220,12 @@ static std::string MakeLogDir(std::string_view dir) { } #ifdef __FRC_ROBORIO__ // prefer a mounted USB drive if one is accessible - constexpr std::string_view usbDir{"/u"}; std::error_code ec; - auto s = fs::status(usbDir, ec); + auto s = fs::status("/u", ec); if (!ec && fs::is_directory(s) && (s.permissions() & fs::perms::others_write) != fs::perms::none) { - return std::string{usbDir}; + fs::create_directory("/u/logs", ec); + return "/u/logs"; } if (RobotBase::GetRuntimeType() == kRoboRIO) { FRC_ReportError(warn::Warning, @@ -232,7 +235,10 @@ static std::string MakeLogDir(std::string_view dir) { fs::create_directory("/home/lvuser/logs", ec); return "/home/lvuser/logs"; #else - return filesystem::GetOperatingDirectory(); + std::string logDir = filesystem::GetOperatingDirectory() + "/logs"; + std::error_code ec; + fs::create_directory(logDir, ec); + return logDir; #endif } @@ -307,7 +313,7 @@ void Thread::Main() { break; } } else { - fmt::print(stderr, "DataLogManager: could not delete {}\n", + wpi::print(stderr, "DataLogManager: could not delete {}\n", entry.path().string()); } } @@ -458,7 +464,7 @@ Instance::Instance(std::string_view dir, std::string_view filename, if (wpi::starts_with(entry.path().stem().string(), "FRC_TBD_") && entry.path().extension() == ".wpilog") { if (!fs::remove(entry, ec)) { - fmt::print(stderr, "DataLogManager: could not delete {}\n", + wpi::print(stderr, "DataLogManager: could not delete {}\n", entry.path().string()); } } @@ -490,7 +496,7 @@ void DataLogManager::Stop() { void DataLogManager::Log(std::string_view message) { GetInstance().owner.GetThread()->m_messageLog.Append(message); - fmt::print("{}\n", message); + wpi::print("{}\n", message); } wpi::log::DataLog& DataLogManager::GetLog() { diff --git a/ntcoreffi/src/main/native/include/DataLogManager.h b/ntcoreffi/src/main/native/include/DataLogManager.h index d2635c17e40..79d73eaaec7 100644 --- a/ntcoreffi/src/main/native/include/DataLogManager.h +++ b/ntcoreffi/src/main/native/include/DataLogManager.h @@ -20,8 +20,8 @@ namespace wpi { * Centralized data log that provides automatic data log file management. It * automatically cleans up old files when disk space is low and renames the file * based either on current date/time or (if available) competition match number. - * The deta file will be saved to a USB flash drive if one is attached, or to - * /home/lvuser otherwise. + * The data file will be saved to a USB flash drive in a folder named "logs" if + * one is attached, or to /home/lvuser/logs otherwise. * * Log files are initially named "FRC_TBD_{random}.wpilog" until the DS * connects. After the DS connects, the log file is renamed to diff --git a/ntcoreffi/src/main/native/symbols.txt b/ntcoreffi/src/main/native/symbols.txt index c18014b71c8..aeacd0f849e 100644 --- a/ntcoreffi/src/main/native/symbols.txt +++ b/ntcoreffi/src/main/native/symbols.txt @@ -18,7 +18,6 @@ NT_AllocateCharArray NT_AllocateDoubleArray NT_AllocateFloatArray NT_AllocateIntegerArray -NT_AllocateStringArray NT_CreateInstance NT_CreateListenerPoller NT_DeleteTopicProperty @@ -27,7 +26,6 @@ NT_DestroyListenerPoller NT_DisposeConnectionInfoArray NT_DisposeEvent NT_DisposeEventArray -NT_DisposeString NT_DisposeTimestampedBoolean NT_DisposeTimestampedBooleanArray NT_DisposeTimestampedDouble @@ -62,7 +60,6 @@ NT_FreeQueueIntegerArray NT_FreeQueueRaw NT_FreeQueueString NT_FreeQueueStringArray -NT_FreeStringArray NT_FreeTopicInfoForTesting NT_GetAtomicBoolean NT_GetAtomicBooleanArray @@ -135,7 +132,12 @@ NT_GetValueStringArray NT_GetValueStringArrayForTesting NT_GetValueStringForTesting NT_GetValueType -NT_InitString +WPI_InitString +WPI_InitStringWithLength +WPI_AllocateString +WPI_FreeString +WPI_AllocateStringArray +WPI_FreeStringArray NT_InitValue NT_IsConnected NT_Meta_DecodeClientPublishers @@ -236,22 +238,24 @@ WPI_DataLog_AppendIntegerArray WPI_DataLog_AppendRaw WPI_DataLog_AppendString WPI_DataLog_AppendStringArray -WPI_DataLog_Create -WPI_DataLog_Create_Func +WPI_DataLog_CreateBackgroundWriter +WPI_DataLog_CreateBackgroundWriter_Func +WPI_DataLog_CreateWriter WPI_DataLog_Finish +WPI_DataLog_SetMetadata +WPI_DataLog_Start WPI_DataLog_Flush WPI_DataLog_Pause WPI_DataLog_Release WPI_DataLog_Resume -WPI_DataLog_SetFilename -WPI_DataLog_SetMetadata -WPI_DataLog_Start +WPI_DataLog_SetBackgroundWriterFilename WPI_DataLog_Stop WPI_DestroyEvent WPI_DestroySemaphore WPI_DestroySignalObject WPI_GetSystemTime -WPI_Impl_SetupNowRio +WPI_Impl_SetupNowUseDefaultOnRio +WPI_Impl_SetupNowRioWithSession WPI_Impl_ShutdownNowRio WPI_Now WPI_NowDefault diff --git a/outlineviewer/CMakeLists.txt b/outlineviewer/CMakeLists.txt index a92498e9ef5..eb22df8597e 100644 --- a/outlineviewer/CMakeLists.txt +++ b/outlineviewer/CMakeLists.txt @@ -9,7 +9,7 @@ generate_resources(src/main/native/resources generated/main/cpp OV ov outlinevie file(GLOB outlineviewer_src src/main/native/cpp/*.cpp ${CMAKE_CURRENT_BINARY_DIR}/WPILibVersion.cpp) -if (WIN32) +if(WIN32) set(outlineviewer_rc src/main/native/win/outlineviewer.rc) elseif(APPLE) set(MACOSX_BUNDLE_ICON_FILE ov.icns) @@ -17,12 +17,18 @@ elseif(APPLE) set_source_files_properties(${APP_ICON_MACOSX} PROPERTIES MACOSX_PACKAGE_LOCATION "Resources") endif() -add_executable(outlineviewer ${outlineviewer_src} ${outlineviewer_resources_src} ${outlineviewer_rc} ${APP_ICON_MACOSX}) +add_executable( + outlineviewer + ${outlineviewer_src} + ${outlineviewer_resources_src} + ${outlineviewer_rc} + ${APP_ICON_MACOSX} +) wpilib_link_macos_gui(outlineviewer) wpilib_target_warnings(outlineviewer) target_link_libraries(outlineviewer libglassnt libglass) -if (WIN32) +if(WIN32) set_target_properties(outlineviewer PROPERTIES WIN32_EXECUTABLE YES) elseif(APPLE) set_target_properties(outlineviewer PROPERTIES MACOSX_BUNDLE YES OUTPUT_NAME "OutlineViewer") diff --git a/outlineviewer/publish.gradle b/outlineviewer/publish.gradle index 58222bed964..4cfb7bf14aa 100644 --- a/outlineviewer/publish.gradle +++ b/outlineviewer/publish.gradle @@ -29,51 +29,8 @@ model { def applicationPath = binary.executable.file def icon = file("$project.projectDir/src/main/native/mac/ov.icns") - // Create the macOS bundle. - def bundleTask = project.tasks.create("bundleOutlineViewerOsxApp" + binary.targetPlatform.architecture.name, Copy) { - description("Creates a macOS application bundle for OutlineViewer") - from(file("$project.projectDir/Info.plist")) - into(file("$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name/OutlineViewer.app/Contents")) - into("MacOS") { - with copySpec { - from binary.executable.file - } - } - into("Resources") { - with copySpec { - from icon - } - } - - inputs.property "HasDeveloperId", project.hasProperty("developerID") - - doLast { - if (project.hasProperty("developerID")) { - // Get path to binary. - exec { - workingDir rootDir - def args = [ - "sh", - "-c", - "codesign --force --strict --deep " + - "--timestamp --options=runtime " + - "--verbose -s ${project.findProperty("developerID")} " + - "$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name/OutlineViewer.app/" - ] - commandLine args - } - } - } - } - - // Reset the application path if we are creating a bundle. - if (binary.targetPlatform.operatingSystem.isMacOsX()) { - applicationPath = file("$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name") - project.build.dependsOn bundleTask - } - // Create the ZIP. - def task = project.tasks.create("copyOutlineViewerExecutable" + binary.targetPlatform.architecture.name, Zip) { + def task = project.tasks.create("copyOutlineViewerExecutable" + binary.targetPlatform.operatingSystem.name + binary.targetPlatform.architecture.name, Zip) { description("Copies the OutlineViewer executable to the outputs directory.") destinationDirectory = outputsFolder @@ -85,8 +42,6 @@ model { into '/' } - from(applicationPath) - if (binary.targetPlatform.operatingSystem.isWindows()) { def exePath = binary.executable.file.absolutePath exePath = exePath.substring(0, exePath.length() - 4) @@ -98,8 +53,52 @@ model { } if (binary.targetPlatform.operatingSystem.isMacOsX()) { + // Create the macOS bundle. + def bundleTask = project.tasks.create("bundleOutlineViewerOsxApp" + binary.targetPlatform.architecture.name, Copy) { + description("Creates a macOS application bundle for OutlineViewer") + from(file("$project.projectDir/Info.plist")) + into(file("$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name/OutlineViewer.app/Contents")) + into("MacOS") { + with copySpec { + from binary.executable.file + } + } + into("Resources") { + with copySpec { + from icon + } + } + + inputs.property "HasDeveloperId", project.hasProperty("developerID") + + doLast { + if (project.hasProperty("developerID")) { + // Get path to binary. + exec { + workingDir rootDir + def args = [ + "sh", + "-c", + "codesign --force --strict --deep " + + "--timestamp --options=runtime " + + "--verbose -s ${project.findProperty("developerID")} " + + "$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name/OutlineViewer.app/" + ] + commandLine args + } + } + } + } + + // Reset the application path if we are creating a bundle. + applicationPath = file("$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name") + task.from(applicationPath) + project.build.dependsOn bundleTask + bundleTask.dependsOn binary.tasks.link task.dependsOn(bundleTask) + } else { + task.from(applicationPath) } task.dependsOn binary.tasks.link diff --git a/outlineviewer/src/main/generate/WPILibVersion.cpp.in b/outlineviewer/src/main/generate/WPILibVersion.cpp.in index b0a44905207..cfe24411588 100644 --- a/outlineviewer/src/main/generate/WPILibVersion.cpp.in +++ b/outlineviewer/src/main/generate/WPILibVersion.cpp.in @@ -1,4 +1,4 @@ -/* +/** * Autogenerated file! Do not manually edit this file. This version is regenerated * any time the publish task is run, or when this file is deleted. */ diff --git a/outlineviewer/src/main/native/cpp/main.cpp b/outlineviewer/src/main/native/cpp/main.cpp index 03107569fdf..36801ee3dac 100644 --- a/outlineviewer/src/main/native/cpp/main.cpp +++ b/outlineviewer/src/main/native/cpp/main.cpp @@ -62,7 +62,7 @@ static void NtInitialize() { auto inst = nt::GetDefaultInstance(); auto poller = nt::CreateListenerPoller(inst); nt::AddPolledListener(poller, inst, NT_EVENT_CONNECTION | NT_EVENT_IMMEDIATE); - nt::AddPolledLogger(poller, 0, 100); + nt::AddPolledLogger(poller, NT_LOG_INFO, 100); gui::AddEarlyExecute([inst, poller] { auto win = gui::GetSystemWindow(); if (!win) { diff --git a/roborioteamnumbersetter/CMakeLists.txt b/roborioteamnumbersetter/CMakeLists.txt index 4e2c5e01973..7a43baaed9d 100644 --- a/roborioteamnumbersetter/CMakeLists.txt +++ b/roborioteamnumbersetter/CMakeLists.txt @@ -9,7 +9,7 @@ generate_resources(src/main/native/resources generated/main/cpp RTNS rtns rtns_r file(GLOB rtns_src src/main/native/cpp/*.cpp ${CMAKE_CURRENT_BINARY_DIR}/WPILibVersion.cpp) -if (WIN32) +if(WIN32) set(rtns_rc src/main/native/win/roborioteamnumbersetter.rc) elseif(APPLE) set(MACOSX_BUNDLE_ICON_FILE rtns.icns) @@ -17,13 +17,22 @@ elseif(APPLE) set_source_files_properties(${APP_ICON_MACOSX} PROPERTIES MACOSX_PACKAGE_LOCATION "Resources") endif() -add_executable(roborioteamnumbersetter ${rtns_src} ${rtns_resources_src} ${rtns_rc} ${APP_ICON_MACOSX}) +add_executable( + roborioteamnumbersetter + ${rtns_src} + ${rtns_resources_src} + ${rtns_rc} + ${APP_ICON_MACOSX} +) wpilib_link_macos_gui(roborioteamnumbersetter) target_link_libraries(roborioteamnumbersetter libglass wpinet ${LIBSSH_LIBRARIES}) target_include_directories(roborioteamnumbersetter SYSTEM PRIVATE ${LIBSSH_INCLUDE_DIRS}) -if (WIN32) +if(WIN32) set_target_properties(roborioteamnumbersetter PROPERTIES WIN32_EXECUTABLE YES) elseif(APPLE) - set_target_properties(roborioteamnumbersetter PROPERTIES MACOSX_BUNDLE YES OUTPUT_NAME "roborioTeamNumberSetter") + set_target_properties( + roborioteamnumbersetter + PROPERTIES MACOSX_BUNDLE YES OUTPUT_NAME "roborioTeamNumberSetter" + ) endif() diff --git a/roborioteamnumbersetter/publish.gradle b/roborioteamnumbersetter/publish.gradle index 824c2b91788..83d798d4061 100644 --- a/roborioteamnumbersetter/publish.gradle +++ b/roborioteamnumbersetter/publish.gradle @@ -42,8 +42,6 @@ model { into '/' } - from(applicationPath) - if (binary.targetPlatform.operatingSystem.isWindows()) { def exePath = binary.executable.file.absolutePath exePath = exePath.substring(0, exePath.length() - 4) @@ -94,10 +92,13 @@ model { // Reset the application path if we are creating a bundle. applicationPath = file("$project.buildDir/outputs/bundles/$binary.targetPlatform.architecture.name") + task.from(applicationPath) project.build.dependsOn bundleTask bundleTask.dependsOn binary.tasks.link task.dependsOn(bundleTask) + } else { + task.from(applicationPath) } task.dependsOn binary.tasks.link diff --git a/roborioteamnumbersetter/src/main/generate/WPILibVersion.cpp.in b/roborioteamnumbersetter/src/main/generate/WPILibVersion.cpp.in index b0a44905207..cfe24411588 100644 --- a/roborioteamnumbersetter/src/main/generate/WPILibVersion.cpp.in +++ b/roborioteamnumbersetter/src/main/generate/WPILibVersion.cpp.in @@ -1,4 +1,4 @@ -/* +/** * Autogenerated file! Do not manually edit this file. This version is regenerated * any time the publish task is run, or when this file is deleted. */ diff --git a/roborioteamnumbersetter/src/main/native/cpp/App.cpp b/roborioteamnumbersetter/src/main/native/cpp/App.cpp index eefb52b3a3d..d961fae5eff 100644 --- a/roborioteamnumbersetter/src/main/native/cpp/App.cpp +++ b/roborioteamnumbersetter/src/main/native/cpp/App.cpp @@ -57,6 +57,8 @@ struct TeamNumberRefHolder { static std::unique_ptr teamNumberRef; static std::unordered_map> foundDevices; +static std::unordered_map> + deviceStatuses; static wpi::Logger logger; static sysid::DeploySession deploySession{logger}; static std::unique_ptr multicastResolver; @@ -76,7 +78,12 @@ static void FindDevices() { [](const auto& a) { return a.first == "MAC"; }); if (macKey != data.txt.end()) { auto& mac = macKey->second; - foundDevices[mac] = std::make_pair(data.ipv4Address, data.hostName); + auto& foundDevice = foundDevices[mac]; + foundDevice = std::make_pair(data.ipv4Address, data.hostName); + auto& deviceStatus = deviceStatuses[mac]; + if (!deviceStatus) { + deploySession.GetStatus(mac, foundDevice.first); + } } } } @@ -146,15 +153,12 @@ static void DisplayGui() { int macWidth = ImGui::CalcTextSize("88:88:88:88:88:88").x; int ipAddressWidth = ImGui::CalcTextSize("255.255.255.255").x; int setWidth = ImGui::CalcTextSize(" Set Team To 99999 ").x; - int blinkWidth = ImGui::CalcTextSize(" Blink ").x; - int rebootWidth = ImGui::CalcTextSize(" Reboot ").x; - minWidth = nameWidth + macWidth + ipAddressWidth + setWidth + blinkWidth + - rebootWidth + 100; + minWidth = nameWidth + macWidth + ipAddressWidth + setWidth + 100; std::string setString = fmt::format("Set team to {}", teamNumber); - if (ImGui::BeginTable("Table", 6)) { + if (ImGui::BeginTable("Table", 4)) { ImGui::TableSetupColumn( "Name", ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, @@ -171,17 +175,33 @@ static void DisplayGui() { "Set", ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, setWidth); - ImGui::TableSetupColumn( - "Blink", - ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, - blinkWidth); - ImGui::TableSetupColumn( - "Reboot", - ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, - rebootWidth); ImGui::TableHeadersRow(); - for (auto&& i : foundDevices) { + ImGui::EndTable(); + } + + for (auto&& i : foundDevices) { + std::future* future = deploySession.GetFuture(i.first); + std::future* futureStatus = + deploySession.GetStatusFuture(i.first); + if (ImGui::BeginTable("Table", 4)) { + ImGui::TableSetupColumn( + "Name", + ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, + nameWidth); + ImGui::TableSetupColumn( + "MAC Address", + ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, + macWidth); + ImGui::TableSetupColumn( + "IP Address", + ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, + ipAddressWidth); + ImGui::TableSetupColumn( + "Set", + ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthFixed, + setWidth); + ImGui::TableNextRow(); ImGui::TableNextColumn(); ImGui::Text("%s", i.second.second.c_str()); @@ -192,11 +212,8 @@ static void DisplayGui() { in.s_addr = i.second.first; ImGui::Text("%s", inet_ntoa(in)); ImGui::TableNextColumn(); - std::future* future = deploySession.GetFuture(i.first); ImGui::PushID(i.first.c_str()); if (future) { - ImGui::Button("Deploying"); - ImGui::TableNextColumn(); ImGui::TableNextColumn(); const auto fs = future->wait_for(std::chrono::seconds(0)); if (fs == std::future_status::ready) { @@ -207,18 +224,62 @@ static void DisplayGui() { deploySession.ChangeTeamNumber(i.first, teamNumber, i.second.first); } ImGui::TableNextColumn(); - if (ImGui::Button("Blink")) { - deploySession.Blink(i.first, i.second.first); - } - ImGui::TableNextColumn(); - if (ImGui::Button("Reboot")) { - deploySession.Reboot(i.first, i.second.first); - } } + ImGui::PopID(); + ImGui::EndTable(); } - ImGui::EndTable(); + ImGui::PushID(i.first.c_str()); + if (futureStatus) { + ImGui::Text("Refreshing Status"); + const auto fs = futureStatus->wait_for(std::chrono::seconds(0)); + if (fs == std::future_status::ready) { + deviceStatuses[i.first] = futureStatus->get(); + deploySession.DestroyStatusFuture(i.first); + } + } else { + auto& deviceStatus = deviceStatuses[i.first]; + if (deviceStatus) { + if (ImGui::Button("Refresh Status")) { + deploySession.GetStatus(i.first, i.second.first); + } + std::string formatted = + fmt::format("Image: {}", deviceStatus.value().image); + ImGui::Text("%s", formatted.c_str()); + formatted = fmt::format("Serial Number: {}", + deviceStatus.value().serialNumber); + ImGui::Text("%s", formatted.c_str()); + formatted = fmt::format( + "Web Server Status: {}", + deviceStatus.value().webServerEnabled ? "Enabled" : "Disabled"); + ImGui::Text("%s", formatted.c_str()); + } else { + ImGui::Text("Waiting for refresh"); + } + } + + if (future) { + ImGui::Text("Deploying"); + } else { + if (ImGui::Button("Blink")) { + deploySession.Blink(i.first, i.second.first); + } + ImGui::SameLine(); + if (ImGui::Button("Reboot")) { + deploySession.Reboot(i.first, i.second.first); + } + ImGui::SameLine(); + if (ImGui::Button("Disable Web Server")) { + deploySession.DisableWebServer(i.first, i.second.first); + } + ImGui::SameLine(); + if (ImGui::Button("Enable Web Server")) { + deploySession.EnableWebServer(i.first, i.second.first); + } + } + ImGui::Separator(); + ImGui::PopID(); } ImGui::Columns(6, "Devices"); diff --git a/roborioteamnumbersetter/src/main/native/cpp/DeploySession.cpp b/roborioteamnumbersetter/src/main/native/cpp/DeploySession.cpp index 3fd63cd7129..48fa19852db 100644 --- a/roborioteamnumbersetter/src/main/native/cpp/DeploySession.cpp +++ b/roborioteamnumbersetter/src/main/native/cpp/DeploySession.cpp @@ -37,6 +37,7 @@ static constexpr std::string_view kUsername = "admin"; static constexpr std::string_view kPassword = ""; std::unordered_map> s_outstanding; +std::unordered_map> s_outstandingStatus; DeploySession::DeploySession(wpi::Logger& logger) : m_logger{logger} {} @@ -59,6 +60,19 @@ void DeploySession::DestroyFuture(const std::string& macAddress) { s_outstanding.erase(macAddress); } +std::future* DeploySession::GetStatusFuture( + const std::string& macAddress) { + auto itr = s_outstandingStatus.find(macAddress); + if (itr == s_outstandingStatus.end()) { + return nullptr; + } + return &itr->second; +} + +void DeploySession::DestroyStatusFuture(const std::string& macAddress) { + s_outstandingStatus.erase(macAddress); +} + bool DeploySession::ChangeTeamNumber(const std::string& macAddress, int teamNumber, unsigned int ipAddress) { auto itr = s_outstanding.find(macAddress); @@ -184,3 +198,147 @@ bool DeploySession::Blink(const std::string& macAddress, s_outstanding[macAddress] = std::move(future); return true; } + +bool DeploySession::DisableWebServer(const std::string& macAddress, + unsigned int ipAddress) { + auto itr = s_outstanding.find(macAddress); + if (itr != s_outstanding.end()) { + return false; + } + + std::future future = + std::async(std::launch::async, [this, ipAddress, mac = macAddress]() { + // Convert to IP address. + wpi::SmallString<16> ip; + in_addr addr; + addr.s_addr = ipAddress; + wpi::uv::AddrToName(addr, &ip); + DEBUG("Trying to establish SSH connection to {}.", ip.str()); + try { + SshSession session{ip.str(), kPort, kUsername, kPassword, m_logger}; + session.Open(); + DEBUG("SSH connection to {} was successful.", ip.str()); + + SUCCESS("roboRIO Connected!"); + + try { + session.Execute( + "/bin/bash -c \"/etc/init.d/systemWebServer stop\""); + session.Execute( + "/bin/bash -c \"update-rc.d -f systemWebServer remove\""); + session.Execute("/bin/bash -c \"sync\""); + } catch (const SshSession::SshException& e) { + ERROR("An exception occurred: {}", e.what()); + throw e; + } + } catch (const SshSession::SshException& e) { + DEBUG("SSH connection to {} failed with {}.", ip.str(), e.what()); + throw e; + } + return 0; + }); + + s_outstanding[macAddress] = std::move(future); + return true; +} + +bool DeploySession::EnableWebServer(const std::string& macAddress, + unsigned int ipAddress) { + auto itr = s_outstanding.find(macAddress); + if (itr != s_outstanding.end()) { + return false; + } + + std::future future = + std::async(std::launch::async, [this, ipAddress, mac = macAddress]() { + // Convert to IP address. + wpi::SmallString<16> ip; + in_addr addr; + addr.s_addr = ipAddress; + wpi::uv::AddrToName(addr, &ip); + DEBUG("Trying to establish SSH connection to {}.", ip.str()); + try { + SshSession session{ip.str(), kPort, kUsername, kPassword, m_logger}; + session.Open(); + DEBUG("SSH connection to {} was successful.", ip.str()); + + SUCCESS("roboRIO Connected!"); + + try { + session.Execute( + "/bin/bash -c \"update-rc.d -f systemWebServer defaults\""); + session.Execute( + "/bin/bash -c \"/etc/init.d/systemWebServer start\""); + session.Execute("/bin/bash -c \"sync\""); + } catch (const SshSession::SshException& e) { + ERROR("An exception occurred: {}", e.what()); + throw e; + } + } catch (const SshSession::SshException& e) { + DEBUG("SSH connection to {} failed with {}.", ip.str(), e.what()); + throw e; + } + return 0; + }); + + s_outstanding[macAddress] = std::move(future); + return true; +} + +bool DeploySession::GetStatus(const std::string& macAddress, + unsigned int ipAddress) { + auto itr = s_outstandingStatus.find(macAddress); + if (itr != s_outstandingStatus.end()) { + return false; + } + + std::future future = + std::async(std::launch::async, [this, ipAddress, mac = macAddress]() { + // Convert to IP address. + wpi::SmallString<16> ip; + in_addr addr; + addr.s_addr = ipAddress; + wpi::uv::AddrToName(addr, &ip); + DEBUG("Trying to establish SSH connection to {}.", ip.str()); + DeviceStatus status; + try { + SshSession session{ip.str(), kPort, kUsername, kPassword, m_logger}; + session.Open(); + DEBUG("SSH connection to {} was successful.", ip.str()); + + SUCCESS("roboRIO Connected!"); + + try { + int exitStatus = 0; + session.ExecuteResult( + "start-stop-daemon --status -x " + "/usr/local/natinst/share/NIWebServer/SystemWebServer", + &exitStatus); + status.webServerEnabled = exitStatus == 0; + auto serialNumber = session.ExecuteResult( + "/sbin/fw_printenv -n serial#", &exitStatus); + if (exitStatus == 0) { + status.serialNumber = wpi::trim(serialNumber); + } + auto image = session.ExecuteResult( + "/usr/local/natinst/bin/nirtcfg --file " + "/etc/natinst/share/scs_imagemetadata.ini --get " + "section=ImageMetadata,token=IMAGEVERSION,value=UNKNOWN", + &exitStatus); + if (exitStatus == 0) { + status.image = wpi::trim(image); + } + } catch (const SshSession::SshException& e) { + ERROR("An exception occurred: {}", e.what()); + throw e; + } + } catch (const SshSession::SshException& e) { + DEBUG("SSH connection to {} failed with {}.", ip.str(), e.what()); + throw e; + } + return status; + }); + + s_outstandingStatus[macAddress] = std::move(future); + return true; +} diff --git a/roborioteamnumbersetter/src/main/native/cpp/DeploySession.h b/roborioteamnumbersetter/src/main/native/cpp/DeploySession.h index 7cc5bc78535..5586e9826c1 100644 --- a/roborioteamnumbersetter/src/main/native/cpp/DeploySession.h +++ b/roborioteamnumbersetter/src/main/native/cpp/DeploySession.h @@ -18,6 +18,12 @@ namespace sysid { // GUI). static constexpr unsigned int kLogSuccess = 31; +struct DeviceStatus { + bool webServerEnabled = false; + std::string serialNumber; + std::string image; +}; + /** * Represents a single deploy session. * @@ -49,15 +55,19 @@ class DeploySession { bool Blink(const std::string& macAddress, unsigned int ipAddress); + bool DisableWebServer(const std::string& macAddress, unsigned int ipAddress); + + bool EnableWebServer(const std::string& macAddress, unsigned int ipAddress); + bool Reboot(const std::string& macAddress, unsigned int ipAddress); + bool GetStatus(const std::string& macAddress, unsigned int ipAddress); + std::future* GetFuture(const std::string& macAddress); void DestroyFuture(const std::string& macAddress); - /** - * Returns the state of the deploy session. - */ - Status GetStatus() const; + std::future* GetStatusFuture(const std::string& macAddress); + void DestroyStatusFuture(const std::string& macAddress); private: // Logger reference where log messages will be sent. diff --git a/roborioteamnumbersetter/src/main/native/cpp/SshSession.cpp b/roborioteamnumbersetter/src/main/native/cpp/SshSession.cpp index 74fc6385b89..95bbb158015 100644 --- a/roborioteamnumbersetter/src/main/native/cpp/SshSession.cpp +++ b/roborioteamnumbersetter/src/main/native/cpp/SshSession.cpp @@ -86,13 +86,28 @@ void SshSession::Execute(std::string_view cmd) { ssh_channel_free(channel); throw SshException(ssh_get_error(m_session)); } - INFO("{}", cmd); + INFO("{} {}", ssh_channel_get_exit_status(channel), cmd); // Log output. char buf[512]; int read = ssh_channel_read(channel, buf, sizeof(buf), 0); if (read != 0) { - INFO("{}", cmd); + if (read < static_cast(sizeof(buf) / sizeof(buf[0]))) { + buf[read] = 0; + } else { + buf[(sizeof(buf) / sizeof(buf[0])) - 1] = 0; + } + INFO("stdout: {} {}", read, buf); + } + + read = ssh_channel_read(channel, buf, sizeof(buf), 1); + if (read != 0) { + if (read < static_cast(sizeof(buf) / sizeof(buf[0]))) { + buf[read] = 0; + } else { + buf[(sizeof(buf) / sizeof(buf[0])) - 1] = 0; + } + INFO("stderr: {} {}", read, buf); } // Close and free channel. @@ -100,6 +115,64 @@ void SshSession::Execute(std::string_view cmd) { ssh_channel_free(channel); } +std::string SshSession::ExecuteResult(std::string_view cmd, int* exitStatus) { + // Allocate a new channel. + ssh_channel channel = ssh_channel_new(m_session); + if (!channel) { + throw SshException(ssh_get_error(m_session)); + } + + // Open the channel. + int rc = ssh_channel_open_session(channel); + if (rc != SSH_OK) { + throw SshException(ssh_get_error(m_session)); + } + + // Execute the command. + std::string command{cmd}; + rc = ssh_channel_request_exec(channel, command.c_str()); + if (rc != SSH_OK) { + ssh_channel_close(channel); + ssh_channel_free(channel); + throw SshException(ssh_get_error(m_session)); + } + INFO("{} {}", ssh_channel_get_exit_status(channel), cmd); + + std::string result; + if (exitStatus) { + *exitStatus = ssh_channel_get_exit_status(channel); + } + + // Log output. + char buf[512]; + int read = ssh_channel_read(channel, buf, sizeof(buf), 0); + if (read != 0) { + if (read < static_cast(sizeof(buf) / sizeof(buf[0]))) { + buf[read] = 0; + } else { + buf[(sizeof(buf) / sizeof(buf[0])) - 1] = 0; + } + result = buf; + INFO("stdout: {} {}", read, buf); + } + + read = ssh_channel_read(channel, buf, sizeof(buf), 1); + if (read != 0) { + if (read < static_cast(sizeof(buf) / sizeof(buf[0]))) { + buf[read] = 0; + } else { + buf[(sizeof(buf) / sizeof(buf[0])) - 1] = 0; + } + INFO("stderr: {} {}", read, buf); + } + + // Close and free channel. + ssh_channel_close(channel); + ssh_channel_free(channel); + + return result; +} + void SshSession::Put(std::string_view path, std::string_view contents) { // Allocate the SFTP session. sftp_session sftp = sftp_new(m_session); diff --git a/roborioteamnumbersetter/src/main/native/cpp/SshSession.h b/roborioteamnumbersetter/src/main/native/cpp/SshSession.h index 47db332dad2..df91a07f65f 100644 --- a/roborioteamnumbersetter/src/main/native/cpp/SshSession.h +++ b/roborioteamnumbersetter/src/main/native/cpp/SshSession.h @@ -58,6 +58,8 @@ class SshSession { */ void Execute(std::string_view cmd); + std::string ExecuteResult(std::string_view cmd, int* exitStatus); + /** * Puts a file on the server using SFTP. * diff --git a/roborioteamnumbersetter/src/main/native/cpp/main.cpp b/roborioteamnumbersetter/src/main/native/cpp/main.cpp index 5f1261b00f4..3d1a1965f29 100644 --- a/roborioteamnumbersetter/src/main/native/cpp/main.cpp +++ b/roborioteamnumbersetter/src/main/native/cpp/main.cpp @@ -1,25 +1,25 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include - -void Application(std::string_view saveDir); - -#ifdef _WIN32 -int __stdcall WinMain(void* hInstance, void* hPrevInstance, char* pCmdLine, - int nCmdShow) { - int argc = __argc; - char** argv = __argv; -#else -int main(int argc, char** argv) { -#endif - std::string_view saveDir; - if (argc == 2) { - saveDir = argv[1]; - } - - Application(saveDir); - - return 0; -} +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include + +void Application(std::string_view saveDir); + +#ifdef _WIN32 +int __stdcall WinMain(void* hInstance, void* hPrevInstance, char* pCmdLine, + int nCmdShow) { + int argc = __argc; + char** argv = __argv; +#else +int main(int argc, char** argv) { +#endif + std::string_view saveDir; + if (argc == 2) { + saveDir = argv[1]; + } + + Application(saveDir); + + return 0; +} diff --git a/romiVendordep/CMakeLists.txt b/romiVendordep/CMakeLists.txt index 72b55c815b3..4cc6a075e49 100644 --- a/romiVendordep/CMakeLists.txt +++ b/romiVendordep/CMakeLists.txt @@ -4,38 +4,50 @@ include(SubDirList) include(CompileWarnings) include(AddTest) -if (WITH_JAVA) - find_package(Java REQUIRED) - include(UseJava) - set(CMAKE_JAVA_COMPILE_FLAGS "-encoding" "UTF8" "-Xlint:unchecked") - - file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java) - add_jar(romiVendordep_jar ${JAVA_SOURCES} INCLUDE_JARS hal_jar ntcore_jar cscore_jar cameraserver_jar wpimath_jar wpiunits_jar wpiutil_jar wpilibj_jar OUTPUT_NAME romiVendordep) - - get_property(ROMIVENDORDEP_JAR_FILE TARGET romiVendordep_jar PROPERTY JAR_FILE) - install(FILES ${ROMIVENDORDEP_JAR_FILE} DESTINATION "${java_lib_dest}") - - set_property(TARGET romiVendordep_jar PROPERTY FOLDER "java") - - if (WITH_FLAT_INSTALL) - set (romiVendordep_config_dir ${wpilib_dest}) - else() - set (romiVendordep_config_dir share/romiVendordep) - endif() +if(WITH_JAVA) + find_package(Java REQUIRED) + include(UseJava) + set(CMAKE_JAVA_COMPILE_FLAGS "-encoding" "UTF8" "-Xlint:unchecked") + + file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java) + add_jar( + romiVendordep_jar + ${JAVA_SOURCES} + INCLUDE_JARS + hal_jar + ntcore_jar + cscore_jar + cameraserver_jar + wpimath_jar + wpiunits_jar + wpiutil_jar + wpilibj_jar + OUTPUT_NAME romiVendordep + ) + + install_jar(romiVendordep_jar DESTINATION ${java_lib_dest}) + install_jar_exports( + TARGETS romiVendordep_jar + FILE romiVendordep_jar.cmake + DESTINATION share/romiVendordep + ) endif() -if (WITH_JAVA_SOURCE) - find_package(Java REQUIRED) - include(UseJava) - file(GLOB_RECURSE ROMIVENDORDEP_SOURCES src/main/java/*.java) - add_jar(romiVendordep_src_jar - RESOURCES NAMESPACE "edu/wpi/first/wpilibj/romi" ${ROMIVENDORDEP_SOURCES} - OUTPUT_NAME romiVendordep-sources) - - get_property(ROMIVENDORDEP_SRC_JAR_FILE TARGET romiVendordep_src_jar PROPERTY JAR_FILE) - install(FILES ${ROMIVENDORDEP_JAR_FILE} DESTINATION "${java_lib_dest}") - - set_property(TARGET romiVendordep_src_jar PROPERTY FOLDER "java") +if(WITH_JAVA_SOURCE) + find_package(Java REQUIRED) + include(UseJava) + file(GLOB_RECURSE ROMIVENDORDEP_SOURCES src/main/java/*.java) + add_jar( + romiVendordep_src_jar + RESOURCES + NAMESPACE "edu/wpi/first/wpilibj/romi" ${ROMIVENDORDEP_SOURCES} + OUTPUT_NAME romiVendordep-sources + ) + + get_property(ROMIVENDORDEP_SRC_JAR_FILE TARGET romiVendordep_src_jar PROPERTY JAR_FILE) + install(FILES ${ROMIVENDORDEP_JAR_FILE} DESTINATION "${java_lib_dest}") + + set_property(TARGET romiVendordep_src_jar PROPERTY FOLDER "java") endif() file(GLOB_RECURSE romiVendordep_native_src src/main/native/cpp/*.cpp) @@ -47,25 +59,23 @@ target_compile_features(romiVendordep PUBLIC cxx_std_20) wpilib_target_warnings(romiVendordep) target_link_libraries(romiVendordep wpilibc) -target_include_directories(romiVendordep PUBLIC - $ - $) +target_include_directories( + romiVendordep + PUBLIC + $ + $ +) -install(TARGETS romiVendordep EXPORT romiVendordep DESTINATION "${main_lib_dest}") +install(TARGETS romiVendordep EXPORT romivendordep DESTINATION "${main_lib_dest}") +export(TARGETS romiVendordep FILE romivendordep.cmake NAMESPACE romivendordep::) install(DIRECTORY src/main/native/include/ DESTINATION "${include_dest}/romiVendordep") -if (FLAT_INSTALL_WPILIB) - set(romiVendordep_config_dir ${wpilib_dest}) - else() - set(romiVendordep_config_dir share/romiVendordep) - endif() +configure_file(romivendordep-config.cmake.in ${WPILIB_BINARY_DIR}/romivendordep-config.cmake) +install(FILES ${WPILIB_BINARY_DIR}/romivendordep-config.cmake DESTINATION share/romiVendordep) +install(EXPORT romivendordep DESTINATION share/romiVendordep) - configure_file(romiVendordep-config.cmake.in ${WPILIB_BINARY_DIR}/romiVendordep-config.cmake) - install(FILES ${WPILIB_BINARY_DIR}/romiVendordep-config.cmake DESTINATION ${romiVendordep_config_dir}) - install(EXPORT romiVendordep DESTINATION ${romiVendordep_config_dir}) - - if (WITH_TESTS) - wpilib_add_test(romiVendordep src/test/native/cpp) - target_include_directories(romiVendordep_test PRIVATE src/test/native/include) - target_link_libraries(romiVendordep_test romiVendordep gmock_main) - endif() +if(WITH_TESTS) + wpilib_add_test(romiVendordep src/test/native/cpp) + target_include_directories(romiVendordep_test PRIVATE src/test/native/include) + target_link_libraries(romiVendordep_test romiVendordep gmock_main) +endif() diff --git a/romiVendordep/romiVendordep-config.cmake.in b/romiVendordep/romiVendordep-config.cmake.in deleted file mode 100644 index 3711d9cd6dc..00000000000 --- a/romiVendordep/romiVendordep-config.cmake.in +++ /dev/null @@ -1,11 +0,0 @@ -include(CMakeFindDependencyMacro) - @WPIUTIL_DEP_REPLACE@ - @NTCORE_DEP_REPLACE@ - @CSCORE_DEP_REPLACE@ - @CAMERASERVER_DEP_REPLACE@ - @HAL_DEP_REPLACE@ - @WPILIBC_DEP_REPLACE@ - @WPIMATH_DEP_REPLACE@ - - @FILENAME_DEP_REPLACE@ - include(${SELF_DIR}/romiVendordep.cmake) diff --git a/romiVendordep/romivendordep-config.cmake.in b/romiVendordep/romivendordep-config.cmake.in new file mode 100644 index 00000000000..d4a80f0d6ae --- /dev/null +++ b/romiVendordep/romivendordep-config.cmake.in @@ -0,0 +1,14 @@ +include(CMakeFindDependencyMacro) +@WPIUTIL_DEP_REPLACE@ +@NTCORE_DEP_REPLACE@ +@CSCORE_DEP_REPLACE@ +@CAMERASERVER_DEP_REPLACE@ +@HAL_DEP_REPLACE@ +@WPILIBC_DEP_REPLACE@ +@WPIMATH_DEP_REPLACE@ + +@FILENAME_DEP_REPLACE@ +include(${SELF_DIR}/romivendordep.cmake) +if(@WITH_JAVA@) + include(${SELF_DIR}/romiVendordep_jar.cmake) +endif() diff --git a/romiVendordep/src/main/java/edu/wpi/first/wpilibj/romi/RomiMotor.java b/romiVendordep/src/main/java/edu/wpi/first/wpilibj/romi/RomiMotor.java index 93024f6a2cd..1a56bf78bc5 100644 --- a/romiVendordep/src/main/java/edu/wpi/first/wpilibj/romi/RomiMotor.java +++ b/romiVendordep/src/main/java/edu/wpi/first/wpilibj/romi/RomiMotor.java @@ -14,7 +14,7 @@ */ public class RomiMotor extends PWMMotorController { /** Common initialization code called by all constructors. */ - protected void initRomiMotor() { + protected final void initRomiMotor() { m_pwm.setPeriodMultiplier(PWM.PeriodMultiplier.k1X); m_pwm.setSpeed(0.0); m_pwm.setZeroLatch(); diff --git a/romiVendordep/src/test/native/cpp/main.cpp b/romiVendordep/src/test/native/cpp/main.cpp index 2d710be58f7..a2b90c59137 100644 --- a/romiVendordep/src/test/native/cpp/main.cpp +++ b/romiVendordep/src/test/native/cpp/main.cpp @@ -1,10 +1,10 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include - -int main(int argc, char** argv) { - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/shared/config.gradle b/shared/config.gradle index 36aee7f5cdf..5acadb030bc 100644 --- a/shared/config.gradle +++ b/shared/config.gradle @@ -15,7 +15,7 @@ nativeUtils { configureDependencies { opencvYear = "frc2024" googleTestYear = "frc2024" - niLibVersion = "2024.1.1" + niLibVersion = "2024.2.1" opencvVersion = "4.8.0-2" googleTestVersion = "1.14.0-1" } diff --git a/shared/java/javacommon.gradle b/shared/java/javacommon.gradle index 32078f8f108..46ad707bb60 100644 --- a/shared/java/javacommon.gradle +++ b/shared/java/javacommon.gradle @@ -104,7 +104,7 @@ configurations { tasks.withType(JavaCompile).configureEach { options.compilerArgs = [ '--release', - '11', + '17', '-encoding', 'UTF8', "-Werror", @@ -117,9 +117,8 @@ tasks.withType(JavaCompile).configureEach { } dependencies { - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.0' - testImplementation 'org.junit.jupiter:junit-jupiter-params:5.10.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.0' + testImplementation 'org.junit.jupiter:junit-jupiter:5.10.1' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' devImplementation sourceSets.main.output } @@ -147,22 +146,12 @@ protobuf { protoc { artifact = 'com.google.protobuf:protoc:3.21.12' } - plugins { - quickbuf { - artifact = 'us.hebi.quickbuf:protoc-gen-quickbuf:1.3.2' - } - } generateProtoTasks { all().configureEach { task -> task.builtins { cpp {} remove java } - task.plugins { - quickbuf { - option "gen_descriptors=true" - } - } } } } diff --git a/shared/java/javastyle.gradle b/shared/java/javastyle.gradle index 49332bf7484..41ddb47e6d0 100644 --- a/shared/java/javastyle.gradle +++ b/shared/java/javastyle.gradle @@ -1,83 +1,85 @@ -if (!project.hasProperty('skipJavaFormat')) { - apply plugin: 'checkstyle' +if (project.hasProperty('skipJavaFormat')) { + return; +} - checkstyle { - toolVersion = "10.12.2" - configDirectory = file("${project.rootDir}/styleguide") - config = resources.text.fromFile(new File(configDirectory.get().getAsFile(), "checkstyle.xml")) - } +apply plugin: 'checkstyle' + +checkstyle { + toolVersion = "10.12.2" + configDirectory = file("${project.rootDir}/styleguide") + config = resources.text.fromFile(new File(configDirectory.get().getAsFile(), "checkstyle.xml")) +} - apply plugin: 'pmd' +apply plugin: 'pmd' - pmd { - toolVersion = '6.55.0' - consoleOutput = true - reportsDir = file("$project.buildDir/reports/pmd") - ruleSetFiles = files(new File(rootDir, "styleguide/pmd-ruleset.xml")) - ruleSets = [] - } +pmd { + toolVersion = '6.55.0' + consoleOutput = true + reportsDir = file("$project.buildDir/reports/pmd") + ruleSetFiles = files(new File(rootDir, "styleguide/pmd-ruleset.xml")) + ruleSets = [] +} - apply plugin: 'com.diffplug.spotless' +apply plugin: 'com.diffplug.spotless' - spotless { - java { - target fileTree('.') { - include '**/*.java' - exclude '**/build/**', '**/build-*/**', '**/bin/**' - } - toggleOffOn() - googleJavaFormat() - removeUnusedImports() - trimTrailingWhitespace() - endWithNewline() +spotless { + java { + target fileTree('.') { + include '**/*.java' + exclude '**/build/**', '**/build-*/**', '**/bin/**', "src/generated/**" } - groovyGradle { - target fileTree('.') { - include '**/*.gradle' - exclude '**/build/**', '**/build-*/**', '**/bin/**' - } - greclipse() - indentWithSpaces(4) - trimTrailingWhitespace() - endWithNewline() + toggleOffOn() + googleJavaFormat() + removeUnusedImports() + trimTrailingWhitespace() + endWithNewline() + } + groovyGradle { + target fileTree('.') { + include '**/*.gradle' + exclude '**/build/**', '**/build-*/**', '**/bin/**' } - json { - target fileTree('.') { - include '**/*.json' - exclude '**/build/**', '**/build-*/**', '**/bin/**' - exclude '**/simgui-ds.json', '**/simgui-window.json', '**/simgui.json', '**/networktables.json' - } - gson() - .indentWithSpaces(2) + greclipse() + indentWithSpaces(4) + trimTrailingWhitespace() + endWithNewline() + } + json { + target fileTree('.') { + include '**/*.json' + exclude '**/build/**', '**/build-*/**', '**/bin/**' + exclude '**/simgui-ds.json', '**/simgui-window.json', '**/simgui.json', '**/networktables.json' } - format 'xml', { - target fileTree('.') { - include '**/*.xml' - exclude '**/build/**', '**/build-*/**', '**/bin/**', '**/.idea/**', '**/.run/**' - } - eclipseWtp('xml') - trimTrailingWhitespace() - indentWithSpaces(2) - endWithNewline() + gson() + .indentWithSpaces(2) + } + format 'xml', { + target fileTree('.') { + include '**/*.xml' + exclude '**/build/**', '**/build-*/**', '**/bin/**', '**/.idea/**', '**/.run/**' } - format 'misc', { - target fileTree('.') { - include '**/*.md', '**/.gitignore' - exclude '**/build/**', '**/build-*/**', '**/bin/**' - } - trimTrailingWhitespace() - indentWithSpaces(2) - endWithNewline() + eclipseWtp('xml') + trimTrailingWhitespace() + indentWithSpaces(2) + endWithNewline() + } + format 'misc', { + target fileTree('.') { + include '**/*.md', '**/.gitignore' + exclude '**/build/**', '**/build-*/**', '**/bin/**' } + trimTrailingWhitespace() + indentWithSpaces(2) + endWithNewline() } +} - apply plugin: 'com.github.spotbugs' +apply plugin: 'com.github.spotbugs' - spotbugs { - ignoreFailures = false - effort = 'max' - excludeFilter = file("${project.rootDir}/styleguide/spotbugs-exclude.xml") - } +spotbugs { + ignoreFailures = false + effort = spotbugsEffort + excludeFilter = file("${project.rootDir}/styleguide/spotbugs-exclude.xml") } task javaFormat { diff --git a/shared/jni/setupBuild.gradle b/shared/jni/setupBuild.gradle index de7c50f49ba..fda467366e1 100644 --- a/shared/jni/setupBuild.gradle +++ b/shared/jni/setupBuild.gradle @@ -62,8 +62,8 @@ model { it.buildable = false return } - it.cppCompiler.define 'WPILIB_EXPORTS' - it.cCompiler.define 'WPILIB_EXPORTS' + it.cppCompiler.define 'WPILIB_EXPORTS', 'SLEIPNIR_EXPORTS' + it.cCompiler.define 'WPILIB_EXPORTS', 'SLEIPNIR_EXPORTS' if (!project.hasProperty('noWpiutil')) { lib project: ':wpiutil', library: 'wpiutil', linkage: 'shared' } diff --git a/simulation/CMakeLists.txt b/simulation/CMakeLists.txt index 0a1a9535434..e6bc35c7d16 100644 --- a/simulation/CMakeLists.txt +++ b/simulation/CMakeLists.txt @@ -1,4 +1,4 @@ -if (WITH_GUI) +if(WITH_GUI) add_subdirectory(halsim_gui) endif() add_subdirectory(halsim_ds_socket) diff --git a/simulation/halsim_ds_socket/CMakeLists.txt b/simulation/halsim_ds_socket/CMakeLists.txt index 4eb23bb708f..c549bd3195e 100644 --- a/simulation/halsim_ds_socket/CMakeLists.txt +++ b/simulation/halsim_ds_socket/CMakeLists.txt @@ -14,3 +14,4 @@ target_include_directories(halsim_ds_socket PRIVATE src/main/native/include) set_property(TARGET halsim_ds_socket PROPERTY FOLDER "libraries") install(TARGETS halsim_ds_socket EXPORT halsim_ds_socket) +export(TARGETS halsim_ds_socket FILE halsim_ds_socket.cmake NAMESPACE halsim_ds_socket::) diff --git a/simulation/halsim_ds_socket/src/main/native/cpp/main.cpp b/simulation/halsim_ds_socket/src/main/native/cpp/main.cpp index e602ecc08be..7bb86d71c59 100644 --- a/simulation/halsim_ds_socket/src/main/native/cpp/main.cpp +++ b/simulation/halsim_ds_socket/src/main/native/cpp/main.cpp @@ -20,8 +20,8 @@ #include #include -#include #include +#include #include #include #include @@ -119,7 +119,7 @@ static void SetupUdp(wpi::uv::Loop& loop) { simLoopTimer->timeout.connect([udpLocal = udp.get(), simAddr] { udpLocal->Send(simAddr, {singleByte.get(), 1}, [](auto buf, Error err) { if (err) { - fmt::print(stderr, "{}\n", err.str()); + wpi::print(stderr, "{}\n", err.str()); std::fflush(stderr); } }); @@ -131,7 +131,7 @@ static void SetupUdp(wpi::uv::Loop& loop) { try { timeoutMs = std::stoi(envTimeout); } catch (const std::exception& e) { - fmt::print(stderr, "Error parsing DS_TIMEOUT_MS: {}\n", e.what()); + wpi::print(stderr, "Error parsing DS_TIMEOUT_MS: {}\n", e.what()); } } auto autoDisableTimer = Timer::Create(loop); @@ -158,7 +158,7 @@ static void SetupUdp(wpi::uv::Loop& loop) { udpLocal->Send(outAddr, sendBufs, [](auto bufs, Error err) { GetBufferPool().Release(bufs); if (err) { - fmt::print(stderr, "{}\n", err.str()); + wpi::print(stderr, "{}\n", err.str()); std::fflush(stderr); } }); diff --git a/simulation/halsim_gui/CMakeLists.txt b/simulation/halsim_gui/CMakeLists.txt index 957a9c223fb..81d57d200f8 100644 --- a/simulation/halsim_gui/CMakeLists.txt +++ b/simulation/halsim_gui/CMakeLists.txt @@ -17,3 +17,4 @@ target_include_directories(halsim_gui PRIVATE src/main/native/include) set_property(TARGET halsim_gui PROPERTY FOLDER "libraries") install(TARGETS halsim_gui EXPORT halsim_gui) +export(TARGETS halsim_gui FILE halsim_gui.cmake NAMESPACE halsim_gui::) diff --git a/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.cpp b/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.cpp index 4edaa5c770d..5639c147c27 100644 --- a/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.cpp @@ -227,37 +227,25 @@ class FMSSimModel : public glass::FMSModel { glass::DataSource* GetAutonomousData() override { return &m_autonomous; } std::string_view GetGameSpecificMessage( wpi::SmallVectorImpl& buf) override { - HAL_MatchInfo info; - HALSIM_GetMatchInfo(&info); - buf.clear(); - buf.append(info.gameSpecificMessage, - info.gameSpecificMessage + info.gameSpecificMessageSize); - return std::string_view(buf.begin(), buf.size()); + return m_gameMessage; } - void SetFmsAttached(bool val) override { - HALSIM_SetDriverStationFmsAttached(val); - } - void SetDsAttached(bool val) override { - HALSIM_SetDriverStationDsAttached(val); - } + void SetFmsAttached(bool val) override { m_fmsAttached.SetValue(val); } + void SetDsAttached(bool val) override { m_dsAttached.SetValue(val); } void SetAllianceStationId(int val) override { - HALSIM_SetDriverStationAllianceStationId( - static_cast(val)); - } - void SetMatchTime(double val) override { - HALSIM_SetDriverStationMatchTime(val); - } - void SetEStop(bool val) override { HALSIM_SetDriverStationEStop(val); } - void SetEnabled(bool val) override { HALSIM_SetDriverStationEnabled(val); } - void SetTest(bool val) override { HALSIM_SetDriverStationTest(val); } - void SetAutonomous(bool val) override { - HALSIM_SetDriverStationAutonomous(val); + m_allianceStationId.SetValue(val); } + void SetMatchTime(double val) override { m_matchTime.SetValue(val); } + void SetEStop(bool val) override { m_estop.SetValue(val); } + void SetEnabled(bool val) override { m_enabled.SetValue(val); } + void SetTest(bool val) override { m_test.SetValue(val); } + void SetAutonomous(bool val) override { m_autonomous.SetValue(val); } void SetGameSpecificMessage(std::string_view val) override { - HALSIM_SetGameSpecificMessage(val.data(), val.size()); + m_gameMessage = val; } + void UpdateHAL(); + void Update() override; bool Exists() override { return true; } @@ -274,6 +262,7 @@ class FMSSimModel : public glass::FMSModel { glass::DataSource m_test{"FMS:TestMode"}; glass::DataSource m_autonomous{"FMS:AutonomousMode"}; double m_startMatchTime = -1.0; + std::string m_gameMessage; }; } // namespace @@ -609,6 +598,7 @@ void KeyboardJoystick::EditKey(const char* label, int* key) { void KeyboardJoystick::SettingsDisplay() { if (s_keyEdit) { ImGuiIO& io = ImGui::GetIO(); + // NOLINTNEXTLINE(bugprone-sizeof-expression) for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); ++i) { if (io.KeysDown[i]) { // remove all other uses @@ -1018,6 +1008,21 @@ void RobotJoystick::GetHAL(int i) { HALSIM_GetJoystickPOVs(i, &data.povs); } +static void DriverStationConnect(bool enabled, bool autonomous, bool test) { + if (!HALSIM_GetDriverStationDsAttached()) { + // initialize FMS bits too + gFMSModel->SetDsAttached(true); + gFMSModel->SetEnabled(enabled); + gFMSModel->SetAutonomous(autonomous); + gFMSModel->SetTest(test); + gFMSModel->UpdateHAL(); + } else { + HALSIM_SetDriverStationEnabled(enabled); + HALSIM_SetDriverStationAutonomous(autonomous); + HALSIM_SetDriverStationTest(test); + } +} + static void DriverStationExecute() { // update sources for (int i = 0; i < HAL_kMaxJoysticks; ++i) { @@ -1071,6 +1076,7 @@ static void DriverStationExecute() { joy.Update(); } + bool isAttached = HALSIM_GetDriverStationDsAttached(); bool isEnabled = HALSIM_GetDriverStationEnabled(); bool isAuto = HALSIM_GetDriverStationAutonomous(); bool isTest = HALSIM_GetDriverStationTest(); @@ -1099,38 +1105,45 @@ static void DriverStationExecute() { ImGui::SetNextWindowPos(ImVec2{5, 20}, ImGuiCond_FirstUseEver); ImGui::Begin("Robot State", nullptr, ImGuiWindowFlags_AlwaysAutoResize); - if (ImGui::Selectable("Disabled", !isEnabled) || disableHotkey) { + if (ImGui::Selectable("Disconnected", !isAttached)) { HALSIM_SetDriverStationEnabled(false); + HALSIM_SetDriverStationDsAttached(false); + isAttached = false; + gFMSModel->Update(); + } + if (ImGui::Selectable("Disabled", isAttached && !isEnabled) || + disableHotkey) { + DriverStationConnect(false, false, false); } - if (ImGui::Selectable("Autonomous", isEnabled && isAuto && !isTest)) { - HALSIM_SetDriverStationAutonomous(true); - HALSIM_SetDriverStationTest(false); - HALSIM_SetDriverStationEnabled(true); + if (ImGui::Selectable("Autonomous", + isAttached && isEnabled && isAuto && !isTest)) { + DriverStationConnect(true, true, false); } - if (ImGui::Selectable("Teleoperated", isEnabled && !isAuto && !isTest) || + if (ImGui::Selectable("Teleoperated", + isAttached && isEnabled && !isAuto && !isTest) || enableHotkey) { - HALSIM_SetDriverStationAutonomous(false); - HALSIM_SetDriverStationTest(false); - HALSIM_SetDriverStationEnabled(true); + DriverStationConnect(true, false, false); } if (ImGui::Selectable("Test", isEnabled && isTest)) { - HALSIM_SetDriverStationAutonomous(false); - HALSIM_SetDriverStationTest(true); - HALSIM_SetDriverStationEnabled(true); + DriverStationConnect(true, false, true); } ImGui::End(); } // Update HAL - for (int i = 0, end = gRobotJoysticks.size(); - i < end && i < HAL_kMaxJoysticks; ++i) { - gRobotJoysticks[i].SetHAL(i); + if (isAttached) { + for (int i = 0, end = gRobotJoysticks.size(); + i < end && i < HAL_kMaxJoysticks; ++i) { + gRobotJoysticks[i].SetHAL(i); + } } // Send new data every 20 ms (may be slower depending on GUI refresh rate) static double lastNewDataTime = 0.0; - if ((curTime - lastNewDataTime) > 0.02 && !HALSIM_IsTimingPaused()) { + if ((curTime - lastNewDataTime) > 0.02 && !HALSIM_IsTimingPaused() && + isAttached) { lastNewDataTime = curTime; + gFMSModel->Update(); HALSIM_NotifyDriverStationNewData(); } } @@ -1143,6 +1156,21 @@ FMSSimModel::FMSSimModel() { m_test.SetDigital(true); m_autonomous.SetDigital(true); m_matchTime.SetValue(-1.0); + m_allianceStationId.SetValue(HAL_AllianceStationID_kRed1); +} + +void FMSSimModel::UpdateHAL() { + HALSIM_SetDriverStationFmsAttached(m_fmsAttached.GetValue()); + HALSIM_SetDriverStationAllianceStationId( + static_cast(m_allianceStationId.GetValue())); + HALSIM_SetDriverStationEStop(m_estop.GetValue()); + HALSIM_SetDriverStationEnabled(m_enabled.GetValue()); + HALSIM_SetDriverStationTest(m_test.GetValue()); + HALSIM_SetDriverStationAutonomous(m_autonomous.GetValue()); + HALSIM_SetDriverStationMatchTime(m_matchTime.GetValue()); + auto str = wpi::make_string(m_gameMessage); + HALSIM_SetGameSpecificMessage(&str); + HALSIM_SetDriverStationDsAttached(m_dsAttached.GetValue()); } void FMSSimModel::Update() { @@ -1175,6 +1203,11 @@ void FMSSimModel::Update() { m_startMatchTime = -1.0; } m_matchTime.SetValue(matchTime); + + HAL_MatchInfo info; + HALSIM_GetMatchInfo(&info); + m_gameMessage.assign(info.gameSpecificMessage, + info.gameSpecificMessage + info.gameSpecificMessageSize); } bool FMSSimModel::IsReadOnly() { @@ -1386,7 +1419,6 @@ void DriverStationGui::GlobalInit() { gFMSModel = std::make_unique(); wpi::gui::AddEarlyExecute(DriverStationExecute); - wpi::gui::AddEarlyExecute([] { gFMSModel->Update(); }); storageRoot.SetCustomApply([&storageRoot] { gpDisableDS = &storageRoot.GetBool("disable", false); @@ -1432,8 +1464,13 @@ void DriverStationGui::GlobalInit() { win->SetDefaultSize(300, 560); } } - if (auto win = - dsManager->AddWindow("FMS", [] { DisplayFMS(gFMSModel.get()); })) { + if (auto win = dsManager->AddWindow("FMS", [] { + if (HALSIM_GetDriverStationDsAttached()) { + DisplayFMSReadOnly(gFMSModel.get()); + } else { + DisplayFMS(gFMSModel.get(), false); + } + })) { win->DisableRenamePopup(); win->SetFlags(ImGuiWindowFlags_AlwaysAutoResize); win->SetDefaultPos(5, 540); diff --git a/simulation/halsim_gui/src/main/native/cpp/main.cpp b/simulation/halsim_gui/src/main/native/cpp/main.cpp index 0cedd369784..54510239bc8 100644 --- a/simulation/halsim_gui/src/main/native/cpp/main.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/main.cpp @@ -51,6 +51,8 @@ __declspec(dllexport) glass::SetStorageName("simgui"); + gui::AddInit([] { ImGui::GetIO().ConfigDockingWithShift = true; }); + HAL_RegisterExtension(HALSIMGUI_EXT_ADDGUIINIT, reinterpret_cast((AddGuiInitFn)&AddGuiInit)); HAL_RegisterExtension( diff --git a/simulation/halsim_ws_client/CMakeLists.txt b/simulation/halsim_ws_client/CMakeLists.txt index 18a2a120d2f..90de8110ea1 100644 --- a/simulation/halsim_ws_client/CMakeLists.txt +++ b/simulation/halsim_ws_client/CMakeLists.txt @@ -14,3 +14,4 @@ target_include_directories(halsim_ws_client PRIVATE src/main/native/include) set_property(TARGET halsim_ws_client PROPERTY FOLDER "libraries") install(TARGETS halsim_ws_client EXPORT halsim_ws_client) +export(TARGETS halsim_ws_client FILE halsim_ws_client.cmake NAMESPACE halsim_ws_client::) diff --git a/simulation/halsim_ws_client/src/dev/native/cpp/main.cpp b/simulation/halsim_ws_client/src/dev/native/cpp/main.cpp index cf32a3fd956..9bec8b88dba 100644 --- a/simulation/halsim_ws_client/src/dev/native/cpp/main.cpp +++ b/simulation/halsim_ws_client/src/dev/native/cpp/main.cpp @@ -4,10 +4,10 @@ #include -#include #include #include #include +#include extern "C" int HALSIM_InitExtension(void); @@ -21,9 +21,9 @@ int main() { while (cycleCount < 100) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); cycleCount++; - fmt::print("Count: {}\n", cycleCount); + wpi::print("Count: {}\n", cycleCount); } - fmt::print("DONE\n"); + wpi::print("DONE\n"); HAL_ExitMain(); } diff --git a/simulation/halsim_ws_client/src/main/native/cpp/HALSimWS.cpp b/simulation/halsim_ws_client/src/main/native/cpp/HALSimWS.cpp index bc38c3cc500..21742f06126 100644 --- a/simulation/halsim_ws_client/src/main/native/cpp/HALSimWS.cpp +++ b/simulation/halsim_ws_client/src/main/native/cpp/HALSimWS.cpp @@ -6,10 +6,10 @@ #include -#include #include #include #include +#include #include #include "HALSimWSClientConnection.h" @@ -26,7 +26,7 @@ HALSimWS::HALSimWS(wpi::uv::Loop& loop, ProviderContainer& providers, m_providers(providers), m_simDevicesProvider(simDevicesProvider) { m_loop.error.connect([](uv::Error err) { - fmt::print(stderr, "HALSim WS Client libuv Error: {}\n", err.str()); + wpi::print(stderr, "HALSim WS Client libuv Error: {}\n", err.str()); }); m_tcp_client = uv::Tcp::Create(m_loop); @@ -54,7 +54,7 @@ bool HALSimWS::Initialize() { try { m_port = std::stoi(port); } catch (const std::invalid_argument& err) { - fmt::print(stderr, "Error decoding HALSIMWS_PORT ({})\n", err.what()); + wpi::print(stderr, "Error decoding HALSIMWS_PORT ({})\n", err.what()); return false; } } else { @@ -109,16 +109,16 @@ void HALSimWS::Start() { // Print any filters we are using if (m_useMsgFiltering) { - fmt::print("WS Message Filters:"); + wpi::print("WS Message Filters:"); for (auto filter : m_msgFilters.keys()) { - fmt::print("* \"{}\"\n", filter); + wpi::print("* \"{}\"\n", filter); } } else { - fmt::print("No WS Message Filters specified"); + wpi::print("No WS Message Filters specified"); } // Set up the connection timer - fmt::print("Will attempt to connect to ws://{}:{}{}\n", m_host, m_port, + wpi::print("Will attempt to connect to ws://{}:{}{}\n", m_host, m_port, m_uri); // Set up the timer to attempt connection @@ -132,7 +132,7 @@ void HALSimWS::Start() { void HALSimWS::AttemptConnect() { m_connect_attempts++; - fmt::print("Connection Attempt {}\n", m_connect_attempts); + wpi::print("Connection Attempt {}\n", m_connect_attempts); struct sockaddr_in dest; uv::NameToAddr(m_host, m_port, &dest); @@ -197,7 +197,7 @@ void HALSimWS::OnNetValueChanged(const wpi::json& msg) { provider->OnNetValueChanged(msg.at("data")); } } catch (wpi::json::exception& e) { - fmt::print(stderr, "Error with incoming message: {}\n", e.what()); + wpi::print(stderr, "Error with incoming message: {}\n", e.what()); } } diff --git a/simulation/halsim_ws_client/src/main/native/cpp/HALSimWSClientConnection.cpp b/simulation/halsim_ws_client/src/main/native/cpp/HALSimWSClientConnection.cpp index cba94c8df4a..760398f6f82 100644 --- a/simulation/halsim_ws_client/src/main/native/cpp/HALSimWSClientConnection.cpp +++ b/simulation/halsim_ws_client/src/main/native/cpp/HALSimWSClientConnection.cpp @@ -6,7 +6,7 @@ #include -#include +#include #include #include "HALSimWS.h" @@ -52,7 +52,7 @@ void HALSimWSClientConnection::Initialize() { } catch (const wpi::json::parse_error& e) { std::string err("JSON parse failed: "); err += e.what(); - fmt::print(stderr, "{}\n", err); + wpi::print(stderr, "{}\n", err); m_websocket->Fail(1003, err); return; } @@ -82,7 +82,7 @@ void HALSimWSClientConnection::OnSimValueChanged(const wpi::json& msg) { return; } } catch (wpi::json::exception& e) { - fmt::print(stderr, "Error with message: {}\n", e.what()); + wpi::print(stderr, "Error with message: {}\n", e.what()); } wpi::SmallVector sendBufs; @@ -103,7 +103,7 @@ void HALSimWSClientConnection::OnSimValueChanged(const wpi::json& msg) { } if (err) { - fmt::print(stderr, "{}\n", err.str()); + wpi::print(stderr, "{}\n", err.str()); std::fflush(stderr); } }); diff --git a/simulation/halsim_ws_core/CMakeLists.txt b/simulation/halsim_ws_core/CMakeLists.txt index f7e240fd2b9..9d0b29996e1 100644 --- a/simulation/halsim_ws_core/CMakeLists.txt +++ b/simulation/halsim_ws_core/CMakeLists.txt @@ -14,3 +14,4 @@ target_include_directories(halsim_ws_core PUBLIC src/main/native/include) set_property(TARGET halsim_ws_core PROPERTY FOLDER "libraries") install(TARGETS halsim_ws_core EXPORT halsim_ws_core) +export(TARGETS halsim_ws_core FILE halsim_ws_core.cmake NAMESPACE halsim_ws_core::) diff --git a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_DriverStation.cpp b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_DriverStation.cpp index ee959b6be07..27495263b92 100644 --- a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_DriverStation.cpp +++ b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_DriverStation.cpp @@ -170,7 +170,8 @@ void HALSimWSProviderDriverStation::OnNetValueChanged(const wpi::json& json) { } if ((it = json.find(">game_data")) != json.end()) { std::string message = it.value().get_ref(); - HALSIM_SetGameSpecificMessage(message.c_str(), message.length()); + auto str = wpi::make_string(message); + HALSIM_SetGameSpecificMessage(&str); } // Only notify usercode if we get the new data message diff --git a/simulation/halsim_ws_server/CMakeLists.txt b/simulation/halsim_ws_server/CMakeLists.txt index 370d2f83f5d..8c275599d42 100644 --- a/simulation/halsim_ws_server/CMakeLists.txt +++ b/simulation/halsim_ws_server/CMakeLists.txt @@ -14,3 +14,4 @@ target_include_directories(halsim_ws_server PRIVATE src/main/native/include) set_property(TARGET halsim_ws_server PROPERTY FOLDER "libraries") install(TARGETS halsim_ws_server EXPORT halsim_ws_server) +export(TARGETS halsim_ws_server FILE halsim_ws_server.cmake NAMESPACE halsim_ws_server::) diff --git a/simulation/halsim_ws_server/src/dev/native/cpp/main.cpp b/simulation/halsim_ws_server/src/dev/native/cpp/main.cpp index ad76c6b1cfe..5621b7f9d7b 100644 --- a/simulation/halsim_ws_server/src/dev/native/cpp/main.cpp +++ b/simulation/halsim_ws_server/src/dev/native/cpp/main.cpp @@ -5,10 +5,10 @@ #include #include -#include #include #include #include +#include extern "C" int HALSIM_InitExtension(void); @@ -24,7 +24,7 @@ int main() { while (cycleCount < 1000) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); cycleCount++; - fmt::print("Count: {}\n", cycleCount); + wpi::print("Count: {}\n", cycleCount); } std::puts("DONE"); diff --git a/simulation/halsim_ws_server/src/main/native/cpp/HALSimHttpConnection.cpp b/simulation/halsim_ws_server/src/main/native/cpp/HALSimHttpConnection.cpp index ee188b32084..d2b860ea976 100644 --- a/simulation/halsim_ws_server/src/main/native/cpp/HALSimHttpConnection.cpp +++ b/simulation/halsim_ws_server/src/main/native/cpp/HALSimHttpConnection.cpp @@ -8,11 +8,11 @@ #include -#include #include #include #include #include +#include #include #include #include @@ -83,7 +83,7 @@ void HALSimHttpConnection::OnSimValueChanged(const wpi::json& msg) { return; } } catch (wpi::json::exception& e) { - fmt::print(stderr, "Error with message: {}\n", e.what()); + wpi::print(stderr, "Error with message: {}\n", e.what()); } // render json to buffers @@ -104,7 +104,7 @@ void HALSimHttpConnection::OnSimValueChanged(const wpi::json& msg) { } if (err) { - fmt::print(stderr, "{}\n", err.str()); + wpi::print(stderr, "{}\n", err.str()); std::fflush(stderr); } }); @@ -201,6 +201,6 @@ void HALSimHttpConnection::MySendError(int code, std::string_view message) { void HALSimHttpConnection::Log(int code) { auto method = wpi::http_method_str(m_request.GetMethod()); - fmt::print(stderr, "{} {} HTTP/{}.{} {}\n", method, m_request.GetUrl(), + wpi::print(stderr, "{} {} HTTP/{}.{} {}\n", method, m_request.GetUrl(), m_request.GetMajor(), m_request.GetMinor(), code); } diff --git a/simulation/halsim_ws_server/src/main/native/cpp/HALSimWeb.cpp b/simulation/halsim_ws_server/src/main/native/cpp/HALSimWeb.cpp index 790d0b57902..163af753f21 100644 --- a/simulation/halsim_ws_server/src/main/native/cpp/HALSimWeb.cpp +++ b/simulation/halsim_ws_server/src/main/native/cpp/HALSimWeb.cpp @@ -4,9 +4,9 @@ #include "HALSimWeb.h" -#include #include #include +#include #include #include #include @@ -25,7 +25,7 @@ HALSimWeb::HALSimWeb(wpi::uv::Loop& loop, ProviderContainer& providers, m_providers(providers), m_simDevicesProvider(simDevicesProvider) { m_loop.error.connect([](uv::Error err) { - fmt::print(stderr, "HALSim WS Server libuv ERROR: {}\n", err.str()); + wpi::print(stderr, "HALSim WS Server libuv ERROR: {}\n", err.str()); }); m_server = uv::Tcp::Create(m_loop); @@ -70,7 +70,7 @@ bool HALSimWeb::Initialize() { try { m_port = std::stoi(port); } catch (const std::invalid_argument& err) { - fmt::print(stderr, "Error decoding HALSIMWS_PORT ({})\n", err.what()); + wpi::print(stderr, "Error decoding HALSIMWS_PORT ({})\n", err.what()); return false; } } else { @@ -114,17 +114,17 @@ void HALSimWeb::Start() { // start listening for incoming connections m_server->Listen(); - fmt::print("Listening at http://localhost:{}\n", m_port); - fmt::print("WebSocket URI: {}\n", m_uri); + wpi::print("Listening at http://localhost:{}\n", m_port); + wpi::print("WebSocket URI: {}\n", m_uri); // Print any filters we are using if (m_useMsgFiltering) { - fmt::print("WS Message Filters:"); + wpi::print("WS Message Filters:"); for (auto filter : m_msgFilters.keys()) { - fmt::print("* \"{}\"\n", filter); + wpi::print("* \"{}\"\n", filter); } } else { - fmt::print("No WS Message Filters specified"); + wpi::print("No WS Message Filters specified"); } } @@ -180,7 +180,7 @@ void HALSimWeb::OnNetValueChanged(const wpi::json& msg) { provider->OnNetValueChanged(msg.at("data")); } } catch (wpi::json::exception& e) { - fmt::print(stderr, "Error with incoming message: {}\n", e.what()); + wpi::print(stderr, "Error with incoming message: {}\n", e.what()); } } diff --git a/simulation/halsim_ws_server/src/test/native/cpp/WebServerClientTest.cpp b/simulation/halsim_ws_server/src/test/native/cpp/WebServerClientTest.cpp index fff4ae90ba4..f377e1f8f7b 100644 --- a/simulation/halsim_ws_server/src/test/native/cpp/WebServerClientTest.cpp +++ b/simulation/halsim_ws_server/src/test/native/cpp/WebServerClientTest.cpp @@ -6,8 +6,8 @@ #include -#include #include +#include #include #include @@ -20,7 +20,7 @@ namespace wpilibws { // Create Web Socket and specify event callbacks void WebServerClientTest::InitializeWebSocket(const std::string& host, int port, const std::string& uri) { - fmt::print("Will attempt to connect to: {}:{}{}\n", host, port, uri); + wpi::print("Will attempt to connect to: {}:{}{}\n", host, port, uri); m_websocket = wpi::WebSocket::CreateClient(*m_tcp_client.get(), uri, fmt::format("{}:{}", host, port)); @@ -46,7 +46,7 @@ void WebServerClientTest::InitializeWebSocket(const std::string& host, int port, } catch (const wpi::json::parse_error& e) { std::string err("JSON parse failed: "); err += e.what(); - fmt::print(stderr, "{}\n", err); + wpi::print(stderr, "{}\n", err); m_websocket->Fail(1003, err); return; } @@ -65,7 +65,7 @@ void WebServerClientTest::InitializeWebSocket(const std::string& host, int port, // Create tcp client, specify callbacks, and create timers for loop bool WebServerClientTest::Initialize() { m_loop.error.connect( - [](uv::Error err) { fmt::print(stderr, "uv Error: {}\n", err.str()); }); + [](uv::Error err) { wpi::print(stderr, "uv Error: {}\n", err.str()); }); m_tcp_client = uv::Tcp::Create(m_loop); if (!m_tcp_client) { @@ -106,7 +106,7 @@ bool WebServerClientTest::Initialize() { void WebServerClientTest::AttemptConnect() { m_connect_attempts++; - fmt::print("Test Client Connection Attempt {}\n", m_connect_attempts); + wpi::print("Test Client Connection Attempt {}\n", m_connect_attempts); if (m_connect_attempts >= 5) { std::fputs("Test Client Timeout. Unable to connect\n", stderr); @@ -144,7 +144,7 @@ void WebServerClientTest::SendMessage(const wpi::json& msg) { m_buffers->Release(bufs); } if (err) { - fmt::print(stderr, "{}\n", err.str()); + wpi::print(stderr, "{}\n", err.str()); std::fflush(stderr); } }); diff --git a/simulation/halsim_ws_server/src/test/native/cpp/main.cpp b/simulation/halsim_ws_server/src/test/native/cpp/main.cpp index 61e3a887af6..254cc092b76 100644 --- a/simulation/halsim_ws_server/src/test/native/cpp/main.cpp +++ b/simulation/halsim_ws_server/src/test/native/cpp/main.cpp @@ -4,12 +4,12 @@ #include -#include #include #include #include #include #include +#include #include #include "HALSimWSServer.h" @@ -55,7 +55,7 @@ TEST_F(WebServerIntegrationTest, DISABLED_DigitalOutput) { return; } if (IsConnectedClientWS()) { - fmt::print("***** Setting DIO value for pin {} to {}\n", PIN, + wpi::print("***** Setting DIO value for pin {} to {}\n", PIN, (EXPECTED_VALUE ? "true" : "false")); HALSIM_SetDIOValue(PIN, EXPECTED_VALUE); done = true; @@ -83,7 +83,7 @@ TEST_F(WebServerIntegrationTest, DISABLED_DigitalOutput) { test_value = it.value(); } } catch (wpi::json::exception& e) { - fmt::print(stderr, "Error with incoming message: {}\n", e.what()); + wpi::print(stderr, "Error with incoming message: {}\n", e.what()); } // Compare results @@ -109,7 +109,7 @@ TEST_F(WebServerIntegrationTest, DISABLED_DigitalInput) { wpi::json msg = {{"type", "DIO"}, {"device", std::to_string(PIN)}, {"data", {{"<>value", EXPECTED_VALUE}}}}; - fmt::print("***** Input JSON: {}\n", msg.dump()); + wpi::print("***** Input JSON: {}\n", msg.dump()); m_webserverClient->SendMessage(msg); done = true; } @@ -144,7 +144,7 @@ TEST_F(WebServerIntegrationTest, DriverStation) { {"type", "DriverStation"}, {"device", ""}, {"data", {{">enabled", EXPECTED_VALUE}, {">new_data", true}}}}; - fmt::print("***** Input JSON: {}\n", msg.dump()); + wpi::print("***** Input JSON: {}\n", msg.dump()); m_webserverClient->SendMessage(msg); done = true; } diff --git a/simulation/halsim_xrp/CMakeLists.txt b/simulation/halsim_xrp/CMakeLists.txt index cc838744407..f961f3b94d2 100644 --- a/simulation/halsim_xrp/CMakeLists.txt +++ b/simulation/halsim_xrp/CMakeLists.txt @@ -14,3 +14,4 @@ target_include_directories(halsim_xrp PRIVATE src/main/native/include) set_property(TARGET halsim_xrp PROPERTY FOLDER "libraries") install(TARGETS halsim_xrp EXPORT halsim_xrp DESTINATION "${main_lib_dest}") +export(TARGETS halsim_xrp FILE halsim_xrp.cmake NAMESPACE halsim_xrp::) diff --git a/simulation/halsim_xrp/src/main/native/cpp/HALSimXRP.cpp b/simulation/halsim_xrp/src/main/native/cpp/HALSimXRP.cpp index 0f2b93b0424..8a85bfaac8d 100644 --- a/simulation/halsim_xrp/src/main/native/cpp/HALSimXRP.cpp +++ b/simulation/halsim_xrp/src/main/native/cpp/HALSimXRP.cpp @@ -6,10 +6,10 @@ #include -#include #include #include #include +#include #include #include @@ -24,7 +24,7 @@ HALSimXRP::HALSimXRP(wpi::uv::Loop& loop, m_providers(providers), m_simDevicesProvider(simDevicesProvider) { m_loop.error.connect([](uv::Error err) { - fmt::print(stderr, "HALSim XRP Client libuv Error: {}\n", err.str()); + wpi::print(stderr, "HALSim XRP Client libuv Error: {}\n", err.str()); }); m_udp_client = uv::Udp::Create(m_loop); @@ -51,7 +51,7 @@ bool HALSimXRP::Initialize() { try { m_port = std::stoi(port); } catch (const std::invalid_argument& err) { - fmt::print(stderr, "Error decoding HALSIMXRP_PORT ({})\n", err.what()); + wpi::print(stderr, "Error decoding HALSIMXRP_PORT ({})\n", err.what()); return false; } } else { @@ -79,7 +79,7 @@ void HALSimXRP::Start() { ParsePacket({reinterpret_cast(data.base), len}); }); - m_udp_client->closed.connect([]() { fmt::print("Socket Closed\n"); }); + m_udp_client->closed.connect([]() { wpi::print("Socket Closed\n"); }); // Fake the OnNetworkConnected call auto hws = shared_from_this(); @@ -120,7 +120,7 @@ void HALSimXRP::OnNetValueChanged(const wpi::json& msg) { provider->OnNetValueChanged(msg.at("data")); } } catch (wpi::json::exception& e) { - fmt::print(stderr, "Error with incoming message: {}\n", e.what()); + wpi::print(stderr, "Error with incoming message: {}\n", e.what()); } } diff --git a/styleguide/checkstyle-suppressions.xml b/styleguide/checkstyle-suppressions.xml index 2197fe27ba4..f42b176a636 100644 --- a/styleguide/checkstyle-suppressions.xml +++ b/styleguide/checkstyle-suppressions.xml @@ -10,6 +10,6 @@ suppressions PUBLIC "-//Puppy Crawl//DTD Suppressions 1.1//EN" checks="(LocalVariableName|MemberName|MethodName|MethodTypeParameterName|ParameterName)" /> - diff --git a/styleguide/pmd-ruleset.xml b/styleguide/pmd-ruleset.xml index f2ef2bc8dbe..1f6577e6f18 100644 --- a/styleguide/pmd-ruleset.xml +++ b/styleguide/pmd-ruleset.xml @@ -8,7 +8,7 @@ .*/*JNI.* .*/*IntegrationTests.* - .*/quickbuf/.* + .*/math/proto.* diff --git a/styleguide/spotbugs-exclude.xml b/styleguide/spotbugs-exclude.xml index f224099af60..e015399a7fd 100644 --- a/styleguide/spotbugs-exclude.xml +++ b/styleguide/spotbugs-exclude.xml @@ -1,5 +1,8 @@ + + + @@ -72,6 +75,9 @@ + + + @@ -132,6 +138,10 @@ + + + + @@ -145,4 +155,13 @@ + + + + diff --git a/sysid/CMakeLists.txt b/sysid/CMakeLists.txt index 31fbe08d0da..e8555e8e1b8 100644 --- a/sysid/CMakeLists.txt +++ b/sysid/CMakeLists.txt @@ -10,7 +10,7 @@ generate_resources(src/main/native/resources generated/main/cpp SYSID sysid sysi file(GLOB_RECURSE sysid_src src/main/native/cpp/*.cpp ${CMAKE_CURRENT_BINARY_DIR}/WPILibVersion.cpp) -if (WIN32) +if(WIN32) set(sysid_rc src/main/native/win/sysid.rc) elseif(APPLE) set(MACOSX_BUNDLE_ICON_FILE sysid.icns) @@ -19,23 +19,28 @@ elseif(APPLE) endif() add_executable(sysid ${sysid_src} ${sysid_resources_src} ${sysid_rc} ${APP_ICON_MACOSX}) +if(MSVC) + target_compile_options(sysid PRIVATE /utf-8) +endif() wpilib_link_macos_gui(sysid) wpilib_target_warnings(sysid) target_include_directories(sysid PRIVATE src/main/native/include) target_link_libraries(sysid wpimath libglassnt libglass) -if (WIN32) +if(WIN32) set_target_properties(sysid PROPERTIES WIN32_EXECUTABLE YES) elseif(APPLE) set_target_properties(sysid PROPERTIES MACOSX_BUNDLE YES OUTPUT_NAME "SysId") endif() -if (WITH_TESTS) +if(WITH_TESTS) wpilib_add_test(sysid src/test/native/cpp) wpilib_link_macos_gui(sysid_test) target_sources(sysid_test PRIVATE ${sysid_src}) target_compile_definitions(sysid_test PRIVATE RUNNING_SYSID_TESTS) - target_include_directories(sysid_test PRIVATE src/main/native/cpp - src/main/native/include) + if(MSVC) + target_compile_options(sysid_test PRIVATE /utf-8) + endif() + target_include_directories(sysid_test PRIVATE src/main/native/cpp src/main/native/include) target_link_libraries(sysid_test wpimath libglassnt libglass gtest) endif() diff --git a/sysid/README.md b/sysid/README.md new file mode 100644 index 00000000000..842f3bec684 --- /dev/null +++ b/sysid/README.md @@ -0,0 +1,14 @@ +# SysId: System Identification for Robot Mechanisms + +## Building and Running SysId + +See [here](../README.md#Requirements) for build requirements. + +Run the following in the monorepo root. +```bash +./gradlew sysid:run +``` + +## Troubleshooting + +Use [AdvantageScope](https://docs.wpilib.org/en/stable/docs/software/dashboards/advantagescope.html) (shipped with the WPILib installer) to view .wpilog files for troubleshooting when SysId fails to generate plots. diff --git a/sysid/build.gradle b/sysid/build.gradle index e6709fc8285..b9689e96b35 100644 --- a/sysid/build.gradle +++ b/sysid/build.gradle @@ -102,8 +102,8 @@ model { lib project: ':glass', library: 'glass', linkage: 'static' project(':ntcore').addNtcoreDependency(it, 'static') lib project: ':wpinet', library: 'wpinet', linkage: 'static' - lib project: ':wpiutil', library: 'wpiutil', linkage: 'static' lib project: ':wpimath', library: 'wpimath', linkage: 'static' + lib project: ':wpiutil', library: 'wpiutil', linkage: 'static' lib project: ':wpigui', library: 'wpigui', linkage: 'static' nativeUtils.useRequiredLibrary(it, 'imgui') if (it.targetPlatform.operatingSystem.isWindows()) { @@ -144,8 +144,8 @@ model { lib project: ':glass', library: 'glass', linkage: 'static' project(':ntcore').addNtcoreDependency(it, 'static') lib project: ':wpinet', library: 'wpinet', linkage: 'static' - lib project: ':wpiutil', library: 'wpiutil', linkage: 'static' lib project: ':wpimath', library: 'wpimath', linkage: 'static' + lib project: ':wpiutil', library: 'wpiutil', linkage: 'static' lib project: ':wpigui', library: 'wpigui', linkage: 'static' nativeUtils.useRequiredLibrary(it, 'imgui') if (it.targetPlatform.operatingSystem.isWindows()) { diff --git a/sysid/docs/data-collection.md b/sysid/docs/data-collection.md index 9d28a151a0d..538aff40cb9 100644 --- a/sysid/docs/data-collection.md +++ b/sysid/docs/data-collection.md @@ -15,7 +15,7 @@ Here is a list of the NT entries that are used to send and collect data between ## Telemetry Format -There are two formats used to send telemetry from the robot program. One format is for non-drivetrain mechanisms, whereas the other is for all drivetrain tests (linear and angular). +There are two formats used to send telemetry from the robot program. One format is for non-drivetrain mechanisms, whereas the other is for all drivetrain tests (linear and angular). All timestamps must be in seconds. ### Non-Drivetrain Mechanisms diff --git a/sysid/docs/arm-ols-with-angle-offset.md b/sysid/docs/ols-derivations.md similarity index 64% rename from sysid/docs/arm-ols-with-angle-offset.md rename to sysid/docs/ols-derivations.md index ecb5c439820..53a8eb28fdb 100644 --- a/sysid/docs/arm-ols-with-angle-offset.md +++ b/sysid/docs/ols-derivations.md @@ -1,28 +1,84 @@ -# Arm OLS with angle offset +# OLS derivations + +## Simple/drivetrain + +Here's the ODE for a drivetrain. +``` +dx/dt = -Kv/Ka x + 1/Ka u - Ks/Ka sgn(x) +``` + +### OLS setup + +Let `α = -Kv/Ka`, `β = 1/Ka`, and `γ = -Ks/Ka`. +``` +dx/dt = αx + βu + γ sgn(x) +``` + +### Feedforward gains + +Divide the OLS terms by each other to obtain `Ks`, `Kv`, and `Ka`. +``` +Ks = -γ/β +Kv = -α/β +Ka = 1/β +``` + +## Elevator + +Here's the ODE for an elevator. +``` +dx/dt = -Kv/Ka x + 1/Ka u - Ks/Ka sgn(x) - Kg/Ka +``` + +### OLS setup + +Let `α = -Kv/Ka`, `β = 1/Ka`, `γ = -Ks/Ka`, and `δ = -Kg/Ka`. +``` +dx/dt = αx + βu + γ sgn(x) + δ +``` + +### Feedforward gains + +Divide the OLS terms by each other to obtain `Ks`, `Kv`, `Ka`, and `Kg`. +``` +Ks = -γ/β +Kv = -α/β +Ka = 1/β +Kg = −δ/β +``` + +## Arm + +Here's the ODE for an arm: +``` +dx/dt = -Kv/Ka x + 1/Ka u - Ks/Ka sgn(x) - Kg/Ka cos(angle) +``` If the arm encoder doesn't read zero degrees when the arm is horizontal, the fit for `Kg` will be wrong. An angle offset should be added to the model like so. ``` dx/dt = -Kv/Ka x + 1/Ka u - Ks/Ka sgn(x) - Kg/Ka cos(angle + offset) ``` + Use a trig identity to split the cosine into two terms. ``` dx/dt = -Kv/Ka x + 1/Ka u - Ks/Ka sgn(x) - Kg/Ka (cos(angle) cos(offset) - sin(angle) sin(offset)) dx/dt = -Kv/Ka x + 1/Ka u - Ks/Ka sgn(x) - Kg/Ka cos(angle) cos(offset) + Kg/Ka sin(angle) sin(offset) ``` + Reorder multiplicands so the offset trig is absorbed by the OLS terms. ``` dx/dt = -Kv/Ka x + 1/Ka u - Ks/Ka sgn(x) - Kg/Ka cos(offset) cos(angle) + Kg/Ka sin(offset) sin(angle) ``` -## OLS +### OLS setup Let `α = -Kv/Ka`, `β = 1/Ka`, `γ = -Ks/Ka`, `δ = -Kg/Ka cos(offset)`, and `ε = Kg/Ka sin(offset)`. ``` dx/dt = αx + βu + γ sgn(x) + δ cos(angle) + ε sin(angle) ``` -### Ks, Kv, Ka +### Feedforward gains: Ks, Kv, Ka Divide the OLS terms by each other to obtain `Ks`, `Kv`, and `Ka`. ``` @@ -31,7 +87,7 @@ Kv = -α/β Ka = 1/β ``` -### Kg +### Feedforward gains: Kg Take the sum of squares of the OLS terms containing the angle offset. The angle offset trig functions will form a trig identity that cancels out. Then, just @@ -44,14 +100,12 @@ solve for `Kg`. δ²+ε² = (Kg/Ka)² (1) δ²+ε² = (Kg/Ka)² √(δ²+ε²) = Kg/Ka -√(δ²+ε²) = Kg β -Kg = √(δ²+ε²)/β +hypot(δ, ε) = Kg/Ka +hypot(δ, ε) = Kg β +Kg = hypot(δ, ε)/β ``` -As a sanity check, when the offset is zero, ε is zero and the equation for -`Kg` simplifies to -δ/β, the equation previously used by SysId. - -### Angle offset +### Feedforward gains: offset Divide ε by δ, combine the trig functions into `tan(offset)`, then use `atan2()` to preserve the angle quadrant. Maintaining the proper negative signs in the diff --git a/sysid/scripts/time_plots.py b/sysid/scripts/time_plots.py deleted file mode 100755 index 6878126af2c..00000000000 --- a/sysid/scripts/time_plots.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env python3 - -import json -import pathlib - -import matplotlib.pyplot as plt -import pandas as pd -import sys - -# Load data -filename = pathlib.Path(sys.argv[1]) - -UNIT_TO_ABBREVIATION = { - "Meters": "m", - "Feet": "ft", - "Inches": "in", - "Degrees": "deg", - "Rotations": "rot", - "Radians": "rad", -} - -# Make DataFrame to facilitate plotting -if filename.suffix == ".json": - raw_data = json.loads(filename.read_text()) - unit = raw_data["units"] - - # Get Unit - try: - abbreviation = UNIT_TO_ABBREVIATION[unit] - except KeyError: - raise ValueError("Invalid Unit") - - # Make Columns - columns = ["Timestamp (s)", "Test"] - if "Drive" in raw_data["test"]: - columns.extend( - [ - "Left Volts (V)", - "Right Volts (V)", - f"Left Position ({abbreviation})", - f"Right Position ({abbreviation})", - f"Left Velocity ({abbreviation}/s)", - f"Right Velocity ({abbreviation}/s)", - "Gyro Position (deg)", - "Gyro Rate (deg/s)", - ] - ) - unit_columns = columns[4:8] - else: - columns.extend( - ["Volts (V)", f"Position ({abbreviation})", f"Velocity ({abbreviation}/s)"] - ) - unit_columns = columns[3:] - - prepared_data = pd.DataFrame(columns=columns) - for test in raw_data.keys(): - if "-" not in test: - continue - formatted_entry = [[pt[0], test, *pt[1:]] for pt in raw_data[test]] - prepared_data = pd.concat( - [prepared_data, pd.DataFrame(formatted_entry, columns=columns)] - ) - - units_per_rot = raw_data["unitsPerRotation"] - - for column in unit_columns: - prepared_data[column] *= units_per_rot -else: - prepared_data = pd.read_csv(filename) - -# First 2 columns are Timestamp and Test -for column in prepared_data.columns[2:]: - # Configure Plot Labels - plt.figure() - plt.xlabel("Timestamp (s)") - plt.ylabel(column) - - # Configure title without units - print(column) - end = column.find("(") - plt.title(f"{column[:end].strip()} vs Time") - - # Plot data for each test - for test in pd.unique(prepared_data["Test"]): - test_data = prepared_data[prepared_data["Test"] == test] - plt.plot(test_data["Timestamp (s)"], test_data[column], label=test) - plt.legend() - -plt.show() diff --git a/sysid/src/main/generate/WPILibVersion.cpp.in b/sysid/src/main/generate/WPILibVersion.cpp.in index b0a44905207..cfe24411588 100644 --- a/sysid/src/main/generate/WPILibVersion.cpp.in +++ b/sysid/src/main/generate/WPILibVersion.cpp.in @@ -1,4 +1,4 @@ -/* +/** * Autogenerated file! Do not manually edit this file. This version is regenerated * any time the publish task is run, or when this file is deleted. */ diff --git a/sysid/src/main/native/cpp/App.cpp b/sysid/src/main/native/cpp/App.cpp index 947ea434a65..8b35dca2d3d 100644 --- a/sysid/src/main/native/cpp/App.cpp +++ b/sysid/src/main/native/cpp/App.cpp @@ -10,7 +10,6 @@ #include #include -#include #include #include #include @@ -20,25 +19,25 @@ #include #include #include +#include #include #include #include "sysid/view/Analyzer.h" -#include "sysid/view/JSONConverter.h" -#include "sysid/view/Logger.h" +#include "sysid/view/DataSelector.h" +#include "sysid/view/LogLoader.h" #include "sysid/view/UILayout.h" namespace gui = wpi::gui; static std::unique_ptr gWindowManager; -glass::Window* gLoggerWindow; +glass::Window* gLogLoaderWindow; +glass::Window* gDataSelectorWindow; glass::Window* gAnalyzerWindow; glass::Window* gProgramLogWindow; static glass::MainMenuBar gMainMenu; -std::unique_ptr gJSONConverter; - glass::LogData gLog; wpi::Logger gLogger; @@ -90,7 +89,7 @@ void Application(std::string_view saveDir) { std::string filename = std::filesystem::path{file}.filename().string(); gLog.Append(fmt::format("{}{} ({}:{})\n", lvl, msg, filename, line)); #ifndef NDEBUG - fmt::print(stderr, "{}{} ({}:{})\n", lvl, msg, filename, line); + wpi::print(stderr, "{}{} ({}:{})\n", lvl, msg, filename, line); #endif }); @@ -103,11 +102,23 @@ void Application(std::string_view saveDir) { gWindowManager = std::make_unique(storage); gWindowManager->GlobalInit(); - gLoggerWindow = gWindowManager->AddWindow( - "Logger", std::make_unique(storage, gLogger)); + auto logLoader = std::make_unique(storage, gLogger); + auto dataSelector = std::make_unique(storage, gLogger); + auto analyzer = std::make_unique(storage, gLogger); + + logLoader->unload.connect([ds = dataSelector.get()] { ds->Reset(); }); + dataSelector->testdata = [_analyzer = analyzer.get()](auto data) { + _analyzer->m_data = data; + _analyzer->AnalyzeData(); + }; + + gLogLoaderWindow = + gWindowManager->AddWindow("Log Loader", std::move(logLoader)); - gAnalyzerWindow = gWindowManager->AddWindow( - "Analyzer", std::make_unique(storage, gLogger)); + gDataSelectorWindow = + gWindowManager->AddWindow("Data Selector", std::move(dataSelector)); + + gAnalyzerWindow = gWindowManager->AddWindow("Analyzer", std::move(analyzer)); gProgramLogWindow = gWindowManager->AddWindow( "Program Log", std::make_unique(&gLog)); @@ -115,10 +126,16 @@ void Application(std::string_view saveDir) { // Set default positions and sizes for windows. // Logger window position/size - gLoggerWindow->SetDefaultPos(sysid::kLoggerWindowPos.x, - sysid::kLoggerWindowPos.y); - gLoggerWindow->SetDefaultSize(sysid::kLoggerWindowSize.x, - sysid::kLoggerWindowSize.y); + gLogLoaderWindow->SetDefaultPos(sysid::kLogLoaderWindowPos.x, + sysid::kLogLoaderWindowPos.y); + gLogLoaderWindow->SetDefaultSize(sysid::kLogLoaderWindowSize.x, + sysid::kLogLoaderWindowSize.y); + + // Data selector window position/size + gDataSelectorWindow->SetDefaultPos(sysid::kDataSelectorWindowPos.x, + sysid::kDataSelectorWindowPos.y); + gDataSelectorWindow->SetDefaultSize(sysid::kDataSelectorWindowSize.x, + sysid::kDataSelectorWindowSize.y); // Analyzer window position/size gAnalyzerWindow->SetDefaultPos(sysid::kAnalyzerWindowPos.x, @@ -133,8 +150,6 @@ void Application(std::string_view saveDir) { sysid::kProgramLogWindowSize.y); gProgramLogWindow->DisableRenamePopup(); - gJSONConverter = std::make_unique(gLogger); - // Configure save file. gui::ConfigurePlatformSaveFile("sysid.ini"); @@ -157,15 +172,6 @@ void Application(std::string_view saveDir) { ImGui::EndMenu(); } - bool toCSV = false; - if (ImGui::BeginMenu("JSON Converters")) { - if (ImGui::MenuItem("JSON to CSV Converter")) { - toCSV = true; - } - - ImGui::EndMenu(); - } - if (ImGui::BeginMenu("Docs")) { if (ImGui::MenuItem("Online documentation")) { wpi::gui::OpenURL( @@ -178,19 +184,6 @@ void Application(std::string_view saveDir) { ImGui::EndMainMenuBar(); - if (toCSV) { - ImGui::OpenPopup("SysId JSON to CSV Converter"); - toCSV = false; - } - - if (ImGui::BeginPopupModal("SysId JSON to CSV Converter")) { - gJSONConverter->DisplayCSVConvert(); - if (ImGui::Button("Close")) { - ImGui::CloseCurrentPopup(); - } - ImGui::EndPopup(); - } - if (about) { ImGui::OpenPopup("About"); about = false; diff --git a/sysid/src/main/native/cpp/Util.cpp b/sysid/src/main/native/cpp/Util.cpp index a9acc537a7a..c4dc7803046 100644 --- a/sysid/src/main/native/cpp/Util.cpp +++ b/sysid/src/main/native/cpp/Util.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -23,6 +24,20 @@ void sysid::CreateTooltip(const char* text) { } } +void sysid::CreateErrorTooltip(const char* text) { + ImGui::SameLine(); + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), + ICON_FA_TRIANGLE_EXCLAMATION); + + if (ImGui::IsItemHovered()) { + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", text); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + void sysid::CreateErrorPopup(bool& isError, std::string_view errorMessage) { if (isError) { ImGui::OpenPopup("Exception Caught!"); diff --git a/sysid/src/main/native/cpp/analysis/AnalysisManager.cpp b/sysid/src/main/native/cpp/analysis/AnalysisManager.cpp index 0710d93e0fa..52121ebdda4 100644 --- a/sysid/src/main/native/cpp/analysis/AnalysisManager.cpp +++ b/sysid/src/main/native/cpp/analysis/AnalysisManager.cpp @@ -5,24 +5,39 @@ #include "sysid/analysis/AnalysisManager.h" #include -#include #include -#include #include #include -#include +#include #include #include #include -#include "sysid/Util.h" #include "sysid/analysis/FilteringUtils.h" -#include "sysid/analysis/JSONConverter.h" -#include "sysid/analysis/TrackWidthAnalysis.h" using namespace sysid; +static double Lerp(units::second_t time, + std::vector>& data) { + auto next = std::find_if(data.begin(), data.end(), [&](const auto& entry) { + return entry.time > time; + }); + + if (next == data.begin()) { + next++; + } + + if (next == data.end()) { + next--; + } + + const auto prev = next - 1; + + return wpi::Lerp(prev->measurement, next->measurement, + (time - prev->time) / (next->time - prev->time)); +} + /** * Converts a raw data vector into a PreparedData vector with only the * timestamp, voltage, position, and velocity fields filled out. @@ -38,18 +53,25 @@ using namespace sysid; * * @return A PreparedData vector */ -template -static std::vector ConvertToPrepared( - const std::vector>& data) { +static std::vector ConvertToPrepared(const MotorData& data) { std::vector prepared; - for (int i = 0; i < static_cast(data.size()) - 1; ++i) { - const auto& pt1 = data[i]; - const auto& pt2 = data[i + 1]; - prepared.emplace_back(PreparedData{ - units::second_t{pt1[Timestamp]}, pt1[Voltage], pt1[Position], - pt1[Velocity], units::second_t{pt2[Timestamp] - pt1[Timestamp]}}); + // assume we've selected down to a single contiguous run by this point + auto run = data.runs[0]; + + for (int i = 0; i < static_cast(run.voltage.size()) - 1; ++i) { + const auto& currentVoltage = run.voltage[i]; + const auto& nextVoltage = run.voltage[i + 1]; + + auto currentPosition = Lerp(currentVoltage.time, run.position); + + auto currentVelocity = Lerp(currentVoltage.time, run.velocity); + + prepared.emplace_back(PreparedData{currentVoltage.time, + currentVoltage.measurement.value(), + currentPosition, currentVelocity, + nextVoltage.time - currentVoltage.time}); } + return prepared; } @@ -62,18 +84,16 @@ static std::vector ConvertToPrepared( * * @param dataset A reference to the dataset being used */ -template -static void CopyRawData( - wpi::StringMap>>* dataset) { +static void CopyRawData(wpi::StringMap* dataset) { auto& data = *dataset; // Loads the Raw Data for (auto& it : data) { auto key = it.first(); - auto& dataset = it.getValue(); + auto& motorData = it.getValue(); if (!wpi::contains(key, "raw")) { - data[fmt::format("raw-{}", key)] = dataset; - data[fmt::format("original-raw-{}", key)] = dataset; + data[fmt::format("raw-{}", key)] = motorData; + data[fmt::format("original-raw-{}", key)] = motorData; } } } @@ -94,416 +114,73 @@ static Storage CombineDatasets(const std::vector& slowForward, } void AnalysisManager::PrepareGeneralData() { - using Data = std::array; - wpi::StringMap> data; wpi::StringMap> preparedData; - // Store the raw data columns. - static constexpr size_t kTimeCol = 0; - static constexpr size_t kVoltageCol = 1; - static constexpr size_t kPosCol = 2; - static constexpr size_t kVelCol = 3; - - WPI_INFO(m_logger, "{}", "Reading JSON data."); - // Get the major components from the JSON and store them inside a StringMap. - for (auto&& key : AnalysisManager::kJsonDataKeys) { - data[key] = m_json.at(key).get>(); - } - WPI_INFO(m_logger, "{}", "Preprocessing raw data."); - // Ensure that voltage and velocity have the same sign. Also multiply - // positions and velocities by the factor. - for (auto it = data.begin(); it != data.end(); ++it) { - for (auto&& pt : it->second) { - pt[kVoltageCol] = std::copysign(pt[kVoltageCol], pt[kVelCol]); - pt[kPosCol] *= m_factor; - pt[kVelCol] *= m_factor; - } - } WPI_INFO(m_logger, "{}", "Copying raw data."); - CopyRawData(&data); + CopyRawData(&m_data.motorData); WPI_INFO(m_logger, "{}", "Converting raw data to PreparedData struct."); // Convert data to PreparedData structs - for (auto& it : data) { + for (auto& it : m_data.motorData) { auto key = it.first(); - preparedData[key] = - ConvertToPrepared<4, kTimeCol, kVoltageCol, kPosCol, kVelCol>( - data[key]); + preparedData[key] = ConvertToPrepared(m_data.motorData[key]); + WPI_INFO(m_logger, "SAMPLES {}", preparedData[key].size()); } // Store the original datasets - m_originalDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kCombined)] = - CombineDatasets(preparedData["original-raw-slow-forward"], - preparedData["original-raw-slow-backward"], - preparedData["original-raw-fast-forward"], - preparedData["original-raw-fast-backward"]); + m_originalDataset = + CombineDatasets(preparedData["original-raw-quasistatic-forward"], + preparedData["original-raw-quasistatic-reverse"], + preparedData["original-raw-dynamic-forward"], + preparedData["original-raw-dynamic-reverse"]); WPI_INFO(m_logger, "{}", "Initial trimming and filtering."); sysid::InitialTrimAndFilter(&preparedData, &m_settings, m_positionDelays, m_velocityDelays, m_minStepTime, m_maxStepTime, - m_unit); + m_data.distanceUnit); + + WPI_INFO(m_logger, "{}", m_minStepTime); + WPI_INFO(m_logger, "{}", m_maxStepTime); WPI_INFO(m_logger, "{}", "Acceleration filtering."); sysid::AccelFilter(&preparedData); WPI_INFO(m_logger, "{}", "Storing datasets."); // Store the raw datasets - m_rawDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kCombined)] = - CombineDatasets( - preparedData["raw-slow-forward"], preparedData["raw-slow-backward"], - preparedData["raw-fast-forward"], preparedData["raw-fast-backward"]); + m_rawDataset = CombineDatasets(preparedData["raw-quasistatic-forward"], + preparedData["raw-quasistatic-reverse"], + preparedData["raw-dynamic-forward"], + preparedData["raw-dynamic-reverse"]); // Store the filtered datasets - m_filteredDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kCombined)] = - CombineDatasets( - preparedData["slow-forward"], preparedData["slow-backward"], - preparedData["fast-forward"], preparedData["fast-backward"]); - - m_startTimes = {preparedData["raw-slow-forward"][0].timestamp, - preparedData["raw-slow-backward"][0].timestamp, - preparedData["raw-fast-forward"][0].timestamp, - preparedData["raw-fast-backward"][0].timestamp}; -} - -void AnalysisManager::PrepareAngularDrivetrainData() { - using Data = std::array; - wpi::StringMap> data; - wpi::StringMap> preparedData; - - // Store the relevant raw data columns. - static constexpr size_t kTimeCol = 0; - static constexpr size_t kLVoltageCol = 1; - static constexpr size_t kRVoltageCol = 2; - static constexpr size_t kLPosCol = 3; - static constexpr size_t kRPosCol = 4; - static constexpr size_t kLVelCol = 5; - static constexpr size_t kRVelCol = 6; - static constexpr size_t kAngleCol = 7; - static constexpr size_t kAngularRateCol = 8; - - WPI_INFO(m_logger, "{}", "Reading JSON data."); - // Get the major components from the JSON and store them inside a StringMap. - for (auto&& key : AnalysisManager::kJsonDataKeys) { - data[key] = m_json.at(key).get>(); - } - - WPI_INFO(m_logger, "{}", "Preprocessing raw data."); - // Ensure that voltage and velocity have the same sign. Also multiply - // positions and velocities by the factor. - for (auto it = data.begin(); it != data.end(); ++it) { - for (auto&& pt : it->second) { - pt[kLPosCol] *= m_factor; - pt[kRPosCol] *= m_factor; - pt[kLVelCol] *= m_factor; - pt[kRVelCol] *= m_factor; - - // Stores the average voltages in the left voltage column. - // This aggregates the left and right voltages into a single voltage - // column for the ConvertToPrepared() method. std::copysign() ensures the - // polarity of the voltage matches the direction the robot turns. - pt[kLVoltageCol] = std::copysign( - (std::abs(pt[kLVoltageCol]) + std::abs(pt[kRVoltageCol])) / 2, - pt[kAngularRateCol]); - - // ω = (v_r - v_l) / trackwidth - // v = ωr => v = ω * trackwidth / 2 - // (v_r - v_l) / trackwidth * (trackwidth / 2) = (v_r - v_l) / 2 - // However, since we know this is an angular test, the left and right - // wheel velocities will have opposite signs, allowing us to add their - // absolute values and get the same result (in terms of magnitude). - // std::copysign() is used to make sure the direction of the wheel - // velocities matches the direction the robot turns. - pt[kAngularRateCol] = - std::copysign((std::abs(pt[kRVelCol]) + std::abs(pt[kLVelCol])) / 2, - pt[kAngularRateCol]); - } - } - - WPI_INFO(m_logger, "{}", "Calculating trackwidth"); - // Aggregating all the deltas from all the tests - double leftDelta = 0.0; - double rightDelta = 0.0; - double angleDelta = 0.0; - for (const auto& it : data) { - auto key = it.first(); - auto& trackWidthData = data[key]; - leftDelta += std::abs(trackWidthData.back()[kLPosCol] - - trackWidthData.front()[kLPosCol]); - rightDelta += std::abs(trackWidthData.back()[kRPosCol] - - trackWidthData.front()[kRPosCol]); - angleDelta += std::abs(trackWidthData.back()[kAngleCol] - - trackWidthData.front()[kAngleCol]); - } - m_trackWidth = sysid::CalculateTrackWidth(leftDelta, rightDelta, - units::radian_t{angleDelta}); - - WPI_INFO(m_logger, "{}", "Copying raw data."); - CopyRawData(&data); - - WPI_INFO(m_logger, "{}", "Converting to PreparedData struct."); - // Convert raw data to prepared data - for (const auto& it : data) { - auto key = it.first(); - preparedData[key] = ConvertToPrepared<9, kTimeCol, kLVoltageCol, kAngleCol, - kAngularRateCol>(data[key]); - } - - // Create the distinct datasets and store them - m_originalDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kCombined)] = - CombineDatasets(preparedData["original-raw-slow-forward"], - preparedData["original-raw-slow-backward"], - preparedData["original-raw-fast-forward"], - preparedData["original-raw-fast-backward"]); - - WPI_INFO(m_logger, "{}", "Applying trimming and filtering."); - sysid::InitialTrimAndFilter(&preparedData, &m_settings, m_positionDelays, - m_velocityDelays, m_minStepTime, m_maxStepTime); - - WPI_INFO(m_logger, "{}", "Acceleration filtering."); - sysid::AccelFilter(&preparedData); - - WPI_INFO(m_logger, "{}", "Storing datasets."); - // Create the distinct datasets and store them - m_rawDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kCombined)] = - CombineDatasets( - preparedData["raw-slow-forward"], preparedData["raw-slow-backward"], - preparedData["raw-fast-forward"], preparedData["raw-fast-backward"]); - m_filteredDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kCombined)] = - CombineDatasets( - preparedData["slow-forward"], preparedData["slow-backward"], - preparedData["fast-forward"], preparedData["fast-backward"]); - - m_startTimes = {preparedData["slow-forward"][0].timestamp, - preparedData["slow-backward"][0].timestamp, - preparedData["fast-forward"][0].timestamp, - preparedData["fast-backward"][0].timestamp}; -} - -void AnalysisManager::PrepareLinearDrivetrainData() { - using Data = std::array; - wpi::StringMap> data; - wpi::StringMap> preparedData; - - // Store the relevant raw data columns. - static constexpr size_t kTimeCol = 0; - static constexpr size_t kLVoltageCol = 1; - static constexpr size_t kRVoltageCol = 2; - static constexpr size_t kLPosCol = 3; - static constexpr size_t kRPosCol = 4; - static constexpr size_t kLVelCol = 5; - static constexpr size_t kRVelCol = 6; - - // Get the major components from the JSON and store them inside a StringMap. - WPI_INFO(m_logger, "{}", "Reading JSON data."); - for (auto&& key : AnalysisManager::kJsonDataKeys) { - data[key] = m_json.at(key).get>(); - } - - // Ensure that voltage and velocity have the same sign. Also multiply - // positions and velocities by the factor. - WPI_INFO(m_logger, "{}", "Preprocessing raw data."); - for (auto it = data.begin(); it != data.end(); ++it) { - for (auto&& pt : it->second) { - pt[kLVoltageCol] = std::copysign(pt[kLVoltageCol], pt[kLVelCol]); - pt[kRVoltageCol] = std::copysign(pt[kRVoltageCol], pt[kRVelCol]); - pt[kLPosCol] *= m_factor; - pt[kRPosCol] *= m_factor; - pt[kLVelCol] *= m_factor; - pt[kRVelCol] *= m_factor; - } - } - - WPI_INFO(m_logger, "{}", "Copying raw data."); - CopyRawData(&data); - - // Convert data to PreparedData - WPI_INFO(m_logger, "{}", "Converting to PreparedData struct."); - for (auto& it : data) { - auto key = it.first(); - - preparedData[fmt::format("left-{}", key)] = - ConvertToPrepared<9, kTimeCol, kLVoltageCol, kLPosCol, kLVelCol>( - data[key]); - preparedData[fmt::format("right-{}", key)] = - ConvertToPrepared<9, kTimeCol, kRVoltageCol, kRPosCol, kRVelCol>( - data[key]); - } - - // Create the distinct raw datasets and store them - auto originalSlowForward = AnalysisManager::DataConcat( - preparedData["left-original-raw-slow-forward"], - preparedData["right-original-raw-slow-forward"]); - auto originalSlowBackward = AnalysisManager::DataConcat( - preparedData["left-original-raw-slow-backward"], - preparedData["right-original-raw-slow-backward"]); - auto originalFastForward = AnalysisManager::DataConcat( - preparedData["left-original-raw-fast-forward"], - preparedData["right-original-raw-fast-forward"]); - auto originalFastBackward = AnalysisManager::DataConcat( - preparedData["left-original-raw-fast-backward"], - preparedData["right-original-raw-fast-backward"]); - m_originalDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kCombined)] = - CombineDatasets(originalSlowForward, originalSlowBackward, - originalFastForward, originalFastBackward); - m_originalDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kLeft)] = - CombineDatasets(preparedData["left-original-raw-slow-forward"], - preparedData["left-original-raw-slow-backward"], - preparedData["left-original-raw-fast-forward"], - preparedData["left-original-raw-fast-backward"]); - m_originalDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kRight)] = - CombineDatasets(preparedData["right-original-raw-slow-forward"], - preparedData["right-original-raw-slow-backward"], - preparedData["right-original-raw-fast-forward"], - preparedData["right-original-raw-fast-backward"]); - - WPI_INFO(m_logger, "{}", "Applying trimming and filtering."); - sysid::InitialTrimAndFilter(&preparedData, &m_settings, m_positionDelays, - m_velocityDelays, m_minStepTime, m_maxStepTime); - - auto slowForward = AnalysisManager::DataConcat( - preparedData["left-slow-forward"], preparedData["right-slow-forward"]); - auto slowBackward = AnalysisManager::DataConcat( - preparedData["left-slow-backward"], preparedData["right-slow-backward"]); - auto fastForward = AnalysisManager::DataConcat( - preparedData["left-fast-forward"], preparedData["right-fast-forward"]); - auto fastBackward = AnalysisManager::DataConcat( - preparedData["left-fast-backward"], preparedData["right-fast-backward"]); - - WPI_INFO(m_logger, "{}", "Acceleration filtering."); - sysid::AccelFilter(&preparedData); - - WPI_INFO(m_logger, "{}", "Storing datasets."); - - // Create the distinct raw datasets and store them - auto rawSlowForward = - AnalysisManager::DataConcat(preparedData["left-raw-slow-forward"], - preparedData["right-raw-slow-forward"]); - auto rawSlowBackward = - AnalysisManager::DataConcat(preparedData["left-raw-slow-backward"], - preparedData["right-raw-slow-backward"]); - auto rawFastForward = - AnalysisManager::DataConcat(preparedData["left-raw-fast-forward"], - preparedData["right-raw-fast-forward"]); - auto rawFastBackward = - AnalysisManager::DataConcat(preparedData["left-raw-fast-backward"], - preparedData["right-raw-fast-backward"]); - - m_rawDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kCombined)] = - CombineDatasets(rawSlowForward, rawSlowBackward, rawFastForward, - rawFastBackward); - m_rawDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kLeft)] = - CombineDatasets(preparedData["left-raw-slow-forward"], - preparedData["left-raw-slow-backward"], - preparedData["left-raw-fast-forward"], - preparedData["left-raw-fast-backward"]); - m_rawDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kRight)] = - CombineDatasets(preparedData["right-raw-slow-forward"], - preparedData["right-raw-slow-backward"], - preparedData["right-raw-fast-forward"], - preparedData["right-raw-fast-backward"]); - - // Create the distinct filtered datasets and store them - m_filteredDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kCombined)] = - CombineDatasets(slowForward, slowBackward, fastForward, fastBackward); - m_filteredDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kLeft)] = - CombineDatasets(preparedData["left-slow-forward"], - preparedData["left-slow-backward"], - preparedData["left-fast-forward"], - preparedData["left-fast-backward"]); - m_filteredDataset[static_cast( - AnalysisManager::Settings::DrivetrainDataset::kRight)] = - CombineDatasets(preparedData["right-slow-forward"], - preparedData["right-slow-backward"], - preparedData["right-fast-forward"], - preparedData["right-fast-backward"]); - - m_startTimes = { - rawSlowForward.front().timestamp, rawSlowBackward.front().timestamp, - rawFastForward.front().timestamp, rawFastBackward.front().timestamp}; + m_filteredDataset = CombineDatasets( + preparedData["quasistatic-forward"], preparedData["quasistatic-reverse"], + preparedData["dynamic-forward"], preparedData["dynamic-reverse"]); + + m_startTimes = {preparedData["raw-quasistatic-forward"][0].timestamp, + preparedData["raw-quasistatic-reverse"][0].timestamp, + preparedData["raw-dynamic-forward"][0].timestamp, + preparedData["raw-dynamic-reverse"][0].timestamp}; } AnalysisManager::AnalysisManager(Settings& settings, wpi::Logger& logger) - : m_logger{logger}, - m_settings{settings}, - m_type{analysis::kSimple}, - m_unit{"Meters"}, - m_factor{1} {} + : m_logger{logger}, m_settings{settings} {} -AnalysisManager::AnalysisManager(std::string_view path, Settings& settings, +AnalysisManager::AnalysisManager(TestData data, Settings& settings, wpi::Logger& logger) - : m_logger{logger}, m_settings{settings} { - { - // Read JSON from the specified path - std::error_code ec; - std::unique_ptr fileBuffer = - wpi::MemoryBuffer::GetFile(path, ec); - if (fileBuffer == nullptr || ec) { - throw FileReadingError(path); - } - - m_json = wpi::json::parse(fileBuffer->GetCharBuffer()); - - WPI_INFO(m_logger, "Read {}", path); - } - - // Check that we have a sysid JSON - if (m_json.find("sysid") == m_json.end()) { - // If it's not a sysid JSON, try converting it from frc-char format - std::string newPath = sysid::ConvertJSON(path, logger); - - // Read JSON from the specified path - std::error_code ec; - std::unique_ptr fileBuffer = - wpi::MemoryBuffer::GetFile(path, ec); - if (fileBuffer == nullptr || ec) { - throw FileReadingError(newPath); - } - - m_json = wpi::json::parse(fileBuffer->GetCharBuffer()); - - WPI_INFO(m_logger, "Read {}", newPath); - } - - WPI_INFO(m_logger, "Parsing initial data of {}", path); - // Get the analysis type from the JSON. - m_type = sysid::analysis::FromName(m_json.at("test").get()); - - // Get the rotation -> output units factor from the JSON. - m_unit = m_json.at("units").get(); - m_factor = m_json.at("unitsPerRotation").get(); - WPI_DEBUG(m_logger, "Parsing units per rotation as {} {} per rotation", - m_factor, m_unit); - + : m_data{std::move(data)}, m_logger{logger}, m_settings{settings} { // Reset settings for Dynamic Test Limits m_settings.stepTestDuration = units::second_t{0.0}; - m_settings.motionThreshold = std::numeric_limits::infinity(); + m_settings.velocityThreshold = std::numeric_limits::infinity(); } void AnalysisManager::PrepareData() { - WPI_INFO(m_logger, "Preparing {} data", m_type.name); - if (m_type == analysis::kDrivetrain) { - PrepareLinearDrivetrainData(); - } else if (m_type == analysis::kDrivetrainAngular) { - PrepareAngularDrivetrainData(); - } else { - PrepareGeneralData(); - } + // WPI_INFO(m_logger, "Preparing {} data", m_data.mechanismType.name); + + PrepareGeneralData(); + WPI_INFO(m_logger, "{}", "Finished Preparing Data"); } @@ -515,54 +192,97 @@ AnalysisManager::FeedforwardGains AnalysisManager::CalculateFeedforward() { WPI_INFO(m_logger, "{}", "Calculating Gains"); // Calculate feedforward gains from the data. - const auto& ff = sysid::CalculateFeedforwardGains(GetFilteredData(), m_type); - FeedforwardGains ffGains = {ff, m_trackWidth}; - - const auto& Ks = std::get<0>(ff)[0]; - const auto& Kv = std::get<0>(ff)[1]; - const auto& Ka = std::get<0>(ff)[2]; - - if (Ka <= 0 || Kv < 0) { - throw InvalidDataError( - fmt::format("The calculated feedforward gains of kS: {}, Kv: {}, Ka: " - "{} are erroneous. Your Ka should be > 0 while your Kv and " - "Ks constants should both >= 0. Try adjusting the " - "filtering and trimming settings or collect better data.", - Ks, Kv, Ka)); + const auto& analysisType = m_data.mechanismType; + const auto& ff = + sysid::CalculateFeedforwardGains(GetFilteredData(), analysisType, false); + + const auto& Ks = ff.coeffs[0]; + FeedforwardGain KsGain = { + .gain = Ks, .descriptor = "Voltage needed to overcome static friction."}; + if (Ks < 0) { + KsGain.isValidGain = false; + KsGain.errorMessage = fmt::format( + "Calculated Ks gain of: {0:.3f} is erroneous! Ks should be >= 0.", Ks); } - return ffGains; + const auto& Kv = ff.coeffs[1]; + FeedforwardGain KvGain = { + .gain = Kv, + .descriptor = + "Voltage needed to hold/cruise at a constant velocity while " + "overcoming the counter-electromotive force and any additional " + "friction."}; + if (Kv < 0) { + KvGain.isValidGain = false; + KvGain.errorMessage = fmt::format( + "Calculated Kv gain of: {0:.3f} is erroneous! Kv should be >= 0.", Kv); + } + + const auto& Ka = ff.coeffs[2]; + FeedforwardGain KaGain = { + .gain = Ka, + .descriptor = + "Voltage needed to induce a given acceleration in the motor shaft."}; + if (Ka <= 0) { + KaGain.isValidGain = false; + KaGain.errorMessage = fmt::format( + "Calculated Ka gain of: {0:.3f} is erroneous! Ka should be > 0.", Ka); + } + + if (analysisType == analysis::kSimple) { + return FeedforwardGains{ + .olsResult = ff, .Ks = KsGain, .Kv = KvGain, .Ka = KaGain}; + } + + if (analysisType == analysis::kElevator || analysisType == analysis::kArm) { + const auto& Kg = ff.coeffs[3]; + FeedforwardGain KgGain = { + Kg, "Voltage needed to counteract the force of gravity."}; + if (Kg < 0) { + KgGain.isValidGain = false; + KgGain.errorMessage = fmt::format( + "Calculated Kg gain of: {0:.3f} is erroneous! Kg should be >= 0.", + Ka); + } + + // Elevator analysis only requires Kg + if (analysisType == analysis::kElevator) { + return FeedforwardGains{.olsResult = ff, + .Ks = KsGain, + .Kv = KvGain, + .Ka = KaGain, + .Kg = KgGain}; + } else { + // Arm analysis requires Kg and an angle offset + FeedforwardGain offset = { + .gain = ff.coeffs[4], + .descriptor = + "This is the angle offset which, when added to the angle " + "measurement, zeroes it out when the arm is horizontal. This is " + "needed for the arm feedforward to work."}; + return FeedforwardGains{ff, KsGain, KvGain, KaGain, KgGain, offset}; + } + } + + return FeedforwardGains{.olsResult = ff}; } sysid::FeedbackGains AnalysisManager::CalculateFeedback( - std::vector ff) { - const auto& Kv = ff[1]; - const auto& Ka = ff[2]; + const FeedforwardGain& Kv, const FeedforwardGain& Ka) { FeedbackGains fb; if (m_settings.type == FeedbackControllerLoopType::kPosition) { fb = sysid::CalculatePositionFeedbackGains( - m_settings.preset, m_settings.lqr, Kv, Ka, - m_settings.convertGainsToEncTicks - ? m_settings.gearing * m_settings.cpr * m_factor - : 1); + m_settings.preset, m_settings.lqr, Kv.gain, Ka.gain); } else { fb = sysid::CalculateVelocityFeedbackGains( - m_settings.preset, m_settings.lqr, Kv, Ka, - m_settings.convertGainsToEncTicks - ? m_settings.gearing * m_settings.cpr * m_factor - : 1); + m_settings.preset, m_settings.lqr, Kv.gain, Ka.gain); } return fb; } -void AnalysisManager::OverrideUnits(std::string_view unit, - double unitsPerRotation) { - m_unit = unit; - m_factor = unitsPerRotation; +void AnalysisManager::OverrideUnits(std::string_view unit) { + m_data.distanceUnit = unit; } -void AnalysisManager::ResetUnitsFromJSON() { - m_unit = m_json.at("units").get(); - m_factor = m_json.at("unitsPerRotation").get(); -} +void AnalysisManager::ResetUnitsFromJSON() {} diff --git a/sysid/src/main/native/cpp/analysis/AnalysisType.cpp b/sysid/src/main/native/cpp/analysis/AnalysisType.cpp index 18b461fe6d8..6ef27c93875 100644 --- a/sysid/src/main/native/cpp/analysis/AnalysisType.cpp +++ b/sysid/src/main/native/cpp/analysis/AnalysisType.cpp @@ -7,12 +7,6 @@ using namespace sysid; AnalysisType sysid::analysis::FromName(std::string_view name) { - if (name == "Drivetrain") { - return sysid::analysis::kDrivetrain; - } - if (name == "Drivetrain (Angular)") { - return sysid::analysis::kDrivetrainAngular; - } if (name == "Elevator") { return sysid::analysis::kElevator; } diff --git a/sysid/src/main/native/cpp/analysis/FeedbackAnalysis.cpp b/sysid/src/main/native/cpp/analysis/FeedbackAnalysis.cpp index 0691aaf6ebb..7821812bd4e 100644 --- a/sysid/src/main/native/cpp/analysis/FeedbackAnalysis.cpp +++ b/sysid/src/main/native/cpp/analysis/FeedbackAnalysis.cpp @@ -4,9 +4,10 @@ #include "sysid/analysis/FeedbackAnalysis.h" +#include + #include #include -#include #include #include #include @@ -20,23 +21,31 @@ using Ka_t = decltype(1_V / 1_mps_sq); FeedbackGains sysid::CalculatePositionFeedbackGains( const FeedbackControllerPreset& preset, const LQRParameters& params, - double Kv, double Ka, double encFactor) { + double Kv, double Ka) { + if (!std::isfinite(Kv) || !std::isfinite(Ka)) { + return {0.0, 0.0}; + } + // If acceleration requires no effort, velocity becomes an input for position // control. We choose an appropriate model in this case to avoid numerical // instabilities in the LQR. if (Ka > 1E-7) { // Create a position system from our feedforward gains. - auto system = frc::LinearSystemId::IdentifyPositionSystem( - Kv_t(Kv), Ka_t(Ka)); + frc::LinearSystem<2, 1, 1> system{ + frc::Matrixd<2, 2>{{0.0, 1.0}, {0.0, -Kv / Ka}}, + frc::Matrixd<2, 1>{0.0, 1.0 / Ka}, frc::Matrixd<1, 2>{1.0, 0.0}, + frc::Matrixd<1, 1>{0.0}}; // Create an LQR with 2 states to control -- position and velocity. frc::LinearQuadraticRegulator<2, 1> controller{ system, {params.qp, params.qv}, {params.r}, preset.period}; // Compensate for any latency from sensor measurements, filtering, etc. - controller.LatencyCompensate(system, preset.period, 0.0_s); + controller.LatencyCompensate(system, preset.period, + preset.measurementDelay); - return {controller.K(0, 0) * preset.outputConversionFactor / encFactor, - controller.K(0, 1) * preset.outputConversionFactor / - (encFactor * (preset.normalized ? 1 : preset.period.value()))}; + return { + controller.K(0, 0) * preset.outputConversionFactor, + controller.K(0, 1) * preset.outputConversionFactor / + (preset.normalized ? 1 : units::second_t{preset.period}.value())}; } // This is our special model to avoid instabilities in the LQR. @@ -47,15 +56,18 @@ FeedbackGains sysid::CalculatePositionFeedbackGains( frc::LinearQuadraticRegulator<1, 1> controller{ system, {params.qp}, {params.r}, preset.period}; // Compensate for any latency from sensor measurements, filtering, etc. - controller.LatencyCompensate(system, preset.period, 0.0_s); + controller.LatencyCompensate(system, preset.period, preset.measurementDelay); - return {Kv * controller.K(0, 0) * preset.outputConversionFactor / encFactor, - 0.0}; + return {Kv * controller.K(0, 0) * preset.outputConversionFactor, 0.0}; } FeedbackGains sysid::CalculateVelocityFeedbackGains( const FeedbackControllerPreset& preset, const LQRParameters& params, double Kv, double Ka, double encFactor) { + if (!std::isfinite(Kv) || !std::isfinite(Ka)) { + return {0.0, 0.0}; + } + // If acceleration for velocity control requires no effort, the feedback // control gains approach zero. We special-case it here because numerical // instabilities arise in LQR otherwise. @@ -64,8 +76,9 @@ FeedbackGains sysid::CalculateVelocityFeedbackGains( } // Create a velocity system from our feedforward gains. - auto system = frc::LinearSystemId::IdentifyVelocitySystem( - Kv_t(Kv), Ka_t(Ka)); + frc::LinearSystem<1, 1, 1> system{ + frc::Matrixd<1, 1>{-Kv / Ka}, frc::Matrixd<1, 1>{1.0 / Ka}, + frc::Matrixd<1, 1>{1.0}, frc::Matrixd<1, 1>{0.0}}; // Create an LQR controller with 1 state -- velocity. frc::LinearQuadraticRegulator<1, 1> controller{ system, {params.qv}, {params.r}, preset.period}; diff --git a/sysid/src/main/native/cpp/analysis/FeedforwardAnalysis.cpp b/sysid/src/main/native/cpp/analysis/FeedforwardAnalysis.cpp index b7a9fce79b7..110ff9463f1 100644 --- a/sysid/src/main/native/cpp/analysis/FeedforwardAnalysis.cpp +++ b/sysid/src/main/native/cpp/analysis/FeedforwardAnalysis.cpp @@ -4,8 +4,13 @@ #include "sysid/analysis/FeedforwardAnalysis.h" +#include +#include #include +#include +#include +#include #include #include @@ -13,10 +18,25 @@ #include "sysid/analysis/FilteringUtils.h" #include "sysid/analysis/OLS.h" -using namespace sysid; +namespace sysid { /** - * Populates OLS data for (xₖ₊₁ − xₖ)/τ = αxₖ + βuₖ + γ sgn(xₖ). + * Populates OLS data for the following models: + * + * Simple, Drivetrain, DrivetrainAngular: + * + * (xₖ₊₁ − xₖ)/τ = αxₖ + βuₖ + γ sgn(xₖ) + * + * Elevator: + * + * (xₖ₊₁ − xₖ)/τ = αxₖ + βuₖ + γ sgn(xₖ) + δ + * + * Arm: + * + * (xₖ₊₁ − xₖ)/τ = αxₖ + βuₖ + γ sgn(xₖ) + δ cos(angle) + ε sin(angle) + * + * OLS performs best with the noisiest variable as the dependent variable, so we + * regress acceleration in terms of the other variables. * * @param d List of characterization data. * @param type Type of system being identified. @@ -27,36 +47,136 @@ static void PopulateOLSData(const std::vector& d, const AnalysisType& type, Eigen::Block X, Eigen::VectorBlock y) { + // Fill in X and y row-wise for (size_t sample = 0; sample < d.size(); ++sample) { const auto& pt = d[sample]; - // Add the velocity term (for α) + // Set the velocity term (for α) X(sample, 0) = pt.velocity; - // Add the voltage term (for β) + // Set the voltage term (for β) X(sample, 1) = pt.voltage; - // Add the intercept term (for γ) + // Set the intercept term (for γ) X(sample, 2) = std::copysign(1, pt.velocity); - // Add test-specific variables + // Set test-specific variables if (type == analysis::kElevator) { - // Add the gravity term (for Kg) + // Set the gravity term (for δ) X(sample, 3) = 1.0; } else if (type == analysis::kArm) { - // Add the cosine and sine terms (for Kg) + // Set the cosine and sine terms (for δ and ε) X(sample, 3) = pt.cos; X(sample, 4) = pt.sin; } - // Add the dependent variable (acceleration) + // Set the dependent variable (acceleration) y(sample) = pt.acceleration; } } -std::tuple, double, double> -sysid::CalculateFeedforwardGains(const Storage& data, - const AnalysisType& type) { +/** + * Throws an InsufficientSamplesError if the collected data is poor for OLS. + * + * @param X The collected data in matrix form for OLS. + * @param type The analysis type. + */ +static void CheckOLSDataQuality(const Eigen::MatrixXd& X, + const AnalysisType& type) { + Eigen::SelfAdjointEigenSolver eigSolver{X.transpose() * X}; + const Eigen::VectorXd& eigvals = eigSolver.eigenvalues(); + const Eigen::MatrixXd& eigvecs = eigSolver.eigenvectors(); + + // Bits are Ks, Kv, Ka, Kg, offset + std::bitset<5> badGains; + + constexpr double threshold = 10.0; + + // For n x n matrix XᵀX, need n nonzero eigenvalues for good fit + for (int row = 0; row < eigvals.rows(); ++row) { + // Find row of eigenvector with largest magnitude. This determines the + // primary regression variable that corresponds to the eigenvalue. + int maxIndex; + double maxCoeff = eigvecs.col(row).cwiseAbs().maxCoeff(&maxIndex); + + // Check whether the eigenvector component along the regression variable's + // direction is below the threshold. If it is, the regression variable's fit + // is bad. + if (std::abs(eigvals(row) * maxCoeff) <= threshold) { + // Fit for α is bad + if (maxIndex == 0) { + // Affects Kv + badGains.set(1); + } + + // Fit for β is bad + if (maxIndex == 1) { + // Affects all gains + badGains.set(); + break; + } + + // Fit for γ is bad + if (maxIndex == 2) { + // Affects Ks + badGains.set(0); + } + + // Fit for δ is bad + if (maxIndex == 3) { + if (type == analysis::kElevator) { + // Affects Kg + badGains.set(3); + } else if (type == analysis::kArm) { + // Affects Kg and offset + badGains.set(3); + badGains.set(4); + } + } + + // Fit for ε is bad + if (maxIndex == 4) { + // Affects Kg and offset + badGains.set(3); + badGains.set(4); + } + } + } + + // If any gains are bad, throw an error + if (badGains.any()) { + // Create list of bad gain names + constexpr std::array gainNames{"Ks", "Kv", "Ka", "Kg", "offset"}; + std::vector badGainsList; + for (size_t i = 0; i < badGains.size(); ++i) { + if (badGains.test(i)) { + badGainsList.emplace_back(gainNames[i]); + } + } + + std::string error = fmt::format("Insufficient samples to compute {}.\n\n", + fmt::join(badGainsList, ", ")); + + // If all gains are bad, the robot may not have moved + if (badGains.all()) { + error += "Either no data was collected or the robot didn't move.\n\n"; + } + + // Append guidance for fixing the data + error += + "Ensure the data has:\n\n" + " * at least 2 steady-state velocity events to separate Ks from Kv\n" + " * at least 1 acceleration event to find Ka\n" + " * for elevators, enough vertical motion to measure gravity\n" + " * for arms, enough range of motion to measure gravity and encoder " + "offset\n"; + throw InsufficientSamplesError{error}; + } +} + +OLSResult CalculateFeedforwardGains(const Storage& data, + const AnalysisType& type, + bool throwOnBadData) { // Iterate through the data and add it to our raw vector. const auto& [slowForward, slowBackward, fastForward, fastBackward] = data; @@ -87,34 +207,68 @@ sysid::CalculateFeedforwardGains(const Storage& data, X.block(rowOffset, 0, fastBackward.size(), X.cols()), y.segment(rowOffset, fastBackward.size())); - // Perform OLS with accel = alpha*vel + beta*voltage + gamma*signum(vel) - // OLS performs best with the noisiest variable as the dependent var, - // so we regress accel in terms of the other variables. - auto ols = sysid::OLS(X, y); - double alpha = std::get<0>(ols)[0]; // -Kv/Ka - double beta = std::get<0>(ols)[1]; // 1/Ka - double gamma = std::get<0>(ols)[2]; // -Ks/Ka - - // Initialize gains list with Ks, Kv, and Ka - std::vector gains{-gamma / beta, -alpha / beta, 1 / beta}; - - if (type == analysis::kElevator) { - // Add Kg to gains list - double delta = std::get<0>(ols)[3]; // -Kg/Ka - gains.emplace_back(-delta / beta); + // Check quality of collected data + if (throwOnBadData) { + CheckOLSDataQuality(X, type); } - if (type == analysis::kArm) { - double delta = std::get<0>(ols)[3]; // -Kg/Ka cos(offset) - double epsilon = std::get<0>(ols)[4]; // Kg/Ka sin(offset) + std::vector gains; + gains.reserve(X.rows()); + + auto ols = OLS(X, y); + + // Calculate feedforward gains + // + // See docs/ols-derivations.md for more details. + { + // dx/dt = -Kv/Ka x + 1/Ka u - Ks/Ka sgn(x) + // dx/dt = αx + βu + γ sgn(x) - // Add Kg to gains list - gains.emplace_back(std::hypot(delta, epsilon) / beta); + // α = -Kv/Ka + // β = 1/Ka + // γ = -Ks/Ka + double α = ols.coeffs[0]; + double β = ols.coeffs[1]; + double γ = ols.coeffs[2]; - // Add offset to gains list - gains.emplace_back(std::atan2(epsilon, -delta)); + // Ks = -γ/β + // Kv = -α/β + // Ka = 1/β + gains.emplace_back(-γ / β); + gains.emplace_back(-α / β); + gains.emplace_back(1 / β); + + if (type == analysis::kElevator) { + // dx/dt = -Kv/Ka x + 1/Ka u - Ks/Ka sgn(x) - Kg/Ka + // dx/dt = αx + βu + γ sgn(x) + δ + + // δ = -Kg/Ka + double δ = ols.coeffs[3]; + + // Kg = -δ/β + gains.emplace_back(-δ / β); + } + + if (type == analysis::kArm) { + // dx/dt = -Kv/Ka x + 1/Ka u - Ks/Ka sgn(x) + // - Kg/Ka cos(offset) cos(angle) NOLINT + // + Kg/Ka sin(offset) sin(angle) NOLINT + // dx/dt = αx + βu + γ sgn(x) + δ cos(angle) + ε sin(angle) NOLINT + + // δ = -Kg/Ka cos(offset) + // ε = Kg/Ka sin(offset) + double δ = ols.coeffs[3]; + double ε = ols.coeffs[4]; + + // Kg = hypot(δ, ε)/β NOLINT + // offset = atan2(ε, -δ) NOLINT + gains.emplace_back(std::hypot(δ, ε) / β); + gains.emplace_back(std::atan2(ε, -δ)); + } } // Gains are Ks, Kv, Ka, Kg (elevator/arm only), offset (arm only) - return std::tuple{gains, std::get<1>(ols), std::get<2>(ols)}; + return OLSResult{gains, ols.rSquared, ols.rmse}; } + +} // namespace sysid diff --git a/sysid/src/main/native/cpp/analysis/FilteringUtils.cpp b/sysid/src/main/native/cpp/analysis/FilteringUtils.cpp index 6c66ef8b424..8432e7c8ff7 100644 --- a/sysid/src/main/native/cpp/analysis/FilteringUtils.cpp +++ b/sysid/src/main/native/cpp/analysis/FilteringUtils.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include using namespace sysid; @@ -126,7 +127,7 @@ sysid::TrimStepVoltageData(std::vector* data, auto motionBegins = std::find_if( data->begin(), data->end(), [settings, firstPosition](auto& datum) { return std::abs(datum.position - firstPosition) > - (settings->motionThreshold * datum.dt.value()); + (settings->velocityThreshold * datum.dt.value()); }); units::second_t positionDelay; @@ -138,12 +139,25 @@ sysid::TrimStepVoltageData(std::vector* data, auto maxAccel = std::max_element( data->begin(), data->end(), [](const auto& a, const auto& b) { - return std::abs(a.acceleration) < std::abs(b.acceleration); + // Since we don't know if its a forward or backwards test here, we use + // the sign of each point's velocity to determine how to compare their + // accelerations. + return wpi::sgn(a.velocity) * a.acceleration < + wpi::sgn(b.velocity) * b.acceleration; + }); + + // Current limiting can delay onset of the peak acceleration, so we need to + // find the first acceleration *near* the max. Magic number tolerance here + // because this whole file is tech debt already + auto accelBegins = std::find_if( + data->begin(), data->end(), [&maxAccel](const auto& measurement) { + return wpi::sgn(measurement.velocity) * measurement.acceleration > + 0.8 * wpi::sgn(maxAccel->velocity) * maxAccel->acceleration; }); units::second_t velocityDelay; - if (maxAccel != data->end()) { - velocityDelay = maxAccel->timestamp - firstTimestamp; + if (accelBegins != data->end()) { + velocityDelay = accelBegins->timestamp - firstTimestamp; // Trim data before max acceleration data->erase(data->begin(), maxAccel); @@ -153,32 +167,28 @@ sysid::TrimStepVoltageData(std::vector* data, minStepTime = std::min(data->at(0).timestamp - firstTimestamp, minStepTime); - // If step duration hasn't been set yet, calculate a default (find the entry - // before the acceleration first hits zero) - if (settings->stepTestDuration <= minStepTime) { - // Get noise floor - const double accelNoiseFloor = GetNoiseFloor( - *data, kNoiseMeanWindow, [](auto&& pt) { return pt.acceleration; }); - // Find latest element with nonzero acceleration + // If step test duration not yet specified, calculate default + if (settings->stepTestDuration == 0_s) { + // Find maximum speed reached + const auto maxSpeed = + GetMaxSpeed(*data, [](auto&& pt) { return pt.velocity; }); + // Find place where 90% of maximum speed exceeded auto endIt = std::find_if( - data->rbegin(), data->rend(), [&](const PreparedData& entry) { - return std::abs(entry.acceleration) > accelNoiseFloor; + data->begin(), data->end(), [&](const PreparedData& entry) { + return std::abs(entry.velocity) > maxSpeed * 0.9; }); - if (endIt != data->rend()) { - // Calculate default duration - settings->stepTestDuration = std::min( - endIt->timestamp - data->front().timestamp + minStepTime + 1_s, - maxStepTime); - } else { - settings->stepTestDuration = maxStepTime; + if (endIt != data->end()) { + settings->stepTestDuration = + std::min(endIt->timestamp - data->front().timestamp + minStepTime, + maxStepTime); } } // Find first entry greater than the step test duration auto maxIt = std::find_if(data->begin(), data->end(), [&](PreparedData entry) { - return entry.timestamp - data->front().timestamp + minStepTime > + return entry.timestamp - data->front().timestamp > settings->stepTestDuration; }); @@ -186,6 +196,7 @@ sysid::TrimStepVoltageData(std::vector* data, if (maxIt != data->end()) { data->erase(maxIt, data->end()); } + return std::make_tuple(minStepTime, positionDelay, velocityDelay); } @@ -204,6 +215,16 @@ double sysid::GetNoiseFloor( return std::sqrt(sum / (data.size() - step)); } +double sysid::GetMaxSpeed( + const std::vector& data, + std::function accessorFunction) { + double max = 0.0; + for (size_t i = 0; i < data.size(); i++) { + max = std::max(max, std::abs(accessorFunction(data[i]))); + } + return max; +} + units::second_t sysid::GetMeanTimeDelta(const std::vector& data) { std::vector dts; @@ -301,7 +322,7 @@ static units::second_t GetMaxStepTime( auto key = it.first(); auto& dataset = it.getValue(); - if (IsRaw(key) && wpi::contains(key, "fast")) { + if (IsRaw(key) && wpi::contains(key, "dynamic")) { auto duration = dataset.back().timestamp - dataset.front().timestamp; if (duration > maxStepTime) { maxStepTime = duration; @@ -323,13 +344,13 @@ void sysid::InitialTrimAndFilter( maxStepTime = GetMaxStepTime(preparedData); // Calculate Velocity Threshold if it hasn't been set yet - if (settings->motionThreshold == std::numeric_limits::infinity()) { + if (settings->velocityThreshold == std::numeric_limits::infinity()) { for (auto& it : preparedData) { auto key = it.first(); auto& dataset = it.getValue(); - if (wpi::contains(key, "slow")) { - settings->motionThreshold = - std::min(settings->motionThreshold, + if (wpi::contains(key, "quasistatic")) { + settings->velocityThreshold = + std::min(settings->velocityThreshold, GetNoiseFloor(dataset, kNoiseMeanWindow, [](auto&& pt) { return pt.velocity; })); } @@ -341,13 +362,13 @@ void sysid::InitialTrimAndFilter( auto& dataset = it.getValue(); // Trim quasistatic test data to remove all points where voltage is zero or - // velocity < motion threshold. - if (wpi::contains(key, "slow")) { + // velocity < velocity threshold. + if (wpi::contains(key, "quasistatic")) { dataset.erase(std::remove_if(dataset.begin(), dataset.end(), [&](const auto& pt) { return std::abs(pt.voltage) <= 0 || std::abs(pt.velocity) < - settings->motionThreshold; + settings->velocityThreshold; }), dataset.end()); @@ -366,7 +387,7 @@ void sysid::InitialTrimAndFilter( PrepareMechData(&dataset, unit); // Trims filtered Dynamic Test Data - if (IsFiltered(key) && wpi::contains(key, "fast")) { + if (IsFiltered(key) && wpi::contains(key, "dynamic")) { // Get the filtered dataset name auto filteredKey = RemoveStr(key, "raw-"); diff --git a/sysid/src/main/native/cpp/analysis/JSONConverter.cpp b/sysid/src/main/native/cpp/analysis/JSONConverter.cpp deleted file mode 100644 index 5060679d989..00000000000 --- a/sysid/src/main/native/cpp/analysis/JSONConverter.cpp +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "sysid/analysis/JSONConverter.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "sysid/Util.h" -#include "sysid/analysis/AnalysisManager.h" -#include "sysid/analysis/AnalysisType.h" - -// Sizes of the arrays for new sysid data. -static constexpr size_t kDrivetrainSize = 9; -static constexpr size_t kGeneralSize = 4; - -// Indices for the old data. -static constexpr size_t kTimestampCol = 0; -static constexpr size_t kLVoltsCol = 3; -static constexpr size_t kRVoltsCol = 4; -static constexpr size_t kLPosCol = 5; -static constexpr size_t kRPosCol = 6; -static constexpr size_t kLVelCol = 7; -static constexpr size_t kRVelCol = 8; - -static wpi::json GetJSON(std::string_view path, wpi::Logger& logger) { - std::error_code ec; - std::unique_ptr fileBuffer = - wpi::MemoryBuffer::GetFile(path, ec); - if (fileBuffer == nullptr || ec) { - throw std::runtime_error(fmt::format("Unable to read: {}", path)); - } - - wpi::json json = wpi::json::parse(fileBuffer->GetCharBuffer()); - WPI_INFO(logger, "Read frc-characterization JSON from {}", path); - return json; -} - -std::string sysid::ConvertJSON(std::string_view path, wpi::Logger& logger) { - wpi::json ojson = GetJSON(path, logger); - - auto type = sysid::analysis::FromName(ojson.at("test").get()); - auto factor = ojson.at("unitsPerRotation").get(); - auto unit = ojson.at("units").get(); - - wpi::json json; - for (auto&& key : AnalysisManager::kJsonDataKeys) { - if (type == analysis::kDrivetrain) { - // Get the old data; create a vector for the new data; reserve the - // appropriate size for the new data. - auto odata = ojson.at(key).get>>(); - std::vector> data; - data.reserve(odata.size()); - - // Transfer the data. - for (auto&& pt : odata) { - data.push_back(std::array{ - pt[kTimestampCol], pt[kLVoltsCol], pt[kRVoltsCol], pt[kLPosCol], - pt[kRPosCol], pt[kLVelCol], pt[kRVelCol], 0.0, 0.0}); - } - json[key] = data; - } else { - // Get the old data; create a vector for the new data; reserve the - // appropriate size for the new data. - auto odata = ojson.at(key).get>>(); - std::vector> data; - data.reserve(odata.size()); - - // Transfer the data. - for (auto&& pt : odata) { - data.push_back(std::array{ - pt[kTimestampCol], pt[kLVoltsCol], pt[kLPosCol], pt[kLVelCol]}); - } - json[key] = data; - } - } - json["units"] = unit; - json["unitsPerRotation"] = factor; - json["test"] = type.name; - json["sysid"] = true; - - // Write the new file with "_new" appended to it. - path.remove_suffix(std::string_view{".json"}.size()); - std::string loc = fmt::format("{}_new.json", path); - - sysid::SaveFile(json.dump(2), std::filesystem::path{loc}); - - WPI_INFO(logger, "Wrote new JSON to: {}", loc); - return loc; -} - -std::string sysid::ToCSV(std::string_view path, wpi::Logger& logger) { - wpi::json json = GetJSON(path, logger); - - auto type = sysid::analysis::FromName(json.at("test").get()); - auto factor = json.at("unitsPerRotation").get(); - auto unit = json.at("units").get(); - std::string_view abbreviation = GetAbbreviation(unit); - - std::error_code ec; - // Naming: {sysid-json-name}(Test, Units).csv - path.remove_suffix(std::string_view{".json"}.size()); - std::string loc = fmt::format("{} ({}, {}).csv", path, type.name, unit); - wpi::raw_fd_ostream outputFile{loc, ec}; - - if (ec) { - throw std::runtime_error("Unable to write to: " + loc); - } - - fmt::print(outputFile, "Timestamp (s),Test,"); - if (type == analysis::kDrivetrain || type == analysis::kDrivetrainAngular) { - fmt::print( - outputFile, - "Left Volts (V),Right Volts (V),Left Position ({0}),Right " - "Position ({0}),Left Velocity ({0}/s),Right Velocity ({0}/s),Gyro " - "Position (deg),Gyro Rate (deg/s)\n", - abbreviation); - } else { - fmt::print(outputFile, "Volts (V),Position({0}),Velocity ({0}/s)\n", - abbreviation); - } - outputFile << "\n"; - - for (auto&& key : AnalysisManager::kJsonDataKeys) { - if (type == analysis::kDrivetrain || type == analysis::kDrivetrainAngular) { - auto tempData = - json.at(key).get>>(); - for (auto&& pt : tempData) { - fmt::print(outputFile, "{},{},{},{},{},{},{},{},{},{}\n", - pt[0], // Timestamp - key, // Test - pt[1], pt[2], // Left and Right Voltages - pt[3] * factor, pt[4] * factor, // Left and Right Positions - pt[5] * factor, pt[6] * factor, // Left and Right Velocity - pt[7], pt[8] // Gyro Position and Velocity - ); - } - } else { - auto tempData = - json.at(key).get>>(); - for (auto&& pt : tempData) { - fmt::print(outputFile, "{},{},{},{},{}\n", - pt[0], // Timestamp, - key, // Test - pt[1], // Voltage - pt[2] * factor, // Position - pt[3] * factor // Velocity - ); - } - } - } - outputFile.flush(); - WPI_INFO(logger, "Wrote CSV to: {}", loc); - return loc; -} diff --git a/sysid/src/main/native/cpp/analysis/OLS.cpp b/sysid/src/main/native/cpp/analysis/OLS.cpp index d095a485d50..254898bffb0 100644 --- a/sysid/src/main/native/cpp/analysis/OLS.cpp +++ b/sysid/src/main/native/cpp/analysis/OLS.cpp @@ -4,45 +4,85 @@ #include "sysid/analysis/OLS.h" -#include -#include +#include +#include #include -#include -using namespace sysid; +namespace sysid { -std::tuple, double, double> sysid::OLS( - const Eigen::MatrixXd& X, const Eigen::VectorXd& y) { +OLSResult OLS(const Eigen::MatrixXd& X, const Eigen::VectorXd& y) { assert(X.rows() == y.rows()); - // The linear model can be written as follows: - // y = Xβ + u, where y is the dependent observed variable, X is the matrix - // of independent variables, β is a vector of coefficients, and u is a - // vector of residuals. + // The linear regression model can be written as follows: + // + // y = Xβ + ε + // + // where y is the dependent observed variable, X is the matrix of independent + // variables, β is a vector of coefficients, and ε is a vector of residuals. + // + // We want to find the value of β that minimizes εᵀε. + // + // ε = y − Xβ + // εᵀε = (y − Xβ)ᵀ(y − Xβ) + // + // β̂ = argmin (y − Xβ)ᵀ(y − Xβ) + // β + // + // Take the partial derivative of the cost function with respect to β and set + // it equal to zero, then solve for β̂ . + // + // 0 = −2Xᵀ(y − Xβ̂) + // 0 = Xᵀ(y − Xβ̂) + // 0 = Xᵀy − XᵀXβ̂ + // XᵀXβ̂ = Xᵀy + // β̂ = (XᵀX)⁻¹Xᵀy - // We want to minimize u² = uᵀu = (y - Xβ)ᵀ(y - Xβ). // β = (XᵀX)⁻¹Xᵀy + // + // XᵀX is guaranteed to be symmetric positive definite, so an LLT + // decomposition can be used. + Eigen::MatrixXd β = (X.transpose() * X).llt().solve(X.transpose() * y); - // Calculate β that minimizes uᵀu. - Eigen::MatrixXd beta = (X.transpose() * X).llt().solve(X.transpose() * y); + // Error sum of squares + double SSE = (y - X * β).squaredNorm(); - // We will now calculate R² or the coefficient of determination, which - // tells us how much of the total variation (variation in y) can be - // explained by the regression model. + // Sample size + int n = X.rows(); - // We will first calculate the sum of the squares of the error, or the - // variation in error (SSE). - double SSE = (y - X * beta).squaredNorm(); + // Number of explanatory variables + int p = β.rows(); - int n = X.cols(); + // Total sum of squares (total variation in y) + // + // From slide 24 of + // http://www.stat.columbia.edu/~fwood/Teaching/w4315/Fall2009/lecture_11: + // + // SSTO = yᵀy - 1/n yᵀJy + // + // where J is a matrix of ones. + double SSTO = + (y.transpose() * y - 1.0 / y.rows() * y.transpose() * + Eigen::MatrixXd::Ones(y.rows(), y.rows()) * y) + .value(); - // Now we will calculate the total variation in y, known as SSTO. - double SSTO = ((y.transpose() * y) - (1.0 / n) * (y.transpose() * y)).value(); + // R² or the coefficient of determination, which represents how much of the + // total variation (variation in y) can be explained by the regression model + double rSquared = 1.0 - SSE / SSTO; - double rSquared = (SSTO - SSE) / SSTO; - double adjRSquared = 1.0 - (1.0 - rSquared) * ((n - 1.0) / (n - 3.0)); + // Adjusted R² + // + // n − 1 + // R̅² = 1 − (1 − R²) --------- + // n − p − 1 + // + // See https://en.wikipedia.org/wiki/Coefficient_of_determination#Adjusted_R2 + double adjRSquared = 1.0 - (1.0 - rSquared) * ((n - 1.0) / (n - p - 1.0)); + + // Root-mean-square error double RMSE = std::sqrt(SSE / n); - return {{beta.data(), beta.data() + beta.rows()}, adjRSquared, RMSE}; + return {{β.data(), β.data() + β.size()}, adjRSquared, RMSE}; } + +} // namespace sysid diff --git a/sysid/src/main/native/cpp/telemetry/TelemetryManager.cpp b/sysid/src/main/native/cpp/telemetry/TelemetryManager.cpp deleted file mode 100644 index ac97cdbca4d..00000000000 --- a/sysid/src/main/native/cpp/telemetry/TelemetryManager.cpp +++ /dev/null @@ -1,275 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "sysid/telemetry/TelemetryManager.h" - -#include -#include // for ::tolower -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "sysid/Util.h" -#include "sysid/analysis/AnalysisType.h" - -using namespace sysid; - -TelemetryManager::TelemetryManager(const Settings& settings, - wpi::Logger& logger, - nt::NetworkTableInstance instance) - : m_settings(settings), m_logger(logger), m_inst(instance) {} - -void TelemetryManager::BeginTest(std::string_view name) { - // Create a new test params instance for this test. - m_params = - TestParameters{name.starts_with("fast"), name.ends_with("forward"), - m_settings.mechanism == analysis::kDrivetrainAngular, - State::WaitingForEnable}; - - // Add this test to the list of running tests and set the running flag. - m_tests.push_back(std::string{name}); - m_isRunningTest = true; - - // Set the Voltage Command Entry - m_voltageCommand.Set((m_params.fast ? m_settings.stepVoltage - : m_settings.quasistaticRampRate) * - (m_params.forward ? 1 : -1)); - - // Set the test type - m_testType.Set(m_params.fast ? "Dynamic" : "Quasistatic"); - - // Set the rotate entry - m_rotate.Set(m_params.rotate); - - // Set the current mechanism in NT. - m_mechanism.Set(m_settings.mechanism.name); - // Set Overflow to False - m_overflowPub.Set(false); - // Set Mechanism Error to False - m_mechErrorPub.Set(false); - m_inst.Flush(); - - // Display the warning message. - for (auto&& func : m_callbacks) { - func( - "Please enable the robot in autonomous mode, and then " - "disable it " - "before it runs out of space. \n Note: The robot will " - "continue " - "to move until you disable it - It is your " - "responsibility to " - "ensure it does not hit anything!"); - } - - WPI_INFO(m_logger, "Started {} test.", m_tests.back()); -} - -void TelemetryManager::EndTest() { - // If there is no test running, this is a no-op - if (!m_isRunningTest) { - return; - } - - // Disable the running flag and store the data in the JSON. - m_isRunningTest = false; - m_data[m_tests.back()] = m_params.data; - - // Call the cancellation callbacks. - for (auto&& func : m_callbacks) { - std::string msg; - if (m_params.mechError) { - msg += - "\nERROR: The robot indicated that you are using the wrong project " - "for characterizing your mechanism. \nThis most likely means you " - "are trying to characterize a mechanism like a Drivetrain with a " - "deployed config for a General Mechanism (e.g. Arm, Flywheel, and " - "Elevator) or vice versa. Please double check your settings and " - "try again."; - } else if (!m_params.data.empty()) { - std::string units = m_settings.units; - std::transform(m_settings.units.begin(), m_settings.units.end(), - units.begin(), ::tolower); - - if (std::string_view{m_settings.mechanism.name}.starts_with( - "Drivetrain")) { - double p = (m_params.data.back()[3] - m_params.data.front()[3]) * - m_settings.unitsPerRotation; - double s = (m_params.data.back()[4] - m_params.data.front()[4]) * - m_settings.unitsPerRotation; - double g = m_params.data.back()[7] - m_params.data.front()[7]; - - msg = fmt::format( - "The left and right encoders traveled {} {} and {} {} " - "respectively.\nThe gyro angle delta was {} degrees.", - p, units, s, units, g * 180.0 / std::numbers::pi); - } else { - double p = (m_params.data.back()[2] - m_params.data.front()[2]) * - m_settings.unitsPerRotation; - msg = fmt::format("The encoder reported traveling {} {}.", p, units); - } - - if (m_params.overflow) { - msg += - "\nNOTE: the robot stopped recording data early because the entry " - "storage was exceeded."; - } - } else { - msg = "No data was detected."; - } - func(msg); - } - - // Remove previously run test from list of tests if no data was detected. - if (m_params.data.empty()) { - m_tests.pop_back(); - } - - // Send a zero command over NT. - m_voltageCommand.Set(0.0); - m_inst.Flush(); -} - -void TelemetryManager::Update() { - // If there is no test running, these is nothing to update. - if (!m_isRunningTest) { - return; - } - - // Update the NT entries that we're reading. - - int currAckNumber = m_ackNumberSub.Get(); - std::string telemetryValue; - - // Get the FMS Control Word. - for (auto tsValue : m_fmsControlData.ReadQueue()) { - uint32_t ctrl = tsValue.value; - m_params.enabled = ctrl & 0x01; - } - - // Get the string in the data field. - for (auto tsValue : m_telemetry.ReadQueue()) { - telemetryValue = tsValue.value; - } - - // Get the overflow flag - for (auto tsValue : m_overflowSub.ReadQueue()) { - m_params.overflow = tsValue.value; - } - - // Get the mechanism error flag - for (auto tsValue : m_mechErrorSub.ReadQueue()) { - m_params.mechError = tsValue.value; - } - - // Go through our state machine. - if (m_params.state == State::WaitingForEnable) { - if (m_params.enabled) { - m_params.enableStart = wpi::Now() * 1E-6; - m_params.state = State::RunningTest; - m_ackNumber = currAckNumber; - WPI_INFO(m_logger, "{}", "Transitioned to running test state."); - } - } - - if (m_params.state == State::RunningTest) { - // If for some reason we've disconnected, end the test. - if (!m_inst.IsConnected()) { - WPI_WARNING(m_logger, "{}", - "NT connection was dropped when executing the test. The test " - "has been canceled."); - EndTest(); - } - - // If the robot has disabled, then we can move on to the next step. - if (!m_params.enabled) { - m_params.disableStart = wpi::Now() * 1E-6; - m_params.state = State::WaitingForData; - WPI_INFO(m_logger, "{}", "Transitioned to waiting for data."); - } - } - - if (m_params.state == State::WaitingForData) { - double now = wpi::Now() * 1E-6; - m_voltageCommand.Set(0.0); - m_inst.Flush(); - - // Process valid data - if (!telemetryValue.empty() && m_ackNumber < currAckNumber) { - m_params.raw = std::move(telemetryValue); - m_ackNumber = currAckNumber; - } - - // We have the data that we need, so we can parse it and end the test. - if (!m_params.raw.empty() && - wpi::starts_with(m_params.raw, m_tests.back())) { - // Remove test type from start of string - m_params.raw.erase(0, m_params.raw.find(';') + 1); - - // Clean up the string -- remove spaces if there are any. - m_params.raw.erase( - std::remove_if(m_params.raw.begin(), m_params.raw.end(), ::isspace), - m_params.raw.end()); - - // Split the string into individual components. - wpi::SmallVector res; - wpi::split(m_params.raw, res, ','); - - // Convert each string to double. - std::vector values; - values.reserve(res.size()); - for (auto&& str : res) { - values.push_back(wpi::parse_float(str).value()); - } - - // Add the values to our result vector. - for (size_t i = 0; i < values.size() - m_settings.mechanism.rawDataSize; - i += m_settings.mechanism.rawDataSize) { - std::vector d(m_settings.mechanism.rawDataSize); - - std::copy_n(std::make_move_iterator(values.begin() + i), - m_settings.mechanism.rawDataSize, d.begin()); - m_params.data.push_back(std::move(d)); - } - - WPI_INFO(m_logger, - "Received data with size: {} for the {} test in {} seconds.", - m_params.data.size(), m_tests.back(), - m_params.data.back()[0] - m_params.data.front()[0]); - m_ackNumberPub.Set(++m_ackNumber); - EndTest(); - } - - // If we timed out, end the test and let the user know. - if (now - m_params.disableStart > 5.0) { - WPI_WARNING(m_logger, "{}", - "TelemetryManager did not receieve data 5 seconds after " - "completing the test..."); - EndTest(); - } - } -} - -std::string TelemetryManager::SaveJSON(std::string_view location) { - m_data["test"] = m_settings.mechanism.name; - m_data["units"] = m_settings.units; - m_data["unitsPerRotation"] = m_settings.unitsPerRotation; - m_data["sysid"] = true; - - std::string loc = fmt::format("{}/sysid_data{:%Y%m%d-%H%M%S}.json", location, - std::chrono::system_clock::now()); - - sysid::SaveFile(m_data.dump(2), std::filesystem::path{loc}); - WPI_INFO(m_logger, "Wrote JSON to: {}", loc); - - return loc; -} diff --git a/sysid/src/main/native/cpp/view/Analyzer.cpp b/sysid/src/main/native/cpp/view/Analyzer.cpp index 32709188ca6..457a26295ba 100644 --- a/sysid/src/main/native/cpp/view/Analyzer.cpp +++ b/sysid/src/main/native/cpp/view/Analyzer.cpp @@ -28,14 +28,13 @@ using namespace sysid; Analyzer::Analyzer(glass::Storage& storage, wpi::Logger& logger) - : m_location(""), m_logger(logger) { + : m_logger(logger) { // Fill the StringMap with preset values. m_presets["Default"] = presets::kDefault; - m_presets["WPILib (2020-)"] = presets::kWPILibNew; - m_presets["WPILib (Pre-2020)"] = presets::kWPILibOld; - m_presets["CANCoder"] = presets::kCTRECANCoder; - m_presets["CTRE"] = presets::kCTREDefault; - m_presets["CTRE (Pro)"] = presets::kCTREProDefault; + m_presets["WPILib"] = presets::kWPILib; + m_presets["CTRE Phoenix 5 CANcoder"] = presets::kCTREv5CANCoder; + m_presets["CTRE Phoenix 5"] = presets::kCTREv5; + m_presets["CTRE Phoenix 6"] = presets::kCTREv6; m_presets["REV Brushless Encoder Port"] = presets::kREVNEOBuiltIn; m_presets["REV Brushed Encoder Port"] = presets::kREVNonNEO; m_presets["REV Data Port"] = presets::kREVNonNEO; @@ -48,22 +47,20 @@ Analyzer::Analyzer(glass::Storage& storage, wpi::Logger& logger) void Analyzer::UpdateFeedforwardGains() { WPI_INFO(m_logger, "{}", "Gain calc"); try { - const auto& [ff, trackWidth] = m_manager->CalculateFeedforward(); - m_ff = std::get<0>(ff); - m_accelRSquared = std::get<1>(ff); - m_accelRMSE = std::get<2>(ff); - m_trackWidth = trackWidth; + const auto& feedforwardGains = m_manager->CalculateFeedforward(); + m_feedforwardGains = feedforwardGains; + m_accelRSquared = feedforwardGains.olsResult.rSquared; + m_accelRMSE = feedforwardGains.olsResult.rmse; m_settings.preset.measurementDelay = m_settings.type == FeedbackControllerLoopType::kPosition ? m_manager->GetPositionDelay() : m_manager->GetVelocityDelay(); - m_conversionFactor = m_manager->GetFactor(); PrepareGraphs(); } catch (const sysid::InvalidDataError& e) { m_state = AnalyzerState::kGeneralDataError; HandleError(e.what()); } catch (const sysid::NoQuasistaticDataError& e) { - m_state = AnalyzerState::kMotionThresholdError; + m_state = AnalyzerState::kVelocityThresholdError; HandleError(e.what()); } catch (const sysid::NoDynamicDataError& e) { m_state = AnalyzerState::kTestDurationError; @@ -81,16 +78,23 @@ void Analyzer::UpdateFeedforwardGains() { } void Analyzer::UpdateFeedbackGains() { - if (m_ff[1] > 0 && m_ff[2] > 0) { - const auto& fb = m_manager->CalculateFeedback(m_ff); - m_timescale = units::second_t{m_ff[2] / m_ff[1]}; + WPI_INFO(m_logger, "{}", "Updating feedback gains"); + + const auto& Kv = m_feedforwardGains.Kv; + const auto& Ka = m_feedforwardGains.Ka; + if (Kv.isValidGain && Ka.isValidGain) { + const auto& fb = m_manager->CalculateFeedback(Kv, Ka); + m_timescale = units::second_t{Ka.gain / Kv.gain}; + m_timescaleValid = true; m_Kp = fb.Kp; m_Kd = fb.Kd; + } else { + m_timescaleValid = false; } } -bool Analyzer::DisplayGain(const char* text, double* data, - bool readOnly = true) { +bool Analyzer::DisplayDouble(const char* text, double* data, + bool readOnly = true) { ImGui::SetNextItemWidth(ImGui::GetFontSize() * 5); if (readOnly) { return ImGui::InputDouble(text, data, 0.0, 0.0, "%.5G", @@ -107,40 +111,22 @@ static void SetPosition(double beginX, double beginY, double xShift, } bool Analyzer::IsErrorState() { - return m_state == AnalyzerState::kMotionThresholdError || + return m_state == AnalyzerState::kVelocityThresholdError || m_state == AnalyzerState::kTestDurationError || m_state == AnalyzerState::kGeneralDataError || m_state == AnalyzerState::kFileError; } bool Analyzer::IsDataErrorState() { - return m_state == AnalyzerState::kMotionThresholdError || + return m_state == AnalyzerState::kVelocityThresholdError || m_state == AnalyzerState::kTestDurationError || m_state == AnalyzerState::kGeneralDataError; } -void Analyzer::DisplayFileSelector() { - // Get the current width of the window. This will be used to scale - // our UI elements. - float width = ImGui::GetContentRegionAvail().x; - - // Show the file location along with an option to choose. - if (ImGui::Button("Select")) { - m_selector = std::make_unique( - "Select Data", "", - std::vector{"JSON File", SYSID_PFD_JSON_EXT}); - } - ImGui::SameLine(); - ImGui::SetNextItemWidth(width - ImGui::CalcTextSize("Select").x - - ImGui::GetFontSize() * 5); - ImGui::InputText("##location", &m_location, ImGuiInputTextFlags_ReadOnly); -} - void Analyzer::ResetData() { m_plot.ResetData(); m_manager = std::make_unique(m_settings, m_logger); - m_location = ""; - m_ff = std::vector{1, 1, 1}; + m_feedforwardGains = AnalysisManager::FeedforwardGains{}; UpdateFeedbackGains(); } @@ -152,38 +138,15 @@ bool Analyzer::DisplayResetAndUnitOverride() { ImGui::SameLine(width - ImGui::CalcTextSize("Reset").x); if (ImGui::Button("Reset")) { ResetData(); - m_state = AnalyzerState::kWaitingForJSON; + m_state = AnalyzerState::kWaitingForData; return true; } - if (type == analysis::kDrivetrain) { - ImGui::SetNextItemWidth(ImGui::GetFontSize() * kTextBoxWidthMultiple); - if (ImGui::Combo("Dataset", &m_dataset, kDatasets, 3)) { - m_settings.dataset = - static_cast(m_dataset); - PrepareData(); - } - ImGui::SameLine(); - } else { - m_settings.dataset = - AnalysisManager::Settings::DrivetrainDataset::kCombined; - } - ImGui::Spacing(); ImGui::Text( "Units: %s\n" - "Units Per Rotation: %.4f\n" "Type: %s", - std::string(unit).c_str(), m_conversionFactor, type.name); - - if (type == analysis::kDrivetrainAngular) { - ImGui::SameLine(); - sysid::CreateTooltip( - "Here, the units and units per rotation represent what the wheel " - "positions and velocities were captured in. The track width value " - "will reflect the unit selected here. However, the Kv and Ka will " - "always be in Vs/rad and Vs^2 / rad respectively."); - } + std::string(unit).c_str(), type.name); if (ImGui::Button("Override Units")) { ImGui::OpenPopup("Override Units"); @@ -197,24 +160,11 @@ bool Analyzer::DisplayResetAndUnitOverride() { IM_ARRAYSIZE(kUnits)); unit = kUnits[m_selectedOverrideUnit]; - if (unit == "Degrees") { - m_conversionFactor = 360.0; - } else if (unit == "Radians") { - m_conversionFactor = 2 * std::numbers::pi; - } else if (unit == "Rotations") { - m_conversionFactor = 1.0; - } - - bool isRotational = m_selectedOverrideUnit > 2; - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 7); - ImGui::InputDouble( - "Units Per Rotation", &m_conversionFactor, 0.0, 0.0, "%.4f", - isRotational ? ImGuiInputTextFlags_ReadOnly : ImGuiInputTextFlags_None); if (ImGui::Button("Close")) { ImGui::CloseCurrentPopup(); - m_manager->OverrideUnits(unit, m_conversionFactor); + m_manager->OverrideUnits(unit); PrepareData(); } @@ -234,22 +184,22 @@ void Analyzer::ConfigParamsOnFileSelect() { WPI_INFO(m_logger, "{}", "Configuring Params"); m_stepTestDuration = m_settings.stepTestDuration.to(); - // Estimate qp as 1/8 * units-per-rot - m_settings.lqr.qp = 0.125 * m_manager->GetFactor(); + // Estimate qp as 1/10 native distance unit + m_settings.lqr.qp = 0.1; // Estimate qv as 1/4 * max velocity = 1/4 * (12V - kS) / kV - m_settings.lqr.qv = 0.25 * (12.0 - m_ff[0]) / m_ff[1]; + m_settings.lqr.qv = + 0.25 * (12.0 - m_feedforwardGains.Ks.gain) / m_feedforwardGains.Kv.gain; } void Analyzer::Display() { - DisplayFileSelector(); DisplayGraphs(); switch (m_state) { - case AnalyzerState::kWaitingForJSON: { + case AnalyzerState::kWaitingForData: { ImGui::Text( "SysId is currently in theoretical analysis mode.\n" "To analyze recorded test data, select a " - "data JSON."); + "data file (.wpilog)."); sysid::CreateTooltip( "Theoretical feedback gains can be calculated from a " "physical model of the mechanism being controlled. " @@ -295,14 +245,14 @@ void Analyzer::Display() { case AnalyzerState::kFileError: { CreateErrorPopup(m_errorPopup, m_exception); if (!m_errorPopup) { - m_state = AnalyzerState::kWaitingForJSON; + m_state = AnalyzerState::kWaitingForData; return; } break; } case AnalyzerState::kGeneralDataError: case AnalyzerState::kTestDurationError: - case AnalyzerState::kMotionThresholdError: { + case AnalyzerState::kVelocityThresholdError: { CreateErrorPopup(m_errorPopup, m_exception); if (DisplayResetAndUnitOverride()) { return; @@ -313,20 +263,10 @@ void Analyzer::Display() { break; } } - - // Periodic functions - try { - SelectFile(); - } catch (const AnalysisManager::FileReadingError& e) { - m_state = AnalyzerState::kFileError; - HandleError(e.what()); - } catch (const wpi::json::exception& e) { - m_state = AnalyzerState::kFileError; - HandleError(e.what()); - } } void Analyzer::PrepareData() { + WPI_INFO(m_logger, "{}", "Preparing data"); try { m_manager->PrepareData(); UpdateFeedforwardGains(); @@ -335,7 +275,7 @@ void Analyzer::PrepareData() { m_state = AnalyzerState::kGeneralDataError; HandleError(e.what()); } catch (const sysid::NoQuasistaticDataError& e) { - m_state = AnalyzerState::kMotionThresholdError; + m_state = AnalyzerState::kVelocityThresholdError; HandleError(e.what()); } catch (const sysid::NoDynamicDataError& e) { m_state = AnalyzerState::kTestDurationError; @@ -368,8 +308,9 @@ void Analyzer::PrepareGraphs() { AbortDataPrep(); m_dataThread = std::thread([&] { m_plot.SetData(m_manager->GetRawData(), m_manager->GetFilteredData(), - m_manager->GetUnit(), m_ff, m_manager->GetStartTimes(), - m_manager->GetAnalysisType(), m_abortDataPrep); + m_manager->GetUnit(), m_feedforwardGains, + m_manager->GetStartTimes(), m_manager->GetAnalysisType(), + m_abortDataPrep); }); UpdateFeedbackGains(); m_state = AnalyzerState::kNominalDisplay; @@ -379,9 +320,6 @@ void Analyzer::PrepareGraphs() { void Analyzer::HandleError(std::string_view msg) { m_exception = msg; m_errorPopup = true; - if (m_state == AnalyzerState::kFileError) { - m_location = ""; - } PrepareRawGraphs(); } @@ -424,28 +362,28 @@ void Analyzer::DisplayGraphs() { // If a JSON is selected if (m_state == AnalyzerState::kNominalDisplay) { - DisplayGain("Acceleration R²", &m_accelRSquared); + DisplayDouble("Acceleration R²", &m_accelRSquared); CreateTooltip( "The coefficient of determination of the OLS fit of acceleration " "versus velocity and voltage. Acceleration is extremely noisy, " "so this is generally quite small."); ImGui::SameLine(); - DisplayGain("Acceleration RMSE", &m_accelRMSE); + DisplayDouble("Acceleration RMSE", &m_accelRMSE); CreateTooltip( "The standard deviation of the residuals from the predicted " "acceleration." "This can be interpreted loosely as the mean measured disturbance " "from the \"ideal\" system equation."); - DisplayGain("Sim velocity R²", m_plot.GetSimRSquared()); + DisplayDouble("Sim velocity R²", m_plot.GetSimRSquared()); CreateTooltip( "The coefficient of determination the simulated velocity. " "Velocity is much less-noisy than acceleration, so this " "is pretty close to 1 for a decent fit."); ImGui::SameLine(); - DisplayGain("Sim velocity RMSE", m_plot.GetSimRMSE()); + DisplayDouble("Sim velocity RMSE", m_plot.GetSimRMSE()); CreateTooltip( "The standard deviation of the residuals from the simulated velocity " "predictions - essentially the size of the mean error of the " @@ -458,23 +396,12 @@ void Analyzer::DisplayGraphs() { ImGui::End(); } -void Analyzer::SelectFile() { - // If the selector exists and is ready with a result, we can store it. - if (m_selector && m_selector->ready() && !m_selector->result().empty()) { - // Store the location of the file and reset the selector. - WPI_INFO(m_logger, "Opening File: {}", m_selector->result()[0]); - m_location = m_selector->result()[0]; - m_selector.reset(); - WPI_INFO(m_logger, "{}", "Opened File"); - m_manager = - std::make_unique(m_location, m_settings, m_logger); - PrepareData(); - m_dataset = 0; - m_settings.dataset = - AnalysisManager::Settings::DrivetrainDataset::kCombined; - ConfigParamsOnFileSelect(); - UpdateFeedbackGains(); - } +void Analyzer::AnalyzeData() { + m_manager = std::make_unique(m_data, m_settings, m_logger); + PrepareData(); + m_dataset = 0; + ConfigParamsOnFileSelect(); + UpdateFeedbackGains(); } void Analyzer::AbortDataPrep() { @@ -487,7 +414,7 @@ void Analyzer::AbortDataPrep() { void Analyzer::DisplayFeedforwardParameters(float beginX, float beginY) { // Increase spacing to not run into trackwidth in the normal analyzer view - constexpr double kHorizontalOffset = 0.9; + constexpr double kHorizontalOffset = 1.1; SetPosition(beginX, beginY, kHorizontalOffset, 0); bool displayAll = @@ -509,15 +436,15 @@ void Analyzer::DisplayFeedforwardParameters(float beginX, float beginY) { "filter's sliding window."); } - if (displayAll || m_state == AnalyzerState::kMotionThresholdError) { + if (displayAll || m_state == AnalyzerState::kVelocityThresholdError) { // Wait for enter before refresh so decimal inputs like "0.2" don't // prematurely refresh with a velocity threshold of "0". SetPosition(beginX, beginY, kHorizontalOffset, 1); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 4); - double threshold = m_settings.motionThreshold; + double threshold = m_settings.velocityThreshold; if (ImGui::InputDouble("Velocity Threshold", &threshold, 0.0, 0.0, "%.3f", ImGuiInputTextFlags_EnterReturnsTrue)) { - m_settings.motionThreshold = std::max(0.0, threshold); + m_settings.velocityThreshold = std::max(0.0, threshold); PrepareData(); } CreateTooltip("Velocity data below this threshold will be ignored."); @@ -537,20 +464,20 @@ void Analyzer::DisplayFeedforwardParameters(float beginX, float beginY) { void Analyzer::CollectFeedforwardGains(float beginX, float beginY) { SetPosition(beginX, beginY, 0, 0); - if (DisplayGain("Kv", &m_ff[1], false)) { + if (DisplayDouble("Kv", &m_feedforwardGains.Kv.gain, false)) { UpdateFeedbackGains(); } SetPosition(beginX, beginY, 0, 1); - if (DisplayGain("Ka", &m_ff[2], false)) { + if (DisplayDouble("Ka", &m_feedforwardGains.Ka.gain, false)) { UpdateFeedbackGains(); } SetPosition(beginX, beginY, 0, 2); // Show Timescale ImGui::SetNextItemWidth(ImGui::GetFontSize() * 4); - DisplayGain("Response Timescale (ms)", - reinterpret_cast(&m_timescale)); + DisplayDouble("Response Timescale (ms)", + reinterpret_cast(&m_timescale)); CreateTooltip( "The characteristic timescale of the system response in milliseconds. " "Both the control loop period and total signal delay should be " @@ -558,21 +485,39 @@ void Analyzer::CollectFeedforwardGains(float beginX, float beginY) { "system."); } +void Analyzer::DisplayFeedforwardGain(const char* text, + AnalysisManager::FeedforwardGain& ffGain, + bool readOnly = true) { + DisplayDouble(text, &ffGain.gain, readOnly); + if (!ffGain.isValidGain) { + // Display invalid gain message with warning and tooltip + CreateErrorTooltip(ffGain.errorMessage.c_str()); + } + + // Display descriptor message as tooltip, whether the gain is valid or not + CreateTooltip(ffGain.descriptor.c_str()); +} + void Analyzer::DisplayFeedforwardGains(float beginX, float beginY) { SetPosition(beginX, beginY, 0, 0); - DisplayGain("Ks", &m_ff[0]); + DisplayFeedforwardGain("Ks", m_feedforwardGains.Ks); SetPosition(beginX, beginY, 0, 1); - DisplayGain("Kv", &m_ff[1]); + DisplayFeedforwardGain("Kv", m_feedforwardGains.Kv); SetPosition(beginX, beginY, 0, 2); - DisplayGain("Ka", &m_ff[2]); + DisplayFeedforwardGain("Ka", m_feedforwardGains.Ka); SetPosition(beginX, beginY, 0, 3); // Show Timescale ImGui::SetNextItemWidth(ImGui::GetFontSize() * 4); - DisplayGain("Response Timescale (ms)", - reinterpret_cast(&m_timescale)); + DisplayDouble("Response Timescale (ms)", + reinterpret_cast(&m_timescale)); + if (!m_timescaleValid) { + CreateErrorTooltip( + "Response timescale calculation invalid. Ensure that calculated gains " + "are valid."); + } CreateTooltip( "The characteristic timescale of the system response in milliseconds. " "Both the control loop period and total signal delay should be " @@ -581,8 +526,8 @@ void Analyzer::DisplayFeedforwardGains(float beginX, float beginY) { SetPosition(beginX, beginY, 0, 4); auto positionDelay = m_manager->GetPositionDelay(); - DisplayGain("Position Measurement Delay (ms)", - reinterpret_cast(&positionDelay)); + DisplayDouble("Position Measurement Delay (ms)", + reinterpret_cast(&positionDelay)); CreateTooltip( "The average elapsed time between the first application of " "voltage and the first detected change in mechanism position " @@ -592,8 +537,8 @@ void Analyzer::DisplayFeedforwardGains(float beginX, float beginY) { SetPosition(beginX, beginY, 0, 5); auto velocityDelay = m_manager->GetVelocityDelay(); - DisplayGain("Velocity Measurement Delay (ms)", - reinterpret_cast(&velocityDelay)); + DisplayDouble("Velocity Measurement Delay (ms)", + reinterpret_cast(&velocityDelay)); CreateTooltip( "The average elapsed time between the first application of " "voltage and the maximum calculated mechanism acceleration " @@ -604,20 +549,20 @@ void Analyzer::DisplayFeedforwardGains(float beginX, float beginY) { SetPosition(beginX, beginY, 0, 6); if (m_manager->GetAnalysisType() == analysis::kElevator) { - DisplayGain("Kg", &m_ff[3]); + DisplayFeedforwardGain("Kg", m_feedforwardGains.Kg); } else if (m_manager->GetAnalysisType() == analysis::kArm) { - DisplayGain("Kg", &m_ff[3]); + DisplayFeedforwardGain("Kg", m_feedforwardGains.Kg); double offset; auto unit = m_manager->GetUnit(); if (unit == "Radians") { - offset = m_ff[4]; + offset = m_feedforwardGains.offset.gain; } else if (unit == "Degrees") { - offset = m_ff[4] / std::numbers::pi * 180.0; + offset = m_feedforwardGains.offset.gain / std::numbers::pi * 180.0; } else if (unit == "Rotations") { - offset = m_ff[4] / (2 * std::numbers::pi); + offset = m_feedforwardGains.offset.gain / (2 * std::numbers::pi); } - DisplayGain( + DisplayDouble( fmt::format("Angle offset to horizontal ({})", GetAbbreviation(unit)) .c_str(), &offset); @@ -625,8 +570,6 @@ void Analyzer::DisplayFeedforwardGains(float beginX, float beginY) { "This is the angle offset which, when added to the angle measurement, " "zeroes it out when the arm is horizontal. This is needed for the arm " "feedforward to work."); - } else if (m_trackWidth) { - DisplayGain("Track Width", &*m_trackWidth); } double endY = ImGui::GetCursorPosY(); @@ -644,7 +587,6 @@ void Analyzer::DisplayFeedbackGains() { m_settings.type = FeedbackControllerLoopType::kVelocity; m_selectedLoopType = static_cast(FeedbackControllerLoopType::kVelocity); - m_settings.convertGainsToEncTicks = m_selectedPreset > 2; UpdateFeedbackGains(); } ImGui::SameLine(); @@ -728,59 +670,6 @@ void Analyzer::DisplayFeedbackGains() { "accurate if the characteristic timescale of the mechanism " "is small."); - // Add CPR and Gearing for converting Feedback Gains - ImGui::Separator(); - ImGui::Spacing(); - - if (ImGui::Checkbox("Convert Gains to Encoder Counts", - &m_settings.convertGainsToEncTicks)) { - UpdateFeedbackGains(); - } - sysid::CreateTooltip( - "Whether the feedback gains should be in terms of encoder counts or " - "output units. Because smart motor controllers usually don't have " - "direct access to the output units (i.e. m/s for a drivetrain), they " - "perform feedback on the encoder counts directly. If you are using a " - "PID Controller on the RoboRIO, you are probably performing feedback " - "on the output units directly.\n\nNote that if you have properly set " - "up position and velocity conversion factors with the SPARK MAX, you " - "can leave this box unchecked. The motor controller will perform " - "feedback on the output directly."); - - if (m_settings.convertGainsToEncTicks) { - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 5); - if (ImGui::InputDouble("##Numerator", &m_gearingNumerator, 0.0, 0.0, "%.4f", - ImGuiInputTextFlags_EnterReturnsTrue) && - m_gearingNumerator > 0) { - m_settings.gearing = m_gearingNumerator / m_gearingDenominator; - UpdateFeedbackGains(); - } - ImGui::SameLine(); - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 5); - if (ImGui::InputDouble("##Denominator", &m_gearingDenominator, 0.0, 0.0, - "%.4f", ImGuiInputTextFlags_EnterReturnsTrue) && - m_gearingDenominator > 0) { - m_settings.gearing = m_gearingNumerator / m_gearingDenominator; - UpdateFeedbackGains(); - } - sysid::CreateTooltip( - "The gearing between the encoder and the motor shaft (# of encoder " - "turns / # of motor shaft turns)."); - - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 5); - if (ImGui::InputInt("CPR", &m_settings.cpr, 0, 0, - ImGuiInputTextFlags_EnterReturnsTrue) && - m_settings.cpr > 0) { - UpdateFeedbackGains(); - } - sysid::CreateTooltip( - "The counts per rotation of your encoder. This is the number of counts " - "reported in user code when the encoder is rotated exactly once. Some " - "common values for various motors/encoders are:\n\n" - "Falcon 500: 2048\nNEO: 1\nCTRE Mag Encoder / CANCoder: 4096\nREV " - "Through Bore Encoder: 8192\n"); - } - ImGui::Separator(); ImGui::Spacing(); @@ -790,7 +679,7 @@ void Analyzer::DisplayFeedbackGains() { IM_ARRAYSIZE(kLoopTypes))) { m_settings.type = static_cast(m_selectedLoopType); - if (m_state == AnalyzerState::kWaitingForJSON) { + if (m_state == AnalyzerState::kWaitingForData) { m_settings.preset.measurementDelay = 0_ms; } else { if (m_settings.type == FeedbackControllerLoopType::kPosition) { @@ -807,23 +696,23 @@ void Analyzer::DisplayFeedbackGains() { // Show Kp and Kd. float beginY = ImGui::GetCursorPosY(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 4); - DisplayGain("Kp", &m_Kp); + DisplayDouble("Kp", &m_Kp); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 4); - DisplayGain("Kd", &m_Kd); + DisplayDouble("Kd", &m_Kd); // Come back to the starting y pos. ImGui::SetCursorPosY(beginY); if (m_selectedLoopType == 0) { std::string unit; - if (m_state != AnalyzerState::kWaitingForJSON) { + if (m_state != AnalyzerState::kWaitingForData) { unit = fmt::format(" ({})", GetAbbreviation(m_manager->GetUnit())); } ImGui::SetCursorPosX(ImGui::GetFontSize() * 9); - if (DisplayGain(fmt::format("Max Position Error{}", unit).c_str(), - &m_settings.lqr.qp, false)) { + if (DisplayDouble(fmt::format("Max Position Error{}", unit).c_str(), + &m_settings.lqr.qp, false)) { if (m_settings.lqr.qp > 0) { UpdateFeedbackGains(); } @@ -831,19 +720,19 @@ void Analyzer::DisplayFeedbackGains() { } std::string unit; - if (m_state != AnalyzerState::kWaitingForJSON) { + if (m_state != AnalyzerState::kWaitingForData) { unit = fmt::format(" ({}/s)", GetAbbreviation(m_manager->GetUnit())); } ImGui::SetCursorPosX(ImGui::GetFontSize() * 9); - if (DisplayGain(fmt::format("Max Velocity Error{}", unit).c_str(), - &m_settings.lqr.qv, false)) { + if (DisplayDouble(fmt::format("Max Velocity Error{}", unit).c_str(), + &m_settings.lqr.qv, false)) { if (m_settings.lqr.qv > 0) { UpdateFeedbackGains(); } } ImGui::SetCursorPosX(ImGui::GetFontSize() * 9); - if (DisplayGain("Max Control Effort (V)", &m_settings.lqr.r, false)) { + if (DisplayDouble("Max Control Effort (V)", &m_settings.lqr.r, false)) { if (m_settings.lqr.r > 0) { UpdateFeedbackGains(); } diff --git a/sysid/src/main/native/cpp/view/AnalyzerPlot.cpp b/sysid/src/main/native/cpp/view/AnalyzerPlot.cpp index d8afbaf06c0..6963f2c1b8f 100644 --- a/sysid/src/main/native/cpp/view/AnalyzerPlot.cpp +++ b/sysid/src/main/native/cpp/view/AnalyzerPlot.cpp @@ -127,16 +127,16 @@ void AnalyzerPlot::SetRawData(const Storage& data, std::string_view unit, void AnalyzerPlot::SetData(const Storage& rawData, const Storage& filteredData, std::string_view unit, - const std::vector& ffGains, + const AnalysisManager::FeedforwardGains& ffGains, const std::array& startTimes, AnalysisType type, std::atomic& abort) { double simSquaredErrorSum = 0; double squaredVariationSum = 0; int timeSeriesPoints = 0; - const auto& Ks = ffGains[0]; - const auto& Kv = ffGains[1]; - const auto& Ka = ffGains[2]; + const auto& Ks = ffGains.Ks.gain; + const auto& Kv = ffGains.Kv.gain; + const auto& Ka = ffGains.Ka.gain; auto& [slowForward, slowBackward, fastForward, fastBackward] = filteredData; auto& [rawSlowForward, rawSlowBackward, rawFastForward, rawFastBackward] = @@ -223,7 +223,7 @@ void AnalyzerPlot::SetData(const Storage& rawData, const Storage& filteredData, // Populate simulated time domain data if (type == analysis::kElevator) { - const auto& Kg = ffGains[3]; + const auto& Kg = ffGains.Kg.gain; m_quasistaticData.simData = PopulateTimeDomainSim( rawSlow, startTimes, fastStep, sysid::ElevatorSim{Ks, Kv, Ka, Kg}, &simSquaredErrorSum, &squaredVariationSum, &timeSeriesPoints); @@ -231,8 +231,8 @@ void AnalyzerPlot::SetData(const Storage& rawData, const Storage& filteredData, rawFast, startTimes, fastStep, sysid::ElevatorSim{Ks, Kv, Ka, Kg}, &simSquaredErrorSum, &squaredVariationSum, &timeSeriesPoints); } else if (type == analysis::kArm) { - const auto& Kg = ffGains[3]; - const auto& offset = ffGains[4]; + const auto& Kg = ffGains.Kg.gain; + const auto& offset = ffGains.offset.gain; m_quasistaticData.simData = PopulateTimeDomainSim( rawSlow, startTimes, fastStep, sysid::ArmSim{Ks, Kv, Ka, Kg, offset}, &simSquaredErrorSum, &squaredVariationSum, &timeSeriesPoints); @@ -288,10 +288,10 @@ void AnalyzerPlot::SetData(const Storage& rawData, const Storage& filteredData, std::copysign(Ks / Ka, slow[i].velocity); if (type == analysis::kElevator) { - const auto& Kg = ffGains[3]; + const auto& Kg = ffGains.Kg.gain; accelPortion -= Kg / Ka; } else if (type == analysis::kArm) { - const auto& Kg = ffGains[3]; + const auto& Kg = ffGains.Kg.gain; accelPortion -= Kg / Ka * slow[i].cos; } @@ -307,10 +307,10 @@ void AnalyzerPlot::SetData(const Storage& rawData, const Storage& filteredData, std::copysign(Ks / Ka, fast[i].velocity); if (type == analysis::kElevator) { - const auto& Kg = ffGains[3]; + const auto& Kg = ffGains.Kg.gain; accelPortion -= Kg / Ka; } else if (type == analysis::kArm) { - const auto& Kg = ffGains[3]; + const auto& Kg = ffGains.Kg.gain; accelPortion -= Kg / Ka * fast[i].cos; } diff --git a/sysid/src/main/native/cpp/view/DataSelector.cpp b/sysid/src/main/native/cpp/view/DataSelector.cpp new file mode 100644 index 00000000000..75b12e5e3ab --- /dev/null +++ b/sysid/src/main/native/cpp/view/DataSelector.cpp @@ -0,0 +1,295 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "sysid/view/DataSelector.h" + +#include +#include +#include +#include +#include +#include + +#include "sysid/Util.h" +#include "sysid/analysis/AnalysisType.h" +#include "sysid/analysis/Storage.h" + +using namespace sysid; + +static constexpr const char* kAnalysisTypes[] = {"Elevator", "Arm", "Simple"}; + +static bool EmitEntryTarget(const char* name, bool isString, + const glass::DataLogReaderEntry** entry) { + if (*entry) { + auto text = + fmt::format("{}: {} ({})", name, (*entry)->name, (*entry)->type); + ImGui::TextUnformatted(text.c_str()); + } else { + ImGui::Text("%s: (%s)", name, + isString ? "string" : "number"); + } + bool rv = false; + if (ImGui::BeginDragDropTarget()) { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload( + isString ? "DataLogEntryString" : "DataLogEntry")) { + assert(payload->DataSize == sizeof(const glass::DataLogReaderEntry*)); + *entry = *static_cast(payload->Data); + rv = true; + } + ImGui::EndDragDropTarget(); + } + return rv; +} + +void DataSelector::Display() { + using namespace std::chrono_literals; + + // building test data is modal (due to async access) + if (m_testdataFuture.valid()) { + if (m_testdataFuture.wait_for(0s) == std::future_status::ready) { + TestData data = m_testdataFuture.get(); + for (auto&& motordata : data.motorData) { + m_testdataStats.emplace_back( + fmt::format("Test State: {}", motordata.first())); + int i = 0; + for (auto&& run : motordata.second.runs) { + m_testdataStats.emplace_back(fmt::format( + " Run {} samples: {} Volt {} Pos {} Vel", ++i, + run.voltage.size(), run.position.size(), run.velocity.size())); + } + } + if (testdata) { + testdata(std::move(data)); + } + } + ImGui::Text("Loading data..."); + return; + } + + if (!m_testdataStats.empty()) { + for (auto&& line : m_testdataStats) { + ImGui::TextUnformatted(line.c_str()); + } + if (ImGui::Button("Ok")) { + m_testdataStats.clear(); + } + return; + } + + if (EmitEntryTarget("Test State", true, &m_testStateEntry)) { + m_testsFuture = + std::async(std::launch::async, [testStateEntry = m_testStateEntry] { + return LoadTests(*testStateEntry); + }); + } + + if (!m_testStateEntry) { + return; + } + + if (m_testsFuture.valid() && + m_testsFuture.wait_for(0s) == std::future_status::ready) { + m_tests = m_testsFuture.get(); + for (auto it = m_tests.begin(); it != m_tests.end();) { + if (it->first != "quasistatic" && it->first != "dynamic") { + WPI_WARNING(m_logger, "Unrecognized test {}, removing", it->first); + it = m_tests.erase(it); + continue; + } + for (auto it2 = it->second.begin(); it2 != it->second.end();) { + auto direction = wpi::rsplit(it2->first, '-').second; + if (direction != "forward" && direction != "reverse") { + WPI_WARNING(m_logger, "Unrecognized direction {}, removing", + direction); + it2 = it->second.erase(it2); + continue; + } + WPI_INFO(m_logger, "Loaded test state {}", it2->first); + ++it2; + } + if (it->second.empty()) { + WPI_WARNING(m_logger, "No data for test {}, removing", it->first); + it = m_tests.erase(it); + continue; + } + ++it; + } + WPI_INFO(m_logger, "Loaded {} tests", m_tests.size()); + } + + if (m_tests.empty()) { + if (m_testsFuture.valid()) { + ImGui::TextUnformatted("Reading tests..."); + } else { + ImGui::TextUnformatted("No tests found"); + } + return; + } + +#if 0 + // Test filtering + if (ImGui::BeginCombo("Test", m_selectedTest.c_str())) { + for (auto&& test : m_tests) { + if (ImGui::Selectable(test.first.c_str(), test.first == m_selectedTest)) { + m_selectedTest = test.first; + } + } + ImGui::EndCombo(); + } +#endif + + ImGui::Combo("Analysis Type", &m_selectedAnalysis, kAnalysisTypes, + IM_ARRAYSIZE(kAnalysisTypes)); + + // DND targets + EmitEntryTarget("Velocity", false, &m_velocityEntry); + EmitEntryTarget("Position", false, &m_positionEntry); + EmitEntryTarget("Voltage", false, &m_voltageEntry); + + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 7); + ImGui::Combo("Units", &m_selectedUnit, kUnits, IM_ARRAYSIZE(kUnits)); + + ImGui::InputDouble("Velocity scaling", &m_velocityScale); + ImGui::InputDouble("Position scaling", &m_positionScale); + + if (/*!m_selectedTest.empty() &&*/ m_velocityEntry && m_positionEntry && + m_voltageEntry) { + if (ImGui::Button("Load")) { + m_testdataFuture = + std::async(std::launch::async, [this] { return BuildTestData(); }); + } + } +} + +void DataSelector::Reset() { + m_testsFuture = {}; + m_tests.clear(); + m_selectedTest.clear(); + m_testStateEntry = nullptr; + m_velocityEntry = nullptr; + m_positionEntry = nullptr; + m_voltageEntry = nullptr; + m_testdataFuture = {}; +} + +DataSelector::Tests DataSelector::LoadTests( + const glass::DataLogReaderEntry& testStateEntry) { + Tests tests; + for (auto&& range : testStateEntry.ranges) { + std::string_view prevState; + Runs* curRuns = nullptr; + wpi::log::DataLogReader::iterator lastStart = range.begin(); + int64_t ts = lastStart->GetTimestamp(); + for (auto it = range.begin(), end = range.end(); it != end; ++it) { + ts = it->GetTimestamp(); + std::string_view testState; + if (it->GetEntry() != testStateEntry.entry || + !it->GetString(&testState)) { + continue; + } + + // track runs as iterator ranges of the same test + if (testState != prevState) { + if (curRuns) { + curRuns->emplace_back(lastStart->GetTimestamp(), ts); + } + lastStart = it; + } + prevState = testState; + + if (testState == "none") { + curRuns = nullptr; + continue; + } + + auto [testName, direction] = wpi::rsplit(testState, '-'); + auto testIt = tests.find(testName); + if (testIt == tests.end()) { + testIt = tests.emplace(std::string{testName}, State{}).first; + } + auto stateIt = testIt->second.find(testState); + if (stateIt == testIt->second.end()) { + stateIt = testIt->second.emplace(std::string{testState}, Runs{}).first; + } + curRuns = &stateIt->second; + } + + if (curRuns) { + curRuns->emplace_back(lastStart->GetTimestamp(), ts); + } + } + return tests; +} + +template +static void AddSamples(std::vector>& samples, + const std::vector>& data, + int64_t tsbegin, int64_t tsend) { + // data is sorted, so do a binary search for tsbegin and tsend + auto begin = std::lower_bound( + data.begin(), data.end(), tsbegin, + [](const auto& datapoint, double val) { return datapoint.first < val; }); + auto end = std::lower_bound( + begin, data.end(), tsend, + [](const auto& datapoint, double val) { return datapoint.first < val; }); + + for (auto it = begin; it != end; ++it) { + samples.emplace_back(units::second_t{it->first * 1.0e-6}, T{it->second}); + } +} + +static std::vector> GetData( + const glass::DataLogReaderEntry& entry, double scale) { + std::vector> rv; + bool isDouble = entry.type == "double"; + for (auto&& range : entry.ranges) { + for (auto&& record : range) { + if (record.GetEntry() != entry.entry) { + continue; + } + if (isDouble) { + double val; + if (record.GetDouble(&val)) { + rv.emplace_back(record.GetTimestamp(), val * scale); + } + } else { + float val; + if (record.GetFloat(&val)) { + rv.emplace_back(record.GetTimestamp(), + static_cast(val * scale)); + } + } + } + } + + std::sort(rv.begin(), rv.end(), + [](const auto& a, const auto& b) { return a.first < b.first; }); + return rv; +} + +TestData DataSelector::BuildTestData() { + TestData data; + data.distanceUnit = kUnits[m_selectedUnit]; + data.mechanismType = analysis::FromName(kAnalysisTypes[m_selectedAnalysis]); + + // read and sort the entire dataset first; this is memory hungry but + // dramatically speeds up splitting it into runs. + auto voltageData = GetData(*m_voltageEntry, 1.0); + auto positionData = GetData(*m_positionEntry, m_positionScale); + auto velocityData = GetData(*m_velocityEntry, m_velocityScale); + + for (auto&& test : m_tests) { + for (auto&& state : test.second) { + auto& motorData = data.motorData[state.first]; + for (auto [tsbegin, tsend] : state.second) { + auto& run = motorData.runs.emplace_back(); + AddSamples(run.voltage, voltageData, tsbegin, tsend); + AddSamples(run.position, positionData, tsbegin, tsend); + AddSamples(run.velocity, velocityData, tsbegin, tsend); + } + } + } + + return data; +} diff --git a/sysid/src/main/native/cpp/view/JSONConverter.cpp b/sysid/src/main/native/cpp/view/JSONConverter.cpp deleted file mode 100644 index 88eaa6a02f0..00000000000 --- a/sysid/src/main/native/cpp/view/JSONConverter.cpp +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "sysid/analysis/JSONConverter.h" -#include "sysid/view/JSONConverter.h" - -#include - -#include -#include -#include - -#include "sysid/Util.h" - -using namespace sysid; - -void JSONConverter::DisplayConverter( - const char* tooltip, - std::function converter) { - if (ImGui::Button(tooltip)) { - m_opener = std::make_unique( - tooltip, "", std::vector{"JSON File", SYSID_PFD_JSON_EXT}); - } - - if (m_opener && m_opener->ready()) { - if (!m_opener->result().empty()) { - m_location = m_opener->result()[0]; - try { - converter(m_location, m_logger); - m_timestamp = wpi::Now() * 1E-6; - } catch (const std::exception& e) { - ImGui::OpenPopup("Exception Caught!"); - m_exception = e.what(); - } - } - m_opener.reset(); - } - - if (wpi::Now() * 1E-6 - m_timestamp < 5) { - ImGui::SameLine(); - ImGui::Text("Saved!"); - } - - // Handle exceptions. - ImGui::SetNextWindowSize(ImVec2(480.f, 0.0f)); - if (ImGui::BeginPopupModal("Exception Caught!")) { - ImGui::PushTextWrapPos(0.0f); - ImGui::Text( - "An error occurred when parsing the JSON. This most likely means that " - "the JSON data is incorrectly formatted."); - ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", - m_exception.c_str()); - ImGui::PopTextWrapPos(); - if (ImGui::Button("Close")) { - ImGui::CloseCurrentPopup(); - } - ImGui::EndPopup(); - } -} - -void JSONConverter::DisplayCSVConvert() { - DisplayConverter("Select SysId JSON", sysid::ToCSV); -} diff --git a/sysid/src/main/native/cpp/view/LogLoader.cpp b/sysid/src/main/native/cpp/view/LogLoader.cpp new file mode 100644 index 00000000000..fdaa3af11be --- /dev/null +++ b/sysid/src/main/native/cpp/view/LogLoader.cpp @@ -0,0 +1,208 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "sysid/view/LogLoader.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace sysid; + +LogLoader::LogLoader(glass::Storage& storage, wpi::Logger& logger) {} + +LogLoader::~LogLoader() = default; + +void LogLoader::Display() { + if (ImGui::Button("Open data log file...")) { + m_opener = std::make_unique( + "Select Data Log", "", + std::vector{"DataLog Files", "*.wpilog"}); + } + + // Handle opening the file + if (m_opener && m_opener->ready(0)) { + if (!m_opener->result().empty()) { + m_filename = m_opener->result()[0]; + + std::error_code ec; + auto buf = wpi::MemoryBuffer::GetFile(m_filename, ec); + if (ec) { + ImGui::OpenPopup("Error"); + m_error = fmt::format("Could not open file: {}", ec.message()); + return; + } + + wpi::log::DataLogReader reader{std::move(buf)}; + if (!reader.IsValid()) { + ImGui::OpenPopup("Error"); + m_error = "Not a valid datalog file"; + return; + } + unload(); + m_reader = + std::make_unique(std::move(reader)); + m_entryTree.clear(); + } + m_opener.reset(); + } + + // Handle errors + ImGui::SetNextWindowSize(ImVec2(480.f, 0.0f)); + if (ImGui::BeginPopupModal("Error")) { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextUnformatted(m_error.c_str()); + ImGui::PopTextWrapPos(); + if (ImGui::Button("Close")) { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); + } + + if (!m_reader) { + return; + } + + // Summary info + ImGui::TextUnformatted(fs::path{m_filename}.stem().string().c_str()); + ImGui::Text("%u records, %u entries%s", m_reader->GetNumRecords(), + m_reader->GetNumEntries(), + m_reader->IsDone() ? "" : " (working)"); + + if (!m_reader->IsDone()) { + return; + } + + bool refilter = ImGui::InputText("Filter", &m_filter); + + // Display tree of entries + if (m_entryTree.empty() || refilter) { + RebuildEntryTree(); + } + + ImGui::BeginTable( + "Entries", 2, + ImGuiTableFlags_Borders | ImGuiTableFlags_SizingStretchProp); + ImGui::TableSetupColumn("Name"); + ImGui::TableSetupColumn("Type"); + // ImGui::TableSetupColumn("Metadata"); + ImGui::TableHeadersRow(); + DisplayEntryTree(m_entryTree); + ImGui::EndTable(); +} + +void LogLoader::RebuildEntryTree() { + m_entryTree.clear(); + wpi::SmallVector parts; + m_reader->ForEachEntryName([&](const glass::DataLogReaderEntry& entry) { + // only show double/float/string entries (TODO: support struct/protobuf) + if (entry.type != "double" && entry.type != "float" && + entry.type != "string") { + return; + } + + // filter on name + if (!m_filter.empty() && !wpi::contains_lower(entry.name, m_filter)) { + return; + } + + parts.clear(); + // split on first : if one is present + auto [prefix, mainpart] = wpi::split(entry.name, ':'); + if (mainpart.empty() || wpi::contains(prefix, '/')) { + mainpart = entry.name; + } else { + parts.emplace_back(prefix); + } + wpi::split(mainpart, parts, '/', -1, false); + + // ignore a raw "/" key + if (parts.empty()) { + return; + } + + // get to leaf + auto nodes = &m_entryTree; + for (auto part : wpi::drop_back(std::span{parts.begin(), parts.end()})) { + auto it = + std::find_if(nodes->begin(), nodes->end(), + [&](const auto& node) { return node.name == part; }); + if (it == nodes->end()) { + nodes->emplace_back(part); + // path is from the beginning of the string to the end of the current + // part; this works because part is a reference to the internals of + // entry.name + nodes->back().path.assign( + entry.name.data(), part.data() + part.size() - entry.name.data()); + it = nodes->end() - 1; + } + nodes = &it->children; + } + + auto it = std::find_if(nodes->begin(), nodes->end(), [&](const auto& node) { + return node.name == parts.back(); + }); + if (it == nodes->end()) { + nodes->emplace_back(parts.back()); + // no need to set path, as it's identical to entry.name + it = nodes->end() - 1; + } + it->entry = &entry; + }); +} + +static void EmitEntry(const std::string& name, + const glass::DataLogReaderEntry& entry) { + ImGui::TableNextColumn(); + ImGui::Selectable(name.c_str()); + if (ImGui::BeginDragDropSource()) { + auto entryPtr = &entry; + ImGui::SetDragDropPayload( + entry.type == "string" ? "DataLogEntryString" : "DataLogEntry", + &entryPtr, + sizeof(entryPtr)); // NOLINT + ImGui::TextUnformatted(entry.name.data(), + entry.name.data() + entry.name.size()); + ImGui::EndDragDropSource(); + } + ImGui::TableNextColumn(); + ImGui::TextUnformatted(entry.type.data(), + entry.type.data() + entry.type.size()); +#if 0 + ImGui::TableNextColumn(); + ImGui::TextUnformatted(entry.metadata.data(), + entry.metadata.data() + entry.metadata.size()); +#endif +} + +void LogLoader::DisplayEntryTree(const std::vector& tree) { + for (auto&& node : tree) { + if (node.entry) { + EmitEntry(node.name, *node.entry); + } + + if (!node.children.empty()) { + ImGui::TableNextColumn(); + bool open = ImGui::TreeNodeEx(node.name.c_str(), + ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::TableNextColumn(); +#if 0 + ImGui::TableNextColumn(); +#endif + if (open) { + DisplayEntryTree(node.children); + ImGui::TreePop(); + } + } + } +} diff --git a/sysid/src/main/native/cpp/view/Logger.cpp b/sysid/src/main/native/cpp/view/Logger.cpp deleted file mode 100644 index 5e7773dbd0f..00000000000 --- a/sysid/src/main/native/cpp/view/Logger.cpp +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "sysid/view/Logger.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "sysid/Util.h" -#include "sysid/analysis/AnalysisType.h" -#include "sysid/view/UILayout.h" - -using namespace sysid; - -Logger::Logger(glass::Storage& storage, wpi::Logger& logger) - : m_logger{logger}, m_ntSettings{"sysid", storage} { - wpi::gui::AddEarlyExecute([&] { m_ntSettings.Update(); }); - - m_ntSettings.EnableServerOption(false); -} - -void Logger::Display() { - // Get the current width of the window. This will be used to scale - // our UI elements. - float width = ImGui::GetContentRegionAvail().x; - - // Add team number input and apply button for NT connection. - m_ntSettings.Display(); - - // Reset and clear the internal manager state. - ImGui::SameLine(); - if (ImGui::Button("Reset Telemetry")) { - m_settings = TelemetryManager::Settings{}; - m_manager = std::make_unique(m_settings, m_logger); - m_settings.mechanism = analysis::FromName(kTypes[m_selectedType]); - } - - // Add NT connection indicator. - static ImVec4 kColorDisconnected{1.0f, 0.4f, 0.4f, 1.0f}; - static ImVec4 kColorConnected{0.2f, 1.0f, 0.2f, 1.0f}; - ImGui::SameLine(); - bool ntConnected = nt::NetworkTableInstance::GetDefault().IsConnected(); - ImGui::TextColored(ntConnected ? kColorConnected : kColorDisconnected, - ntConnected ? "NT Connected" : "NT Disconnected"); - - // Create a Section for project configuration - ImGui::Separator(); - ImGui::Spacing(); - ImGui::Text("Project Parameters"); - - // Add a dropdown for mechanism type. - ImGui::SetNextItemWidth(ImGui::GetFontSize() * kTextBoxWidthMultiple); - - if (ImGui::Combo("Mechanism", &m_selectedType, kTypes, - IM_ARRAYSIZE(kTypes))) { - m_settings.mechanism = analysis::FromName(kTypes[m_selectedType]); - } - - // Add Dropdown for Units - ImGui::SetNextItemWidth(ImGui::GetFontSize() * kTextBoxWidthMultiple); - if (ImGui::Combo("Unit Type", &m_selectedUnit, kUnits, - IM_ARRAYSIZE(kUnits))) { - m_settings.units = kUnits[m_selectedUnit]; - } - - sysid::CreateTooltip( - "This is the type of units that your gains will be in. For example, if " - "you want your flywheel gains in terms of radians, then use the radians " - "unit. On the other hand, if your drivetrain will use gains in meters, " - "choose meters."); - - // Rotational units have fixed Units per rotations - m_isRotationalUnits = - (m_settings.units == "Rotations" || m_settings.units == "Degrees" || - m_settings.units == "Radians"); - if (m_settings.units == "Degrees") { - m_settings.unitsPerRotation = 360.0; - } else if (m_settings.units == "Radians") { - m_settings.unitsPerRotation = 2 * std::numbers::pi; - } else if (m_settings.units == "Rotations") { - m_settings.unitsPerRotation = 1.0; - } - - // Units Per Rotations entry - ImGui::SetNextItemWidth(ImGui::GetFontSize() * kTextBoxWidthMultiple); - ImGui::InputDouble("Units Per Rotation", &m_settings.unitsPerRotation, 0.0f, - 0.0f, "%.4f", - m_isRotationalUnits ? ImGuiInputTextFlags_ReadOnly - : ImGuiInputTextFlags_None); - sysid::CreateTooltip( - "The logger assumes that the code will be sending recorded motor shaft " - "rotations over NetworkTables. This value will then be multiplied by the " - "units per rotation to get the measurement in the units you " - "specified.\n\nFor non-rotational units (e.g. meters), this value is " - "usually the wheel diameter times pi (should not include gearing)."); - // Create a section for voltage parameters. - ImGui::Separator(); - ImGui::Spacing(); - ImGui::Text("Voltage Parameters"); - - auto CreateVoltageParameters = [this](const char* text, double* data, - float min, float max) { - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 6); - ImGui::PushItemFlag(ImGuiItemFlags_Disabled, - m_manager && m_manager->IsActive()); - float value = static_cast(*data); - if (ImGui::SliderFloat(text, &value, min, max, "%.2f")) { - *data = value; - } - ImGui::PopItemFlag(); - }; - - CreateVoltageParameters("Quasistatic Ramp Rate (V/s)", - &m_settings.quasistaticRampRate, 0.10f, 0.60f); - sysid::CreateTooltip( - "This is the rate at which the voltage will increase during the " - "quasistatic test."); - - CreateVoltageParameters("Dynamic Step Voltage (V)", &m_settings.stepVoltage, - 0.0f, 10.0f); - sysid::CreateTooltip( - "This is the voltage that will be applied for the " - "dynamic voltage (acceleration) tests."); - - // Create a section for tests. - ImGui::Separator(); - ImGui::Spacing(); - ImGui::Text("Tests"); - - auto CreateTest = [this, width](const char* text, const char* itext) { - // Display buttons if we have an NT connection. - if (nt::NetworkTableInstance::GetDefault().IsConnected()) { - // Create button to run tests. - if (ImGui::Button(text)) { - // Open the warning message. - ImGui::OpenPopup("Warning"); - m_manager->BeginTest(itext); - m_opened = text; - } - if (m_opened == text && ImGui::BeginPopupModal("Warning")) { - ImGui::TextWrapped("%s", m_popupText.c_str()); - if (ImGui::Button(m_manager->IsActive() ? "End Test" : "Close")) { - m_manager->EndTest(); - ImGui::CloseCurrentPopup(); - m_opened = ""; - } - ImGui::EndPopup(); - } - } else { - // Show disabled text when there is no connection. - ImGui::TextDisabled("%s", text); - } - - // Show whether the tests were run or not. - bool run = m_manager->HasRunTest(itext); - ImGui::SameLine(width * 0.7); - ImGui::Text(run ? "Run" : "Not Run"); - }; - - CreateTest("Quasistatic Forward", "slow-forward"); - CreateTest("Quasistatic Backward", "slow-backward"); - CreateTest("Dynamic Forward", "fast-forward"); - CreateTest("Dynamic Backward", "fast-backward"); - - m_manager->RegisterDisplayCallback( - [this](const auto& str) { m_popupText = str; }); - - // Display the path to where the JSON will be saved and a button to select the - // location. - ImGui::Separator(); - ImGui::Spacing(); - ImGui::Text("Save Location"); - if (ImGui::Button("Choose")) { - m_selector = std::make_unique("Select Folder"); - } - ImGui::SameLine(); - ImGui::InputText("##savelocation", &m_jsonLocation, - ImGuiInputTextFlags_ReadOnly); - - // Add button to save. - ImGui::SameLine(width * 0.9); - if (ImGui::Button("Save")) { - try { - m_manager->SaveJSON(m_jsonLocation); - } catch (const std::exception& e) { - ImGui::OpenPopup("Exception Caught!"); - m_exception = e.what(); - } - } - - // Handle exceptions. - if (ImGui::BeginPopupModal("Exception Caught!")) { - ImGui::Text("%s", m_exception.c_str()); - if (ImGui::Button("Close")) { - ImGui::CloseCurrentPopup(); - } - ImGui::EndPopup(); - } - - // Run periodic methods. - SelectDataFolder(); - m_ntSettings.Update(); - m_manager->Update(); -} - -void Logger::SelectDataFolder() { - // If the selector exists and is ready with a result, we can store it. - if (m_selector && m_selector->ready()) { - m_jsonLocation = m_selector->result(); - m_selector.reset(); - } -} diff --git a/sysid/src/main/native/include/sysid/Util.h b/sysid/src/main/native/include/sysid/Util.h index 38cf8b2e42f..500601c9710 100644 --- a/sysid/src/main/native/include/sysid/Util.h +++ b/sysid/src/main/native/include/sysid/Util.h @@ -34,7 +34,7 @@ #define STRINGIZE(s) #s namespace sysid { -static constexpr const char* kUnits[] = {"Meters", "Feet", "Inches", +inline constexpr const char* kUnits[] = {"Meters", "Feet", "Inches", "Radians", "Rotations", "Degrees"}; /** @@ -45,6 +45,14 @@ static constexpr const char* kUnits[] = {"Meters", "Feet", "Inches", */ void CreateTooltip(const char* text); +/** + * Displays an error tooltip beside the widget that this method is called after + * with the provided text. + * + * @param text The text to show in the error tooltip. + */ +void CreateErrorTooltip(const char* text); + /** * Utility function to launch an error popup if an exception is detected. * diff --git a/sysid/src/main/native/include/sysid/analysis/AnalysisManager.h b/sysid/src/main/native/include/sysid/analysis/AnalysisManager.h index d572578b011..6dfe51cb358 100644 --- a/sysid/src/main/native/include/sysid/analysis/AnalysisManager.h +++ b/sysid/src/main/native/include/sysid/analysis/AnalysisManager.h @@ -17,6 +17,7 @@ #include #include +#include #include #include "sysid/analysis/AnalysisType.h" @@ -33,14 +34,16 @@ namespace sysid { */ class AnalysisManager { public: + // This contains data for each test (e.g. quasistatic-forward, + // quasistatic-backward, etc) indexed by test name + TestData m_data; /** * Represents settings for an instance of the analysis manager. This contains - * information about the feedback controller preset, loop type, motion + * information about the feedback controller preset, loop type, velocity * threshold, acceleration window size, LQR parameters, and the selected * dataset. */ struct Settings { - enum class DrivetrainDataset { kCombined = 0, kLeft = 1, kRight = 2 }; /** * The feedback controller preset used to calculate gains. */ @@ -57,9 +60,9 @@ class AnalysisManager { LQRParameters lqr{1, 1.5, 7}; /** - * The motion threshold (units/s) for trimming quasistatic test data. + * The velocity threshold (units/s) for trimming quasistatic test data. */ - double motionThreshold = 0.2; + double velocityThreshold = 0.2; /** * The window size for the median filter. @@ -71,45 +74,70 @@ class AnalysisManager { * zero indicates it needs to be set to the default. */ units::second_t stepTestDuration = 0_s; + }; + struct FeedforwardGain { /** - * The conversion factor of counts per revolution. + * The feedforward gain. */ - int cpr = 1440; + double gain = 1; /** - * The conversion factor of gearing. + * Descriptor attached to the feedforward gain. */ - double gearing = 1; + std::string descriptor = "Feedforward gain."; /** - * Whether or not the gains should be in the encoder's units (mainly for use - * in a smart motor controller). + * Whether the feedforward gain is valid. */ - bool convertGainsToEncTicks = false; + bool isValidGain = true; - DrivetrainDataset dataset = DrivetrainDataset::kCombined; + /** + * Error message attached to the feedforward gain. + */ + std::string errorMessage = "No error."; }; /** - * Stores feedforward. + * Stores feedforward gains. */ struct FeedforwardGains { /** - * Stores the Feedforward gains. + * Stores the raw OLSResult from analysis. + */ + OLSResult olsResult; + + /** + * The static gain Ks. + */ + FeedforwardGain Ks = {}; + + /** + * The velocity gain kV. + */ + FeedforwardGain Kv = {}; + + /** + * The acceleration gain kA. */ - std::tuple, double, double> ffGains; + FeedforwardGain Ka = {}; /** - * Stores the trackwidth for angular drivetrain tests. + * The gravity gain Kg. */ - std::optional trackWidth; + FeedforwardGain Kg = {}; + + /** + * The offset (arm). + */ + FeedforwardGain offset = {}; }; /** * Exception for File Reading Errors. */ - struct FileReadingError : public std::exception { + class FileReadingError : public std::exception { + public: /** * Creates a FileReadingError object * @@ -119,18 +147,21 @@ class AnalysisManager { msg = fmt::format("Unable to read: {}", path); } + const char* what() const noexcept override { return msg.c_str(); } + + private: /** * The path of the file that was opened. */ std::string msg; - const char* what() const noexcept override { return msg.c_str(); } }; /** * The keys (which contain sysid data) that are in the JSON to analyze. */ static constexpr const char* kJsonDataKeys[] = { - "slow-forward", "slow-backward", "fast-forward", "fast-backward"}; + "quasistatic-forward", "quasistatic-reverse", "dynamic-forward", + "dynamic-reverse"}; /** * Concatenates a list of vectors. The contents of the source vectors are @@ -167,12 +198,11 @@ class AnalysisManager { * Constructs an instance of the analysis manager with the given path (to the * JSON) and analysis manager settings. * - * @param path The path to the JSON containing the sysid data. + * @param data The data from the SysId routine. * @param settings The settings for this instance of the analysis manager. * @param logger The logger instance to use for log data. */ - AnalysisManager(std::string_view path, Settings& settings, - wpi::Logger& logger); + AnalysisManager(TestData data, Settings& settings, wpi::Logger& logger); /** * Prepares data from the JSON and stores the output in Storage member @@ -194,16 +224,15 @@ class AnalysisManager { * @param ff The feedforward gains. * @return The calculated feedback gains. */ - FeedbackGains CalculateFeedback(std::vector ff); + FeedbackGains CalculateFeedback(const FeedforwardGain& Kv, + const FeedforwardGain& Ka); /** * Overrides the units in the JSON with the user-provided ones. * * @param unit The unit to output gains in. - * @param unitsPerRotation The conversion factor between rotations and the - * selected unit. */ - void OverrideUnits(std::string_view unit, double unitsPerRotation); + void OverrideUnits(std::string_view unit); /** * Resets the units back to those defined in the JSON. @@ -215,21 +244,14 @@ class AnalysisManager { * * @return The analysis type. */ - const AnalysisType& GetAnalysisType() const { return m_type; } + const AnalysisType& GetAnalysisType() const { return m_data.mechanismType; } /** * Returns the units of analysis. * * @return The units of analysis. */ - std::string_view GetUnit() const { return m_unit; } - - /** - * Returns the factor (a.k.a. units per rotation) for analysis. - * - * @return The factor (a.k.a. units per rotation) for analysis. - */ - double GetFactor() const { return m_factor; } + std::string_view GetUnit() const { return m_data.distanceUnit; } /** * Returns a reference to the iterator of the currently selected raw datset. @@ -238,9 +260,7 @@ class AnalysisManager { * * @return A reference to the raw internal data. */ - Storage& GetRawData() { - return m_rawDataset[static_cast(m_settings.dataset)]; - } + Storage& GetRawData() { return m_rawDataset; } /** * Returns a reference to the iterator of the currently selected filtered @@ -249,18 +269,14 @@ class AnalysisManager { * * @return A reference to the filtered internal data. */ - Storage& GetFilteredData() { - return m_filteredDataset[static_cast(m_settings.dataset)]; - } + Storage& GetFilteredData() { return m_filteredDataset; } /** * Returns the original dataset. * * @return The original (untouched) dataset */ - Storage& GetOriginalData() { - return m_originalDataset[static_cast(m_settings.dataset)]; - } + Storage& GetOriginalData() { return m_originalDataset; } /** * Returns the minimum duration of the Step Voltage Test of the currently @@ -311,22 +327,14 @@ class AnalysisManager { return m_startTimes; } - bool HasData() const { - return !m_originalDataset[static_cast( - Settings::DrivetrainDataset::kCombined)] - .empty(); - } + bool HasData() const { return !m_originalDataset.empty(); } private: wpi::Logger& m_logger; - // This is used to store the various datasets (i.e. Combined, Forward, - // Backward, etc.) - wpi::json m_json; - - std::array m_originalDataset; - std::array m_rawDataset; - std::array m_filteredDataset; + Storage m_originalDataset; + Storage m_rawDataset; + Storage m_filteredDataset; // Stores the various start times of the different tests. std::array m_startTimes; @@ -335,24 +343,11 @@ class AnalysisManager { // controller preset, LQR parameters, acceleration window size, etc. Settings& m_settings; - // Miscellaneous data from the JSON -- the analysis type, the units, and the - // units per rotation. - AnalysisType m_type; - std::string m_unit; - double m_factor; - units::second_t m_minStepTime{0}; units::second_t m_maxStepTime{std::numeric_limits::infinity()}; std::vector m_positionDelays; std::vector m_velocityDelays; - // Stores an optional track width if we are doing the drivetrain angular test. - std::optional m_trackWidth; - void PrepareGeneralData(); - - void PrepareAngularDrivetrainData(); - - void PrepareLinearDrivetrainData(); }; } // namespace sysid diff --git a/sysid/src/main/native/include/sysid/analysis/AnalysisType.h b/sysid/src/main/native/include/sysid/analysis/AnalysisType.h index 7feedb3f51a..5a30d7ca868 100644 --- a/sysid/src/main/native/include/sysid/analysis/AnalysisType.h +++ b/sysid/src/main/native/include/sysid/analysis/AnalysisType.h @@ -52,11 +52,9 @@ struct AnalysisType { }; namespace analysis { -constexpr AnalysisType kDrivetrain{3, 9, "Drivetrain"}; -constexpr AnalysisType kDrivetrainAngular{3, 9, "Drivetrain (Angular)"}; -constexpr AnalysisType kElevator{4, 4, "Elevator"}; -constexpr AnalysisType kArm{5, 4, "Arm"}; -constexpr AnalysisType kSimple{3, 4, "Simple"}; +inline constexpr AnalysisType kElevator{4, 4, "Elevator"}; +inline constexpr AnalysisType kArm{5, 4, "Arm"}; +inline constexpr AnalysisType kSimple{3, 4, "Simple"}; AnalysisType FromName(std::string_view name); } // namespace analysis diff --git a/sysid/src/main/native/include/sysid/analysis/ArmSim.h b/sysid/src/main/native/include/sysid/analysis/ArmSim.h index af6c10e5a34..1e80b8203ae 100644 --- a/sysid/src/main/native/include/sysid/analysis/ArmSim.h +++ b/sysid/src/main/native/include/sysid/analysis/ArmSim.h @@ -33,7 +33,7 @@ class ArmSim { * forward dt seconds. * * @param voltage Voltage to apply over the timestep. - * @param dt Sammple period. + * @param dt Sample period. */ void Update(units::volt_t voltage, units::second_t dt); diff --git a/sysid/src/main/native/include/sysid/analysis/ElevatorSim.h b/sysid/src/main/native/include/sysid/analysis/ElevatorSim.h index 2d0c5f68c8b..82db2de7ade 100644 --- a/sysid/src/main/native/include/sysid/analysis/ElevatorSim.h +++ b/sysid/src/main/native/include/sysid/analysis/ElevatorSim.h @@ -31,7 +31,7 @@ class ElevatorSim { * dt seconds. * * @param voltage Voltage to apply over the timestep. - * @param dt Sammple period. + * @param dt Sample period. */ void Update(units::volt_t voltage, units::second_t dt); diff --git a/sysid/src/main/native/include/sysid/analysis/FeedbackAnalysis.h b/sysid/src/main/native/include/sysid/analysis/FeedbackAnalysis.h index 51754a241d4..397aa8797b7 100644 --- a/sysid/src/main/native/include/sysid/analysis/FeedbackAnalysis.h +++ b/sysid/src/main/native/include/sysid/analysis/FeedbackAnalysis.h @@ -48,18 +48,14 @@ struct FeedbackGains { * Calculates position feedback gains for the given controller preset, LQR * controller gain parameters and feedforward gains. * - * @param preset The feedback controller preset. - * @param params The parameters for calculating optimal feedback - * gains. - * @param Kv Velocity feedforward gain. - * @param Ka Acceleration feedforward gain. - * @param encFactor The factor to convert the gains from output units to - * encoder units. This is usually encoder EPR * gearing - * * units per rotation. + * @param preset The feedback controller preset. + * @param params The parameters for calculating optimal feedback gains. + * @param Kv Velocity feedforward gain. + * @param Ka Acceleration feedforward gain. */ FeedbackGains CalculatePositionFeedbackGains( const FeedbackControllerPreset& preset, const LQRParameters& params, - double Kv, double Ka, double encFactor = 1.0); + double Kv, double Ka); /** * Calculates velocity feedback gains for the given controller preset, LQR diff --git a/sysid/src/main/native/include/sysid/analysis/FeedbackControllerPreset.h b/sysid/src/main/native/include/sysid/analysis/FeedbackControllerPreset.h index 4b13c6c38f0..d30d80aae99 100644 --- a/sysid/src/main/native/include/sysid/analysis/FeedbackControllerPreset.h +++ b/sysid/src/main/native/include/sysid/analysis/FeedbackControllerPreset.h @@ -71,11 +71,9 @@ struct FeedbackControllerPreset { enum class FeedbackControllerLoopType { kPosition, kVelocity }; namespace presets { -constexpr FeedbackControllerPreset kDefault{1.0, 1.0, 20_ms, true, 0_s}; +inline constexpr FeedbackControllerPreset kDefault{1.0, 1.0, 20_ms, true, 0_s}; -constexpr FeedbackControllerPreset kWPILibNew{kDefault}; -constexpr FeedbackControllerPreset kWPILibOld{1.0 / 12.0, 1.0, 50_ms, false, - 0_s}; +inline constexpr FeedbackControllerPreset kWPILib{kDefault}; // Measurement delay from a moving average filter: // @@ -117,19 +115,19 @@ constexpr FeedbackControllerPreset kWPILibOld{1.0 / 12.0, 1.0, 50_ms, false, * * Total delay = 50 ms + 31.5 ms = 81.5 ms. */ -constexpr FeedbackControllerPreset kCTRECANCoder{1.0 / 12.0, 60.0, 1_ms, true, - 81.5_ms}; -constexpr FeedbackControllerPreset kCTREDefault{1023.0 / 12.0, 0.1, 1_ms, false, - 81.5_ms}; +inline constexpr FeedbackControllerPreset kCTREv5CANCoder{1.0 / 12.0, 60.0, + 1_ms, true, 81.5_ms}; +inline constexpr FeedbackControllerPreset kCTREv5{1023.0 / 12.0, 0.1, 1_ms, + false, 81.5_ms}; /** * https://api.ctr-electronics.com/phoenixpro/release/cpp/classctre_1_1phoenixpro_1_1hardware_1_1core_1_1_core_c_a_ncoder.html#a718a1a214b58d3c4543e88e3cb51ade5 * - * Phoenix Pro uses standard units and Voltage output. This means the output + * Phoenix 6 uses standard units and Voltage output. This means the output * is 1.0, time factor is 1.0, and closed loop operates at 1 millisecond. All - * Pro devices make use of Kalman filters default-tuned to lowest latency, which - * in testing is roughly 1 millisecond + * Phoenix 6 devices make use of Kalman filters default-tuned to lowest latency, + * which in testing is roughly 1 millisecond */ -constexpr FeedbackControllerPreset kCTREProDefault{1.0, 1.0, 1_ms, true, 1_ms}; +inline constexpr FeedbackControllerPreset kCTREv6{1.0, 1.0, 1_ms, true, 1_ms}; /** * https://github.com/wpilibsuite/sysid/issues/258#issuecomment-1010658237 @@ -138,8 +136,8 @@ constexpr FeedbackControllerPreset kCTREProDefault{1.0, 1.0, 1_ms, true, 1_ms}; * * Total delay = 8-tap moving average delay = (8 - 1) / 2 * 32 ms = 112 ms. */ -constexpr FeedbackControllerPreset kREVNEOBuiltIn{1.0 / 12.0, 60.0, 1_ms, false, - 112_ms}; +inline constexpr FeedbackControllerPreset kREVNEOBuiltIn{1.0 / 12.0, 60.0, 1_ms, + false, 112_ms}; /** * https://www.revrobotics.com/content/sw/max/sw-docs/cpp/classrev_1_1_c_a_n_encoder.html#a7e6ce792bc0c0558fb944771df572e6a @@ -150,15 +148,15 @@ constexpr FeedbackControllerPreset kREVNEOBuiltIn{1.0 / 12.0, 60.0, 1_ms, false, * * Total delay = 50 ms + 31.5 ms = 81.5 ms. */ -constexpr FeedbackControllerPreset kREVNonNEO{1.0 / 12.0, 60.0, 1_ms, false, - 81.5_ms}; +inline constexpr FeedbackControllerPreset kREVNonNEO{1.0 / 12.0, 60.0, 1_ms, + false, 81.5_ms}; /** * https://github.com/wpilibsuite/sysid/pull/138#issuecomment-841734229 * * Backward finite difference delay = 10 ms / 2 = 5 ms. */ -constexpr FeedbackControllerPreset kVenom{4096.0 / 12.0, 60.0, 1_ms, false, - 5_ms}; +inline constexpr FeedbackControllerPreset kVenom{4096.0 / 12.0, 60.0, 1_ms, + false, 5_ms}; } // namespace presets } // namespace sysid diff --git a/sysid/src/main/native/include/sysid/analysis/FeedforwardAnalysis.h b/sysid/src/main/native/include/sysid/analysis/FeedforwardAnalysis.h index fc9e47c185b..d2503ce5cc8 100644 --- a/sysid/src/main/native/include/sysid/analysis/FeedforwardAnalysis.h +++ b/sysid/src/main/native/include/sysid/analysis/FeedforwardAnalysis.h @@ -4,22 +4,50 @@ #pragma once +#include #include #include #include "sysid/analysis/AnalysisType.h" +#include "sysid/analysis/OLS.h" #include "sysid/analysis/Storage.h" namespace sysid { +/** + * Exception for data that doesn't sample enough of the state-input space. + */ +class InsufficientSamplesError : public std::exception { + public: + /** + * Constructs an InsufficientSamplesError. + * + * @param message The error message + */ + explicit InsufficientSamplesError(std::string_view message) { + m_message = message; + } + + const char* what() const noexcept override { return m_message.c_str(); } + + private: + /** + * Stores the error message + */ + std::string m_message; +}; + /** * Calculates feedforward gains given the data and the type of analysis to * perform. * - * @return Tuple containing the coefficients of the analysis along with the - * r-squared (coefficient of determination) and RMSE (standard deviation - * of the residuals) of the fit. + * @param data The OLS input data. + * @param type The analysis type. + * @param throwOnRankDeficiency Whether to throw if the fit is going to be poor. + * This option is provided for unit testing purposes. */ -std::tuple, double, double> CalculateFeedforwardGains( - const Storage& data, const AnalysisType& type); +OLSResult CalculateFeedforwardGains(const Storage& data, + const AnalysisType& type, + bool throwOnRankDeficiency = true); + } // namespace sysid diff --git a/sysid/src/main/native/include/sysid/analysis/FilteringUtils.h b/sysid/src/main/native/include/sysid/analysis/FilteringUtils.h index 9030c007539..76411158b42 100644 --- a/sysid/src/main/native/include/sysid/analysis/FilteringUtils.h +++ b/sysid/src/main/native/include/sysid/analysis/FilteringUtils.h @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -30,7 +31,8 @@ constexpr int kNoiseMeanWindow = 9; * Exception for Invalid Data Errors in which we can't pin the cause of error to * any one specific setting of the GUI. */ -struct InvalidDataError : public std::exception { +class InvalidDataError : public std::exception { + public: /** * Creates an InvalidDataError Exception. It adds additional steps after the * initial error message to inform users in the ways that they could fix their @@ -41,25 +43,28 @@ struct InvalidDataError : public std::exception { explicit InvalidDataError(std::string_view message) { m_message = fmt::format( "{}. Please verify that your units and data is reasonable and then " - "adjust your motion threshold, test duration, and/or window size to " + "adjust your velocity threshold, test duration, and/or window size to " "try to fix this issue.", message); } + const char* what() const noexcept override { return m_message.c_str(); } + + private: /** * Stores the error message */ std::string m_message; - const char* what() const noexcept override { return m_message.c_str(); } }; /** * Exception for Quasistatic Data being completely removed. */ -struct NoQuasistaticDataError : public std::exception { +class NoQuasistaticDataError : public std::exception { + public: const char* what() const noexcept override { return "Quasistatic test trimming removed all data. Please adjust your " - "motion threshold and double check " + "velocity threshold and double check " "your units and test data to make sure that the robot is reporting " "reasonable values."; } @@ -68,7 +73,8 @@ struct NoQuasistaticDataError : public std::exception { /** * Exception for Dynamic Data being completely removed. */ -struct NoDynamicDataError : public std::exception { +class NoDynamicDataError : public std::exception { + public: const char* what() const noexcept override { return "Dynamic test trimming removed all data. Please adjust your test " "duration and double check " @@ -92,6 +98,9 @@ double GetNoiseFloor( const std::vector& data, int window, std::function accessorFunction); +double GetMaxSpeed(const std::vector& data, + std::function accessorFunction); + /** * Reduces noise in velocity data by applying a median filter. * diff --git a/sysid/src/main/native/include/sysid/analysis/JSONConverter.h b/sysid/src/main/native/include/sysid/analysis/JSONConverter.h deleted file mode 100644 index 7581d25fc16..00000000000 --- a/sysid/src/main/native/include/sysid/analysis/JSONConverter.h +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include - -#include - -namespace sysid { -/** - * Converts a JSON from the old frc-characterization format to the new sysid - * format. - * - * @param path The path to the old JSON. - * @param logger The logger instance for log messages. - * @return The full file path of the newly saved JSON. - */ -std::string ConvertJSON(std::string_view path, wpi::Logger& logger); - -std::string ToCSV(std::string_view path, wpi::Logger& logger); -} // namespace sysid diff --git a/sysid/src/main/native/include/sysid/analysis/OLS.h b/sysid/src/main/native/include/sysid/analysis/OLS.h index cf979041565..43f447a8033 100644 --- a/sysid/src/main/native/include/sysid/analysis/OLS.h +++ b/sysid/src/main/native/include/sysid/analysis/OLS.h @@ -5,22 +5,29 @@ #pragma once #include -#include #include #include namespace sysid { +struct OLSResult { + /// Regression coeficients. + std::vector coeffs; + + /// R² (coefficient of determination) + double rSquared = 0.0; + + /// Root-mean-square error + double rmse = 0.0; +}; + /** - * Performs ordinary least squares multiple regression on the provided data and - * returns a vector of coefficients along with the r-squared (coefficient of - * determination) and RMSE (stardard deviation of the residuals) of the fit. + * Performs ordinary least squares multiple regression on the provided data. * * @param X The independent data in y = Xβ. * @param y The dependent data in y = Xβ. */ -std::tuple, double, double> OLS(const Eigen::MatrixXd& X, - const Eigen::VectorXd& y); +OLSResult OLS(const Eigen::MatrixXd& X, const Eigen::VectorXd& y); } // namespace sysid diff --git a/sysid/src/main/native/include/sysid/analysis/SimpleMotorSim.h b/sysid/src/main/native/include/sysid/analysis/SimpleMotorSim.h index a452c640626..920810ffed6 100644 --- a/sysid/src/main/native/include/sysid/analysis/SimpleMotorSim.h +++ b/sysid/src/main/native/include/sysid/analysis/SimpleMotorSim.h @@ -30,7 +30,7 @@ class SimpleMotorSim { * seconds. * * @param voltage Voltage to apply over the timestep. - * @param dt Sammple period. + * @param dt Sample period. */ void Update(units::volt_t voltage, units::second_t dt); diff --git a/sysid/src/main/native/include/sysid/analysis/Storage.h b/sysid/src/main/native/include/sysid/analysis/Storage.h index 52899a0096e..dad38e7cb54 100644 --- a/sysid/src/main/native/include/sysid/analysis/Storage.h +++ b/sysid/src/main/native/include/sysid/analysis/Storage.h @@ -4,12 +4,46 @@ #pragma once +#include #include #include +#include +#include + +#include "sysid/analysis/AnalysisType.h" namespace sysid { +struct MotorData { + // name of the *motor*, not the test + std::string name; + + // Data for a single contiguous motor test + // Timestamps are not necessarily aligned! + struct Run { + template + requires std::is_arithmetic_v || units::traits::is_unit_t_v + struct Sample { + Sample(units::second_t time, T measurement) + : time{time}, measurement{measurement} {} + units::second_t time; + T measurement; + }; + std::vector> voltage; + std::vector> position; + std::vector> velocity; + }; + + std::vector runs; +}; + +struct TestData { + std::string distanceUnit; + AnalysisType mechanismType; + wpi::StringMap motorData; +}; + /** * Represents each data point after it is cleaned and various parameters are * calculated. diff --git a/sysid/src/main/native/include/sysid/telemetry/TelemetryManager.h b/sysid/src/main/native/include/sysid/telemetry/TelemetryManager.h deleted file mode 100644 index 85ee09e520b..00000000000 --- a/sysid/src/main/native/include/sysid/telemetry/TelemetryManager.h +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "sysid/analysis/AnalysisType.h" - -namespace sysid { -/** - * This class is responsible for collecting data from the robot and storing it - * inside a JSON. - */ -class TelemetryManager { - public: - /** - * Represents settings for an instance of the TelemetryManager class. This - * contains information about the quasistatic ramp rate for slow tests, the - * step voltage for fast tests, and the mechanism type for characterization. - */ - struct Settings { - /** - * The rate at which the voltage should increase during the quasistatic test - * (V/s). - */ - double quasistaticRampRate = 0.25; - - /** - * The voltage that the dynamic test should run at (V). - */ - double stepVoltage = 7.0; - - /** - * The units the mechanism moves per recorded rotation. The sysid project - * will be recording things in rotations of the shaft so the - * unitsPerRotation is to convert those measurements to the units the user - * wants to use. - */ - double unitsPerRotation = 1.0; - - /** - * The name of the units used. - * Valid units: "Meters", "Feet", "Inches", "Radians", "Degrees", - * "Rotations" - */ - std::string units = "Meters"; - - /** - * The type of mechanism that will be analyzed. - * Supported mechanisms: Drivetrain, Angular Drivetrain, Elevator, Arm, - * Simple motor. - */ - AnalysisType mechanism = analysis::kDrivetrain; - }; - - /** - * Constructs an instance of the telemetry manager with the provided settings - * and NT instance to collect data over. - * - * @param settings The settings for this instance of the telemetry manager. - * @param logger The logger instance to use for log data. - * @param instance The NT instance to collect data over. The default value of - * this parameter should suffice in production; it should only - * be changed during unit testing. - */ - explicit TelemetryManager(const Settings& settings, wpi::Logger& logger, - nt::NetworkTableInstance instance = - nt::NetworkTableInstance::GetDefault()); - - /** - * Begins a test with the given parameters. - * - * @param name The name of the test. - */ - void BeginTest(std::string_view name); - - /** - * Ends the currently running test. If there is no test running, this is a - * no-op. - */ - void EndTest(); - - /** - * Updates the telemetry manager -- this adds a new autospeed entry and - * collects newest data from the robot. This must be called periodically by - * the user. - */ - void Update(); - - /** - * Registers a callback that's called by the TelemetryManager when there is a - * message to display to the user. - * - * @param callback Callback function that runs based off of the message - */ - void RegisterDisplayCallback(std::function callback) { - m_callbacks.emplace_back(std::move(callback)); - } - - /** - * Saves a JSON with the stored data at the given location. - * - * @param location The location to save the JSON at (this is the folder that - * should contain the saved JSON). - * @return The full file path of the saved JSON. - */ - std::string SaveJSON(std::string_view location); - - /** - * Returns whether a test is currently running. - * - * @return Whether a test is currently running. - */ - bool IsActive() const { return m_isRunningTest; } - - /** - * Returns whether the specified test is running or has run. - * - * @param name The test to check. - * - * @return Whether the specified test is running or has run. - */ - bool HasRunTest(std::string_view name) const { - return std::find(m_tests.cbegin(), m_tests.cend(), name) != m_tests.end(); - } - - /** - * Gets the size of the stored data. - * - * @return The size of the stored data - */ - size_t GetCurrentDataSize() const { return m_params.data.size(); } - - private: - enum class State { WaitingForEnable, RunningTest, WaitingForData }; - - /** - * Stores information about a currently running test. This information - * includes whether the robot will be traveling quickly (dynamic) or slowly - * (quasistatic), the direction of movement, the start time of the test, - * whether the robot is enabled, the current speed of the robot, and the - * collected data. - */ - struct TestParameters { - bool fast = false; - bool forward = false; - bool rotate = false; - - State state = State::WaitingForEnable; - - double enableStart = 0.0; - double disableStart = 0.0; - - bool enabled = false; - double speed = 0.0; - - std::string raw; - std::vector> data{}; - bool overflow = false; - bool mechError = false; - - TestParameters() = default; - TestParameters(bool fast, bool forward, bool rotate, State state) - : fast{fast}, forward{forward}, rotate{rotate}, state{state} {} - }; - - // Settings for this instance. - const Settings& m_settings; - - // Logger. - wpi::Logger& m_logger; - - // Test parameters for the currently running test. - TestParameters m_params; - bool m_isRunningTest = false; - - // A list of running or already run tests. - std::vector m_tests; - - // Stores the test data. - wpi::json m_data; - - // Display callbacks. - wpi::SmallVector, 1> m_callbacks; - - // NetworkTables instance and entries. - nt::NetworkTableInstance m_inst; - std::shared_ptr table = m_inst.GetTable("SmartDashboard"); - nt::DoublePublisher m_voltageCommand = - table->GetDoubleTopic("SysIdVoltageCommand").Publish(); - nt::StringPublisher m_testType = - table->GetStringTopic("SysIdTestType").Publish(); - nt::BooleanPublisher m_rotate = - table->GetBooleanTopic("SysIdRotate").Publish(); - nt::StringPublisher m_mechanism = - table->GetStringTopic("SysIdTest").Publish(); - nt::BooleanPublisher m_overflowPub = - table->GetBooleanTopic("SysIdOverflow").Publish(); - nt::BooleanSubscriber m_overflowSub = - table->GetBooleanTopic("SysIdOverflow").Subscribe(false); - nt::BooleanPublisher m_mechErrorPub = - table->GetBooleanTopic("SysIdWrongMech").Publish(); - nt::BooleanSubscriber m_mechErrorSub = - table->GetBooleanTopic("SysIdWrongMech").Subscribe(false); - nt::StringSubscriber m_telemetry = - table->GetStringTopic("SysIdTelemetry").Subscribe(""); - nt::IntegerSubscriber m_fmsControlData = - m_inst.GetTable("FMSInfo") - ->GetIntegerTopic("FMSControlData") - .Subscribe(0); - nt::DoublePublisher m_ackNumberPub = - table->GetDoubleTopic("SysIdAckNumber").Publish(); - nt::DoubleSubscriber m_ackNumberSub = - table->GetDoubleTopic("SysIdAckNumber").Subscribe(0); - - int m_ackNumber; -}; -} // namespace sysid diff --git a/sysid/src/main/native/include/sysid/view/Analyzer.h b/sysid/src/main/native/include/sysid/view/Analyzer.h index 2f30f610000..330bf0a61f3 100644 --- a/sysid/src/main/native/include/sysid/view/Analyzer.h +++ b/sysid/src/main/native/include/sysid/view/Analyzer.h @@ -40,13 +40,14 @@ namespace sysid { */ class Analyzer : public glass::View { public: + TestData m_data; /** * The different display and processing states for the GUI */ enum class AnalyzerState { - kWaitingForJSON, + kWaitingForData, kNominalDisplay, - kMotionThresholdError, + kVelocityThresholdError, kTestDurationError, kGeneralDataError, kFileError @@ -55,11 +56,10 @@ class Analyzer : public glass::View { * The different motor controller timing presets that can be used. */ static constexpr const char* kPresetNames[] = {"Default", - "WPILib (2020-)", - "WPILib (Pre-2020)", - "CANCoder", - "CTRE (Pro)", - "CTRE", + "WPILib", + "CTRE Phoenix 5 CANcoder", + "CTRE Phoenix 5", + "CTRE Phoenix 6", "REV Brushless Encoder Port", "REV Brushed Encoder Port", "REV Data Port", @@ -90,12 +90,12 @@ class Analyzer : public glass::View { ~Analyzer() override { AbortDataPrep(); }; - private: /** - * Handles the logic for selecting a json to analyze + * Analyzes the selected data. */ - void SelectFile(); + void AnalyzeData(); + private: /** * Kills the data preparation thread */ @@ -112,11 +112,6 @@ class Analyzer : public glass::View { */ void DisplayGraphs(); - /** - * Displays the file selection widget. - */ - void DisplayFileSelector(); - /** * Resets the current analysis data. */ @@ -186,9 +181,17 @@ class Analyzer : public glass::View { void UpdateFeedbackGains(); /** - * Handles logic of displaying a gain on ImGui + * Handles logic of displaying a double on ImGui. */ - bool DisplayGain(const char* text, double* data, bool readOnly); + bool DisplayDouble(const char* text, double* data, bool readOnly); + + /** + * Displays a Feedforward gain, including the gain itself along with its + * validity and message. + */ + void DisplayFeedforwardGain(const char* text, + AnalysisManager::FeedforwardGain& ffGain, + bool readOnly); /** * Handles errors when they pop up. @@ -196,7 +199,7 @@ class Analyzer : public glass::View { void HandleError(std::string_view msg); // State of the Display GUI - AnalyzerState m_state = AnalyzerState::kWaitingForJSON; + AnalyzerState m_state = AnalyzerState::kWaitingForData; // Stores the exception message. std::string m_exception; @@ -214,36 +217,26 @@ class Analyzer : public glass::View { int m_selectedPreset = 0; // Feedforward and feedback gains. - std::vector m_ff; + AnalysisManager::FeedforwardGains m_feedforwardGains; double m_accelRSquared; double m_accelRMSE; double m_Kp; double m_Kd; units::millisecond_t m_timescale; - - // Track width - std::optional m_trackWidth; + bool m_timescaleValid = false; // Units int m_selectedOverrideUnit = 0; - double m_conversionFactor = 0.0; // Data analysis std::unique_ptr m_manager; int m_dataset = 0; int m_window = 8; double m_threshold = 0.2; - float m_stepTestDuration = 0.0; - - double m_gearingNumerator = 1.0; - double m_gearingDenominator = 1.0; + float m_stepTestDuration = 0; bool combinedGraphFit = false; - // File manipulation - std::unique_ptr m_selector; - std::string m_location; - // Logger wpi::Logger& m_logger; diff --git a/sysid/src/main/native/include/sysid/view/AnalyzerPlot.h b/sysid/src/main/native/include/sysid/view/AnalyzerPlot.h index e5fbe8ca959..2c234ad7b8e 100644 --- a/sysid/src/main/native/include/sysid/view/AnalyzerPlot.h +++ b/sysid/src/main/native/include/sysid/view/AnalyzerPlot.h @@ -17,6 +17,7 @@ #include #include +#include "sysid/analysis/AnalysisManager.h" #include "sysid/analysis/AnalysisType.h" #include "sysid/analysis/Storage.h" @@ -44,15 +45,16 @@ class AnalyzerPlot { * @param rawData Raw data storage. * @param filteredData Filtered data storage. * @param unit Unit of the dataset - * @param ff List of feedforward gains (Ks, Kv, Ka, and optionally - * Kg). + * @param ff Feedforward gains (Ks, Kv, Ka, optionally + * Kg and offset). * @param startTimes Array of dataset start times. * @param type Type of analysis. * @param abort Aborts analysis early if set to true from another * thread. */ void SetData(const Storage& rawData, const Storage& filteredData, - std::string_view unit, const std::vector& ff, + std::string_view unit, + const AnalysisManager::FeedforwardGains& ff, const std::array& startTimes, AnalysisType type, std::atomic& abort); diff --git a/sysid/src/main/native/include/sysid/view/DataSelector.h b/sysid/src/main/native/include/sysid/view/DataSelector.h new file mode 100644 index 00000000000..71732a7ed74 --- /dev/null +++ b/sysid/src/main/native/include/sysid/view/DataSelector.h @@ -0,0 +1,81 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "sysid/analysis/Storage.h" + +namespace glass { +class DataLogReaderEntry; +class Storage; +} // namespace glass + +namespace wpi { +class Logger; +} // namespace wpi + +namespace sysid { +/** + * Helps with loading datalog files. + */ +class DataSelector : public glass::View { + public: + /** + * Creates a data selector widget + * + * @param logger The program logger + */ + explicit DataSelector(glass::Storage& storage, wpi::Logger& logger) + : m_logger{logger} {} + + /** + * Displays the log loader window. + */ + void Display() override; + + /** + * Resets view. Must be called whenever the DataLogReader goes away, as this + * class keeps references to DataLogReaderEntry objects. + */ + void Reset(); + + /** + * Called when new test data is loaded. + */ + std::function testdata; + + private: + wpi::Logger& m_logger; + using Runs = std::vector>; + using State = std::map>; // full name + using Tests = std::map>; // e.g. "dynamic" + std::future m_testsFuture; + Tests m_tests; + std::string m_selectedTest; + const glass::DataLogReaderEntry* m_testStateEntry = nullptr; + const glass::DataLogReaderEntry* m_velocityEntry = nullptr; + const glass::DataLogReaderEntry* m_positionEntry = nullptr; + const glass::DataLogReaderEntry* m_voltageEntry = nullptr; + double m_velocityScale = 1.0; + double m_positionScale = 1.0; + int m_selectedUnit = 0; + int m_selectedAnalysis = 0; + std::future m_testdataFuture; + std::vector m_testdataStats; + + static Tests LoadTests(const glass::DataLogReaderEntry& testStateEntry); + TestData BuildTestData(); +}; +} // namespace sysid diff --git a/sysid/src/main/native/include/sysid/view/JSONConverter.h b/sysid/src/main/native/include/sysid/view/JSONConverter.h deleted file mode 100644 index 89bfa3290d1..00000000000 --- a/sysid/src/main/native/include/sysid/view/JSONConverter.h +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include -#include -#include - -#include -#include -#include - -namespace sysid { -/** - * Helps with converting different JSONs into different formats. Primarily - * enables users to convert an old 2020 FRC-Characterization JSON into a SysId - * JSON or a SysId JSON into a CSV file. - */ -class JSONConverter { - public: - /** - * Creates a JSONConverter widget - * - * @param logger The program logger - */ - explicit JSONConverter(wpi::Logger& logger) : m_logger(logger) {} - - /** - * Function to display the SysId JSON to CSV converter. - */ - void DisplayCSVConvert(); - - private: - /** - * Helper method to display a specific JSON converter - * - * @param tooltip The tooltip describing the JSON converter - * @param converter The function that takes a filename path and performs the - * previously specifid JSON conversion. - */ - void DisplayConverter( - const char* tooltip, - std::function converter); - - wpi::Logger& m_logger; - - std::string m_location; - std::unique_ptr m_opener; - - std::string m_exception; - - double m_timestamp = 0; -}; -} // namespace sysid diff --git a/sysid/src/main/native/include/sysid/view/LogLoader.h b/sysid/src/main/native/include/sysid/view/LogLoader.h new file mode 100644 index 00000000000..04ddd84dab3 --- /dev/null +++ b/sysid/src/main/native/include/sysid/view/LogLoader.h @@ -0,0 +1,78 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace glass { +class DataLogReaderEntry; +class DataLogReaderThread; +class Storage; +} // namespace glass + +namespace pfd { +class open_file; +} // namespace pfd + +namespace wpi { +class Logger; +} // namespace wpi + +namespace sysid { +/** + * Helps with loading datalog files. + */ +class LogLoader : public glass::View { + public: + /** + * Creates a log loader widget + * + * @param logger The program logger + */ + explicit LogLoader(glass::Storage& storage, wpi::Logger& logger); + + ~LogLoader() override; + + /** + * Displays the log loader window. + */ + void Display() override; + + /** + * Signal called when the current file is unloaded (invalidates any + * LogEntry*). + */ + wpi::sig::Signal<> unload; + + private: + // wpi::Logger& m_logger; + + std::string m_filename; + std::unique_ptr m_opener; + std::unique_ptr m_reader; + + std::string m_error; + + std::string m_filter; + + struct EntryTreeNode { + explicit EntryTreeNode(std::string_view name) : name{name} {} + std::string name; // name of just this node + std::string path; // full path if entry is nullptr + const glass::DataLogReaderEntry* entry = nullptr; + std::vector children; // children, sorted by name + }; + std::vector m_entryTree; + + void RebuildEntryTree(); + void DisplayEntryTree(const std::vector& nodes); +}; +} // namespace sysid diff --git a/sysid/src/main/native/include/sysid/view/Logger.h b/sysid/src/main/native/include/sysid/view/Logger.h deleted file mode 100644 index d06d6508165..00000000000 --- a/sysid/src/main/native/include/sysid/view/Logger.h +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include - -#include -#include -#include -#include -#include - -#include "sysid/telemetry/TelemetryManager.h" - -namespace glass { -class Storage; -} // namespace glass - -namespace sysid { -/** - * The logger GUI takes care of running the system idenfitication tests over - * NetworkTables and logging the data. This data is then stored in a JSON file - * which can be used for analysis. - */ -class Logger : public glass::View { - public: - /** - * Makes a logger widget. - * - * @param storage The glass storage object - * @param logger A logger object that keeps track of the program's logs - */ - Logger(glass::Storage& storage, wpi::Logger& logger); - - /** - * Displays the logger widget. - */ - void Display() override; - - /** - * The different mechanism / analysis types that are supported. - */ - static constexpr const char* kTypes[] = {"Drivetrain", "Drivetrain (Angular)", - "Arm", "Elevator", "Simple"}; - - /** - * The different units that are supported. - */ - static constexpr const char* kUnits[] = {"Meters", "Feet", "Inches", - "Radians", "Rotations", "Degrees"}; - - private: - /** - * Handles the logic of selecting a folder to save the SysId JSON to - */ - void SelectDataFolder(); - - wpi::Logger& m_logger; - - TelemetryManager::Settings m_settings; - int m_selectedType = 0; - int m_selectedUnit = 0; - - std::unique_ptr m_manager = - std::make_unique(m_settings, m_logger); - - std::unique_ptr m_selector; - std::string m_jsonLocation; - - glass::NetworkTablesSettings m_ntSettings; - - bool m_isRotationalUnits = false; - - std::string m_popupText; - - std::string m_opened; - std::string m_exception; -}; -} // namespace sysid diff --git a/sysid/src/main/native/include/sysid/view/UILayout.h b/sysid/src/main/native/include/sysid/view/UILayout.h index 732a1aaf658..f5d1e440f8f 100644 --- a/sysid/src/main/native/include/sysid/view/UILayout.h +++ b/sysid/src/main/native/include/sysid/view/UILayout.h @@ -62,9 +62,12 @@ inline constexpr Vector2d kLeftColSize{ 310, kAppWindowSize.y - kLeftColPos.y - kWindowGap}; // Left column contents -inline constexpr Vector2d kLoggerWindowPos = kLeftColPos; -inline constexpr Vector2d kLoggerWindowSize{ - kLeftColSize.x, kAppWindowSize.y - kWindowGap - kLoggerWindowPos.y}; +inline constexpr Vector2d kLogLoaderWindowPos = kLeftColPos; +inline constexpr Vector2d kLogLoaderWindowSize{kLeftColSize.x, 450}; +inline constexpr Vector2d kDataSelectorWindowPos = + kLogLoaderWindowPos + Vector2d{0, kLogLoaderWindowSize.y + kWindowGap}; +inline constexpr Vector2d kDataSelectorWindowSize{ + kLeftColSize.x, kAppWindowSize.y - kWindowGap - kDataSelectorWindowPos.y}; // Center column position and size inline constexpr Vector2d kCenterColPos = diff --git a/sysid/src/test/native/cpp/analysis/AnalysisTypeTest.cpp b/sysid/src/test/native/cpp/analysis/AnalysisTypeTest.cpp index 0abb2a1e9cc..51d348ccf37 100644 --- a/sysid/src/test/native/cpp/analysis/AnalysisTypeTest.cpp +++ b/sysid/src/test/native/cpp/analysis/AnalysisTypeTest.cpp @@ -7,10 +7,6 @@ #include "sysid/analysis/AnalysisType.h" TEST(AnalysisTypeTest, FromName) { - EXPECT_EQ(sysid::analysis::kDrivetrain, - sysid::analysis::FromName("Drivetrain")); - EXPECT_EQ(sysid::analysis::kDrivetrainAngular, - sysid::analysis::FromName("Drivetrain (Angular)")); EXPECT_EQ(sysid::analysis::kElevator, sysid::analysis::FromName("Elevator")); EXPECT_EQ(sysid::analysis::kArm, sysid::analysis::FromName("Arm")); EXPECT_EQ(sysid::analysis::kSimple, sysid::analysis::FromName("Simple")); diff --git a/sysid/src/test/native/cpp/analysis/FeedbackAnalysisTest.cpp b/sysid/src/test/native/cpp/analysis/FeedbackAnalysisTest.cpp index 44f664c800d..acb9785284b 100644 --- a/sysid/src/test/native/cpp/analysis/FeedbackAnalysisTest.cpp +++ b/sysid/src/test/native/cpp/analysis/FeedbackAnalysisTest.cpp @@ -55,7 +55,7 @@ TEST(FeedbackAnalysisTest, VelocityCTRE) { sysid::LQRParameters params{1, 1.5, 7}; auto [Kp, Kd] = sysid::CalculateVelocityFeedbackGains( - sysid::presets::kCTRECANCoder, params, Kv, Ka); + sysid::presets::kCTREv5CANCoder, params, Kv, Ka); EXPECT_NEAR(Kp, 0.000417, 0.00005); EXPECT_NEAR(Kd, 0.00, 0.05); @@ -68,7 +68,7 @@ TEST(FeedbackAnalysisTest, VelocityCTREConversion) { sysid::LQRParameters params{1, 1.5, 7}; auto [Kp, Kd] = sysid::CalculateVelocityFeedbackGains( - sysid::presets::kCTRECANCoder, params, Kv, Ka, 3.0); + sysid::presets::kCTREv5CANCoder, params, Kv, Ka, 3.0); // This should have the same Kp as the test above, but scaled by a factor // of 3. @@ -103,3 +103,43 @@ TEST(FeedbackAnalysisTest, VelocityREVConversion) { EXPECT_NEAR(Kp, 0.00241 / 3, 0.005); EXPECT_NEAR(Kd, 0.00, 0.05); } + +TEST(FeedbackAnalysisTest, Position) { + auto Kv = 3.060; + auto Ka = 0.327; + + sysid::LQRParameters params{1, 1.5, 7}; + + auto [Kp, Kd] = sysid::CalculatePositionFeedbackGains( + sysid::presets::kDefault, params, Kv, Ka); + + EXPECT_NEAR(Kp, 6.41, 0.05); + EXPECT_NEAR(Kd, 2.48, 0.05); +} + +TEST(FeedbackAnalysisTest, PositionWithLatencyCompensation) { + auto Kv = 3.060; + auto Ka = 0.327; + + sysid::LQRParameters params{1, 1.5, 7}; + sysid::FeedbackControllerPreset preset{sysid::presets::kDefault}; + + preset.measurementDelay = 10_ms; + auto [Kp, Kd] = sysid::CalculatePositionFeedbackGains(preset, params, Kv, Ka); + + EXPECT_NEAR(Kp, 5.92, 0.05); + EXPECT_NEAR(Kd, 2.12, 0.05); +} + +TEST(FeedbackAnalysisTest, PositionREV) { + auto Kv = 3.060; + auto Ka = 0.327; + + sysid::LQRParameters params{1, 1.5, 7}; + + auto [Kp, Kd] = sysid::CalculatePositionFeedbackGains( + sysid::presets::kREVNEOBuiltIn, params, Kv, Ka); + + EXPECT_NEAR(Kp, 0.30202, 0.05); + EXPECT_NEAR(Kd, 48.518, 0.05); +} diff --git a/sysid/src/test/native/cpp/analysis/FeedforwardAnalysisTest.cpp b/sysid/src/test/native/cpp/analysis/FeedforwardAnalysisTest.cpp index a52840d620d..d8cd79eda8d 100644 --- a/sysid/src/test/native/cpp/analysis/FeedforwardAnalysisTest.cpp +++ b/sysid/src/test/native/cpp/analysis/FeedforwardAnalysisTest.cpp @@ -2,28 +2,43 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +#include + +#include #include +#include #include #include #include #include "sysid/analysis/AnalysisManager.h" +#include "sysid/analysis/AnalysisType.h" #include "sysid/analysis/ArmSim.h" #include "sysid/analysis/ElevatorSim.h" #include "sysid/analysis/FeedforwardAnalysis.h" #include "sysid/analysis/SimpleMotorSim.h" +namespace { + +enum Movements : uint32_t { + kSlowForward, + kSlowBackward, + kFastForward, + kFastBackward +}; + +inline constexpr int kMovementCombinations = 16; + /** * Return simulated test data for a given simulation model. * - * @param Ks Static friction gain. - * @param Kv Velocity gain. - * @param Ka Acceleration gain. - * @param Kg Gravity cosine gain. + * @tparam Model The model type. + * @param model The simulation model. + * @param movements Which movements to do. */ template -sysid::Storage CollectData(Model& model) { +sysid::Storage CollectData(Model& model, std::bitset<4> movements) { constexpr auto kUstep = 0.25_V / 1_s; constexpr units::volt_t kUmax = 7_V; constexpr units::second_t T = 5_ms; @@ -31,221 +46,247 @@ sysid::Storage CollectData(Model& model) { sysid::Storage storage; auto& [slowForward, slowBackward, fastForward, fastBackward] = storage; - - // Slow forward test auto voltage = 0_V; - for (int i = 0; i < (kTestDuration / T).value(); ++i) { - slowForward.emplace_back(sysid::PreparedData{ - i * T, voltage.value(), model.GetPosition(), model.GetVelocity(), T, - model.GetAcceleration(voltage), std::cos(model.GetPosition()), - std::sin(model.GetPosition())}); - - model.Update(voltage, T); - voltage += kUstep * T; + + // Slow forward + if (movements.test(Movements::kSlowForward)) { + model.Reset(); + voltage = 0_V; + for (int i = 0; i < (kTestDuration / T).value(); ++i) { + slowForward.emplace_back(sysid::PreparedData{ + i * T, voltage.value(), model.GetPosition(), model.GetVelocity(), T, + model.GetAcceleration(voltage), std::cos(model.GetPosition()), + std::sin(model.GetPosition())}); + + model.Update(voltage, T); + voltage += kUstep * T; + } } - // Slow backward test - model.Reset(); - voltage = 0_V; - for (int i = 0; i < (kTestDuration / T).value(); ++i) { - slowBackward.emplace_back(sysid::PreparedData{ - i * T, voltage.value(), model.GetPosition(), model.GetVelocity(), T, - model.GetAcceleration(voltage), std::cos(model.GetPosition()), - std::sin(model.GetPosition())}); - - model.Update(voltage, T); - voltage -= kUstep * T; + // Slow backward + if (movements.test(Movements::kSlowBackward)) { + model.Reset(); + voltage = 0_V; + for (int i = 0; i < (kTestDuration / T).value(); ++i) { + slowBackward.emplace_back(sysid::PreparedData{ + i * T, voltage.value(), model.GetPosition(), model.GetVelocity(), T, + model.GetAcceleration(voltage), std::cos(model.GetPosition()), + std::sin(model.GetPosition())}); + + model.Update(voltage, T); + voltage -= kUstep * T; + } } - // Fast forward test - model.Reset(); - voltage = 0_V; - for (int i = 0; i < (kTestDuration / T).value(); ++i) { - fastForward.emplace_back(sysid::PreparedData{ - i * T, voltage.value(), model.GetPosition(), model.GetVelocity(), T, - model.GetAcceleration(voltage), std::cos(model.GetPosition()), - std::sin(model.GetPosition())}); - - model.Update(voltage, T); - voltage = kUmax; + // Fast forward + if (movements.test(Movements::kFastForward)) { + model.Reset(); + voltage = 0_V; + for (int i = 0; i < (kTestDuration / T).value(); ++i) { + fastForward.emplace_back(sysid::PreparedData{ + i * T, voltage.value(), model.GetPosition(), model.GetVelocity(), T, + model.GetAcceleration(voltage), std::cos(model.GetPosition()), + std::sin(model.GetPosition())}); + + model.Update(voltage, T); + voltage = kUmax; + } } - // Fast backward test - model.Reset(); - voltage = 0_V; - for (int i = 0; i < (kTestDuration / T).value(); ++i) { - fastBackward.emplace_back(sysid::PreparedData{ - i * T, voltage.value(), model.GetPosition(), model.GetVelocity(), T, - model.GetAcceleration(voltage), std::cos(model.GetPosition()), - std::sin(model.GetPosition())}); - - model.Update(voltage, T); - voltage = -kUmax; + // Fast backward + if (movements.test(Movements::kFastBackward)) { + model.Reset(); + voltage = 0_V; + for (int i = 0; i < (kTestDuration / T).value(); ++i) { + fastBackward.emplace_back(sysid::PreparedData{ + i * T, voltage.value(), model.GetPosition(), model.GetVelocity(), T, + model.GetAcceleration(voltage), std::cos(model.GetPosition()), + std::sin(model.GetPosition())}); + + model.Update(voltage, T); + voltage = -kUmax; + } } return storage; } -TEST(FeedforwardAnalysisTest, Arm1) { - constexpr double Ks = 1.01; - constexpr double Kv = 3.060; - constexpr double Ka = 0.327; - constexpr double Kg = 0.211; - - for (const auto& offset : {-2.0, -1.0, 0.0, 1.0, 2.0}) { - sysid::ArmSim model{Ks, Kv, Ka, Kg, offset}; - auto ff = sysid::CalculateFeedforwardGains(CollectData(model), - sysid::analysis::kArm); - auto& gains = std::get<0>(ff); - - EXPECT_NEAR(gains[0], Ks, 0.003); - EXPECT_NEAR(gains[1], Kv, 0.003); - EXPECT_NEAR(gains[2], Ka, 0.003); - EXPECT_NEAR(gains[3], Kg, 0.003); - EXPECT_NEAR(gains[4], offset, 0.007); +/** + * Asserts success if the gains contain NaNs or are too far from their expected + * values. + * + * @param expectedGains The expected feedforward gains. + * @param actualGains The calculated feedforward gains. + * @param tolerances The tolerances for the coefficient comparisons. + */ +testing::AssertionResult FitIsBad(std::span expectedGains, + std::span actualGains, + std::span tolerances) { + // Check for NaN + for (const auto& coeff : actualGains) { + if (std::isnan(coeff)) { + return testing::AssertionSuccess(); + } } -} -TEST(FeedforwardAnalysisTest, Arm2) { - constexpr double Ks = 0.547; - constexpr double Kv = 0.0693; - constexpr double Ka = 0.1170; - constexpr double Kg = 0.122; - - for (const auto& offset : {-2.0, -1.0, 0.0, 1.0, 2.0}) { - sysid::ArmSim model{Ks, Kv, Ka, Kg, offset}; - auto ff = sysid::CalculateFeedforwardGains(CollectData(model), - sysid::analysis::kArm); - auto& gains = std::get<0>(ff); - - EXPECT_NEAR(gains[0], Ks, 0.003); - EXPECT_NEAR(gains[1], Kv, 0.003); - EXPECT_NEAR(gains[2], Ka, 0.003); - EXPECT_NEAR(gains[3], Kg, 0.003); - EXPECT_NEAR(gains[4], offset, 0.007); + for (size_t i = 0; i < expectedGains.size(); ++i) { + if (std::abs(expectedGains[i] - actualGains[i]) >= tolerances[i]) { + return testing::AssertionSuccess(); + } } -} -TEST(FeedforwardAnalysisTest, Drivetrain1) { - constexpr double Ks = 1.01; - constexpr double Kv = 3.060; - constexpr double Ka = 0.327; + auto result = testing::AssertionFailure(); + + result << "\n"; + for (size_t i = 0; i < expectedGains.size(); ++i) { + if (i == 0) { + result << "Ks"; + } else if (i == 1) { + result << "Kv"; + } else if (i == 2) { + result << "Ka"; + } else if (i == 3) { + result << "Kg"; + } else if (i == 4) { + result << "offset"; + } + + result << ":\n"; + result << " expected " << expectedGains[i] << ",\n"; + result << " actual " << actualGains[i] << ",\n"; + result << " diff " << std::abs(expectedGains[i] - actualGains[i]) << "\n"; + } - sysid::SimpleMotorSim model{Ks, Kv, Ka}; - auto ff = sysid::CalculateFeedforwardGains(CollectData(model), - sysid::analysis::kDrivetrain); - auto& gains = std::get<0>(ff); + return result; +} - EXPECT_NEAR(gains[0], Ks, 0.003); - EXPECT_NEAR(gains[1], Kv, 0.003); - EXPECT_NEAR(gains[2], Ka, 0.003); +/** + * Asserts that two arrays are equal. + * + * @param expected The expected array. + * @param actual The actual array. + * @param tolerances The tolerances for the element comparisons. + */ +void ExpectArrayNear(std::span expected, + std::span actual, + std::span tolerances) { + // Check size + const size_t size = expected.size(); + EXPECT_EQ(size, actual.size()); + EXPECT_EQ(size, tolerances.size()); + + // Check elements + for (size_t i = 0; i < size; ++i) { + EXPECT_NEAR(expected[i], actual[i], tolerances[i]) << "where i = " << i; + } } -TEST(FeedforwardAnalysisTest, Drivetrain2) { - constexpr double Ks = 0.547; - constexpr double Kv = 0.0693; - constexpr double Ka = 0.1170; +/** + * @tparam Model The model type. + * @param model The simulation model. + * @param type The analysis type. + * @param expectedGains The expected feedforward gains. + * @param tolerances The tolerances for the coefficient comparisons. + */ +template +void RunTests(Model& model, const sysid::AnalysisType& type, + std::span expectedGains, + std::span tolerances) { + // Iterate through all combinations of movements + for (int movements = 0; movements < kMovementCombinations; ++movements) { + try { + auto ff = + sysid::CalculateFeedforwardGains(CollectData(model, movements), type); + + ExpectArrayNear(expectedGains, ff.coeffs, tolerances); + } catch (sysid::InsufficientSamplesError&) { + // If calculation threw an exception, confirm at least one of the gains + // doesn't match + auto ff = sysid::CalculateFeedforwardGains(CollectData(model, movements), + type, false); + EXPECT_TRUE(FitIsBad(expectedGains, ff.coeffs, tolerances)); + } + } +} - sysid::SimpleMotorSim model{Ks, Kv, Ka}; - auto ff = sysid::CalculateFeedforwardGains(CollectData(model), - sysid::analysis::kDrivetrain); - auto& gains = std::get<0>(ff); +} // namespace - EXPECT_NEAR(gains[0], Ks, 0.003); - EXPECT_NEAR(gains[1], Kv, 0.003); - EXPECT_NEAR(gains[2], Ka, 0.003); -} +TEST(FeedforwardAnalysisTest, Arm) { + { + constexpr double Ks = 1.01; + constexpr double Kv = 3.060; + constexpr double Ka = 0.327; + constexpr double Kg = 0.211; -TEST(FeedforwardAnalysisTest, DrivetrainAngular1) { - constexpr double Ks = 1.01; - constexpr double Kv = 3.060; - constexpr double Ka = 0.327; + for (const auto& offset : {-2.0, -1.0, 0.0, 1.0, 2.0}) { + sysid::ArmSim model{Ks, Kv, Ka, Kg, offset}; - sysid::SimpleMotorSim model{Ks, Kv, Ka}; - auto ff = sysid::CalculateFeedforwardGains( - CollectData(model), sysid::analysis::kDrivetrainAngular); - auto& gains = std::get<0>(ff); + RunTests(model, sysid::analysis::kArm, {{Ks, Kv, Ka, Kg, offset}}, + {{8e-3, 8e-3, 8e-3, 8e-3, 3e-2}}); + } + } + + { + constexpr double Ks = 0.547; + constexpr double Kv = 0.0693; + constexpr double Ka = 0.1170; + constexpr double Kg = 0.122; - EXPECT_NEAR(gains[0], Ks, 0.003); - EXPECT_NEAR(gains[1], Kv, 0.003); - EXPECT_NEAR(gains[2], Ka, 0.003); + for (const auto& offset : {-2.0, -1.0, 0.0, 1.0, 2.0}) { + sysid::ArmSim model{Ks, Kv, Ka, Kg, offset}; + + RunTests(model, sysid::analysis::kArm, {{Ks, Kv, Ka, Kg, offset}}, + {{8e-3, 8e-3, 8e-3, 8e-3, 5e-2}}); + } + } } -TEST(FeedforwardAnalysisTest, DrivetrainAngular2) { - constexpr double Ks = 0.547; - constexpr double Kv = 0.0693; - constexpr double Ka = 0.1170; +TEST(FeedforwardAnalysisTest, Elevator) { + { + constexpr double Ks = 1.01; + constexpr double Kv = 3.060; + constexpr double Ka = 0.327; + constexpr double Kg = -0.211; - sysid::SimpleMotorSim model{Ks, Kv, Ka}; - auto ff = sysid::CalculateFeedforwardGains( - CollectData(model), sysid::analysis::kDrivetrainAngular); - auto& gains = std::get<0>(ff); + sysid::ElevatorSim model{Ks, Kv, Ka, Kg}; - EXPECT_NEAR(gains[0], Ks, 0.003); - EXPECT_NEAR(gains[1], Kv, 0.003); - EXPECT_NEAR(gains[2], Ka, 0.003); -} + RunTests(model, sysid::analysis::kElevator, {{Ks, Kv, Ka, Kg}}, + {{8e-3, 8e-3, 8e-3, 8e-3}}); + } -TEST(FeedforwardAnalysisTest, Elevator1) { - constexpr double Ks = 1.01; - constexpr double Kv = 3.060; - constexpr double Ka = 0.327; - constexpr double Kg = -0.211; - - sysid::ElevatorSim model{Ks, Kv, Ka, Kg}; - auto ff = sysid::CalculateFeedforwardGains(CollectData(model), - sysid::analysis::kElevator); - auto& gains = std::get<0>(ff); - - EXPECT_NEAR(gains[0], Ks, 0.003); - EXPECT_NEAR(gains[1], Kv, 0.003); - EXPECT_NEAR(gains[2], Ka, 0.003); - EXPECT_NEAR(gains[3], Kg, 0.003); -} + { + constexpr double Ks = 0.547; + constexpr double Kv = 0.0693; + constexpr double Ka = 0.1170; + constexpr double Kg = -0.122; + + sysid::ElevatorSim model{Ks, Kv, Ka, Kg}; -TEST(FeedforwardAnalysisTest, Elevator2) { - constexpr double Ks = 0.547; - constexpr double Kv = 0.0693; - constexpr double Ka = 0.1170; - constexpr double Kg = -0.122; - - sysid::ElevatorSim model{Ks, Kv, Ka, Kg}; - auto ff = sysid::CalculateFeedforwardGains(CollectData(model), - sysid::analysis::kElevator); - auto& gains = std::get<0>(ff); - - EXPECT_NEAR(gains[0], Ks, 0.003); - EXPECT_NEAR(gains[1], Kv, 0.003); - EXPECT_NEAR(gains[2], Ka, 0.003); - EXPECT_NEAR(gains[3], Kg, 0.003); + RunTests(model, sysid::analysis::kElevator, {{Ks, Kv, Ka, Kg}}, + {{8e-3, 8e-3, 8e-3, 8e-3}}); + } } -TEST(FeedforwardAnalysisTest, Simple1) { - constexpr double Ks = 1.01; - constexpr double Kv = 3.060; - constexpr double Ka = 0.327; +TEST(FeedforwardAnalysisTest, Simple) { + { + constexpr double Ks = 1.01; + constexpr double Kv = 3.060; + constexpr double Ka = 0.327; - sysid::SimpleMotorSim model{Ks, Kv, Ka}; - auto ff = sysid::CalculateFeedforwardGains(CollectData(model), - sysid::analysis::kSimple); - auto& gains = std::get<0>(ff); + sysid::SimpleMotorSim model{Ks, Kv, Ka}; - EXPECT_NEAR(gains[0], Ks, 0.003); - EXPECT_NEAR(gains[1], Kv, 0.003); - EXPECT_NEAR(gains[2], Ka, 0.003); -} + RunTests(model, sysid::analysis::kSimple, {{Ks, Kv, Ka}}, + {{8e-3, 8e-3, 8e-3}}); + } -TEST(FeedforwardAnalysisTest, Simple2) { - constexpr double Ks = 0.547; - constexpr double Kv = 0.0693; - constexpr double Ka = 0.1170; + { + constexpr double Ks = 0.547; + constexpr double Kv = 0.0693; + constexpr double Ka = 0.1170; - sysid::SimpleMotorSim model{Ks, Kv, Ka}; - auto ff = sysid::CalculateFeedforwardGains(CollectData(model), - sysid::analysis::kSimple); - auto& gains = std::get<0>(ff); + sysid::SimpleMotorSim model{Ks, Kv, Ka}; - EXPECT_NEAR(gains[0], Ks, 0.003); - EXPECT_NEAR(gains[1], Kv, 0.003); - EXPECT_NEAR(gains[2], Ka, 0.003); + RunTests(model, sysid::analysis::kSimple, {{Ks, Kv, Ka}}, + {{8e-3, 8e-3, 8e-3}}); + } } diff --git a/sysid/src/test/native/cpp/analysis/FilterTest.cpp b/sysid/src/test/native/cpp/analysis/FilterTest.cpp index a7b03492747..099bebc98a1 100644 --- a/sysid/src/test/native/cpp/analysis/FilterTest.cpp +++ b/sysid/src/test/native/cpp/analysis/FilterTest.cpp @@ -43,33 +43,96 @@ TEST(FilterTest, NoiseFloor) { EXPECT_NEAR(0.953, noiseFloor, 0.001); } +void FillStepVoltageData(std::vector& data) { + auto previousDatum = data.front(); + for (size_t i = 1; i < data.size(); ++i) { + auto& datum = data.at(i); + datum.timestamp = previousDatum.timestamp + previousDatum.dt; + datum.position = 0.5 * previousDatum.acceleration * + units::math::pow<2>(previousDatum.dt).value() + + previousDatum.velocity * previousDatum.dt.value() + + previousDatum.position; + datum.velocity = previousDatum.velocity + + previousDatum.acceleration * previousDatum.dt.value(); + + previousDatum = datum; + } +} + TEST(FilterTest, StepTrim) { - std::vector testData = { - {0_s, 1, 2, 3, 5_ms, 0, 0}, {1_s, 1, 2, 3, 5_ms, 0.25, 0}, - {2_s, 1, 2, 3, 5_ms, 0.5, 0}, {3_s, 1, 2, 3, 5_ms, 0.45, 0}, - {4_s, 1, 2, 3, 5_ms, 0.35, 0}, {5_s, 1, 2, 3, 5_ms, 0.15, 0}, - {6_s, 1, 2, 3, 5_ms, 0, 0}, {7_s, 1, 2, 3, 5_ms, 0.02, 0}, - {8_s, 1, 2, 3, 5_ms, 0.01, 0}, {9_s, 1, 2, 3, 5_ms, 0, 0}, - }; - - std::vector expectedData = { - {2_s, 1, 2, 3, 5_ms, 0.5, 0}, - {3_s, 1, 2, 3, 5_ms, 0.45, 0}, - {4_s, 1, 2, 3, 5_ms, 0.35, 0}, - {5_s, 1, 2, 3, 5_ms, 0.15, 0}}; - - auto maxTime = 9_s; - auto minTime = maxTime; - - sysid::AnalysisManager::Settings settings; - auto [tempMinTime, positionDelay, velocityDelay] = - sysid::TrimStepVoltageData(&testData, &settings, minTime, maxTime); - minTime = tempMinTime; - - EXPECT_EQ(expectedData[0].acceleration, testData[0].acceleration); - EXPECT_EQ(expectedData.back().acceleration, testData.back().acceleration); - EXPECT_EQ(5, settings.stepTestDuration.value()); - EXPECT_EQ(2, minTime.value()); + { + std::vector forwardTestData = { + {0_s, 1, 0, 0, 1_s, 0}, {0_s, 1, 0, 0, 1_s, 0.25}, + {0_s, 1, 0, 0, 1_s, 10}, {0_s, 1, 0, 0, 1_s, 0.45}, + {0_s, 1, 0, 0, 1_s, 0}, {0_s, 1, 0, 0, 1_s, 0.15}, + {0_s, 1, 0, 0, 1_s, 0}, {0_s, 1, 0, 0, 1_s, 0.02}, + {0_s, 1, 0, 0, 1_s, 0}, {0_s, 1, 0, 0, 0_s, 0}, + }; + + FillStepVoltageData(forwardTestData); + + auto maxTime = 9_s; + auto minTime = maxTime; + + sysid::AnalysisManager::Settings settings; + auto [tempMinTime, positionDelay, velocityDelay] = + sysid::TrimStepVoltageData(&forwardTestData, &settings, minTime, + maxTime); + minTime = tempMinTime; + + EXPECT_EQ(3, settings.stepTestDuration.value()); + EXPECT_EQ(2, minTime.value()); + } + + { + std::vector backwardsTestData = { + {0_s, -1, 0, 0, 1_s, 0}, {0_s, -1, 0, 0, 1_s, -0.46}, + {0_s, -1, 0, 0, 1_s, -8}, {0_s, -1, 0, 0, 1_s, -0.32}, + {0_s, -1, 0, 0, 1_s, -0.12}, {0_s, -1, 0, 0, 1_s, -0.08}, + {0_s, -1, 0, 0, 1_s, -0.06}, {0_s, -1, 0, 0, 1_s, -0.02}, + {0_s, -1, 0, 0, 1_s, 0}, {0_s, -1, 0, 0, 0_s, 0}, + }; + + FillStepVoltageData(backwardsTestData); + + auto maxTime = 9_s; + auto minTime = maxTime; + + sysid::AnalysisManager::Settings settings; + auto [tempMinTime, positionDelay, velocityDelay] = + sysid::TrimStepVoltageData(&backwardsTestData, &settings, minTime, + maxTime); + minTime = tempMinTime; + + EXPECT_EQ(3, settings.stepTestDuration.value()); + EXPECT_EQ(2, minTime.value()); + } + + { + // Forward test but with an erroneous negative acceleration at the end + std::vector noisyTestData = { + {0_s, 1, 0, 0, 1_s, 0}, {0_s, 1, 0, 0, 1_s, 0.41}, + {0_s, 1, 0, 0, 1_s, 11.5}, {0_s, 1, 0, 0, 1_s, 1.2}, + {0_s, 1, 0, 0, 1_s, 0.34}, {0_s, 1, 0, 0, 1_s, 0.25}, + {0_s, 1, 0, 0, 1_s, 0.11}, {0_s, 1, 0, 0, 1_s, -0.08}, + {0_s, 1, 0, 0, 1_s, -12}, {0_s, 1, 0, 0, 0_s, 0}, + }; + + FillStepVoltageData(noisyTestData); + + auto maxTime = 9_s; + auto minTime = maxTime; + + sysid::AnalysisManager::Settings settings; + auto [tempMinTime, positionDelay, velocityDelay] = + sysid::TrimStepVoltageData(&noisyTestData, &settings, minTime, maxTime); + minTime = tempMinTime; + + // Expect trimming to reject the erroneous peak negative accel, + // correctly picking up the max positive accel instead. + EXPECT_EQ(4, settings.stepTestDuration.value()); + EXPECT_EQ(2, minTime.value()); + } } template diff --git a/sysid/src/test/native/cpp/analysis/OLSTest.cpp b/sysid/src/test/native/cpp/analysis/OLSTest.cpp index bf205165a93..380a53d0865 100644 --- a/sysid/src/test/native/cpp/analysis/OLSTest.cpp +++ b/sysid/src/test/native/cpp/analysis/OLSTest.cpp @@ -11,12 +11,12 @@ TEST(OLSTest, TwoVariablesTwoPoints) { Eigen::MatrixXd X{{1.0, 1.0}, {1.0, 2.0}}; Eigen::VectorXd y{{3.0}, {5.0}}; - auto [coefficients, cod, rmse] = sysid::OLS(X, y); - EXPECT_EQ(coefficients.size(), 2u); + auto [coeffs, rSquared, rmse] = sysid::OLS(X, y); + EXPECT_EQ(coeffs.size(), 2u); - EXPECT_NEAR(coefficients[0], 1.0, 0.05); - EXPECT_NEAR(coefficients[1], 2.0, 0.05); - EXPECT_NEAR(cod, 1.0, 1E-4); + EXPECT_NEAR(coeffs[0], 1.0, 1e-12); + EXPECT_NEAR(coeffs[1], 2.0, 1e-12); + EXPECT_DOUBLE_EQ(rSquared, 1.0); } TEST(OLSTest, TwoVariablesFivePoints) { @@ -25,12 +25,12 @@ TEST(OLSTest, TwoVariablesFivePoints) { Eigen::MatrixXd X{{1, 2}, {1, 3}, {1, 5}, {1, 7}, {1, 9}}; Eigen::VectorXd y{{4}, {5}, {7}, {10}, {15}}; - auto [coefficients, cod, rmse] = sysid::OLS(X, y); - EXPECT_EQ(coefficients.size(), 2u); + auto [coeffs, rSquared, rmse] = sysid::OLS(X, y); + EXPECT_EQ(coeffs.size(), 2u); - EXPECT_NEAR(coefficients[0], 0.305, 0.05); - EXPECT_NEAR(coefficients[1], 1.518, 0.05); - EXPECT_NEAR(cod, 0.985, 0.05); + EXPECT_NEAR(coeffs[0], 0.30487804878048774, 1e-12); + EXPECT_NEAR(coeffs[1], 1.5182926829268293, 1e-12); + EXPECT_DOUBLE_EQ(rSquared, 0.91906029466386019); } #ifndef NDEBUG diff --git a/test-scripts/run-tests-on-robot.sh b/test-scripts/run-tests-on-robot.sh index 32b66b5eaa9..534eafd3a7c 100755 --- a/test-scripts/run-tests-on-robot.sh +++ b/test-scripts/run-tests-on-robot.sh @@ -11,6 +11,8 @@ # There is one file (delploy-and-run-test-on-robot.sh) that is designed to # deploy this file along with the compiled tests for you. +set -e + # Configurable variables source config.sh @@ -114,7 +116,7 @@ fi /usr/local/natinst/etc/init.d/systemWebServer stop # Kill all running robot programs -killall java FRCUserProgram +killall java FRCUserProgram || true # If we are running with the -d argument move the test to the DEFAULT_TEST_DIR if [[ ! -e "${TEST_DIR}/${TEST_FILE}" ]]; then diff --git a/upstream_utils/eigen_patches/0001-Disable-warnings.patch b/upstream_utils/eigen_patches/0001-Disable-warnings.patch index e89fec5f73f..449b4a4f30f 100644 --- a/upstream_utils/eigen_patches/0001-Disable-warnings.patch +++ b/upstream_utils/eigen_patches/0001-Disable-warnings.patch @@ -1,31 +1,29 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Wed, 18 May 2022 09:14:24 -0700 -Subject: [PATCH 1/3] Disable warnings +Subject: [PATCH 1/4] Disable warnings --- - Eigen/src/Core/util/DisableStupidWarnings.h | 11 +++++++++++ - 1 file changed, 11 insertions(+) + Eigen/src/Core/util/DisableStupidWarnings.h | 9 +++++++++ + 1 file changed, 9 insertions(+) diff --git a/Eigen/src/Core/util/DisableStupidWarnings.h b/Eigen/src/Core/util/DisableStupidWarnings.h -index fe0cfec0bc2461ac44abca8f3d05b468d3c60fd9..9a630e4ae692aee0277d60b3083c968d087920dd 100755 +index 32a427d852355a51dc4263d81498554ff4c3cbba..eb259433c054c21accd2b8a5d744638f8004da40 100644 --- a/Eigen/src/Core/util/DisableStupidWarnings.h +++ b/Eigen/src/Core/util/DisableStupidWarnings.h -@@ -71,6 +71,17 @@ - // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89325 - #pragma GCC diagnostic ignored "-Wattributes" - #endif -+ #if __GNUC__>=8 -+ #pragma GCC diagnostic ignored "-Wclass-memaccess" -+ #endif -+ #if __GNUC__>=11 -+ // This warning is a false positive -+ #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" -+ #endif -+ #if __GNUC__>=12 -+ // This warning is a false positive -+ #pragma GCC diagnostic ignored "-Warray-bounds" -+ #endif +@@ -81,6 +81,15 @@ + // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89325 + #pragma GCC diagnostic ignored "-Wattributes" + #endif ++#if __GNUC__>=8 ++#pragma GCC diagnostic ignored "-Wclass-memaccess" ++#endif ++#if __GNUC__>=11 ++#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" ++#endif ++#if __GNUC__>=12 ++#pragma GCC diagnostic ignored "-Warray-bounds" ++#endif #endif #if defined __NVCC__ diff --git a/upstream_utils/eigen_patches/0002-Intellisense-fix.patch b/upstream_utils/eigen_patches/0002-Intellisense-fix.patch index ce4cdb6a6ed..cf15cf94217 100644 --- a/upstream_utils/eigen_patches/0002-Intellisense-fix.patch +++ b/upstream_utils/eigen_patches/0002-Intellisense-fix.patch @@ -1,30 +1,27 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Peter Johnson Date: Fri, 20 Jan 2023 23:41:56 -0800 -Subject: [PATCH 2/3] Intellisense fix +Subject: [PATCH 2/4] Intellisense fix --- - Eigen/src/Core/util/Macros.h | 10 ++++++++++ - 1 file changed, 10 insertions(+) + Eigen/src/Core/util/ConfigureVectorization.h | 7 +++++++ + 1 file changed, 7 insertions(+) -diff --git a/Eigen/src/Core/util/Macros.h b/Eigen/src/Core/util/Macros.h -index 986c3d44db94c8ba339792b6738c47cdd2c5acbc..81986b9447824c440e004f38a220393ef5a089c6 100644 ---- a/Eigen/src/Core/util/Macros.h -+++ b/Eigen/src/Core/util/Macros.h -@@ -58,6 +58,16 @@ - // Compiler identification, EIGEN_COMP_* - //------------------------------------------------------------------------------------------ +diff --git a/Eigen/src/Core/util/ConfigureVectorization.h b/Eigen/src/Core/util/ConfigureVectorization.h +index 1c7217339bcb2c29366360c56343863126d8aafc..e8f5d2ce0d5917ec7df65800ff115f59e028e14b 100644 +--- a/Eigen/src/Core/util/ConfigureVectorization.h ++++ b/Eigen/src/Core/util/ConfigureVectorization.h +@@ -165,6 +165,13 @@ -+/// \internal Disable NEON features in Intellisense -+#if __INTELLISENSE__ -+#ifdef __ARM_NEON -+#undef __ARM_NEON -+#endif -+#ifdef __ARM_NEON__ -+#undef __ARM_NEON__ + //---------------------------------------------------------------------- + ++// Disable vectorization in intellisense ++#ifdef __INTELLISENSE__ ++#ifndef EIGEN_DONT_VECTORIZE ++#define EIGEN_DONT_VECTORIZE +#endif +#endif + - /// \internal EIGEN_COMP_GNUC set to 1 for all compilers compatible with GCC - #ifdef __GNUC__ - #define EIGEN_COMP_GNUC (__GNUC__*10+__GNUC_MINOR__) + // if alignment is disabled, then disable vectorization. Note: EIGEN_MAX_ALIGN_BYTES is the proper check, it takes into + // account both the user's will (EIGEN_MAX_ALIGN_BYTES,EIGEN_DONT_ALIGN) and our own platform checks + #if EIGEN_MAX_ALIGN_BYTES == 0 diff --git a/upstream_utils/eigen_patches/0003-Eigen-Sparse-fix-warnings-Wunused-but-set-variable.patch b/upstream_utils/eigen_patches/0003-Eigen-Sparse-fix-warnings-Wunused-but-set-variable.patch deleted file mode 100644 index d68f0947994..00000000000 --- a/upstream_utils/eigen_patches/0003-Eigen-Sparse-fix-warnings-Wunused-but-set-variable.patch +++ /dev/null @@ -1,65 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Laurent Rineau -Date: Tue, 11 Oct 2022 17:37:04 +0000 -Subject: [PATCH 3/3] Eigen/Sparse: fix warnings -Wunused-but-set-variable - ---- - Eigen/src/SparseCore/TriangularSolver.h | 4 ++-- - Eigen/src/SparseLU/SparseLU_heap_relax_snode.h | 5 ----- - 2 files changed, 2 insertions(+), 7 deletions(-) - -diff --git a/Eigen/src/SparseCore/TriangularSolver.h b/Eigen/src/SparseCore/TriangularSolver.h -index f9c56ba79800e209dcf3f18ba37dbb8023488bca..7cb2c2665f0e24924da88f11c0fe3ca0c0af52e3 100644 ---- a/Eigen/src/SparseCore/TriangularSolver.h -+++ b/Eigen/src/SparseCore/TriangularSolver.h -@@ -270,11 +270,11 @@ struct sparse_solve_triangular_sparse_selector - } - - -- Index count = 0; -+// Index count = 0; - // FIXME compute a reference value to filter zeros - for (typename AmbiVector::Iterator it(tempVector/*,1e-12*/); it; ++it) - { -- ++ count; -+// ++ count; - // std::cerr << "fill " << it.index() << ", " << col << "\n"; - // std::cout << it.value() << " "; - // FIXME use insertBack -diff --git a/Eigen/src/SparseLU/SparseLU_heap_relax_snode.h b/Eigen/src/SparseLU/SparseLU_heap_relax_snode.h -index 6f75d500e5f831f414175ce46dbceffa0acd5539..7aecbcad8ed2703000d62cfd5d88d983c69a7423 100644 ---- a/Eigen/src/SparseLU/SparseLU_heap_relax_snode.h -+++ b/Eigen/src/SparseLU/SparseLU_heap_relax_snode.h -@@ -75,8 +75,6 @@ void SparseLUImpl::heap_relax_snode (const Index n, IndexVe - // Identify the relaxed supernodes by postorder traversal of the etree - Index snode_start; // beginning of a snode - StorageIndex k; -- Index nsuper_et_post = 0; // Number of relaxed snodes in postordered etree -- Index nsuper_et = 0; // Number of relaxed snodes in the original etree - StorageIndex l; - for (j = 0; j < n; ) - { -@@ -88,7 +86,6 @@ void SparseLUImpl::heap_relax_snode (const Index n, IndexVe - parent = et(j); - } - // Found a supernode in postordered etree, j is the last column -- ++nsuper_et_post; - k = StorageIndex(n); - for (Index i = snode_start; i <= j; ++i) - k = (std::min)(k, inv_post(i)); -@@ -97,7 +94,6 @@ void SparseLUImpl::heap_relax_snode (const Index n, IndexVe - { - // This is also a supernode in the original etree - relax_end(k) = l; // Record last column -- ++nsuper_et; - } - else - { -@@ -107,7 +103,6 @@ void SparseLUImpl::heap_relax_snode (const Index n, IndexVe - if (descendants(i) == 0) - { - relax_end(l) = l; -- ++nsuper_et; - } - } - } diff --git a/upstream_utils/eigen_patches/0003-Suppress-C-23-deprecation-warnings-for-std-has_denor.patch b/upstream_utils/eigen_patches/0003-Suppress-C-23-deprecation-warnings-for-std-has_denor.patch new file mode 100644 index 00000000000..9a80736c2e7 --- /dev/null +++ b/upstream_utils/eigen_patches/0003-Suppress-C-23-deprecation-warnings-for-std-has_denor.patch @@ -0,0 +1,87 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Tyler Veness +Date: Mon, 13 May 2024 12:46:15 -0700 +Subject: [PATCH 3/4] Suppress C++23 deprecation warnings for std::has_denorm + and std::has_denorm_loss + +--- + Eigen/src/Core/arch/Default/BFloat16.h | 14 ++++++++++++++ + Eigen/src/Core/arch/Default/Half.h | 14 ++++++++++++++ + 2 files changed, 28 insertions(+) + +diff --git a/Eigen/src/Core/arch/Default/BFloat16.h b/Eigen/src/Core/arch/Default/BFloat16.h +index f31c6cee6e97e8f1ad6fa4341fec2c1e65dec705..c6fa034b04896e7666e8de53e0e011f9551d5d78 100644 +--- a/Eigen/src/Core/arch/Default/BFloat16.h ++++ b/Eigen/src/Core/arch/Default/BFloat16.h +@@ -139,8 +139,15 @@ struct numeric_limits_bfloat16_impl { + static EIGEN_CONSTEXPR const bool has_infinity = true; + static EIGEN_CONSTEXPR const bool has_quiet_NaN = true; + static EIGEN_CONSTEXPR const bool has_signaling_NaN = true; ++#if __cplusplus >= 202302L ++ EIGEN_DIAGNOSTICS(push) ++ EIGEN_DISABLE_DEPRECATED_WARNING ++#endif + static EIGEN_CONSTEXPR const std::float_denorm_style has_denorm = std::denorm_present; + static EIGEN_CONSTEXPR const bool has_denorm_loss = false; ++#if __cplusplus >= 202302L ++ EIGEN_DIAGNOSTICS(pop) ++#endif + static EIGEN_CONSTEXPR const std::float_round_style round_style = std::numeric_limits::round_style; + static EIGEN_CONSTEXPR const bool is_iec559 = true; + // The C++ standard defines this as "true if the set of values representable +@@ -187,10 +194,17 @@ template + EIGEN_CONSTEXPR const bool numeric_limits_bfloat16_impl::has_quiet_NaN; + template + EIGEN_CONSTEXPR const bool numeric_limits_bfloat16_impl::has_signaling_NaN; ++#if __cplusplus >= 202302L ++EIGEN_DIAGNOSTICS(push) ++EIGEN_DISABLE_DEPRECATED_WARNING ++#endif + template + EIGEN_CONSTEXPR const std::float_denorm_style numeric_limits_bfloat16_impl::has_denorm; + template + EIGEN_CONSTEXPR const bool numeric_limits_bfloat16_impl::has_denorm_loss; ++#if __cplusplus >= 202302L ++EIGEN_DIAGNOSTICS(pop) ++#endif + template + EIGEN_CONSTEXPR const std::float_round_style numeric_limits_bfloat16_impl::round_style; + template +diff --git a/Eigen/src/Core/arch/Default/Half.h b/Eigen/src/Core/arch/Default/Half.h +index 9c195c12a17fcb791c96a0ce6cf873f455c4f8be..506feca058bb7940663d9cda8b2fe902060fdc8f 100644 +--- a/Eigen/src/Core/arch/Default/Half.h ++++ b/Eigen/src/Core/arch/Default/Half.h +@@ -208,8 +208,15 @@ struct numeric_limits_half_impl { + static EIGEN_CONSTEXPR const bool has_infinity = true; + static EIGEN_CONSTEXPR const bool has_quiet_NaN = true; + static EIGEN_CONSTEXPR const bool has_signaling_NaN = true; ++#if __cplusplus >= 202302L ++ EIGEN_DIAGNOSTICS(push) ++ EIGEN_DISABLE_DEPRECATED_WARNING ++#endif + static EIGEN_CONSTEXPR const std::float_denorm_style has_denorm = std::denorm_present; + static EIGEN_CONSTEXPR const bool has_denorm_loss = false; ++#if __cplusplus >= 202302L ++ EIGEN_DIAGNOSTICS(pop) ++#endif + static EIGEN_CONSTEXPR const std::float_round_style round_style = std::round_to_nearest; + static EIGEN_CONSTEXPR const bool is_iec559 = true; + // The C++ standard defines this as "true if the set of values representable +@@ -256,10 +263,17 @@ template + EIGEN_CONSTEXPR const bool numeric_limits_half_impl::has_quiet_NaN; + template + EIGEN_CONSTEXPR const bool numeric_limits_half_impl::has_signaling_NaN; ++#if __cplusplus >= 202302L ++EIGEN_DIAGNOSTICS(push) ++EIGEN_DISABLE_DEPRECATED_WARNING ++#endif + template + EIGEN_CONSTEXPR const std::float_denorm_style numeric_limits_half_impl::has_denorm; + template + EIGEN_CONSTEXPR const bool numeric_limits_half_impl::has_denorm_loss; ++#if __cplusplus >= 202302L ++EIGEN_DIAGNOSTICS(pop) ++#endif + template + EIGEN_CONSTEXPR const std::float_round_style numeric_limits_half_impl::round_style; + template diff --git a/upstream_utils/eigen_patches/0004-Fix-compilation-failures-on-constexpr-matrices-with-.patch b/upstream_utils/eigen_patches/0004-Fix-compilation-failures-on-constexpr-matrices-with-.patch new file mode 100644 index 00000000000..35f57d25c9f --- /dev/null +++ b/upstream_utils/eigen_patches/0004-Fix-compilation-failures-on-constexpr-matrices-with-.patch @@ -0,0 +1,48 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Tyler Veness +Date: Tue, 14 May 2024 14:53:02 -0700 +Subject: [PATCH 4/4] Fix compilation failures on constexpr matrices with GCC + 14 + +DenseBase must have a trivial default constructor. +`constexpr DenseBase() {}` is not sufficient. +--- + Eigen/src/Core/DenseBase.h | 22 +++++++++++----------- + 1 file changed, 11 insertions(+), 11 deletions(-) + +diff --git a/Eigen/src/Core/DenseBase.h b/Eigen/src/Core/DenseBase.h +index 5ab54efa3d8d454b2d5e02cb9d6145a723683b91..297c42679d978c36388ccba5831dab6624b6cb92 100644 +--- a/Eigen/src/Core/DenseBase.h ++++ b/Eigen/src/Core/DenseBase.h +@@ -621,20 +621,20 @@ class DenseBase + protected: + EIGEN_DEFAULT_COPY_CONSTRUCTOR(DenseBase) + /** Default constructor. Do nothing. */ +- EIGEN_DEVICE_FUNC constexpr DenseBase() { +- /* Just checks for self-consistency of the flags. +- * Only do it when debugging Eigen, as this borders on paranoia and could slow compilation down +- */ + #ifdef EIGEN_INTERNAL_DEBUGGING +- EIGEN_STATIC_ASSERT( +- (internal::check_implication(MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1, int(IsRowMajor)) && +- internal::check_implication(MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1, int(!IsRowMajor))), +- INVALID_STORAGE_ORDER_FOR_THIS_VECTOR_EXPRESSION) ++ EIGEN_DEVICE_FUNC constexpr DenseBase(){ ++ /* Just checks for self-consistency of the flags. ++ * Only do it when debugging Eigen, as this borders on paranoia and could slow compilation down ++ */ ++ EIGEN_STATIC_ASSERT( ++ (internal::check_implication(MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1, int(IsRowMajor)) && ++ internal::check_implication(MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1, int(!IsRowMajor))), ++ INVALID_STORAGE_ORDER_FOR_THIS_VECTOR_EXPRESSION)} ++#else ++ EIGEN_DEVICE_FUNC constexpr DenseBase() = default; + #endif +- } + +- private: +- EIGEN_DEVICE_FUNC explicit DenseBase(int); ++ private : EIGEN_DEVICE_FUNC explicit DenseBase(int); + EIGEN_DEVICE_FUNC DenseBase(int, int); + template + EIGEN_DEVICE_FUNC explicit DenseBase(const DenseBase&); diff --git a/upstream_utils/fmt_patches/0001-Don-t-throw-on-write-failure.patch b/upstream_utils/fmt_patches/0001-Don-t-throw-on-write-failure.patch deleted file mode 100644 index 5b05dbf66fc..00000000000 --- a/upstream_utils/fmt_patches/0001-Don-t-throw-on-write-failure.patch +++ /dev/null @@ -1,55 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Tyler Veness -Date: Wed, 18 May 2022 10:21:49 -0700 -Subject: [PATCH 1/2] Don't throw on write failure - ---- - include/fmt/format-inl.h | 4 +--- - include/fmt/xchar.h | 3 +-- - src/os.cc | 4 +--- - 3 files changed, 3 insertions(+), 8 deletions(-) - -diff --git a/include/fmt/format-inl.h b/include/fmt/format-inl.h -index dac2d437a41ab7b0b4e72895212b5a972ada73a9..af6ba74d618f29c77339e8a82906cccd26a2efa4 100644 ---- a/include/fmt/format-inl.h -+++ b/include/fmt/format-inl.h -@@ -75,9 +75,7 @@ FMT_FUNC void report_error(format_func func, int error_code, - // A wrapper around fwrite that throws on error. - inline void fwrite_fully(const void* ptr, size_t size, size_t count, - FILE* stream) { -- size_t written = std::fwrite(ptr, size, count, stream); -- if (written < count) -- FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); -+ std::fwrite(ptr, size, count, stream); - } - - #ifndef FMT_STATIC_THOUSANDS_SEPARATOR -diff --git a/include/fmt/xchar.h b/include/fmt/xchar.h -index 625ec36922e9bcc44a76b3c40792cb08ede63813..0f79c1720a4c855bb7088381e93af08eae56d66c 100644 ---- a/include/fmt/xchar.h -+++ b/include/fmt/xchar.h -@@ -220,8 +220,7 @@ inline void vprint(std::FILE* f, wstring_view fmt, wformat_args args) { - auto buf = wmemory_buffer(); - detail::vformat_to(buf, fmt, args); - buf.push_back(L'\0'); -- if (std::fputws(buf.data(), f) == -1) -- FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); -+ std::fputws(buf.data(), f); - } - - inline void vprint(wstring_view fmt, wformat_args args) { -diff --git a/src/os.cc b/src/os.cc -index bca410e945e0347d349e06179906a43b38b56a5c..d7ded50f9870a885d1ce1835fecc4f740858127a 100644 ---- a/src/os.cc -+++ b/src/os.cc -@@ -258,9 +258,7 @@ long long file::size() const { - std::size_t file::read(void* buffer, std::size_t count) { - rwresult result = 0; - FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count)))); -- if (result < 0) -- FMT_THROW(system_error(errno, FMT_STRING("cannot read from file"))); -- return detail::to_unsigned(result); -+ return count; - } - - std::size_t file::write(const void* buffer, std::size_t count) { diff --git a/upstream_utils/fmt_patches/0002-Suppress-warnings-we-can-t-fix.patch b/upstream_utils/fmt_patches/0001-Suppress-warnings-we-can-t-fix.patch similarity index 79% rename from upstream_utils/fmt_patches/0002-Suppress-warnings-we-can-t-fix.patch rename to upstream_utils/fmt_patches/0001-Suppress-warnings-we-can-t-fix.patch index a3866e22990..b0b08ba836c 100644 --- a/upstream_utils/fmt_patches/0002-Suppress-warnings-we-can-t-fix.patch +++ b/upstream_utils/fmt_patches/0001-Suppress-warnings-we-can-t-fix.patch @@ -1,17 +1,17 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Tue, 16 May 2023 13:49:18 -0700 -Subject: [PATCH 2/2] Suppress warnings we can't fix +Subject: [PATCH 1/2] Suppress warnings we can't fix --- include/fmt/format.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/include/fmt/format.h b/include/fmt/format.h -index e5bd8b110efe49e12a12b004ea246a4dba671a6f..f11be0d6d58f3d992d7d06adb3d9576f81ecfe11 100644 +index 7637c8a0d0687ae3b77a145c2e1ceadf7fe5f67d..bfc6d70d1c5de100b3e413d61f7394cbb3b644f1 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h -@@ -1324,7 +1324,14 @@ inline auto equal2(const char* lhs, const char* rhs) -> bool { +@@ -1289,7 +1289,14 @@ inline auto equal2(const char* lhs, const char* rhs) -> bool { template FMT_CONSTEXPR20 FMT_INLINE void copy2(Char* dst, const char* src) { if (!is_constant_evaluated() && sizeof(Char) == sizeof(char)) { diff --git a/upstream_utils/fmt_patches/0002-Fix-tautological-compare-warning.patch b/upstream_utils/fmt_patches/0002-Fix-tautological-compare-warning.patch new file mode 100644 index 00000000000..2118e2551a4 --- /dev/null +++ b/upstream_utils/fmt_patches/0002-Fix-tautological-compare-warning.patch @@ -0,0 +1,33 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Victor Zverovich +Date: Mon, 29 Jan 2024 07:48:48 -0800 +Subject: [PATCH 2/2] Fix tautological-compare warning + +--- + include/fmt/ranges.h | 13 +++++++------ + 1 file changed, 7 insertions(+), 6 deletions(-) + +diff --git a/include/fmt/ranges.h b/include/fmt/ranges.h +index 3638fffb83bce6035c13659f26fe13749c8b19ea..767378c6203fc34e7d763075bd663d2bb6774a97 100644 +--- a/include/fmt/ranges.h ++++ b/include/fmt/ranges.h +@@ -206,12 +206,13 @@ class is_tuple_formattable_ { + static constexpr const bool value = false; + }; + template class is_tuple_formattable_ { +- template +- static auto check2(index_sequence, +- integer_sequence) -> std::true_type; +- static auto check2(...) -> std::false_type; +- template +- static auto check(index_sequence) -> decltype(check2( ++ template ++ static auto all_true(index_sequence, ++ integer_sequence= 0)...>) -> std::true_type; ++ static auto all_true(...) -> std::false_type; ++ ++ template ++ static auto check(index_sequence) -> decltype(all_true( + index_sequence{}, + integer_sequence::type, diff --git a/upstream_utils/gcem_patches/0001-Call-std-functions-if-not-constant-evaluated.patch b/upstream_utils/gcem_patches/0001-Call-std-functions-if-not-constant-evaluated.patch new file mode 100644 index 00000000000..b7742f0e2b8 --- /dev/null +++ b/upstream_utils/gcem_patches/0001-Call-std-functions-if-not-constant-evaluated.patch @@ -0,0 +1,1933 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Tyler Veness +Date: Sun, 26 Nov 2023 18:09:12 -0800 +Subject: [PATCH 1/2] Call std functions if not constant-evaluated + +The subheaders now have namespace declarations so C++ standard library +headers can be included in the global namespace. Doing otherwise can +cause ambiguous declarations of cmath functions. +--- + include/gcem.hpp | 151 +++++++++--------- + include/gcem_incl/abs.hpp | 12 ++ + include/gcem_incl/acos.hpp | 12 ++ + include/gcem_incl/acosh.hpp | 12 ++ + include/gcem_incl/asin.hpp | 12 ++ + include/gcem_incl/asinh.hpp | 11 ++ + include/gcem_incl/atan.hpp | 12 ++ + include/gcem_incl/atan2.hpp | 12 ++ + include/gcem_incl/atanh.hpp | 12 ++ + include/gcem_incl/beta.hpp | 16 ++ + include/gcem_incl/binomial_coef.hpp | 7 +- + include/gcem_incl/ceil.hpp | 12 ++ + include/gcem_incl/copysign.hpp | 12 ++ + include/gcem_incl/cos.hpp | 12 ++ + include/gcem_incl/cosh.hpp | 12 ++ + include/gcem_incl/erf.hpp | 12 ++ + include/gcem_incl/erf_inv.hpp | 4 + + include/gcem_incl/exp.hpp | 12 ++ + include/gcem_incl/expm1.hpp | 12 ++ + include/gcem_incl/factorial.hpp | 5 + + include/gcem_incl/find_exponent.hpp | 5 + + include/gcem_incl/find_fraction.hpp | 5 + + include/gcem_incl/find_whole.hpp | 5 + + include/gcem_incl/floor.hpp | 12 ++ + include/gcem_incl/fmod.hpp | 12 ++ + include/gcem_incl/gcd.hpp | 5 + + include/gcem_incl/hypot.hpp | 12 ++ + include/gcem_incl/incomplete_beta.hpp | 5 + + include/gcem_incl/incomplete_beta_inv.hpp | 5 + + include/gcem_incl/incomplete_gamma.hpp | 5 + + include/gcem_incl/incomplete_gamma_inv.hpp | 5 + + include/gcem_incl/inv_sqrt.hpp | 5 + + include/gcem_incl/is_even.hpp | 5 + + include/gcem_incl/is_finite.hpp | 5 + + include/gcem_incl/is_inf.hpp | 5 + + include/gcem_incl/is_nan.hpp | 5 + + include/gcem_incl/is_odd.hpp | 5 + + include/gcem_incl/lbeta.hpp | 5 + + include/gcem_incl/lcm.hpp | 5 + + include/gcem_incl/lgamma.hpp | 12 ++ + include/gcem_incl/lmgamma.hpp | 5 + + include/gcem_incl/log.hpp | 12 ++ + include/gcem_incl/log10.hpp | 12 ++ + include/gcem_incl/log1p.hpp | 12 ++ + include/gcem_incl/log2.hpp | 12 ++ + include/gcem_incl/log_binomial_coef.hpp | 7 +- + include/gcem_incl/mantissa.hpp | 5 + + include/gcem_incl/max.hpp | 12 ++ + include/gcem_incl/min.hpp | 12 ++ + include/gcem_incl/neg_zero.hpp | 5 + + include/gcem_incl/pow.hpp | 12 ++ + include/gcem_incl/pow_integral.hpp | 5 + + .../quadrature/gauss_legendre_30.hpp | 5 + + .../quadrature/gauss_legendre_50.hpp | 5 + + include/gcem_incl/round.hpp | 12 ++ + include/gcem_incl/sgn.hpp | 5 + + include/gcem_incl/signbit.hpp | 12 ++ + include/gcem_incl/sin.hpp | 12 ++ + include/gcem_incl/sinh.hpp | 12 ++ + include/gcem_incl/sqrt.hpp | 12 ++ + include/gcem_incl/tan.hpp | 12 ++ + include/gcem_incl/tanh.hpp | 12 ++ + include/gcem_incl/tgamma.hpp | 12 ++ + include/gcem_incl/trunc.hpp | 12 ++ + 64 files changed, 645 insertions(+), 79 deletions(-) + +diff --git a/include/gcem.hpp b/include/gcem.hpp +index 650d05d894786b123aefbc6d88c93604164d56d2..8ea7b2a279ecf4dcf684a39ee7e96db84e61a421 100644 +--- a/include/gcem.hpp ++++ b/include/gcem.hpp +@@ -23,82 +23,79 @@ + + #include "gcem_incl/gcem_options.hpp" + +-namespace gcem +-{ +- #include "gcem_incl/quadrature/gauss_legendre_50.hpp" +- +- #include "gcem_incl/is_inf.hpp" +- #include "gcem_incl/is_nan.hpp" +- #include "gcem_incl/is_finite.hpp" +- +- #include "gcem_incl/signbit.hpp" +- #include "gcem_incl/copysign.hpp" +- #include "gcem_incl/neg_zero.hpp" +- #include "gcem_incl/sgn.hpp" +- +- #include "gcem_incl/abs.hpp" +- #include "gcem_incl/ceil.hpp" +- #include "gcem_incl/floor.hpp" +- #include "gcem_incl/trunc.hpp" +- #include "gcem_incl/is_odd.hpp" +- #include "gcem_incl/is_even.hpp" +- #include "gcem_incl/max.hpp" +- #include "gcem_incl/min.hpp" +- #include "gcem_incl/sqrt.hpp" +- #include "gcem_incl/inv_sqrt.hpp" +- #include "gcem_incl/hypot.hpp" +- +- #include "gcem_incl/find_exponent.hpp" +- #include "gcem_incl/find_fraction.hpp" +- #include "gcem_incl/find_whole.hpp" +- #include "gcem_incl/mantissa.hpp" +- #include "gcem_incl/round.hpp" +- #include "gcem_incl/fmod.hpp" +- +- #include "gcem_incl/pow_integral.hpp" +- #include "gcem_incl/exp.hpp" +- #include "gcem_incl/expm1.hpp" +- #include "gcem_incl/log.hpp" +- #include "gcem_incl/log1p.hpp" +- #include "gcem_incl/log2.hpp" +- #include "gcem_incl/log10.hpp" +- #include "gcem_incl/pow.hpp" +- +- #include "gcem_incl/gcd.hpp" +- #include "gcem_incl/lcm.hpp" +- +- #include "gcem_incl/tan.hpp" +- #include "gcem_incl/cos.hpp" +- #include "gcem_incl/sin.hpp" +- +- #include "gcem_incl/atan.hpp" +- #include "gcem_incl/atan2.hpp" +- #include "gcem_incl/acos.hpp" +- #include "gcem_incl/asin.hpp" +- +- #include "gcem_incl/tanh.hpp" +- #include "gcem_incl/cosh.hpp" +- #include "gcem_incl/sinh.hpp" +- +- #include "gcem_incl/atanh.hpp" +- #include "gcem_incl/acosh.hpp" +- #include "gcem_incl/asinh.hpp" +- +- #include "gcem_incl/binomial_coef.hpp" +- #include "gcem_incl/lgamma.hpp" +- #include "gcem_incl/tgamma.hpp" +- #include "gcem_incl/factorial.hpp" +- #include "gcem_incl/lbeta.hpp" +- #include "gcem_incl/beta.hpp" +- #include "gcem_incl/lmgamma.hpp" +- #include "gcem_incl/log_binomial_coef.hpp" +- +- #include "gcem_incl/erf.hpp" +- #include "gcem_incl/erf_inv.hpp" +- #include "gcem_incl/incomplete_beta.hpp" +- #include "gcem_incl/incomplete_beta_inv.hpp" +- #include "gcem_incl/incomplete_gamma.hpp" +- #include "gcem_incl/incomplete_gamma_inv.hpp" +-} ++#include "gcem_incl/quadrature/gauss_legendre_50.hpp" ++ ++#include "gcem_incl/is_inf.hpp" ++#include "gcem_incl/is_nan.hpp" ++#include "gcem_incl/is_finite.hpp" ++ ++#include "gcem_incl/signbit.hpp" ++#include "gcem_incl/copysign.hpp" ++#include "gcem_incl/neg_zero.hpp" ++#include "gcem_incl/sgn.hpp" ++ ++#include "gcem_incl/abs.hpp" ++#include "gcem_incl/ceil.hpp" ++#include "gcem_incl/floor.hpp" ++#include "gcem_incl/trunc.hpp" ++#include "gcem_incl/is_odd.hpp" ++#include "gcem_incl/is_even.hpp" ++#include "gcem_incl/max.hpp" ++#include "gcem_incl/min.hpp" ++#include "gcem_incl/sqrt.hpp" ++#include "gcem_incl/inv_sqrt.hpp" ++#include "gcem_incl/hypot.hpp" ++ ++#include "gcem_incl/find_exponent.hpp" ++#include "gcem_incl/find_fraction.hpp" ++#include "gcem_incl/find_whole.hpp" ++#include "gcem_incl/mantissa.hpp" ++#include "gcem_incl/round.hpp" ++#include "gcem_incl/fmod.hpp" ++ ++#include "gcem_incl/pow_integral.hpp" ++#include "gcem_incl/exp.hpp" ++#include "gcem_incl/expm1.hpp" ++#include "gcem_incl/log.hpp" ++#include "gcem_incl/log1p.hpp" ++#include "gcem_incl/log2.hpp" ++#include "gcem_incl/log10.hpp" ++#include "gcem_incl/pow.hpp" ++ ++#include "gcem_incl/gcd.hpp" ++#include "gcem_incl/lcm.hpp" ++ ++#include "gcem_incl/tan.hpp" ++#include "gcem_incl/cos.hpp" ++#include "gcem_incl/sin.hpp" ++ ++#include "gcem_incl/atan.hpp" ++#include "gcem_incl/atan2.hpp" ++#include "gcem_incl/acos.hpp" ++#include "gcem_incl/asin.hpp" ++ ++#include "gcem_incl/tanh.hpp" ++#include "gcem_incl/cosh.hpp" ++#include "gcem_incl/sinh.hpp" ++ ++#include "gcem_incl/atanh.hpp" ++#include "gcem_incl/acosh.hpp" ++#include "gcem_incl/asinh.hpp" ++ ++#include "gcem_incl/binomial_coef.hpp" ++#include "gcem_incl/lgamma.hpp" ++#include "gcem_incl/tgamma.hpp" ++#include "gcem_incl/factorial.hpp" ++#include "gcem_incl/lbeta.hpp" ++#include "gcem_incl/beta.hpp" ++#include "gcem_incl/lmgamma.hpp" ++#include "gcem_incl/log_binomial_coef.hpp" ++ ++#include "gcem_incl/erf.hpp" ++#include "gcem_incl/erf_inv.hpp" ++#include "gcem_incl/incomplete_beta.hpp" ++#include "gcem_incl/incomplete_beta_inv.hpp" ++#include "gcem_incl/incomplete_gamma.hpp" ++#include "gcem_incl/incomplete_gamma_inv.hpp" + + #endif +diff --git a/include/gcem_incl/abs.hpp b/include/gcem_incl/abs.hpp +index 6d7b66d91bc9f4d0c05fd0c3dd1571b552d8a19a..8e8330b198a206ea4f422d6782c66fe92bdd6522 100644 +--- a/include/gcem_incl/abs.hpp ++++ b/include/gcem_incl/abs.hpp +@@ -21,6 +21,12 @@ + #ifndef _gcem_abs_HPP + #define _gcem_abs_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + /** + * Compile-time absolute value function + * +@@ -34,12 +40,18 @@ T + abs(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return( // deal with signed-zeros + x == T(0) ? \ + T(0) : + // else + x < T(0) ? \ + - x : x ); ++ } else { ++ return std::abs(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/acos.hpp b/include/gcem_incl/acos.hpp +index a47003d61d8ab2fb7dd0226410e1457809a73458..2e24d2acb61b5a5b647e707950cded8850b0ea66 100644 +--- a/include/gcem_incl/acos.hpp ++++ b/include/gcem_incl/acos.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_acos_HPP + #define _gcem_acos_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -78,7 +84,13 @@ return_t + acos(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::acos_check( static_cast>(x) ); ++ } else { ++ return std::acos(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/acosh.hpp b/include/gcem_incl/acosh.hpp +index 8767200778168aeb409f16945b2ceac75b69158d..778c36cad6ebd849696aaa68d2697a5145a410a3 100644 +--- a/include/gcem_incl/acosh.hpp ++++ b/include/gcem_incl/acosh.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_acosh_HPP + #define _gcem_acosh_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -62,7 +68,13 @@ return_t + acosh(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::acosh_compute( static_cast>(x) ); ++ } else { ++ return std::acosh(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/asin.hpp b/include/gcem_incl/asin.hpp +index 6a79e87df435c7e60b140b7c7133b22deea7fd73..39784aa10eb07ea9328ab819a1f396dd036719b4 100644 +--- a/include/gcem_incl/asin.hpp ++++ b/include/gcem_incl/asin.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_asin_HPP + #define _gcem_asin_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -76,7 +82,13 @@ return_t + asin(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::asin_check( static_cast>(x) ); ++ } else { ++ return std::asin(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/asinh.hpp b/include/gcem_incl/asinh.hpp +index a5f3ff62a0208d350f4027d736ce3fc035c16ded..0a5969369a7a7856e41de1d891d571d5dd3c481f 100644 +--- a/include/gcem_incl/asinh.hpp ++++ b/include/gcem_incl/asinh.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_asinh_HPP + #define _gcem_asinh_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -59,8 +65,13 @@ return_t + asinh(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::asinh_compute( static_cast>(x) ); ++ } else { ++ return std::asinh(x); ++ } + } + ++} + + #endif +diff --git a/include/gcem_incl/atan.hpp b/include/gcem_incl/atan.hpp +index 3f46974c07920fca6396e42e93261d8167a27eb1..19b9d4e10d75b067527133060d3b07719f6cfb4c 100644 +--- a/include/gcem_incl/atan.hpp ++++ b/include/gcem_incl/atan.hpp +@@ -29,6 +29,12 @@ + #ifndef _gcem_atan_HPP + #define _gcem_atan_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -149,7 +155,13 @@ return_t + atan(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::atan_check( static_cast>(x) ); ++ } else { ++ return std::atan(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/atan2.hpp b/include/gcem_incl/atan2.hpp +index 5ca55b79c8e11569511fb6d4842c74be50c70c67..07a02cf4a2e134705b514a1031d1d7f47294bdf1 100644 +--- a/include/gcem_incl/atan2.hpp ++++ b/include/gcem_incl/atan2.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_atan2_HPP + #define _gcem_atan2_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -82,7 +88,13 @@ common_return_t + atan2(const T1 y, const T2 x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::atan2_type_check(x,y); ++ } else { ++ return std::atan2(y, x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/atanh.hpp b/include/gcem_incl/atanh.hpp +index dfb4dc312d479e2c6dd837d2391bc658e3b678ed..5c4475bead1034c1b5b1583ad3050a85d380d629 100644 +--- a/include/gcem_incl/atanh.hpp ++++ b/include/gcem_incl/atanh.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_atanh_HPP + #define _gcem_atanh_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -73,7 +79,13 @@ return_t + atanh(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::atanh_check( static_cast>(x) ); ++ } else { ++ return std::atanh(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/beta.hpp b/include/gcem_incl/beta.hpp +index e43d4fcd9a10e37e16652351ec7092cb7200f808..3439af1b57e0135eb1c53a15d14dbbbfbe57bc13 100644 +--- a/include/gcem_incl/beta.hpp ++++ b/include/gcem_incl/beta.hpp +@@ -21,6 +21,12 @@ + #ifndef _gcem_beta_HPP + #define _gcem_beta_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + /** + * Compile-time beta function + * +@@ -36,7 +42,17 @@ common_return_t + beta(const T1 a, const T2 b) + noexcept + { ++ if (std::is_constant_evaluated()) { ++ return exp( lbeta(a,b) ); ++ } else { ++#ifdef __cpp_lib_math_special_functions ++ return std::beta(a, b); ++#else + return exp( lbeta(a,b) ); ++#endif ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/binomial_coef.hpp b/include/gcem_incl/binomial_coef.hpp +index 0fc17f384d708b4bd81905d49b20f8037c4701ae..a1f764b97b78cbaf8fb66117dab374dc55f04d49 100644 +--- a/include/gcem_incl/binomial_coef.hpp ++++ b/include/gcem_incl/binomial_coef.hpp +@@ -21,6 +21,9 @@ + #ifndef _gcem_binomial_coef_HPP + #define _gcem_binomial_coef_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -88,4 +91,6 @@ noexcept + return internal::binomial_coef_type_check(n,k); + } + +-#endif +\ No newline at end of file ++} ++ ++#endif +diff --git a/include/gcem_incl/ceil.hpp b/include/gcem_incl/ceil.hpp +index ff1097bac2f53c3f6a4b3d4bfc612e0fcd34a63b..2611e6560bfefc4efe782849c88d74bc3ebf9d76 100644 +--- a/include/gcem_incl/ceil.hpp ++++ b/include/gcem_incl/ceil.hpp +@@ -21,6 +21,12 @@ + #ifndef _gcem_ceil_HPP + #define _gcem_ceil_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -124,7 +130,13 @@ return_t + ceil(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::ceil_check( static_cast>(x) ); ++ } else { ++ return std::ceil(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/copysign.hpp b/include/gcem_incl/copysign.hpp +index c1741f7f321110ff3cf52cb9035d5f2dca5f0ffc..d1181995c7d0fd92668c766f7fd9288c17312159 100644 +--- a/include/gcem_incl/copysign.hpp ++++ b/include/gcem_incl/copysign.hpp +@@ -21,6 +21,12 @@ + #ifndef _gcem_copysign_HPP + #define _gcem_copysign_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + /** + * Compile-time copy sign function + * +@@ -35,7 +41,13 @@ T1 + copysign(const T1 x, const T2 y) + noexcept + { ++ if (std::is_constant_evaluated()) { + return( signbit(x) != signbit(y) ? -x : x ); ++ } else { ++ return std::copysign(x, y); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/cos.hpp b/include/gcem_incl/cos.hpp +index 82f4c609f5268d19771e281987ed1653e81ef173..be73b55e3f2023538d33eedc78c9ed3e93014384 100644 +--- a/include/gcem_incl/cos.hpp ++++ b/include/gcem_incl/cos.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_cos_HPP + #define _gcem_cos_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -77,7 +83,13 @@ return_t + cos(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::cos_check( static_cast>(x) ); ++ } else { ++ return std::cos(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/cosh.hpp b/include/gcem_incl/cosh.hpp +index fc89c0d06482a687442998da511eb1e7b17f95d5..53e5bb12641b4f13d43aee7a77c0d02bf845688a 100644 +--- a/include/gcem_incl/cosh.hpp ++++ b/include/gcem_incl/cosh.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_cosh_HPP + #define _gcem_cosh_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -59,7 +65,13 @@ return_t + cosh(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::cosh_compute( static_cast>(x) ); ++ } else { ++ return std::cosh(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/erf.hpp b/include/gcem_incl/erf.hpp +index d0bc83ada14af7a4b50262541c8558016823303a..319669d7f0d0bfd0cd91e3bd94e9bbd0c92c66ea 100644 +--- a/include/gcem_incl/erf.hpp ++++ b/include/gcem_incl/erf.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_erf_HPP + #define _gcem_erf_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -137,7 +143,13 @@ return_t + erf(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::erf_check( static_cast>(x) ); ++ } else { ++ return std::erf(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/erf_inv.hpp b/include/gcem_incl/erf_inv.hpp +index 412d686be268dd7668ca517e10e5e4be4263f0d7..c4f0d9d5abb46172fda7c6702bc31561f5680a37 100644 +--- a/include/gcem_incl/erf_inv.hpp ++++ b/include/gcem_incl/erf_inv.hpp +@@ -28,6 +28,9 @@ + #ifndef _gcem_erf_inv_HPP + #define _gcem_erf_inv_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -260,5 +263,6 @@ noexcept + return internal::erf_inv_begin( static_cast>(p) ); + } + ++} + + #endif +diff --git a/include/gcem_incl/exp.hpp b/include/gcem_incl/exp.hpp +index 595ffc2a6202d763560fd879f27fcef32c6b2d64..1708542df5153aeb6c2366078f32660ea002d51c 100644 +--- a/include/gcem_incl/exp.hpp ++++ b/include/gcem_incl/exp.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_exp_HPP + #define _gcem_exp_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -124,7 +130,13 @@ return_t + exp(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::exp_check( static_cast>(x) ); ++ } else { ++ return std::exp(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/expm1.hpp b/include/gcem_incl/expm1.hpp +index 70c9ecf5a4a241bfef617e6e4ee0000a80978355..6adddc929aff7c87395a6b78070c65646ad61f2f 100644 +--- a/include/gcem_incl/expm1.hpp ++++ b/include/gcem_incl/expm1.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_expm1_HPP + #define _gcem_expm1_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -70,7 +76,13 @@ return_t + expm1(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::expm1_check( static_cast>(x) ); ++ } else { ++ return std::expm1(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/factorial.hpp b/include/gcem_incl/factorial.hpp +index ffb9c824751a572c0982e11b9cddbe40cb567a3f..977e6970e4479ab39e65affbdd400827d29e7809 100644 +--- a/include/gcem_incl/factorial.hpp ++++ b/include/gcem_incl/factorial.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_factorial_HPP + #define _gcem_factorial_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -95,4 +98,6 @@ noexcept + return internal::factorial_recur(x); + } + ++} ++ + #endif +diff --git a/include/gcem_incl/find_exponent.hpp b/include/gcem_incl/find_exponent.hpp +index 200e4e9be1558a61ed608be290bde5a6921363ea..4ffbcf294e61aa847d3e769e50ad9c3eddd8927a 100644 +--- a/include/gcem_incl/find_exponent.hpp ++++ b/include/gcem_incl/find_exponent.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_find_exponent_HPP + #define _gcem_find_exponent_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -54,4 +57,6 @@ noexcept + + } + ++} ++ + #endif +diff --git a/include/gcem_incl/find_fraction.hpp b/include/gcem_incl/find_fraction.hpp +index 5ed3d269ab54b3c90b3d681b76e8420e89e4527f..76893135383e5f6f5993d335c7b232114fdd90e3 100644 +--- a/include/gcem_incl/find_fraction.hpp ++++ b/include/gcem_incl/find_fraction.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_find_fraction_HPP + #define _gcem_find_fraction_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -43,4 +46,6 @@ noexcept + + } + ++} ++ + #endif +diff --git a/include/gcem_incl/find_whole.hpp b/include/gcem_incl/find_whole.hpp +index d19363219871803f8cfeafadb0a88189d2f98f0e..561050e91f9e43faf4d80fd08b7e63537b622422 100644 +--- a/include/gcem_incl/find_whole.hpp ++++ b/include/gcem_incl/find_whole.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_find_whole_HPP + #define _gcem_find_whole_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -43,4 +46,6 @@ noexcept + + } + ++} ++ + #endif +diff --git a/include/gcem_incl/floor.hpp b/include/gcem_incl/floor.hpp +index 8b260ff8a10fb8b9d048307c7d9b18a7e91900c1..3b3b86a12aa49e1c51957d170744a65690aeefdc 100644 +--- a/include/gcem_incl/floor.hpp ++++ b/include/gcem_incl/floor.hpp +@@ -21,6 +21,12 @@ + #ifndef _gcem_floor_HPP + #define _gcem_floor_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -124,7 +130,13 @@ return_t + floor(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::floor_check( static_cast>(x) ); ++ } else { ++ return std::floor(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/fmod.hpp b/include/gcem_incl/fmod.hpp +index 02459efd4b3a016939a306c9fd1a7ead12ff123b..58c454455edf132c078779ec15e254c96228b514 100644 +--- a/include/gcem_incl/fmod.hpp ++++ b/include/gcem_incl/fmod.hpp +@@ -21,6 +21,12 @@ + #ifndef _gcem_fmod_HPP + #define _gcem_fmod_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -64,7 +70,13 @@ common_return_t + fmod(const T1 x, const T2 y) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::fmod_type_check(x,y); ++ } else { ++ return std::fmod(x, y); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/gcd.hpp b/include/gcem_incl/gcd.hpp +index 1e277fbab61a06a20758f55d2c71ca57037f9d57..c5b14a22aafe7738dd14d120cab4dc6b31a5ad91 100644 +--- a/include/gcem_incl/gcd.hpp ++++ b/include/gcem_incl/gcd.hpp +@@ -21,6 +21,9 @@ + #ifndef _gcem_gcd_HPP + #define _gcem_gcd_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -79,4 +82,6 @@ noexcept + return internal::gcd_type_check(a,b); + } + ++} ++ + #endif +diff --git a/include/gcem_incl/hypot.hpp b/include/gcem_incl/hypot.hpp +index 01ad4e9212547c649113e50954a73ee9f7394334..00e10f899ace8f0da925fa9e46fa3f79f7e83aa0 100644 +--- a/include/gcem_incl/hypot.hpp ++++ b/include/gcem_incl/hypot.hpp +@@ -27,6 +27,12 @@ + #ifndef _gcem_hypot_HPP + #define _gcem_hypot_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -84,7 +90,13 @@ common_return_t + hypot(const T1 x, const T2 y) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::hypot_type_check(x,y); ++ } else { ++ return std::hypot(x, y); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/incomplete_beta.hpp b/include/gcem_incl/incomplete_beta.hpp +index dbb9f60341b09102b137de2b9ded75280a315d57..681cc59953f0f2b1bd3603216286edce06ce46cc 100644 +--- a/include/gcem_incl/incomplete_beta.hpp ++++ b/include/gcem_incl/incomplete_beta.hpp +@@ -27,6 +27,9 @@ + #ifndef _gcem_incomplete_beta_HPP + #define _gcem_incomplete_beta_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -191,4 +194,6 @@ noexcept + return internal::incomplete_beta_type_check(a,b,z); + } + ++} ++ + #endif +diff --git a/include/gcem_incl/incomplete_beta_inv.hpp b/include/gcem_incl/incomplete_beta_inv.hpp +index 9f575a360427d8b4ba9ebb940c2baf7ee242251c..3878d37db3bbef56e14bc053b9577b4f96c6c63c 100644 +--- a/include/gcem_incl/incomplete_beta_inv.hpp ++++ b/include/gcem_incl/incomplete_beta_inv.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_incomplete_beta_inv_HPP + #define _gcem_incomplete_beta_inv_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -349,4 +352,6 @@ noexcept + return internal::incomplete_beta_inv_type_check(a,b,p); + } + ++} ++ + #endif +diff --git a/include/gcem_incl/incomplete_gamma.hpp b/include/gcem_incl/incomplete_gamma.hpp +index 9ee4146de0aacffee1f418bd91069c921e0a6a29..0432b7d3c6f75a726847c9d84d52e387df16f618 100644 +--- a/include/gcem_incl/incomplete_gamma.hpp ++++ b/include/gcem_incl/incomplete_gamma.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_incomplete_gamma_HPP + #define _gcem_incomplete_gamma_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -244,4 +247,6 @@ noexcept + return internal::incomplete_gamma_type_check(a,x); + } + ++} ++ + #endif +diff --git a/include/gcem_incl/incomplete_gamma_inv.hpp b/include/gcem_incl/incomplete_gamma_inv.hpp +index e5976d08fddb5eb83ad40d200c5973d8ce2d6a36..6b1575b89c8e7284aee55882d12f1ee308d0cba3 100644 +--- a/include/gcem_incl/incomplete_gamma_inv.hpp ++++ b/include/gcem_incl/incomplete_gamma_inv.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_incomplete_gamma_inv_HPP + #define _gcem_incomplete_gamma_inv_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -268,4 +271,6 @@ noexcept + return internal::incomplete_gamma_inv_type_check(a,p); + } + ++} ++ + #endif +diff --git a/include/gcem_incl/inv_sqrt.hpp b/include/gcem_incl/inv_sqrt.hpp +index d0e33fb743b09e7c72506599414f7a4e0e7e5058..466e76fc5e844ba4b3c6be1a6a2a5f20b4e3607f 100644 +--- a/include/gcem_incl/inv_sqrt.hpp ++++ b/include/gcem_incl/inv_sqrt.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_inv_sqrt_HPP + #define _gcem_inv_sqrt_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -85,4 +88,6 @@ noexcept + return internal::inv_sqrt_check( static_cast>(x) ); + } + ++} ++ + #endif +diff --git a/include/gcem_incl/is_even.hpp b/include/gcem_incl/is_even.hpp +index de0641d85299a77380ba204e5e1d88538106468f..5aff6a3fa634d84b3fad6c831e3bb93797daee37 100644 +--- a/include/gcem_incl/is_even.hpp ++++ b/include/gcem_incl/is_even.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_is_even_HPP + #define _gcem_is_even_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -38,4 +41,6 @@ noexcept + + } + ++} ++ + #endif +diff --git a/include/gcem_incl/is_finite.hpp b/include/gcem_incl/is_finite.hpp +index b632fa34728ea66b595be68d48185474c3fe775e..805cbc4ab6708a51c95186801a1b0b02e0083e92 100644 +--- a/include/gcem_incl/is_finite.hpp ++++ b/include/gcem_incl/is_finite.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_is_finite_HPP + #define _gcem_is_finite_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -75,4 +78,6 @@ noexcept + + } + ++} ++ + #endif +diff --git a/include/gcem_incl/is_inf.hpp b/include/gcem_incl/is_inf.hpp +index 568614f8efa0e25fad4f87e1b71080849127378d..fdc31de71a3e73fda17216fb29e962c9f8a00958 100644 +--- a/include/gcem_incl/is_inf.hpp ++++ b/include/gcem_incl/is_inf.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_is_inf_HPP + #define _gcem_is_inf_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -169,4 +172,6 @@ noexcept + + } + ++} ++ + #endif +diff --git a/include/gcem_incl/is_nan.hpp b/include/gcem_incl/is_nan.hpp +index a3fcbc6c7cf6593965bee84b0eda0fc148f8f7ff..74092e6b087e47df45f70c6fcb5e62da53317f29 100644 +--- a/include/gcem_incl/is_nan.hpp ++++ b/include/gcem_incl/is_nan.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_is_nan_HPP + #define _gcem_is_nan_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -77,4 +80,6 @@ noexcept + + } + ++} ++ + #endif +diff --git a/include/gcem_incl/is_odd.hpp b/include/gcem_incl/is_odd.hpp +index a74a8d34f20da4a060b000b58fe7abd5b53f38b0..a76802f7ffc9b0faecae4f64c981ea76116e7c2a 100644 +--- a/include/gcem_incl/is_odd.hpp ++++ b/include/gcem_incl/is_odd.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_is_odd_HPP + #define _gcem_is_odd_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -39,4 +42,6 @@ noexcept + + } + ++} ++ + #endif +diff --git a/include/gcem_incl/lbeta.hpp b/include/gcem_incl/lbeta.hpp +index 60c87b4f53ec120121f1755635531dc4cc5ab26c..78f6849e72f56c35896e7e00ed9c3227a98114ba 100644 +--- a/include/gcem_incl/lbeta.hpp ++++ b/include/gcem_incl/lbeta.hpp +@@ -21,6 +21,9 @@ + #ifndef _gcem_lbeta_HPP + #define _gcem_lbeta_HPP + ++namespace gcem ++{ ++ + /** + * Compile-time log-beta function + * +@@ -39,4 +42,6 @@ noexcept + return( (lgamma(a) + lgamma(b)) - lgamma(a+b) ); + } + ++} ++ + #endif +diff --git a/include/gcem_incl/lcm.hpp b/include/gcem_incl/lcm.hpp +index a7ca7766f8906c1d26c071146aba3543880d8dd9..aa1f3397309a8a4517fed63d954737e043e28d1b 100644 +--- a/include/gcem_incl/lcm.hpp ++++ b/include/gcem_incl/lcm.hpp +@@ -21,6 +21,9 @@ + #ifndef _gcem_lcm_HPP + #define _gcem_lcm_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -62,4 +65,6 @@ noexcept + return internal::lcm_type_check(a,b); + } + ++} ++ + #endif +diff --git a/include/gcem_incl/lgamma.hpp b/include/gcem_incl/lgamma.hpp +index 507c6d4c91423b31be55426f494f67b0cb085c9f..e349ee88dba2d23982a6d4485bc33da076c70e22 100644 +--- a/include/gcem_incl/lgamma.hpp ++++ b/include/gcem_incl/lgamma.hpp +@@ -28,6 +28,12 @@ + #ifndef _gcem_lgamma_HPP + #define _gcem_lgamma_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -129,7 +135,13 @@ return_t + lgamma(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::lgamma_check( static_cast>(x) ); ++ } else { ++ return std::lgamma(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/lmgamma.hpp b/include/gcem_incl/lmgamma.hpp +index 58915dc1e1a2edbbfdea58b57137cd22aaf4b717..b009de18e71c4360b55d0c1d80763f140190706f 100644 +--- a/include/gcem_incl/lmgamma.hpp ++++ b/include/gcem_incl/lmgamma.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_lmgamma_HPP + #define _gcem_lmgamma_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -70,4 +73,6 @@ noexcept + return internal::lmgamma_recur(static_cast>(a),p); + } + ++} ++ + #endif +diff --git a/include/gcem_incl/log.hpp b/include/gcem_incl/log.hpp +index c2e24b006c2fdd01196b189220f35ca982d8bf9e..15577c8bacca3f4d0036997a2a34603ff56b4b24 100644 +--- a/include/gcem_incl/log.hpp ++++ b/include/gcem_incl/log.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_log_HPP + #define _gcem_log_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -180,7 +186,13 @@ return_t + log(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::log_integral_check( x ); ++ } else { ++ return std::log(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/log10.hpp b/include/gcem_incl/log10.hpp +index cda8894fdd62054f11ec4c3c3e6402c3752e0dd7..0e9a4dbdf58e2ed077e2f682706d98e71d794d67 100644 +--- a/include/gcem_incl/log10.hpp ++++ b/include/gcem_incl/log10.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_log10_HPP + #define _gcem_log10_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -53,7 +59,13 @@ return_t + log10(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::log10_check( x ); ++ } else { ++ return std::log10(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/log1p.hpp b/include/gcem_incl/log1p.hpp +index ccd08b8cb8799f2d4d34d5634dbc2fcabb3fd5b3..ed41daf39ec7e7062dc1da51ef0b0e106b56cf4e 100644 +--- a/include/gcem_incl/log1p.hpp ++++ b/include/gcem_incl/log1p.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_log1p_HPP + #define _gcem_log1p_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -74,7 +80,13 @@ return_t + log1p(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::log1p_check( static_cast>(x) ); ++ } else { ++ return std::log1p(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/log2.hpp b/include/gcem_incl/log2.hpp +index a97fed4c7236f816fa07ac2494f243adbac6742b..f8dc729f4f08348b8cc046468f40cfc84f1c9cb2 100644 +--- a/include/gcem_incl/log2.hpp ++++ b/include/gcem_incl/log2.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_log2_HPP + #define _gcem_log2_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -53,7 +59,13 @@ return_t + log2(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::log2_check( x ); ++ } else { ++ return std::log2(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/log_binomial_coef.hpp b/include/gcem_incl/log_binomial_coef.hpp +index 2bcaadd8bc1c64744eb082955522339d48589aec..c4ba2fa3de9f4f77ac772d24c1432fc93cc51840 100644 +--- a/include/gcem_incl/log_binomial_coef.hpp ++++ b/include/gcem_incl/log_binomial_coef.hpp +@@ -21,6 +21,9 @@ + #ifndef _gcem_log_binomial_coef_HPP + #define _gcem_log_binomial_coef_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -62,4 +65,6 @@ noexcept + return internal::log_binomial_coef_type_check(n,k); + } + +-#endif +\ No newline at end of file ++} ++ ++#endif +diff --git a/include/gcem_incl/mantissa.hpp b/include/gcem_incl/mantissa.hpp +index af23ea21d247327fa224370544e5f4410eac214b..4c95110d627568577440e5e662e72fdeffd95ade 100644 +--- a/include/gcem_incl/mantissa.hpp ++++ b/include/gcem_incl/mantissa.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_mantissa_HPP + #define _gcem_mantissa_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -44,4 +47,6 @@ noexcept + + } + ++} ++ + #endif +diff --git a/include/gcem_incl/max.hpp b/include/gcem_incl/max.hpp +index ddc3e4e6caff1a781e662a3ded8909cb703729ab..9f3901b4b19eb35331cd22be16c5b3a1ab5f65d6 100644 +--- a/include/gcem_incl/max.hpp ++++ b/include/gcem_incl/max.hpp +@@ -21,6 +21,12 @@ + #ifndef _gcem_max_HPP + #define _gcem_max_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + /** + * Compile-time pairwise maximum function + * +@@ -35,7 +41,13 @@ common_t + max(const T1 x, const T2 y) + noexcept + { ++ if (std::is_constant_evaluated()) { + return( y < x ? x : y ); ++ } else { ++ return std::max(x, y); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/min.hpp b/include/gcem_incl/min.hpp +index 5ce70b38e6d243267a053ec33fae31e59f6a359f..a35bcf6e2cb65f8712b873d3ef2827aca2d4d0f0 100644 +--- a/include/gcem_incl/min.hpp ++++ b/include/gcem_incl/min.hpp +@@ -21,6 +21,12 @@ + #ifndef _gcem_min_HPP + #define _gcem_min_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + /** + * Compile-time pairwise minimum function + * +@@ -35,7 +41,13 @@ common_t + min(const T1 x, const T2 y) + noexcept + { ++ if (std::is_constant_evaluated()) { + return( y > x ? x : y ); ++ } else { ++ return std::min(x, y); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/neg_zero.hpp b/include/gcem_incl/neg_zero.hpp +index 79d24a4dd56f4c361774135bc9450c71a9f61627..90923035419d8b7a88ca46c9dcb3294f601312fb 100644 +--- a/include/gcem_incl/neg_zero.hpp ++++ b/include/gcem_incl/neg_zero.hpp +@@ -22,6 +22,9 @@ + * extract signbit for signed zeros + */ + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -35,3 +38,5 @@ noexcept + } + + } ++ ++} +diff --git a/include/gcem_incl/pow.hpp b/include/gcem_incl/pow.hpp +index 3891edef0e8f1e7b64e8632f46e87fd39bdba162..372166d40644ec5403d9308b5325a36a78ad2589 100644 +--- a/include/gcem_incl/pow.hpp ++++ b/include/gcem_incl/pow.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_pow_HPP + #define _gcem_pow_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -76,7 +82,13 @@ common_t + pow(const T1 base, const T2 exp_term) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::pow_check(base,exp_term); ++ } else { ++ return std::pow(base, exp_term); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/pow_integral.hpp b/include/gcem_incl/pow_integral.hpp +index 4e671557071e6377721f3ca721a7b5875f2ffd83..589d16406576bb637963aae33e40aeddf164079a 100644 +--- a/include/gcem_incl/pow_integral.hpp ++++ b/include/gcem_incl/pow_integral.hpp +@@ -25,6 +25,9 @@ + #ifndef _gcem_pow_integral_HPP + #define _gcem_pow_integral_HPP + ++namespace gcem ++{ ++ + namespace internal + { + +@@ -125,4 +128,6 @@ noexcept + + } + ++} ++ + #endif +diff --git a/include/gcem_incl/quadrature/gauss_legendre_30.hpp b/include/gcem_incl/quadrature/gauss_legendre_30.hpp +index 295f43d9522dcdd7cae358dfc5b6382cfa7bd782..a80d2bb6f9b0dbc9936f3ed3e4f3770b4c307b7d 100644 +--- a/include/gcem_incl/quadrature/gauss_legendre_30.hpp ++++ b/include/gcem_incl/quadrature/gauss_legendre_30.hpp +@@ -22,6 +22,9 @@ + * Gauss-Legendre quadrature: 30 points + */ + ++namespace gcem ++{ ++ + static const long double gauss_legendre_30_points[30] = \ + { + -0.05147184255531769583302521316672L, +@@ -89,3 +92,5 @@ static const long double gauss_legendre_30_weights[30] = \ + 0.00796819249616660561546588347467L, + 0.00796819249616660561546588347467L\ + }; ++ ++} +diff --git a/include/gcem_incl/quadrature/gauss_legendre_50.hpp b/include/gcem_incl/quadrature/gauss_legendre_50.hpp +index d4e448c56e923876f2f8627df4caa5d29eb1c501..85244daf1057aa2f07979a19765bcec3865950e2 100644 +--- a/include/gcem_incl/quadrature/gauss_legendre_50.hpp ++++ b/include/gcem_incl/quadrature/gauss_legendre_50.hpp +@@ -22,6 +22,9 @@ + * Gauss-Legendre quadrature: 50 points + */ + ++namespace gcem ++{ ++ + static const long double gauss_legendre_50_points[50] = \ + { + -0.03109833832718887611232898966595L, +@@ -129,3 +132,5 @@ static const long double gauss_legendre_50_weights[50] = \ + 0.00290862255315514095840072434286L, + 0.00290862255315514095840072434286L\ + }; ++ ++} +diff --git a/include/gcem_incl/round.hpp b/include/gcem_incl/round.hpp +index 9ac4a09f0a9e7b09a303795d30ccee32ebe841b1..10fae649f89b0320e4f38f87fa8f8ffb41d75b9f 100644 +--- a/include/gcem_incl/round.hpp ++++ b/include/gcem_incl/round.hpp +@@ -21,6 +21,12 @@ + #ifndef _gcem_round_HPP + #define _gcem_round_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -119,7 +125,13 @@ return_t + round(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::round_check( static_cast>(x) ); ++ } else { ++ return std::round(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/sgn.hpp b/include/gcem_incl/sgn.hpp +index e2eec9e80b57e73396f3cf7f335692d88dcd752b..4c4adfa5a8d9da0e04c55195ec596ce58f63c0a8 100644 +--- a/include/gcem_incl/sgn.hpp ++++ b/include/gcem_incl/sgn.hpp +@@ -21,6 +21,9 @@ + #ifndef _gcem_sgn_HPP + #define _gcem_sgn_HPP + ++namespace gcem ++{ ++ + /** + * Compile-time sign function + * +@@ -42,4 +45,6 @@ noexcept + 0 ); + } + ++} ++ + #endif +diff --git a/include/gcem_incl/signbit.hpp b/include/gcem_incl/signbit.hpp +index 282e24403345dccfa8bf580112c129b43df5aa6d..40ec1dd157a687112f8258f76ea2ceb62d8ae22f 100644 +--- a/include/gcem_incl/signbit.hpp ++++ b/include/gcem_incl/signbit.hpp +@@ -21,6 +21,12 @@ + #ifndef _gcem_signbit_HPP + #define _gcem_signbit_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + /** + * Compile-time sign bit detection function + * +@@ -34,11 +40,17 @@ bool + signbit(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + #ifdef _MSC_VER + return( (x == T(0)) ? (_fpclass(x) == _FPCLASS_NZ) : (x < T(0)) ); + #else + return GCEM_SIGNBIT(x); + #endif ++ } else { ++ return std::signbit(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/sin.hpp b/include/gcem_incl/sin.hpp +index 56c8dcaf62dc22207ee7f41ec84d272e4535ab4e..c7c17600db0c8cb862c433183139d1f727fcea8b 100644 +--- a/include/gcem_incl/sin.hpp ++++ b/include/gcem_incl/sin.hpp +@@ -27,6 +27,12 @@ + #ifndef _gcem_sin_HPP + #define _gcem_sin_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -79,7 +85,13 @@ return_t + sin(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::sin_check( static_cast>(x) ); ++ } else { ++ return std::sin(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/sinh.hpp b/include/gcem_incl/sinh.hpp +index fe3ecdd0e719856c8bcc0e8d692d93c98c496942..9174d5d64a0622b56efac56fbfdc44994f78e78d 100644 +--- a/include/gcem_incl/sinh.hpp ++++ b/include/gcem_incl/sinh.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_sinh_HPP + #define _gcem_sinh_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -59,7 +65,13 @@ return_t + sinh(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::sinh_check( static_cast>(x) ); ++ } else { ++ return std::sinh(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/sqrt.hpp b/include/gcem_incl/sqrt.hpp +index 1b2753c99ede5189fc2272080828c83ca63a184c..201d89fa0df5680ceb53ec3aabb20213b4326325 100644 +--- a/include/gcem_incl/sqrt.hpp ++++ b/include/gcem_incl/sqrt.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_sqrt_HPP + #define _gcem_sqrt_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -103,7 +109,13 @@ return_t + sqrt(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::sqrt_check( static_cast>(x) ); ++ } else { ++ return std::sqrt(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/tan.hpp b/include/gcem_incl/tan.hpp +index 386cce0f412107f65183031b3458455059f55d54..08c12d4ea07ee06d1bd25bfd7cea2c3204a72e6c 100644 +--- a/include/gcem_incl/tan.hpp ++++ b/include/gcem_incl/tan.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_tan_HPP + #define _gcem_tan_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -134,7 +140,13 @@ return_t + tan(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::tan_check( static_cast>(x) ); ++ } else { ++ return std::tan(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/tanh.hpp b/include/gcem_incl/tanh.hpp +index 30b431886601ec9f77ca9a93a6ca62b3cabd9e57..f25dabdb0f075d5597530cb9c1c41d0ba02e3783 100644 +--- a/include/gcem_incl/tanh.hpp ++++ b/include/gcem_incl/tanh.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_tanh_HPP + #define _gcem_tanh_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -83,7 +89,13 @@ return_t + tanh(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::tanh_check( static_cast>(x) ); ++ } else { ++ return std::tanh(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/tgamma.hpp b/include/gcem_incl/tgamma.hpp +index deffd3a8e77c34a9ebfd5209ee32594dc5b241e2..1d9fceecf8f9e062f2f1fa6080091b64cf533849 100644 +--- a/include/gcem_incl/tgamma.hpp ++++ b/include/gcem_incl/tgamma.hpp +@@ -25,6 +25,12 @@ + #ifndef _gcem_tgamma_HPP + #define _gcem_tgamma_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -74,7 +80,13 @@ return_t + tgamma(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::tgamma_check( static_cast>(x) ); ++ } else { ++ return std::tgamma(x); ++ } ++} ++ + } + + #endif +diff --git a/include/gcem_incl/trunc.hpp b/include/gcem_incl/trunc.hpp +index af3f448915f0f9a1b5f2d843596331f7874a6da5..f7a31ce7271339626127d6ca80dfb936fe53cc03 100644 +--- a/include/gcem_incl/trunc.hpp ++++ b/include/gcem_incl/trunc.hpp +@@ -21,6 +21,12 @@ + #ifndef _gcem_trunc_HPP + #define _gcem_trunc_HPP + ++#include ++#include ++ ++namespace gcem ++{ ++ + namespace internal + { + +@@ -115,7 +121,13 @@ return_t + trunc(const T x) + noexcept + { ++ if (std::is_constant_evaluated()) { + return internal::trunc_check( static_cast>(x) ); ++ } else { ++ return std::trunc(x); ++ } ++} ++ + } + + #endif diff --git a/upstream_utils/gcem_patches/0002-Add-hypot-x-y-z.patch b/upstream_utils/gcem_patches/0002-Add-hypot-x-y-z.patch new file mode 100644 index 00000000000..4757239d378 --- /dev/null +++ b/upstream_utils/gcem_patches/0002-Add-hypot-x-y-z.patch @@ -0,0 +1,135 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Tyler Veness +Date: Sun, 3 Dec 2023 14:03:58 -0800 +Subject: [PATCH 2/2] Add hypot(x, y, z) + +--- + include/gcem_incl/hypot.hpp | 85 +++++++++++++++++++++++++++++++++++-- + 1 file changed, 82 insertions(+), 3 deletions(-) + +diff --git a/include/gcem_incl/hypot.hpp b/include/gcem_incl/hypot.hpp +index 00e10f899ace8f0da925fa9e46fa3f79f7e83aa0..13ea80c49d374c23434c1f9859bb6474184dc420 100644 +--- a/include/gcem_incl/hypot.hpp ++++ b/include/gcem_incl/hypot.hpp +@@ -27,6 +27,7 @@ + #ifndef _gcem_hypot_HPP + #define _gcem_hypot_HPP + ++#include + #include + #include + +@@ -39,10 +40,29 @@ namespace internal + template + constexpr + T +-hypot_compute(const T x, const T ydx) ++hypot_compute(const T x, const T y) + noexcept + { +- return abs(x) * sqrt( T(1) + (ydx * ydx) ); ++ T a = std::max(abs(x), abs(y)); ++ if (a) { ++ return a * sqrt((x / a) * (x / a) + (y / a) * (y / a)); ++ } else { ++ return {}; ++ } ++} ++ ++template ++constexpr ++T ++hypot_compute(const T x, const T y, const T z) ++noexcept ++{ ++ T a = std::max({abs(x), abs(y), abs(z)}); ++ if (a) { ++ return a * sqrt((x / a) * (x / a) + (y / a) * (y / a) + (z / a) * (z / a)); ++ } else { ++ return {}; ++ } + } + + template +@@ -62,7 +82,35 @@ noexcept + GCLIM::min() > abs(y) ? \ + abs(x) : + // else +- hypot_compute(x, y/x) ); ++ hypot_compute(x, y) ); ++} ++ ++template ++constexpr ++T ++hypot_vals_check(const T x, const T y, const T z) ++noexcept ++{ ++ return( any_nan(x, y, z) ? \ ++ GCLIM::quiet_NaN() : ++ // ++ any_inf(x,y,z) ? \ ++ GCLIM::infinity() : ++ // indistinguishable from zero or one ++ GCLIM::min() > abs(x) && GCLIM::min() > abs(y) ? \ ++ abs(z) : ++ GCLIM::min() > abs(x) && GCLIM::min() > abs(z) ? \ ++ abs(y) : ++ GCLIM::min() > abs(y) && GCLIM::min() > abs(z) ? \ ++ abs(x) : ++ GCLIM::min() > abs(x) ? \ ++ hypot_vals_check(y, z) : ++ GCLIM::min() > abs(y) ? \ ++ hypot_vals_check(x, z) : ++ GCLIM::min() > abs(z) ? \ ++ hypot_vals_check(x, y) : ++ // else ++ hypot_compute(x, y, z) ); + } + + template> +@@ -74,6 +122,15 @@ noexcept + return hypot_vals_check(static_cast(x),static_cast(y)); + } + ++template> ++constexpr ++TC ++hypot_type_check(const T1 x, const T2 y, const T3 z) ++noexcept ++{ ++ return hypot_vals_check(static_cast(x),static_cast(y),static_cast(z)); ++} ++ + } + + /** +@@ -97,6 +154,28 @@ noexcept + } + } + ++/** ++ * Compile-time Pythagorean addition function ++ * ++ * @param x a real-valued input. ++ * @param y a real-valued input. ++ * @param z a real-valued input. ++ * @return Computes \f$ x \oplus y \oplus z = \sqrt{x^2 + y^2 + z^2} \f$. ++ */ ++ ++template ++constexpr ++common_return_t ++hypot(const T1 x, const T2 y, const T3 z) ++noexcept ++{ ++ if (std::is_constant_evaluated()) { ++ return internal::hypot_type_check(x,y,z); ++ } else { ++ return std::hypot(x, y, z); ++ } ++} ++ + } + + #endif diff --git a/upstream_utils/libuv_patches/0001-Revert-win-process-write-minidumps-when-sending-SIGQ.patch b/upstream_utils/libuv_patches/0001-Revert-win-process-write-minidumps-when-sending-SIGQ.patch index e09186acd10..adc2b3f221b 100644 --- a/upstream_utils/libuv_patches/0001-Revert-win-process-write-minidumps-when-sending-SIGQ.patch +++ b/upstream_utils/libuv_patches/0001-Revert-win-process-write-minidumps-when-sending-SIGQ.patch @@ -1,8 +1,8 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Fri, 14 Jul 2023 17:33:08 -0700 -Subject: [PATCH 01/10] Revert "win,process: write minidumps when sending - SIGQUIT (#3840)" +Subject: [PATCH 1/9] Revert "win,process: write minidumps when sending SIGQUIT + (#3840)" This reverts commit 748d894e82abcdfff7429cf745003e182c47f163. --- diff --git a/upstream_utils/libuv_patches/0002-Fix-missing-casts.patch b/upstream_utils/libuv_patches/0002-Fix-missing-casts.patch index de3bebd093b..917d375e5e1 100644 --- a/upstream_utils/libuv_patches/0002-Fix-missing-casts.patch +++ b/upstream_utils/libuv_patches/0002-Fix-missing-casts.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Tue, 26 Apr 2022 15:01:25 -0400 -Subject: [PATCH 02/10] Fix missing casts +Subject: [PATCH 2/9] Fix missing casts --- src/fs-poll.c | 10 ++++---- diff --git a/upstream_utils/libuv_patches/0003-Fix-warnings.patch b/upstream_utils/libuv_patches/0003-Fix-warnings.patch index 55cbb9f9ed7..1fdfff80989 100644 --- a/upstream_utils/libuv_patches/0003-Fix-warnings.patch +++ b/upstream_utils/libuv_patches/0003-Fix-warnings.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Tue, 26 Apr 2022 15:09:43 -0400 -Subject: [PATCH 03/10] Fix warnings +Subject: [PATCH 3/9] Fix warnings --- include/uv/win.h | 5 +++++ diff --git a/upstream_utils/libuv_patches/0004-Preprocessor-cleanup.patch b/upstream_utils/libuv_patches/0004-Preprocessor-cleanup.patch index d5aa3e2f1bc..2b887e649f8 100644 --- a/upstream_utils/libuv_patches/0004-Preprocessor-cleanup.patch +++ b/upstream_utils/libuv_patches/0004-Preprocessor-cleanup.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Tue, 26 Apr 2022 15:19:14 -0400 -Subject: [PATCH 04/10] Preprocessor cleanup +Subject: [PATCH 4/9] Preprocessor cleanup --- include/uv.h | 12 ------------ diff --git a/upstream_utils/libuv_patches/0005-Cleanup-problematic-language.patch b/upstream_utils/libuv_patches/0005-Cleanup-problematic-language.patch index e016c2ee1c4..fbe7efe6dfd 100644 --- a/upstream_utils/libuv_patches/0005-Cleanup-problematic-language.patch +++ b/upstream_utils/libuv_patches/0005-Cleanup-problematic-language.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Tue, 26 Apr 2022 15:24:47 -0400 -Subject: [PATCH 05/10] Cleanup problematic language +Subject: [PATCH 5/9] Cleanup problematic language --- src/unix/tty.c | 21 +++++++++++---------- diff --git a/upstream_utils/libuv_patches/0007-Fix-Win32-warning-suppression-pragma.patch b/upstream_utils/libuv_patches/0006-Fix-Win32-warning-suppression-pragma.patch similarity index 92% rename from upstream_utils/libuv_patches/0007-Fix-Win32-warning-suppression-pragma.patch rename to upstream_utils/libuv_patches/0006-Fix-Win32-warning-suppression-pragma.patch index a656ba55fa9..fe001590377 100644 --- a/upstream_utils/libuv_patches/0007-Fix-Win32-warning-suppression-pragma.patch +++ b/upstream_utils/libuv_patches/0006-Fix-Win32-warning-suppression-pragma.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Sat, 21 May 2022 22:58:06 -0700 -Subject: [PATCH 07/10] Fix Win32 warning suppression pragma +Subject: [PATCH 6/9] Fix Win32 warning suppression pragma --- src/win/util.c | 2 +- diff --git a/upstream_utils/libuv_patches/0006-Style-comments-cleanup.patch b/upstream_utils/libuv_patches/0006-Style-comments-cleanup.patch deleted file mode 100644 index 494a4099229..00000000000 --- a/upstream_utils/libuv_patches/0006-Style-comments-cleanup.patch +++ /dev/null @@ -1,73 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: PJ Reiniger -Date: Tue, 26 Apr 2022 15:28:52 -0400 -Subject: [PATCH 06/10] Style / comments cleanup - ---- - src/fs-poll.c | 1 + - src/unix/core.c | 1 + - src/uv-common.c | 1 + - src/win/process.c | 1 - - src/win/winsock.c | 1 + - 5 files changed, 4 insertions(+), 1 deletion(-) - -diff --git a/src/fs-poll.c b/src/fs-poll.c -index 5a39daed095502b2db34f23fcaf0ab04f31f96ff..1a7ca70d62c71f6eaef2b9985796cc46a6438869 100644 ---- a/src/fs-poll.c -+++ b/src/fs-poll.c -@@ -34,6 +34,7 @@ - #include - #include - -+ - struct poll_ctx { - uv_fs_poll_t* parent_handle; - int busy_polling; -diff --git a/src/unix/core.c b/src/unix/core.c -index 268fc9652f437eb0d0cda2a9e0b06b9e91eb9742..f53adc156a7c454c492abaeac29d90be436785fc 100644 ---- a/src/unix/core.c -+++ b/src/unix/core.c -@@ -575,6 +575,7 @@ int uv__accept(int sockfd) { - return peerfd; - } - -+ - #if defined(__APPLE__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wdollar-in-identifier-extension" -diff --git a/src/uv-common.c b/src/uv-common.c -index 49126e50f07bac16d198775454b731f40630d1d1..3d802cf1d629272f281d07b9ea424ec259b4377e 100644 ---- a/src/uv-common.c -+++ b/src/uv-common.c -@@ -802,6 +802,7 @@ void uv__fs_readdir_cleanup(uv_fs_t* req) { - } - } - -+ - #ifdef __clang__ - # pragma clang diagnostic push - # pragma clang diagnostic ignored "-Wvarargs" -diff --git a/src/win/process.c b/src/win/process.c -index eeb0f6a984bb0f61b956cb4b907fbfdb3b4ac7e2..69f94b913f0a4051a36690725c7f79eb3535e594 100644 ---- a/src/win/process.c -+++ b/src/win/process.c -@@ -35,7 +35,6 @@ - #include "handle-inl.h" - #include "req-inl.h" - -- - #define SIGKILL 9 - - -diff --git a/src/win/winsock.c b/src/win/winsock.c -index 7843e9f13321c32419cebaacde82d30f471e11d7..cda82bc33c2c6e3dbfa9d978b5b40476228452bd 100644 ---- a/src/win/winsock.c -+++ b/src/win/winsock.c -@@ -25,6 +25,7 @@ - #include "uv.h" - #include "internal.h" - -+ - #pragma comment(lib, "Ws2_32.lib") - - /* Whether there are any non-IFS LSPs stacked on TCP */ diff --git a/upstream_utils/libuv_patches/0008-Use-C-atomics.patch b/upstream_utils/libuv_patches/0007-Use-C-atomics.patch similarity index 98% rename from upstream_utils/libuv_patches/0008-Use-C-atomics.patch rename to upstream_utils/libuv_patches/0007-Use-C-atomics.patch index 7304fe66d21..7fea79060d0 100644 --- a/upstream_utils/libuv_patches/0008-Use-C-atomics.patch +++ b/upstream_utils/libuv_patches/0007-Use-C-atomics.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Thu, 13 Jul 2023 22:13:47 -0700 -Subject: [PATCH 08/10] Use C++ atomics +Subject: [PATCH 7/9] Use C++ atomics --- src/unix/async.c | 25 +++++++++++++------------ @@ -91,7 +91,7 @@ index 0ff2669e30a628dbb2df9e28ba14b38cf14114e5..fef4ae93343edc0341179a1c4739dcd8 continue; diff --git a/src/unix/core.c b/src/unix/core.c -index f53adc156a7c454c492abaeac29d90be436785fc..ce7fd2cdfdd53410dc694450bd56dffc26ff4792 100644 +index 268fc9652f437eb0d0cda2a9e0b06b9e91eb9742..1a52716792d2dbbb71a4ebdd2255173b7447979b 100644 --- a/src/unix/core.c +++ b/src/unix/core.c @@ -45,6 +45,7 @@ @@ -436,10 +436,10 @@ index 1bd217b5a15eed13a8349c479b53471dd36ca216..1304c6d8685cfd122cffea066dc668d1 int uv__tcsetattr(int fd, int how, const struct termios *term) { int rc; diff --git a/src/uv-common.c b/src/uv-common.c -index 3d802cf1d629272f281d07b9ea424ec259b4377e..569c6906b7e54c4af1c17564a18066b847ab7ca1 100644 +index 49126e50f07bac16d198775454b731f40630d1d1..1ce25c24d6c046f7aaeaa52dcfc4fafa5a738650 100644 --- a/src/uv-common.c +++ b/src/uv-common.c -@@ -954,7 +954,7 @@ void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) { +@@ -953,7 +953,7 @@ void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) { __attribute__((destructor)) #endif void uv_library_shutdown(void) { diff --git a/upstream_utils/libuv_patches/0009-Remove-static-from-array-indices.patch b/upstream_utils/libuv_patches/0008-Remove-static-from-array-indices.patch similarity index 97% rename from upstream_utils/libuv_patches/0009-Remove-static-from-array-indices.patch rename to upstream_utils/libuv_patches/0008-Remove-static-from-array-indices.patch index 43d6eddc1e9..0b7ab19ebf6 100644 --- a/upstream_utils/libuv_patches/0009-Remove-static-from-array-indices.patch +++ b/upstream_utils/libuv_patches/0008-Remove-static-from-array-indices.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Thu, 13 Jul 2023 23:30:58 -0700 -Subject: [PATCH 09/10] Remove static from array indices +Subject: [PATCH 8/9] Remove static from array indices --- src/unix/linux.c | 12 ++++++------ diff --git a/upstream_utils/libuv_patches/0010-Add-pragmas-for-missing-libraries-and-set-_WIN32_WIN.patch b/upstream_utils/libuv_patches/0009-Add-pragmas-for-missing-libraries-and-set-_WIN32_WIN.patch similarity index 93% rename from upstream_utils/libuv_patches/0010-Add-pragmas-for-missing-libraries-and-set-_WIN32_WIN.patch rename to upstream_utils/libuv_patches/0009-Add-pragmas-for-missing-libraries-and-set-_WIN32_WIN.patch index 17b2bfd00bd..07407f1fa1a 100644 --- a/upstream_utils/libuv_patches/0010-Add-pragmas-for-missing-libraries-and-set-_WIN32_WIN.patch +++ b/upstream_utils/libuv_patches/0009-Add-pragmas-for-missing-libraries-and-set-_WIN32_WIN.patch @@ -1,8 +1,8 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Fri, 14 Jul 2023 16:40:18 -0700 -Subject: [PATCH 10/10] Add pragmas for missing libraries and set _WIN32_WINNT - to Windows 10 +Subject: [PATCH 9/9] Add pragmas for missing libraries and set _WIN32_WINNT to + Windows 10 This makes GetSystemTimePreciseAsFileTime() available. diff --git a/upstream_utils/llvm_patches/0001-Remove-StringRef-ArrayRef-and-Optional.patch b/upstream_utils/llvm_patches/0001-Remove-StringRef-ArrayRef-and-Optional.patch index 48327f82173..229cc473b65 100644 --- a/upstream_utils/llvm_patches/0001-Remove-StringRef-ArrayRef-and-Optional.patch +++ b/upstream_utils/llvm_patches/0001-Remove-StringRef-ArrayRef-and-Optional.patch @@ -1,40 +1,40 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sat, 7 May 2022 22:09:18 -0400 -Subject: [PATCH 01/31] Remove StringRef, ArrayRef, and Optional +Subject: [PATCH 01/35] Remove StringRef, ArrayRef, and Optional --- - llvm/include/llvm/ADT/PointerUnion.h | 1 - - llvm/include/llvm/ADT/SmallSet.h | 2 +- - llvm/include/llvm/ADT/SmallString.h | 77 ++++++++++--------- - llvm/include/llvm/ADT/SmallVector.h | 7 +- - llvm/include/llvm/ADT/StringMap.h | 38 ++++----- - llvm/include/llvm/ADT/StringMapEntry.h | 20 ++--- - llvm/include/llvm/Support/Chrono.h | 10 +-- - llvm/include/llvm/Support/Compiler.h | 2 +- - llvm/include/llvm/Support/ConvertUTF.h | 31 ++++---- - llvm/include/llvm/Support/ErrorHandling.h | 9 +-- - .../llvm/Support/SmallVectorMemoryBuffer.h | 6 +- - llvm/include/llvm/Support/VersionTuple.h | 6 -- - .../llvm/Support/Windows/WindowsSupport.h | 4 +- - llvm/include/llvm/Support/raw_ostream.h | 46 ++++++----- - llvm/include/llvm/Support/xxhash.h | 16 ++-- - llvm/lib/Support/ConvertUTFWrapper.cpp | 38 ++++----- - llvm/lib/Support/ErrorHandling.cpp | 13 ++-- - llvm/lib/Support/SmallVector.cpp | 5 +- - llvm/lib/Support/StringMap.cpp | 12 +-- - llvm/lib/Support/raw_ostream.cpp | 25 +++--- - llvm/lib/Support/xxhash.cpp | 10 +-- - llvm/unittests/ADT/DenseMapTest.cpp | 29 +------ - llvm/unittests/ADT/FunctionExtrasTest.cpp | 12 +-- - llvm/unittests/ADT/HashingTest.cpp | 2 +- - llvm/unittests/ADT/SmallPtrSetTest.cpp | 1 - - llvm/unittests/ADT/SmallStringTest.cpp | 50 ++++++------ - llvm/unittests/ADT/SmallVectorTest.cpp | 30 ++------ - llvm/unittests/ADT/StringMapTest.cpp | 32 ++++---- - llvm/unittests/Support/ConvertUTFTest.cpp | 41 +++++----- - llvm/unittests/Support/xxhashTest.cpp | 4 +- - 30 files changed, 264 insertions(+), 315 deletions(-) + llvm/include/llvm/ADT/PointerUnion.h | 1 - + llvm/include/llvm/ADT/SmallSet.h | 2 +- + llvm/include/llvm/ADT/SmallString.h | 103 ++++++++++-------- + llvm/include/llvm/ADT/SmallVector.h | 7 +- + llvm/include/llvm/ADT/StringMap.h | 38 +++---- + llvm/include/llvm/ADT/StringMapEntry.h | 20 ++-- + llvm/include/llvm/Support/Chrono.h | 10 +- + llvm/include/llvm/Support/Compiler.h | 2 +- + llvm/include/llvm/Support/ConvertUTF.h | 31 +++--- + llvm/include/llvm/Support/ErrorHandling.h | 9 +- + .../llvm/Support/SmallVectorMemoryBuffer.h | 6 +- + llvm/include/llvm/Support/VersionTuple.h | 6 - + .../llvm/Support/Windows/WindowsSupport.h | 4 +- + llvm/include/llvm/Support/raw_ostream.h | 46 +++++--- + llvm/include/llvm/Support/xxhash.h | 16 +-- + llvm/lib/Support/ConvertUTFWrapper.cpp | 38 +++---- + llvm/lib/Support/ErrorHandling.cpp | 13 +-- + llvm/lib/Support/SmallVector.cpp | 5 +- + llvm/lib/Support/StringMap.cpp | 12 +- + llvm/lib/Support/raw_ostream.cpp | 25 ++--- + llvm/lib/Support/xxhash.cpp | 10 +- + llvm/unittests/ADT/DenseMapTest.cpp | 29 +---- + llvm/unittests/ADT/FunctionExtrasTest.cpp | 12 +- + llvm/unittests/ADT/HashingTest.cpp | 2 +- + llvm/unittests/ADT/SmallPtrSetTest.cpp | 1 - + llvm/unittests/ADT/SmallStringTest.cpp | 50 ++++----- + llvm/unittests/ADT/SmallVectorTest.cpp | 30 +---- + llvm/unittests/ADT/StringMapTest.cpp | 32 +++--- + llvm/unittests/Support/ConvertUTFTest.cpp | 41 ++++--- + llvm/unittests/Support/xxhashTest.cpp | 4 +- + 30 files changed, 282 insertions(+), 323 deletions(-) diff --git a/llvm/include/llvm/ADT/PointerUnion.h b/llvm/include/llvm/ADT/PointerUnion.h index 7d4ed02b622626bb8043acb57b8ce7ed97a5f949..8ac68dbc0a791b8ac0e0ca865e69024cb642aa70 100644 @@ -67,7 +67,7 @@ index a16e8ac6f07552d98250e808190b00ee270f12b3..aeee5f97799aea7e7588d7afba1e47b4 #include #include diff --git a/llvm/include/llvm/ADT/SmallString.h b/llvm/include/llvm/ADT/SmallString.h -index 0052c86fb37b82dcdf577a7acf06e3a47f54da61..4d673cc8b1c49cf8a3f19653de53881cd12662ee 100644 +index a5b9eec50c8257348743f1e32ebd9a9dabd53b25..45fbf13a43a081731186b0f41c553413b0e36e0f 100644 --- a/llvm/include/llvm/ADT/SmallString.h +++ b/llvm/include/llvm/ADT/SmallString.h @@ -15,8 +15,9 @@ @@ -141,155 +141,176 @@ index 0052c86fb37b82dcdf577a7acf06e3a47f54da61..4d673cc8b1c49cf8a3f19653de53881c std::copy(Ref.begin(), Ref.end(), this->begin() + CurrentSize); CurrentSize += Ref.size(); } -@@ -89,30 +90,30 @@ public: +@@ -89,26 +90,30 @@ public: /// Check for string equality. This is more efficient than compare() when /// the relative ordering of inequal strings isn't needed. -- bool equals(StringRef RHS) const { -+ bool equals(std::string_view RHS) const { - return str().equals(RHS); - } +- [[nodiscard]] bool equals(StringRef RHS) const { return str().equals(RHS); } ++ [[nodiscard]] bool equals(std::string_view RHS) const { ++ return str().equals(RHS); ++ } /// Check for string equality, ignoring case. -- bool equals_insensitive(StringRef RHS) const { -+ bool equals_insensitive(std::string_view RHS) const { +- [[nodiscard]] bool equals_insensitive(StringRef RHS) const { ++ [[nodiscard]] bool equals_insensitive(std::string_view RHS) const { return str().equals_insensitive(RHS); } /// compare - Compare two strings; the result is negative, zero, or positive /// if this string is lexicographically less than, equal to, or greater than /// the \p RHS. -- int compare(StringRef RHS) const { -+ int compare(std::string_view RHS) const { - return str().compare(RHS); - } +- [[nodiscard]] int compare(StringRef RHS) const { return str().compare(RHS); } ++ [[nodiscard]] int compare(std::string_view RHS) const { ++ return str().compare(RHS); ++ } /// compare_insensitive - Compare two strings, ignoring case. -- int compare_insensitive(StringRef RHS) const { -+ int compare_insensitive(std::string_view RHS) const { +- [[nodiscard]] int compare_insensitive(StringRef RHS) const { ++ [[nodiscard]] int compare_insensitive(std::string_view RHS) const { return str().compare_insensitive(RHS); } /// compare_numeric - Compare two strings, treating sequences of digits as /// numbers. -- int compare_numeric(StringRef RHS) const { -+ int compare_numeric(std::string_view RHS) const { +- [[nodiscard]] int compare_numeric(StringRef RHS) const { ++ [[nodiscard]] int compare_numeric(std::string_view RHS) const { return str().compare_numeric(RHS); } -@@ -121,12 +122,12 @@ public: +@@ -116,14 +121,14 @@ public: + /// @name String Predicates /// @{ - /// startswith - Check if this string starts with the given \p Prefix. -- bool startswith(StringRef Prefix) const { -+ bool startswith(std::string_view Prefix) const { - return str().startswith(Prefix); +- /// starts_with - Check if this string starts with the given \p Prefix. +- [[nodiscard]] bool starts_with(StringRef Prefix) const { +- return str().starts_with(Prefix); ++ /// startswith - Check if this string starts with the given \p Prefix. ++ [[nodiscard]] bool startswith(std::string_view Prefix) const { ++ return str().startswith(Prefix); } - /// endswith - Check if this string ends with the given \p Suffix. -- bool endswith(StringRef Suffix) const { -+ bool endswith(std::string_view Suffix) const { - return str().endswith(Suffix); +- /// ends_with - Check if this string ends with the given \p Suffix. +- [[nodiscard]] bool ends_with(StringRef Suffix) const { +- return str().ends_with(Suffix); ++ /// endswith - Check if this string ends with the given \p Suffix. ++ [[nodiscard]] bool endswith(std::string_view Suffix) const { ++ return str().endswith(Suffix); } -@@ -146,7 +147,7 @@ public: + /// @} +@@ -142,7 +147,7 @@ public: /// /// \returns The index of the first occurrence of \p Str, or npos if not /// found. -- size_t find(StringRef Str, size_t From = 0) const { -+ size_t find(std::string_view Str, size_t From = 0) const { +- [[nodiscard]] size_t find(StringRef Str, size_t From = 0) const { ++ [[nodiscard]] size_t find(std::string_view Str, size_t From = 0) const { return str().find(Str, From); } -@@ -154,7 +155,7 @@ public: +@@ -150,7 +155,8 @@ public: /// /// \returns The index of the last occurrence of \p C, or npos if not /// found. -- size_t rfind(char C, size_t From = StringRef::npos) const { -+ size_t rfind(char C, size_t From = std::string_view::npos) const { +- [[nodiscard]] size_t rfind(char C, size_t From = StringRef::npos) const { ++ [[nodiscard]] size_t rfind(char C, ++ size_t From = std::string_view::npos) const { return str().rfind(C, From); } -@@ -162,7 +163,7 @@ public: +@@ -158,7 +164,9 @@ public: /// /// \returns The index of the last occurrence of \p Str, or npos if not /// found. -- size_t rfind(StringRef Str) const { -+ size_t rfind(std::string_view Str) const { - return str().rfind(Str); - } +- [[nodiscard]] size_t rfind(StringRef Str) const { return str().rfind(Str); } ++ [[nodiscard]] size_t rfind(std::string_view Str) const { ++ return str().rfind(Str); ++ } -@@ -176,7 +177,7 @@ public: + /// Find the first character in the string that is \p C, or npos if not + /// found. Same as find. +@@ -170,7 +178,8 @@ public: /// not found. /// /// Complexity: O(size() + Chars.size()) -- size_t find_first_of(StringRef Chars, size_t From = 0) const { -+ size_t find_first_of(std::string_view Chars, size_t From = 0) const { +- [[nodiscard]] size_t find_first_of(StringRef Chars, size_t From = 0) const { ++ [[nodiscard]] size_t find_first_of(std::string_view Chars, ++ size_t From = 0) const { return str().find_first_of(Chars, From); } -@@ -190,13 +191,13 @@ public: +@@ -184,15 +193,15 @@ public: /// \p Chars, or npos if not found. /// /// Complexity: O(size() + Chars.size()) -- size_t find_first_not_of(StringRef Chars, size_t From = 0) const { -+ size_t find_first_not_of(std::string_view Chars, size_t From = 0) const { +- [[nodiscard]] size_t find_first_not_of(StringRef Chars, ++ [[nodiscard]] size_t find_first_not_of(std::string_view Chars, + size_t From = 0) const { return str().find_first_not_of(Chars, From); } /// Find the last character in the string that is \p C, or npos if not /// found. -- size_t find_last_of(char C, size_t From = StringRef::npos) const { -+ size_t find_last_of(char C, size_t From = std::string_view::npos) const { +- [[nodiscard]] size_t find_last_of(char C, +- size_t From = StringRef::npos) const { ++ [[nodiscard]] size_t find_last_of( ++ char C, size_t From = std::string_view::npos) const { return str().find_last_of(C, From); } -@@ -205,7 +206,7 @@ public: +@@ -200,8 +209,8 @@ public: + /// found. /// /// Complexity: O(size() + Chars.size()) - size_t find_last_of( -- StringRef Chars, size_t From = StringRef::npos) const { +- [[nodiscard]] size_t find_last_of(StringRef Chars, +- size_t From = StringRef::npos) const { ++ [[nodiscard]] size_t find_last_of( + std::string_view Chars, size_t From = std::string_view::npos) const { return str().find_last_of(Chars, From); } -@@ -220,7 +221,7 @@ public: +@@ -214,7 +223,9 @@ public: /// Return the number of non-overlapped occurrences of \p Str in the /// string. -- size_t count(StringRef Str) const { -+ size_t count(std::string_view Str) const { - return str().count(Str); - } +- [[nodiscard]] size_t count(StringRef Str) const { return str().count(Str); } ++ [[nodiscard]] size_t count(std::string_view Str) const { ++ return str().count(Str); ++ } -@@ -237,7 +238,7 @@ public: + /// @} + /// @name Substring Operations +@@ -229,8 +240,8 @@ public: /// \param N The number of characters to included in the substring. If \p N /// exceeds the number of characters remaining in the string, the string /// suffix (starting with \p Start) will be returned. -- StringRef substr(size_t Start, size_t N = StringRef::npos) const { -+ std::string_view substr(size_t Start, size_t N = std::string_view::npos) const { +- [[nodiscard]] StringRef substr(size_t Start, +- size_t N = StringRef::npos) const { ++ [[nodiscard]] std::string_view substr( ++ size_t Start, size_t N = std::string_view::npos) const { return str().substr(Start, N); } -@@ -251,14 +252,14 @@ public: +@@ -244,15 +255,15 @@ public: /// substring. If this is npos, or less than \p Start, or exceeds the /// number of characters remaining in the string, the string suffix /// (starting with \p Start) will be returned. -- StringRef slice(size_t Start, size_t End) const { -+ std::string_view slice(size_t Start, size_t End) const { +- [[nodiscard]] StringRef slice(size_t Start, size_t End) const { ++ [[nodiscard]] std::string_view slice(size_t Start, size_t End) const { return str().slice(Start, End); } // Extra methods. - /// Explicit conversion to StringRef. -- StringRef str() const { return StringRef(this->data(), this->size()); } +- [[nodiscard]] StringRef str() const { +- return StringRef(this->data(), this->size()); + /// Explicit conversion to std::string_view. -+ std::string_view str() const { return std::string_view(this->begin(), this->size()); } ++ [[nodiscard]] std::string_view str() const { ++ return std::string_view(this->begin(), this->size()); + } // TODO: Make this const, if it's safe... - const char* c_str() { -@@ -267,20 +268,20 @@ public: +@@ -262,20 +273,20 @@ public: return this->data(); } @@ -315,7 +336,7 @@ index 0052c86fb37b82dcdf577a7acf06e3a47f54da61..4d673cc8b1c49cf8a3f19653de53881c return *this; } diff --git a/llvm/include/llvm/ADT/SmallVector.h b/llvm/include/llvm/ADT/SmallVector.h -index 53a107b1574c6a35c66c7fe3c61deb2ffc84b991..4559864ed231206b098936dae4fc378bfa986371 100644 +index 09676d792dfebd88e5c8eace666b3ab0044a962e..c96fd0e4956ee6d586f85dc79623de137e781ce0 100644 --- a/llvm/include/llvm/ADT/SmallVector.h +++ b/llvm/include/llvm/ADT/SmallVector.h @@ -27,13 +27,12 @@ @@ -333,7 +354,7 @@ index 53a107b1574c6a35c66c7fe3c61deb2ffc84b991..4559864ed231206b098936dae4fc378b template class iterator_range; template -@@ -117,7 +116,7 @@ template struct SmallVectorAlignmentAndSize { +@@ -127,7 +126,7 @@ template struct SmallVectorAlignmentAndSize { }; /// This is the part of SmallVectorTemplateBase which does not depend on whether @@ -342,7 +363,7 @@ index 53a107b1574c6a35c66c7fe3c61deb2ffc84b991..4559864ed231206b098936dae4fc378b /// to avoid unnecessarily requiring T to be complete. template class SmallVectorTemplateCommon -@@ -1233,7 +1232,7 @@ public: +@@ -1242,7 +1241,7 @@ public: template ::value>> @@ -576,10 +597,10 @@ index 98b51cc1aebd59eba20076e6d8a4eebc0eebb982..388e81c361642113937f7d5680de73a5 #endif // LLVM_ADT_STRINGMAPENTRY_H diff --git a/llvm/include/llvm/Support/Chrono.h b/llvm/include/llvm/Support/Chrono.h -index 9c2bd45d2803e56ed316d8552d899d87f2fbbb07..a7dea19d9193bcff4bc6b553b80a10b2bc7b64af 100644 +index 71859af7c7e4a595140475daf356744f52d14d24..9c9ba7002310eba5113c14957f769702c61f4326 100644 --- a/llvm/include/llvm/Support/Chrono.h +++ b/llvm/include/llvm/Support/Chrono.h -@@ -70,7 +70,7 @@ raw_ostream &operator<<(raw_ostream &OS, sys::TimePoint<> TP); +@@ -91,7 +91,7 @@ raw_ostream &operator<<(raw_ostream &OS, sys::UtcTime<> TP); template <> struct format_provider> { static void format(const sys::TimePoint<> &TP, llvm::raw_ostream &OS, @@ -587,8 +608,8 @@ index 9c2bd45d2803e56ed316d8552d899d87f2fbbb07..a7dea19d9193bcff4bc6b553b80a10b2 + std::string_view Style); }; - namespace detail { -@@ -122,7 +122,7 @@ private: + template <> struct format_provider> { +@@ -148,7 +148,7 @@ private: return duration_cast>(D).count(); } @@ -597,7 +618,7 @@ index 9c2bd45d2803e56ed316d8552d899d87f2fbbb07..a7dea19d9193bcff4bc6b553b80a10b2 const Dur &D) { using namespace std::chrono; if (Style.consume_front("ns")) -@@ -140,7 +140,7 @@ private: +@@ -166,7 +166,7 @@ private: return {D.count(), detail::unit::value}; } @@ -606,7 +627,7 @@ index 9c2bd45d2803e56ed316d8552d899d87f2fbbb07..a7dea19d9193bcff4bc6b553b80a10b2 if (Style.empty()) return true; if (Style.consume_front("-")) -@@ -152,9 +152,9 @@ private: +@@ -178,9 +178,9 @@ private: } public: @@ -619,10 +640,10 @@ index 9c2bd45d2803e56ed316d8552d899d87f2fbbb07..a7dea19d9193bcff4bc6b553b80a10b2 bool show_unit = consumeShowUnit(Style); diff --git a/llvm/include/llvm/Support/Compiler.h b/llvm/include/llvm/Support/Compiler.h -index 10d5cec231a523c943c37a5464cb3943627239a9..92376629c607461061bc60597a47aed1e535af52 100644 +index 8c315d255bb772d9e3c100adbd2c07b61283219b..6789f0413d8dc94cb465b6e66506b036449ee186 100644 --- a/llvm/include/llvm/Support/Compiler.h +++ b/llvm/include/llvm/Support/Compiler.h -@@ -300,7 +300,7 @@ +@@ -319,7 +319,7 @@ #endif /// LLVM_GSL_POINTER - Apply this to non-owning classes like @@ -800,18 +821,18 @@ index f7f2d4e54e705d6f29812dc93d1fb0a3ca2dee12..b5e321b5f74ce35940649b9d1342b3cd BufferKind getBufferKind() const override { return MemoryBuffer_Malloc; } diff --git a/llvm/include/llvm/Support/VersionTuple.h b/llvm/include/llvm/Support/VersionTuple.h -index 828a6db54708dfa9a1a4b4456a92945a92ad80cb..953b40701dc934c1a356b5413c9c6c692d5f5679 100644 +index 0a4623f049d28825530bf50c8acfe85deaed96ba..e1cdce77ce8659305c99a21e01f9b3cc3481a5fd 100644 --- a/llvm/include/llvm/Support/VersionTuple.h +++ b/llvm/include/llvm/Support/VersionTuple.h -@@ -25,7 +25,6 @@ namespace llvm { - template - class HashBuilderImpl; +@@ -23,7 +23,6 @@ + namespace llvm { + template class HashBuilder; class raw_ostream; -class StringRef; /// Represents a version number in the form major[.minor[.subminor[.build]]]. class VersionTuple { -@@ -182,11 +181,6 @@ public: +@@ -180,11 +179,6 @@ public: /// Retrieve a string representation of the version number. std::string getAsString() const; @@ -846,7 +867,7 @@ index d3aacd14b2097b1e7e13c1003987c1fd52e0cf76..aabdb2f14668a990329b57f5454a0d7d template diff --git a/llvm/include/llvm/Support/raw_ostream.h b/llvm/include/llvm/Support/raw_ostream.h -index 1e01eb9ea19c4187302a91457b6d34fbe5b67584..2463f1af612a78cafafe3c0e16d496e607cdc322 100644 +index 42663a9adf2e51ae36209faf7d465094adbf0943..9345348d9ba555022b31f94299684316ffa15939 100644 --- a/llvm/include/llvm/Support/raw_ostream.h +++ b/llvm/include/llvm/Support/raw_ostream.h @@ -14,13 +14,12 @@ @@ -944,9 +965,9 @@ index 1e01eb9ea19c4187302a91457b6d34fbe5b67584..2463f1af612a78cafafe3c0e16d496e6 - raw_fd_stream(StringRef Filename, std::error_code &EC); + raw_fd_stream(std::string_view Filename, std::error_code &EC); - /// This reads the \p Size bytes into a buffer pointed by \p Ptr. - /// -@@ -693,8 +703,8 @@ public: + raw_fd_stream(int fd, bool shouldClose); + +@@ -695,8 +705,8 @@ public: void flush() = delete; @@ -957,7 +978,7 @@ index 1e01eb9ea19c4187302a91457b6d34fbe5b67584..2463f1af612a78cafafe3c0e16d496e6 void reserveExtraSpace(uint64_t ExtraSize) override { OS.reserve(tell() + ExtraSize); -@@ -751,7 +761,7 @@ class Error; +@@ -753,7 +763,7 @@ class Error; /// for other names. For raw_fd_ostream instances, the stream writes to /// a temporary file. The final output file is atomically replaced with the /// temporary file after the \p Write function is finished. @@ -1178,7 +1199,7 @@ index b8b3b7424ac6b1de782e739782f9671194ce77a1..0aa13a0f78eb370b2a673ca4a773f268 (void)written; // If something went wrong, we deliberately just give up. } diff --git a/llvm/lib/Support/SmallVector.cpp b/llvm/lib/Support/SmallVector.cpp -index f7e7e80332cc337f6dfa388d1e218e6f3ec95cf2..6cefdff7c28060ca18b522acf5279af3a206e23a 100644 +index b6ce37842040b36fc79770ca0296255f2bb42a1a..4f6fee18b659adcbfd79822832f914170cbb1635 100644 --- a/llvm/lib/Support/SmallVector.cpp +++ b/llvm/lib/Support/SmallVector.cpp @@ -11,7 +11,6 @@ @@ -1265,10 +1286,10 @@ index 67c05a87959cf0c243d17646ae2f28f6c9f0d708..7be219323f6d76f32a9a841115f2f146 if (Bucket == -1) return nullptr; diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp -index a4fc605019c211f93dde009e89e7a79b07400aa3..9966a0056ae4f24a7a38346ee1c2f5d83ac20248 100644 +index 3d3a564af51d120786b358b96a3c90e2b7fbf9f3..220d850b9bc69f8fc2fba7cd23629eca487cde23 100644 --- a/llvm/lib/Support/raw_ostream.cpp +++ b/llvm/lib/Support/raw_ostream.cpp -@@ -166,7 +166,7 @@ raw_ostream &raw_ostream::write_uuid(const uuid_t UUID) { +@@ -167,7 +167,7 @@ raw_ostream &raw_ostream::write_uuid(const uuid_t UUID) { } @@ -1277,7 +1298,7 @@ index a4fc605019c211f93dde009e89e7a79b07400aa3..9966a0056ae4f24a7a38346ee1c2f5d8 bool UseHexEscapes) { for (unsigned char c : Str) { switch (c) { -@@ -569,7 +569,7 @@ void format_object_base::home() { +@@ -570,7 +570,7 @@ void format_object_base::home() { // raw_fd_ostream //===----------------------------------------------------------------------===// @@ -1286,7 +1307,7 @@ index a4fc605019c211f93dde009e89e7a79b07400aa3..9966a0056ae4f24a7a38346ee1c2f5d8 sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access, sys::fs::OpenFlags Flags) { assert((Access & sys::fs::FA_Write) && -@@ -595,25 +595,25 @@ static int getFD(StringRef Filename, std::error_code &EC, +@@ -596,25 +596,25 @@ static int getFD(StringRef Filename, std::error_code &EC, return FD; } @@ -1317,7 +1338,7 @@ index a4fc605019c211f93dde009e89e7a79b07400aa3..9966a0056ae4f24a7a38346ee1c2f5d8 sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access, sys::fs::OpenFlags Flags) -@@ -685,8 +685,7 @@ raw_fd_ostream::~raw_fd_ostream() { +@@ -686,8 +686,7 @@ raw_fd_ostream::~raw_fd_ostream() { // has_error() and clear the error flag with clear_error() before // destructing raw_ostream objects which may have errors. if (has_error()) @@ -1327,7 +1348,7 @@ index a4fc605019c211f93dde009e89e7a79b07400aa3..9966a0056ae4f24a7a38346ee1c2f5d8 /*gen_crash_diag=*/false); } -@@ -705,7 +704,7 @@ raw_fd_ostream::~raw_fd_ostream() { +@@ -706,7 +705,7 @@ raw_fd_ostream::~raw_fd_ostream() { // the input is UTF-8 or transcode from the local codepage to UTF-8 before // quoting it. If they don't, this may mess up the encoding, but this is still // probably the best compromise we can make. @@ -1336,7 +1357,7 @@ index a4fc605019c211f93dde009e89e7a79b07400aa3..9966a0056ae4f24a7a38346ee1c2f5d8 SmallVector WideText; // Fall back to ::write if it wasn't valid UTF-8. -@@ -748,7 +747,7 @@ void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) { +@@ -749,7 +748,7 @@ void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) { // If this is a Windows console device, try re-encoding from UTF-8 to UTF-16 // and using WriteConsoleW. If that fails, fall back to plain write(). if (IsWindowsConsole) @@ -1345,7 +1366,7 @@ index a4fc605019c211f93dde009e89e7a79b07400aa3..9966a0056ae4f24a7a38346ee1c2f5d8 return; #endif -@@ -919,7 +918,7 @@ raw_ostream &llvm::nulls() { +@@ -925,7 +924,7 @@ raw_ostream &llvm::nulls() { // File Streams //===----------------------------------------------------------------------===// @@ -1354,7 +1375,7 @@ index a4fc605019c211f93dde009e89e7a79b07400aa3..9966a0056ae4f24a7a38346ee1c2f5d8 : raw_fd_ostream(getFD(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write | sys::fs::FA_Read, sys::fs::OF_None), -@@ -997,7 +996,7 @@ void buffer_ostream::anchor() {} +@@ -998,7 +997,7 @@ void buffer_ostream::anchor() {} void buffer_unique_ostream::anchor() {} @@ -1493,7 +1514,7 @@ index fc856a976946bf6decda9b6724cac66afc7bdcd6..aff9d61c7f0d48834123b04b74a2e4f7 TEST(UniqueFunctionTest, SFINAE) { EXPECT_EQ("not a function", returns("boo!")); diff --git a/llvm/unittests/ADT/HashingTest.cpp b/llvm/unittests/ADT/HashingTest.cpp -index 01a8a962b8e2e33ca8f189c049e9548ced42ec3a..62aff9c3b21eea785ca71c6e290c9c4f3a20ae00 100644 +index ab13ee833ce556945fb9526fd13d8bd5f3e5c95a..3e80467ebd0efddcf2cbbe003bb91f1475ca9cb3 100644 --- a/llvm/unittests/ADT/HashingTest.cpp +++ b/llvm/unittests/ADT/HashingTest.cpp @@ -295,7 +295,7 @@ TEST(HashingTest, HashCombineRangeGoldenTest) { diff --git a/upstream_utils/llvm_patches/0002-Wrap-std-min-max-calls-in-parens-for-Windows-warning.patch b/upstream_utils/llvm_patches/0002-Wrap-std-min-max-calls-in-parens-for-Windows-warning.patch index fe5c48ef497..8adb0bccb35 100644 --- a/upstream_utils/llvm_patches/0002-Wrap-std-min-max-calls-in-parens-for-Windows-warning.patch +++ b/upstream_utils/llvm_patches/0002-Wrap-std-min-max-calls-in-parens-for-Windows-warning.patch @@ -1,14 +1,14 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sat, 7 May 2022 22:12:41 -0400 -Subject: [PATCH 02/31] Wrap std::min/max calls in parens, for Windows warnings +Subject: [PATCH 02/35] Wrap std::min/max calls in parens, for Windows warnings --- llvm/include/llvm/ADT/DenseMap.h | 4 ++-- - llvm/include/llvm/ADT/SmallVector.h | 12 ++++++------ + llvm/include/llvm/ADT/SmallVector.h | 6 +++--- llvm/include/llvm/Support/ConvertUTF.h | 2 +- llvm/include/llvm/Support/MathExtras.h | 18 +++++++++--------- - 4 files changed, 18 insertions(+), 18 deletions(-) + 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/llvm/include/llvm/ADT/DenseMap.h b/llvm/include/llvm/ADT/DenseMap.h index 3ef6a7cd1b4b587e61fcb9475d9f3516018bf2ee..108193f04486425f3b7f039cd9d2004be6facafb 100644 @@ -33,10 +33,10 @@ index 3ef6a7cd1b4b587e61fcb9475d9f3516018bf2ee..108193f04486425f3b7f039cd9d2004b this->BaseT::initEmpty(); return; diff --git a/llvm/include/llvm/ADT/SmallVector.h b/llvm/include/llvm/ADT/SmallVector.h -index 4559864ed231206b098936dae4fc378bfa986371..84f4d0931a30f4be29549354c85cb4c0489e14c9 100644 +index c96fd0e4956ee6d586f85dc79623de137e781ce0..d7600fe209a58deb07c63e2553f9dad62e06e973 100644 --- a/llvm/include/llvm/ADT/SmallVector.h +++ b/llvm/include/llvm/ADT/SmallVector.h -@@ -55,12 +55,12 @@ protected: +@@ -55,7 +55,7 @@ protected: /// The maximum value of the Size_T used. static constexpr size_t SizeTypeMax() { @@ -45,22 +45,7 @@ index 4559864ed231206b098936dae4fc378bfa986371..84f4d0931a30f4be29549354c85cb4c0 } SmallVectorBase() = delete; - SmallVectorBase(void *FirstEl, size_t TotalCapacity) -- : BeginX(FirstEl), Capacity(TotalCapacity) {} -+ : BeginX(FirstEl), Capacity(static_cast(TotalCapacity)) {} - - /// This is a helper for \a grow() that's out of line to reduce code - /// duplication. This function will report a fatal error if it can't grow at -@@ -99,7 +99,7 @@ protected: - /// This does not construct or destroy any elements in the vector. - void set_size(size_t N) { - assert(N <= capacity()); -- Size = N; -+ Size = static_cast(N); - } - }; - -@@ -279,7 +279,7 @@ public: +@@ -289,7 +289,7 @@ public: size_type size_in_bytes() const { return size() * sizeof(T); } size_type max_size() const { @@ -69,16 +54,7 @@ index 4559864ed231206b098936dae4fc378bfa986371..84f4d0931a30f4be29549354c85cb4c0 } size_t capacity_in_bytes() const { return capacity() * sizeof(T); } -@@ -467,7 +467,7 @@ void SmallVectorTemplateBase::takeAllocationForGrow( - free(this->begin()); - - this->BeginX = NewElts; -- this->Capacity = NewCapacity; -+ this->Capacity = static_cast(NewCapacity); - } - - /// SmallVectorTemplateBase - This is where we put -@@ -712,7 +712,7 @@ public: +@@ -721,7 +721,7 @@ public: } // Assign over existing elements. @@ -101,7 +77,7 @@ index 5c0e3009c25446a34882fb98329b1d955231bb39..72321022beb373945f7935ed72944fd6 /* Some fundamental constants */ #define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD diff --git a/llvm/include/llvm/Support/MathExtras.h b/llvm/include/llvm/Support/MathExtras.h -index dc095941fdc8a9f2b3b822e6e014f0640676c0d3..0bd572d07fcbf2ff56998dbf366215068b62f527 100644 +index aa4f4d2ed42e262f27e3f7f5ce275baf7e556c2d..5cabfdd6493fee33fbc74b831dc1fa3c91ba725d 100644 --- a/llvm/include/llvm/Support/MathExtras.h +++ b/llvm/include/llvm/Support/MathExtras.h @@ -311,26 +311,26 @@ template <> constexpr inline size_t CTLog2<1>() { return 0; } @@ -135,7 +111,7 @@ index dc095941fdc8a9f2b3b822e6e014f0640676c0d3..0bd572d07fcbf2ff56998dbf36621506 } /// A and B are either alignments or offsets. Return the minimum alignment that -@@ -479,7 +479,7 @@ SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) { +@@ -482,7 +482,7 @@ SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) { T Z = X + Y; Overflowed = (Z < X || Z < Y); if (Overflowed) @@ -144,7 +120,7 @@ index dc095941fdc8a9f2b3b822e6e014f0640676c0d3..0bd572d07fcbf2ff56998dbf36621506 else return Z; } -@@ -492,7 +492,7 @@ std::enable_if_t, T> SaturatingAdd(T X, T Y, T Z, +@@ -495,7 +495,7 @@ std::enable_if_t, T> SaturatingAdd(T X, T Y, T Z, bool Overflowed = false; T XY = SaturatingAdd(X, Y, &Overflowed); if (Overflowed) @@ -153,7 +129,7 @@ index dc095941fdc8a9f2b3b822e6e014f0640676c0d3..0bd572d07fcbf2ff56998dbf36621506 return SaturatingAdd(XY, Z, Args...); } -@@ -516,7 +516,7 @@ SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) { +@@ -519,7 +519,7 @@ SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) { // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z // will necessarily be less than Log2Max as desired. int Log2Z = Log2_64(X) + Log2_64(Y); @@ -162,7 +138,7 @@ index dc095941fdc8a9f2b3b822e6e014f0640676c0d3..0bd572d07fcbf2ff56998dbf36621506 int Log2Max = Log2_64(Max); if (Log2Z < Log2Max) { return X * Y; -@@ -636,9 +636,9 @@ std::enable_if_t, T> MulOverflow(T X, T Y, T &Result) { +@@ -639,9 +639,9 @@ std::enable_if_t, T> MulOverflow(T X, T Y, T &Result) { // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for // positive) divided by an argument compares to the other. if (IsNegative) diff --git a/upstream_utils/llvm_patches/0003-Change-unique_function-storage-size.patch b/upstream_utils/llvm_patches/0003-Change-unique_function-storage-size.patch index c4e5176663b..8c8ede4797b 100644 --- a/upstream_utils/llvm_patches/0003-Change-unique_function-storage-size.patch +++ b/upstream_utils/llvm_patches/0003-Change-unique_function-storage-size.patch @@ -1,17 +1,17 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sat, 7 May 2022 22:13:55 -0400 -Subject: [PATCH 03/31] Change unique_function storage size +Subject: [PATCH 03/35] Change unique_function storage size --- llvm/include/llvm/ADT/FunctionExtras.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/llvm/include/llvm/ADT/FunctionExtras.h b/llvm/include/llvm/ADT/FunctionExtras.h -index 4cf1de488c7bde2692d4878ccb4c4d60241e3a66..9d10b16e3cbe9c0df818a3254fcd3a6032d54b39 100644 +index c0bc30c7450fe4b2bc6b9b448824eedc8b132e52..5641a913d0a35ee2911cf872ad90c3dc864f20f5 100644 --- a/llvm/include/llvm/ADT/FunctionExtras.h +++ b/llvm/include/llvm/ADT/FunctionExtras.h -@@ -78,7 +78,7 @@ using EnableIfCallable = std::enable_if_t class UniqueFunctionBase { protected: @@ -20,7 +20,7 @@ index 4cf1de488c7bde2692d4878ccb4c4d60241e3a66..9d10b16e3cbe9c0df818a3254fcd3a60 template struct IsSizeLessThanThresholdT : std::false_type {}; -@@ -157,7 +157,7 @@ protected: +@@ -158,7 +158,7 @@ protected: "Should always use all of the out-of-line storage for inline storage!"); // For in-line storage, we just provide an aligned character buffer. We diff --git a/upstream_utils/llvm_patches/0004-Threading-updates.patch b/upstream_utils/llvm_patches/0004-Threading-updates.patch index 98c1d8ad735..4e4c5196005 100644 --- a/upstream_utils/llvm_patches/0004-Threading-updates.patch +++ b/upstream_utils/llvm_patches/0004-Threading-updates.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sat, 7 May 2022 22:17:19 -0400 -Subject: [PATCH 04/31] Threading updates +Subject: [PATCH 04/35] Threading updates - Remove guards for threads and exception - Prefer scope gaurd over lock gaurd @@ -12,10 +12,10 @@ Subject: [PATCH 04/31] Threading updates 3 files changed, 11 insertions(+), 43 deletions(-) diff --git a/llvm/include/llvm/Support/Compiler.h b/llvm/include/llvm/Support/Compiler.h -index 92376629c607461061bc60597a47aed1e535af52..2662839b27bf368cd5da0668099c4b44cbc6435d 100644 +index 6789f0413d8dc94cb465b6e66506b036449ee186..e608f8ea3a837a04d9c29c8bb7a1fab527d512bb 100644 --- a/llvm/include/llvm/Support/Compiler.h +++ b/llvm/include/llvm/Support/Compiler.h -@@ -530,7 +530,6 @@ void AnnotateIgnoreWritesEnd(const char *file, int line); +@@ -555,7 +555,6 @@ void AnnotateIgnoreWritesEnd(const char *file, int line); /// initialize to some constant value. In almost all circumstances this is most /// appropriate for use with a pointer, integer, or small aggregation of /// pointers and integers. @@ -23,7 +23,7 @@ index 92376629c607461061bc60597a47aed1e535af52..2662839b27bf368cd5da0668099c4b44 #if __has_feature(cxx_thread_local) || defined(_MSC_VER) #define LLVM_THREAD_LOCAL thread_local #else -@@ -538,11 +537,6 @@ void AnnotateIgnoreWritesEnd(const char *file, int line); +@@ -563,11 +562,6 @@ void AnnotateIgnoreWritesEnd(const char *file, int line); // we only need the restricted functionality that provides. #define LLVM_THREAD_LOCAL __thread #endif diff --git a/upstream_utils/llvm_patches/0005-ifdef-guard-safety.patch b/upstream_utils/llvm_patches/0005-ifdef-guard-safety.patch index e74cf17593e..803403be992 100644 --- a/upstream_utils/llvm_patches/0005-ifdef-guard-safety.patch +++ b/upstream_utils/llvm_patches/0005-ifdef-guard-safety.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sat, 7 May 2022 22:28:13 -0400 -Subject: [PATCH 05/31] \#ifdef guard safety +Subject: [PATCH 05/35] \#ifdef guard safety Prevents redefinition if someone is pulling in real LLVM, since the macros are in global namespace --- @@ -9,7 +9,7 @@ Prevents redefinition if someone is pulling in real LLVM, since the macros are i 1 file changed, 42 insertions(+) diff --git a/llvm/include/llvm/Support/Compiler.h b/llvm/include/llvm/Support/Compiler.h -index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e848519998685b 100644 +index e608f8ea3a837a04d9c29c8bb7a1fab527d512bb..8f68d79898fe0247f9e17709bf1c1ec2a451c037 100644 --- a/llvm/include/llvm/Support/Compiler.h +++ b/llvm/include/llvm/Support/Compiler.h @@ -90,6 +90,7 @@ @@ -50,7 +50,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #if defined(__clang__) #define LLVM_DEPRECATED(MSG, FIX) __attribute__((deprecated(MSG, FIX))) -@@ -178,11 +184,13 @@ +@@ -197,11 +203,13 @@ // more portable solution: // (void)unused_var_name; // Prefer cast-to-void wherever it is sufficient. @@ -64,7 +64,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 // FIXME: Provide this for PE/COFF targets. #if __has_attribute(weak) && !defined(__MINGW32__) && !defined(__CYGWIN__) && \ -@@ -192,6 +200,7 @@ +@@ -211,6 +219,7 @@ #define LLVM_ATTRIBUTE_WEAK #endif @@ -72,7 +72,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 // Prior to clang 3.2, clang did not accept any spelling of // __has_attribute(const), so assume it is supported. #if defined(__clang__) || defined(__GNUC__) -@@ -200,13 +209,16 @@ +@@ -219,13 +228,16 @@ #else #define LLVM_READNONE #endif @@ -89,7 +89,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #if __has_attribute(minsize) #define LLVM_ATTRIBUTE_MINSIZE __attribute__((minsize)) -@@ -214,6 +226,7 @@ +@@ -233,6 +245,7 @@ #define LLVM_ATTRIBUTE_MINSIZE #endif @@ -97,7 +97,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #if __has_builtin(__builtin_expect) || defined(__GNUC__) #define LLVM_LIKELY(EXPR) __builtin_expect((bool)(EXPR), true) #define LLVM_UNLIKELY(EXPR) __builtin_expect((bool)(EXPR), false) -@@ -221,9 +234,11 @@ +@@ -240,9 +253,11 @@ #define LLVM_LIKELY(EXPR) (EXPR) #define LLVM_UNLIKELY(EXPR) (EXPR) #endif @@ -109,7 +109,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #if __has_attribute(noinline) #define LLVM_ATTRIBUTE_NOINLINE __attribute__((noinline)) #elif defined(_MSC_VER) -@@ -231,9 +246,11 @@ +@@ -250,9 +265,11 @@ #else #define LLVM_ATTRIBUTE_NOINLINE #endif @@ -121,7 +121,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #if __has_attribute(always_inline) #define LLVM_ATTRIBUTE_ALWAYS_INLINE inline __attribute__((always_inline)) #elif defined(_MSC_VER) -@@ -241,6 +258,7 @@ +@@ -260,6 +277,7 @@ #else #define LLVM_ATTRIBUTE_ALWAYS_INLINE inline #endif @@ -129,7 +129,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 /// LLVM_ATTRIBUTE_NO_DEBUG - On compilers where we have a directive to do /// so, mark a method "no debug" because debug info makes the debugger -@@ -251,6 +269,7 @@ +@@ -270,6 +288,7 @@ #define LLVM_ATTRIBUTE_NODEBUG #endif @@ -137,7 +137,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #if __has_attribute(returns_nonnull) #define LLVM_ATTRIBUTE_RETURNS_NONNULL __attribute__((returns_nonnull)) #elif defined(_MSC_VER) -@@ -258,9 +277,11 @@ +@@ -277,9 +296,11 @@ #else #define LLVM_ATTRIBUTE_RETURNS_NONNULL #endif @@ -149,7 +149,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #ifdef __GNUC__ #define LLVM_ATTRIBUTE_RETURNS_NOALIAS __attribute__((__malloc__)) #elif defined(_MSC_VER) -@@ -268,8 +289,10 @@ +@@ -287,8 +308,10 @@ #else #define LLVM_ATTRIBUTE_RETURNS_NOALIAS #endif @@ -160,7 +160,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #if defined(__cplusplus) && __cplusplus > 201402L && LLVM_HAS_CPP_ATTRIBUTE(fallthrough) #define LLVM_FALLTHROUGH [[fallthrough]] #elif LLVM_HAS_CPP_ATTRIBUTE(gnu::fallthrough) -@@ -281,6 +304,7 @@ +@@ -300,6 +323,7 @@ #else #define LLVM_FALLTHROUGH #endif @@ -168,7 +168,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 /// LLVM_REQUIRE_CONSTANT_INITIALIZATION - Apply this to globals to ensure that /// they are constant initialized. -@@ -309,11 +333,13 @@ +@@ -334,11 +358,13 @@ /// LLVM_EXTENSION - Support compilers where we have a keyword to suppress /// pedantic diagnostics. @@ -182,7 +182,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 /// LLVM_BUILTIN_UNREACHABLE - On compilers which support it, expands /// to an expression which states that it is undefined behavior for the -@@ -322,14 +348,17 @@ +@@ -347,14 +373,17 @@ /// '#else' is intentionally left out so that other macro logic (e.g., /// LLVM_ASSUME_ALIGNED and llvm_unreachable()) can detect whether /// LLVM_BUILTIN_UNREACHABLE has a definition. @@ -200,7 +200,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #if __has_builtin(__builtin_trap) || defined(__GNUC__) # define LLVM_BUILTIN_TRAP __builtin_trap() #elif defined(_MSC_VER) -@@ -341,10 +370,12 @@ +@@ -366,10 +395,12 @@ #else # define LLVM_BUILTIN_TRAP *(volatile int*)0x11 = 0 #endif @@ -213,7 +213,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #if __has_builtin(__builtin_debugtrap) # define LLVM_BUILTIN_DEBUGTRAP __builtin_debugtrap() #elif defined(_MSC_VER) -@@ -358,9 +389,11 @@ +@@ -383,9 +414,11 @@ // program to abort if encountered. # define LLVM_BUILTIN_DEBUGTRAP #endif @@ -225,7 +225,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #if __has_builtin(__builtin_assume_aligned) || defined(__GNUC__) # define LLVM_ASSUME_ALIGNED(p, a) __builtin_assume_aligned(p, a) #elif defined(LLVM_BUILTIN_UNREACHABLE) -@@ -369,6 +402,7 @@ +@@ -394,6 +427,7 @@ #else # define LLVM_ASSUME_ALIGNED(p, a) (p) #endif @@ -233,7 +233,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 /// \macro LLVM_PACKED /// Used to specify a packed structure. -@@ -388,6 +422,7 @@ +@@ -413,6 +447,7 @@ /// long long l; /// }; /// LLVM_PACKED_END @@ -241,7 +241,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #ifdef _MSC_VER # define LLVM_PACKED(d) __pragma(pack(push, 1)) d __pragma(pack(pop)) # define LLVM_PACKED_START __pragma(pack(push, 1)) -@@ -397,6 +432,7 @@ +@@ -422,6 +457,7 @@ # define LLVM_PACKED_START _Pragma("pack(push, 1)") # define LLVM_PACKED_END _Pragma("pack(pop)") #endif @@ -249,7 +249,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 /// \macro LLVM_MEMORY_SANITIZER_BUILD /// Whether LLVM itself is built with MemorySanitizer instrumentation. -@@ -488,11 +524,13 @@ void AnnotateIgnoreWritesEnd(const char *file, int line); +@@ -513,11 +549,13 @@ void AnnotateIgnoreWritesEnd(const char *file, int line); /// \macro LLVM_NO_SANITIZE /// Disable a particular sanitizer for a function. @@ -263,7 +263,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 /// Mark debug helper function definitions like dump() that should not be /// stripped from debug builds. -@@ -500,17 +538,20 @@ void AnnotateIgnoreWritesEnd(const char *file, int line); +@@ -525,17 +563,20 @@ void AnnotateIgnoreWritesEnd(const char *file, int line); /// `#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)` so they do always /// get stripped in release builds. // FIXME: Move this to a private config.h as it's not usable in public headers. @@ -284,7 +284,7 @@ index 2662839b27bf368cd5da0668099c4b44cbc6435d..ce75702c8c6f99780ecdb6dc77e84851 #if defined(_MSC_VER) #define LLVM_PRETTY_FUNCTION __FUNCSIG__ #elif defined(__GNUC__) || defined(__clang__) -@@ -518,6 +559,7 @@ void AnnotateIgnoreWritesEnd(const char *file, int line); +@@ -543,6 +584,7 @@ void AnnotateIgnoreWritesEnd(const char *file, int line); #else #define LLVM_PRETTY_FUNCTION __func__ #endif diff --git a/upstream_utils/llvm_patches/0006-Explicitly-use-std.patch b/upstream_utils/llvm_patches/0006-Explicitly-use-std.patch index 0d841d95c74..a7515301b3d 100644 --- a/upstream_utils/llvm_patches/0006-Explicitly-use-std.patch +++ b/upstream_utils/llvm_patches/0006-Explicitly-use-std.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sat, 7 May 2022 22:37:34 -0400 -Subject: [PATCH 06/31] Explicitly use std:: +Subject: [PATCH 06/35] Explicitly use std:: --- llvm/include/llvm/ADT/SmallSet.h | 2 +- diff --git a/upstream_utils/llvm_patches/0007-Remove-format_provider.patch b/upstream_utils/llvm_patches/0007-Remove-format_provider.patch index 6495bb95935..1219cc018be 100644 --- a/upstream_utils/llvm_patches/0007-Remove-format_provider.patch +++ b/upstream_utils/llvm_patches/0007-Remove-format_provider.patch @@ -1,16 +1,16 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sat, 7 May 2022 22:53:50 -0400 -Subject: [PATCH 07/31] Remove format_provider +Subject: [PATCH 07/35] Remove format_provider --- - llvm/include/llvm/Support/Chrono.h | 109 ------------------------ + llvm/include/llvm/Support/Chrono.h | 114 ------------------------ llvm/include/llvm/Support/raw_ostream.h | 6 -- - llvm/unittests/Support/Chrono.cpp | 67 --------------- - 3 files changed, 182 deletions(-) + llvm/unittests/Support/Chrono.cpp | 67 -------------- + 3 files changed, 187 deletions(-) diff --git a/llvm/include/llvm/Support/Chrono.h b/llvm/include/llvm/Support/Chrono.h -index a7dea19d9193bcff4bc6b553b80a10b2bc7b64af..9f9a2b5cab270327898cee3f97d9ae7cf77eb564 100644 +index 9c9ba7002310eba5113c14957f769702c61f4326..b269ff8bb5db7bb3c62c3a87daf255b18ece4cd7 100644 --- a/llvm/include/llvm/Support/Chrono.h +++ b/llvm/include/llvm/Support/Chrono.h @@ -10,7 +10,6 @@ @@ -21,9 +21,9 @@ index a7dea19d9193bcff4bc6b553b80a10b2bc7b64af..9f9a2b5cab270327898cee3f97d9ae7c #include #include -@@ -59,114 +58,6 @@ toTimePoint(std::time_t T, uint32_t nsec) { - +@@ -80,119 +79,6 @@ toTimePoint(std::time_t T, uint32_t nsec) { raw_ostream &operator<<(raw_ostream &OS, sys::TimePoint<> TP); + raw_ostream &operator<<(raw_ostream &OS, sys::UtcTime<> TP); -/// Format provider for TimePoint<> -/// @@ -39,6 +39,11 @@ index a7dea19d9193bcff4bc6b553b80a10b2bc7b64af..9f9a2b5cab270327898cee3f97d9ae7c - std::string_view Style); -}; - +-template <> struct format_provider> { +- static void format(const sys::UtcTime &TP, +- llvm::raw_ostream &OS, StringRef Style); +-}; +- -namespace detail { -template struct unit { static const char value[]; }; -template const char unit::value[] = ""; @@ -137,7 +142,7 @@ index a7dea19d9193bcff4bc6b553b80a10b2bc7b64af..9f9a2b5cab270327898cee3f97d9ae7c #endif // LLVM_SUPPORT_CHRONO_H diff --git a/llvm/include/llvm/Support/raw_ostream.h b/llvm/include/llvm/Support/raw_ostream.h -index 2463f1af612a78cafafe3c0e16d496e607cdc322..5d08596b4cf6bf9e9b8e2c2c1aef731bb8832da5 100644 +index 9345348d9ba555022b31f94299684316ffa15939..862a1db876e9b8467a8839dae8f6632f18d5e7a0 100644 --- a/llvm/include/llvm/Support/raw_ostream.h +++ b/llvm/include/llvm/Support/raw_ostream.h @@ -27,12 +27,6 @@ @@ -154,10 +159,10 @@ index 2463f1af612a78cafafe3c0e16d496e607cdc322..5d08596b4cf6bf9e9b8e2c2c1aef731b namespace sys { diff --git a/llvm/unittests/Support/Chrono.cpp b/llvm/unittests/Support/Chrono.cpp -index daf8a8a350f08c748ba05af44f43f3faca8e2c61..3c049de18c0a80465f4b0a8c054df2602d5e9b1c 100644 +index 7dfc5dd2c29348ea8df9ce87c80f357aaad1a73b..a4d166d435d6d679f773dcf3eab985f0631e12d2 100644 --- a/llvm/unittests/Support/Chrono.cpp +++ b/llvm/unittests/Support/Chrono.cpp -@@ -30,43 +30,6 @@ TEST(Chrono, TimeTConversion) { +@@ -29,43 +29,6 @@ TEST(Chrono, TimeTConversion) { EXPECT_EQ(TP, toTimePoint(toTimeT(TP))); } @@ -201,7 +206,7 @@ index daf8a8a350f08c748ba05af44f43f3faca8e2c61..3c049de18c0a80465f4b0a8c054df260 // Test that toTimePoint and toTimeT can be called with a arguments with varying // precisions. TEST(Chrono, ImplicitConversions) { -@@ -84,34 +47,4 @@ TEST(Chrono, ImplicitConversions) { +@@ -83,34 +46,4 @@ TEST(Chrono, ImplicitConversions) { EXPECT_EQ(TimeT, toTimeT(Nano)); } diff --git a/upstream_utils/llvm_patches/0008-Add-compiler-warning-pragmas.patch b/upstream_utils/llvm_patches/0008-Add-compiler-warning-pragmas.patch index 15442f172fc..c0e51d0ea96 100644 --- a/upstream_utils/llvm_patches/0008-Add-compiler-warning-pragmas.patch +++ b/upstream_utils/llvm_patches/0008-Add-compiler-warning-pragmas.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sun, 8 May 2022 13:34:07 -0400 -Subject: [PATCH 08/31] Add compiler warning pragmas +Subject: [PATCH 08/35] Add compiler warning pragmas --- llvm/include/llvm/ADT/FunctionExtras.h | 11 +++++++++++ @@ -17,10 +17,10 @@ Subject: [PATCH 08/31] Add compiler warning pragmas 10 files changed, 72 insertions(+), 4 deletions(-) diff --git a/llvm/include/llvm/ADT/FunctionExtras.h b/llvm/include/llvm/ADT/FunctionExtras.h -index 9d10b16e3cbe9c0df818a3254fcd3a6032d54b39..1daeae915eb506b32a2d1296d2f0fe4e6dab606e 100644 +index 5641a913d0a35ee2911cf872ad90c3dc864f20f5..043d8d90fff03d571a923c264b49be37a5dffa09 100644 --- a/llvm/include/llvm/ADT/FunctionExtras.h +++ b/llvm/include/llvm/ADT/FunctionExtras.h -@@ -55,6 +55,13 @@ namespace llvm { +@@ -56,6 +56,13 @@ namespace llvm { /// It can hold functions with a non-const operator(), like mutable lambdas. template class unique_function; @@ -34,7 +34,7 @@ index 9d10b16e3cbe9c0df818a3254fcd3a6032d54b39..1daeae915eb506b32a2d1296d2f0fe4e namespace detail { template -@@ -409,6 +416,10 @@ public: +@@ -412,6 +419,10 @@ public: } }; @@ -46,7 +46,7 @@ index 9d10b16e3cbe9c0df818a3254fcd3a6032d54b39..1daeae915eb506b32a2d1296d2f0fe4e #endif // LLVM_ADT_FUNCTIONEXTRAS_H diff --git a/llvm/include/llvm/ADT/Hashing.h b/llvm/include/llvm/ADT/Hashing.h -index ef983105c7bae67bb2ef832e4473939a0406e0df..781bdb7416392e3f60a1ac3a38fbcf5324b5395f 100644 +index a5477362a50793985e1e9df9dc77c8a1d5b5846b..08d6edb14eb3cd51405329aae61b9782266a2590 100644 --- a/llvm/include/llvm/ADT/Hashing.h +++ b/llvm/include/llvm/ADT/Hashing.h @@ -56,6 +56,11 @@ @@ -61,9 +61,9 @@ index ef983105c7bae67bb2ef832e4473939a0406e0df..781bdb7416392e3f60a1ac3a38fbcf53 namespace llvm { template struct DenseMapInfo; -@@ -683,4 +688,8 @@ template <> struct DenseMapInfo { +@@ -697,4 +702,8 @@ struct hash { - } // namespace llvm + } // namespace std; +#ifdef _WIN32 +#pragma warning(pop) @@ -71,7 +71,7 @@ index ef983105c7bae67bb2ef832e4473939a0406e0df..781bdb7416392e3f60a1ac3a38fbcf53 + #endif diff --git a/llvm/include/llvm/ADT/SmallVector.h b/llvm/include/llvm/ADT/SmallVector.h -index 84f4d0931a30f4be29549354c85cb4c0489e14c9..b42438a9b16c273f9ef5b5cce6192873c78cb964 100644 +index d7600fe209a58deb07c63e2553f9dad62e06e973..d7788e94b5379f5eba6fbddee50e4b4359da9d80 100644 --- a/llvm/include/llvm/ADT/SmallVector.h +++ b/llvm/include/llvm/ADT/SmallVector.h @@ -14,6 +14,14 @@ @@ -90,7 +90,7 @@ index 84f4d0931a30f4be29549354c85cb4c0489e14c9..b42438a9b16c273f9ef5b5cce6192873 #include "llvm/Support/type_traits.h" #include diff --git a/llvm/include/llvm/Support/MathExtras.h b/llvm/include/llvm/Support/MathExtras.h -index 0bd572d07fcbf2ff56998dbf366215068b62f527..cd5a64a746b2eb7491e9b6cf8570bdf436d94a6d 100644 +index 5cabfdd6493fee33fbc74b831dc1fa3c91ba725d..7541447fa2db5e1634d952b1f39957eb725611f4 100644 --- a/llvm/include/llvm/Support/MathExtras.h +++ b/llvm/include/llvm/Support/MathExtras.h @@ -208,6 +208,11 @@ inline uint64_t maxUIntN(uint64_t N) { @@ -117,7 +117,7 @@ index 0bd572d07fcbf2ff56998dbf366215068b62f527..cd5a64a746b2eb7491e9b6cf8570bdf4 inline int64_t maxIntN(int64_t N) { assert(N > 0 && N <= 64 && "integer width out of range"); diff --git a/llvm/include/llvm/Support/MemAlloc.h b/llvm/include/llvm/Support/MemAlloc.h -index d6012bd5a6985d8405136039aa85931605cd8a40..01007deb89bba625b1b3ad3e703d0c16ed6f757b 100644 +index f3f378b7697a18f57b189c5322b080fe23d45bec..0028e871f6a05baf6172c60c602b8b26e5f116c6 100644 --- a/llvm/include/llvm/Support/MemAlloc.h +++ b/llvm/include/llvm/Support/MemAlloc.h @@ -22,6 +22,14 @@ @@ -146,7 +146,7 @@ index d6012bd5a6985d8405136039aa85931605cd8a40..01007deb89bba625b1b3ad3e703d0c16 + #endif diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp -index 9966a0056ae4f24a7a38346ee1c2f5d83ac20248..a23f567a37abdc199363607446f33f29e021d7ad 100644 +index 220d850b9bc69f8fc2fba7cd23629eca487cde23..65810ca93fdc1290e3188b5f4fb292a1e1e79b60 100644 --- a/llvm/lib/Support/raw_ostream.cpp +++ b/llvm/lib/Support/raw_ostream.cpp @@ -10,6 +10,10 @@ @@ -176,7 +176,7 @@ index b710ac07461ba58faa99cedeae7f209dc0f5902b..1f232d3046292c0da940ba4bef7d5060 #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/DenseMapInfoVariant.h" diff --git a/llvm/unittests/ADT/MapVectorTest.cpp b/llvm/unittests/ADT/MapVectorTest.cpp -index 1a371cbfba81e8ea4b57c4077ca94c86c3db8991..62fafcaf04a67d4c67b98b8f42d837ccca245fe9 100644 +index e0f11b60a0223da7c00a47c20b61136bd608bae6..9c802ab30721c9ce58ed65052a6ab467039226ff 100644 --- a/llvm/unittests/ADT/MapVectorTest.cpp +++ b/llvm/unittests/ADT/MapVectorTest.cpp @@ -6,6 +6,13 @@ diff --git a/upstream_utils/llvm_patches/0009-Remove-unused-functions.patch b/upstream_utils/llvm_patches/0009-Remove-unused-functions.patch index 13bec69dc9f..3a383040938 100644 --- a/upstream_utils/llvm_patches/0009-Remove-unused-functions.patch +++ b/upstream_utils/llvm_patches/0009-Remove-unused-functions.patch @@ -1,52 +1,50 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sun, 8 May 2022 13:43:50 -0400 -Subject: [PATCH 09/31] Remove unused functions +Subject: [PATCH 09/35] Remove unused functions --- - llvm/include/llvm/ADT/SmallString.h | 85 +----- + llvm/include/llvm/ADT/SmallString.h | 79 ------ llvm/include/llvm/Support/Errno.h | 9 - llvm/include/llvm/Support/VersionTuple.h | 39 --- - llvm/include/llvm/Support/raw_ostream.h | 127 +-------- - llvm/lib/Support/raw_ostream.cpp | 329 ----------------------- - 5 files changed, 10 insertions(+), 579 deletions(-) + llvm/include/llvm/Support/raw_ostream.h | 129 +-------- + llvm/lib/Support/raw_ostream.cpp | 332 ----------------------- + 5 files changed, 8 insertions(+), 580 deletions(-) diff --git a/llvm/include/llvm/ADT/SmallString.h b/llvm/include/llvm/ADT/SmallString.h -index 4d673cc8b1c49cf8a3f19653de53881cd12662ee..bfa965fd68a09d7ca3b332e38585ae37a5982ed0 100644 +index 45fbf13a43a081731186b0f41c553413b0e36e0f..cb6136d8fd1886e8dc444cb807b33a5f1e18aa44 100644 --- a/llvm/include/llvm/ADT/SmallString.h +++ b/llvm/include/llvm/ADT/SmallString.h -@@ -88,49 +88,12 @@ public: +@@ -88,17 +88,6 @@ public: /// @name String Comparison /// @{ - /// Check for string equality. This is more efficient than compare() when - /// the relative ordering of inequal strings isn't needed. -- bool equals(std::string_view RHS) const { +- [[nodiscard]] bool equals(std::string_view RHS) const { - return str().equals(RHS); - } - - /// Check for string equality, ignoring case. -- bool equals_insensitive(std::string_view RHS) const { +- [[nodiscard]] bool equals_insensitive(std::string_view RHS) const { - return str().equals_insensitive(RHS); - } - -- /// compare - Compare two strings; the result is negative, zero, or positive -- /// if this string is lexicographically less than, equal to, or greater than -- /// the \p RHS. -+ /// Compare two strings; the result is -1, 0, or 1 if this string is -+ /// lexicographically less than, equal to, or greater than the \p RHS. - int compare(std::string_view RHS) const { + /// compare - Compare two strings; the result is negative, zero, or positive + /// if this string is lexicographically less than, equal to, or greater than + /// the \p RHS. +@@ -106,31 +95,6 @@ public: return str().compare(RHS); } - /// compare_insensitive - Compare two strings, ignoring case. -- int compare_insensitive(std::string_view RHS) const { +- [[nodiscard]] int compare_insensitive(std::string_view RHS) const { - return str().compare_insensitive(RHS); - } - - /// compare_numeric - Compare two strings, treating sequences of digits as - /// numbers. -- int compare_numeric(std::string_view RHS) const { +- [[nodiscard]] int compare_numeric(std::string_view RHS) const { - return str().compare_numeric(RHS); - } - @@ -55,19 +53,19 @@ index 4d673cc8b1c49cf8a3f19653de53881cd12662ee..bfa965fd68a09d7ca3b332e38585ae37 - /// @{ - - /// startswith - Check if this string starts with the given \p Prefix. -- bool startswith(std::string_view Prefix) const { +- [[nodiscard]] bool startswith(std::string_view Prefix) const { - return str().startswith(Prefix); - } - - /// endswith - Check if this string ends with the given \p Suffix. -- bool endswith(std::string_view Suffix) const { +- [[nodiscard]] bool endswith(std::string_view Suffix) const { - return str().endswith(Suffix); - } - /// @} /// @name String Searching /// @{ -@@ -211,50 +174,6 @@ public: +@@ -215,49 +179,6 @@ public: } /// @} @@ -75,13 +73,11 @@ index 4d673cc8b1c49cf8a3f19653de53881cd12662ee..bfa965fd68a09d7ca3b332e38585ae37 - /// @{ - - /// Return the number of occurrences of \p C in the string. -- size_t count(char C) const { -- return str().count(C); -- } +- [[nodiscard]] size_t count(char C) const { return str().count(C); } - - /// Return the number of non-overlapped occurrences of \p Str in the - /// string. -- size_t count(std::string_view Str) const { +- [[nodiscard]] size_t count(std::string_view Str) const { - return str().count(Str); - } - @@ -98,7 +94,8 @@ index 4d673cc8b1c49cf8a3f19653de53881cd12662ee..bfa965fd68a09d7ca3b332e38585ae37 - /// \param N The number of characters to included in the substring. If \p N - /// exceeds the number of characters remaining in the string, the string - /// suffix (starting with \p Start) will be returned. -- std::string_view substr(size_t Start, size_t N = std::string_view::npos) const { +- [[nodiscard]] std::string_view substr( +- size_t Start, size_t N = std::string_view::npos) const { - return str().substr(Start, N); - } - @@ -112,7 +109,7 @@ index 4d673cc8b1c49cf8a3f19653de53881cd12662ee..bfa965fd68a09d7ca3b332e38585ae37 - /// substring. If this is npos, or less than \p Start, or exceeds the - /// number of characters remaining in the string, the string suffix - /// (starting with \p Start) will be returned. -- std::string_view slice(size_t Start, size_t End) const { +- [[nodiscard]] std::string_view slice(size_t Start, size_t End) const { - return str().slice(Start, End); - } @@ -139,10 +136,10 @@ index e095c66b90860001d90b5c2eb74f6032de6de454..787805dac6c5e3c8cb85dabeb8025444 inline decltype(auto) RetryAfterSignal(const FailT &Fail, const Fun &F, const Args &... As) { diff --git a/llvm/include/llvm/Support/VersionTuple.h b/llvm/include/llvm/Support/VersionTuple.h -index 953b40701dc934c1a356b5413c9c6c692d5f5679..30cf717973fb15ff65a47a2d80795c351b0d2768 100644 +index e1cdce77ce8659305c99a21e01f9b3cc3481a5fd..9102ff063afedc03bd524b2805cba98ea5afeba8 100644 --- a/llvm/include/llvm/Support/VersionTuple.h +++ b/llvm/include/llvm/Support/VersionTuple.h -@@ -168,45 +168,6 @@ public: +@@ -166,45 +166,6 @@ public: friend bool operator>=(const VersionTuple &X, const VersionTuple &Y) { return !(X < Y); } @@ -151,8 +148,8 @@ index 953b40701dc934c1a356b5413c9c6c692d5f5679..30cf717973fb15ff65a47a2d80795c35 - return hash_combine(VT.Major, VT.Minor, VT.Subminor, VT.Build); - } - -- template -- friend void addHash(HashBuilderImpl &HBuilder, +- template +- friend void addHash(HashBuilder &HBuilder, - const VersionTuple &VT) { - HBuilder.add(VT.Major, VT.Minor, VT.Subminor, VT.Build); - } @@ -189,7 +186,7 @@ index 953b40701dc934c1a356b5413c9c6c692d5f5679..30cf717973fb15ff65a47a2d80795c35 } // end namespace llvm diff --git a/llvm/include/llvm/Support/raw_ostream.h b/llvm/include/llvm/Support/raw_ostream.h -index 5d08596b4cf6bf9e9b8e2c2c1aef731bb8832da5..95019180a9deb406ed4f2991c664a4cc4e956dac 100644 +index 862a1db876e9b8467a8839dae8f6632f18d5e7a0..95019180a9deb406ed4f2991c664a4cc4e956dac 100644 --- a/llvm/include/llvm/Support/raw_ostream.h +++ b/llvm/include/llvm/Support/raw_ostream.h @@ -261,32 +261,6 @@ public: @@ -339,10 +336,12 @@ index 5d08596b4cf6bf9e9b8e2c2c1aef731bb8832da5..95019180a9deb406ed4f2991c664a4cc }; /// This returns a reference to a raw_fd_ostream for standard output. Use it -@@ -619,17 +542,6 @@ public: +@@ -619,19 +542,6 @@ public: /// immediately destroyed. raw_fd_stream(std::string_view Filename, std::error_code &EC); +- raw_fd_stream(int fd, bool shouldClose); +- - /// This reads the \p Size bytes into a buffer pointed by \p Ptr. - /// - /// \param Ptr The start of the buffer to hold data to be read. @@ -357,7 +356,7 @@ index 5d08596b4cf6bf9e9b8e2c2c1aef731bb8832da5..95019180a9deb406ed4f2991c664a4cc /// Check if \p OS is a pointer of type raw_fd_stream*. static bool classof(const raw_ostream *OS); }; -@@ -747,29 +659,6 @@ public: +@@ -749,29 +659,6 @@ public: ~buffer_unique_ostream() override { *OS << str(); } }; @@ -388,18 +387,18 @@ index 5d08596b4cf6bf9e9b8e2c2c1aef731bb8832da5..95019180a9deb406ed4f2991c664a4cc #endif // LLVM_SUPPORT_RAW_OSTREAM_H diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp -index a23f567a37abdc199363607446f33f29e021d7ad..76c32155b4296fbbf3f4b164cd58d63f472ccd5e 100644 +index 65810ca93fdc1290e3188b5f4fb292a1e1e79b60..c65fb70a4d22db51f4140b910c308333289b6248 100644 --- a/llvm/lib/Support/raw_ostream.cpp +++ b/llvm/lib/Support/raw_ostream.cpp -@@ -18,7 +18,6 @@ - #include "llvm/ADT/StringExtras.h" +@@ -19,7 +19,6 @@ #include "llvm/Config/config.h" + #include "llvm/Support/AutoConvert.h" #include "llvm/Support/Compiler.h" -#include "llvm/Support/Duration.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" -@@ -127,49 +126,6 @@ void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size, +@@ -128,49 +127,6 @@ void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size, assert(OutBufStart <= OutBufEnd && "Invalid size!"); } @@ -449,7 +448,7 @@ index a23f567a37abdc199363607446f33f29e021d7ad..76c32155b4296fbbf3f4b164cd58d63f raw_ostream &raw_ostream::write_escaped(std::string_view Str, bool UseHexEscapes) { for (unsigned char c : Str) { -@@ -315,173 +271,6 @@ void raw_ostream::flush_tied_then_write(const char *Ptr, size_t Size) { +@@ -316,173 +272,6 @@ void raw_ostream::flush_tied_then_write(const char *Ptr, size_t Size) { write_impl(Ptr, Size); } @@ -623,7 +622,7 @@ index a23f567a37abdc199363607446f33f29e021d7ad..76c32155b4296fbbf3f4b164cd58d63f template static raw_ostream &write_padding(raw_ostream &OS, unsigned NumChars) { static const char Chars[] = {C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, -@@ -512,63 +301,8 @@ raw_ostream &raw_ostream::write_zeros(unsigned NumZeros) { +@@ -513,63 +302,8 @@ raw_ostream &raw_ostream::write_zeros(unsigned NumZeros) { return write_padding<'\0'>(*this, NumZeros); } @@ -687,7 +686,7 @@ index a23f567a37abdc199363607446f33f29e021d7ad..76c32155b4296fbbf3f4b164cd58d63f //===----------------------------------------------------------------------===// // raw_fd_ostream //===----------------------------------------------------------------------===// -@@ -867,31 +601,6 @@ size_t raw_fd_ostream::preferred_buffer_size() const { +@@ -865,31 +599,6 @@ size_t raw_fd_ostream::preferred_buffer_size() const { #endif } @@ -719,10 +718,13 @@ index a23f567a37abdc199363607446f33f29e021d7ad..76c32155b4296fbbf3f4b164cd58d63f void raw_fd_ostream::anchor() {} //===----------------------------------------------------------------------===// -@@ -934,16 +643,6 @@ raw_fd_stream::raw_fd_stream(std::string_view Filename, std::error_code &EC) +@@ -940,19 +649,6 @@ raw_fd_stream::raw_fd_stream(std::string_view Filename, std::error_code &EC) EC = std::make_error_code(std::errc::invalid_argument); } +-raw_fd_stream::raw_fd_stream(int fd, bool shouldClose) +- : raw_fd_ostream(fd, shouldClose, false, OStreamKind::OK_FDStream) {} +- -ssize_t raw_fd_stream::read(char *Ptr, size_t Size) { - assert(get_fd() >= 0 && "File already closed."); - ssize_t Ret = ::read(get_fd(), (void *)Ptr, Size); @@ -736,7 +738,7 @@ index a23f567a37abdc199363607446f33f29e021d7ad..76c32155b4296fbbf3f4b164cd58d63f bool raw_fd_stream::classof(const raw_ostream *OS) { return OS->get_kind() == OStreamKind::OK_FDStream; } -@@ -999,31 +698,3 @@ void raw_pwrite_stream::anchor() {} +@@ -1000,31 +696,3 @@ void raw_pwrite_stream::anchor() {} void buffer_ostream::anchor() {} void buffer_unique_ostream::anchor() {} diff --git a/upstream_utils/llvm_patches/0010-Detemplatize-SmallVectorBase.patch b/upstream_utils/llvm_patches/0010-Detemplatize-SmallVectorBase.patch index 8d28e0fadea..5ab041a1180 100644 --- a/upstream_utils/llvm_patches/0010-Detemplatize-SmallVectorBase.patch +++ b/upstream_utils/llvm_patches/0010-Detemplatize-SmallVectorBase.patch @@ -1,18 +1,18 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Thu, 5 May 2022 23:18:34 -0400 -Subject: [PATCH 10/31] Detemplatize SmallVectorBase +Subject: [PATCH 10/35] Detemplatize SmallVectorBase --- - llvm/include/llvm/ADT/SmallVector.h | 27 +++++++-------------- + llvm/include/llvm/ADT/SmallVector.h | 35 ++++++++++----------------- llvm/lib/Support/SmallVector.cpp | 37 +++++------------------------ - 2 files changed, 14 insertions(+), 50 deletions(-) + 2 files changed, 18 insertions(+), 54 deletions(-) diff --git a/llvm/include/llvm/ADT/SmallVector.h b/llvm/include/llvm/ADT/SmallVector.h -index b42438a9b16c273f9ef5b5cce6192873c78cb964..7775ed7e8e083908f033529c30b1e4beae91b10a 100644 +index d7788e94b5379f5eba6fbddee50e4b4359da9d80..b953ae45a34772eb7fd04c3af0275a7d093e1242 100644 --- a/llvm/include/llvm/ADT/SmallVector.h +++ b/llvm/include/llvm/ADT/SmallVector.h -@@ -56,14 +56,14 @@ using EnableIfConvertibleToInputIterator = std::enable_if_t, where a /// 32 bit size would limit the vector to ~4GB. SmallVectors are used for /// buffering bitcode output - which can exceed 4GB. @@ -23,14 +23,35 @@ index b42438a9b16c273f9ef5b5cce6192873c78cb964..7775ed7e8e083908f033529c30b1e4be - Size_T Size = 0, Capacity; + unsigned Size = 0, Capacity; - /// The maximum value of the Size_T used. +- /// The maximum value of the Size_T used. ++ /// The maximum value of the unsigned used. static constexpr size_t SizeTypeMax() { - return (std::numeric_limits::max)(); + return (std::numeric_limits::max)(); } SmallVectorBase() = delete; -@@ -111,15 +111,10 @@ protected: + SmallVectorBase(void *FirstEl, size_t TotalCapacity) +- : BeginX(FirstEl), Capacity(static_cast(TotalCapacity)) {} ++ : BeginX(FirstEl), Capacity(static_cast(TotalCapacity)) {} + + /// This is a helper for \a grow() that's out of line to reduce code + /// duplication. This function will report a fatal error if it can't grow at +@@ -107,7 +107,7 @@ protected: + /// This does not construct or destroy any elements in the vector. + void set_size(size_t N) { + assert(N <= capacity()); // implies no overflow in assignment +- Size = static_cast(N); ++ Size = static_cast(N); + } + + /// Set the array data pointer to \p Begin and capacity to \p N. +@@ -117,19 +117,14 @@ protected: + void set_allocation_range(void *Begin, size_t N) { + assert(N <= SizeTypeMax()); + BeginX = Begin; +- Capacity = static_cast(N); ++ Capacity = static_cast(N); } }; @@ -48,7 +69,7 @@ index b42438a9b16c273f9ef5b5cce6192873c78cb964..7775ed7e8e083908f033529c30b1e4be alignas(T) char FirstEl[sizeof(T)]; }; -@@ -128,8 +123,8 @@ template struct SmallVectorAlignmentAndSize { +@@ -138,8 +133,8 @@ template struct SmallVectorAlignmentAndSize { /// to avoid unnecessarily requiring T to be complete. template class SmallVectorTemplateCommon @@ -59,7 +80,7 @@ index b42438a9b16c273f9ef5b5cce6192873c78cb964..7775ed7e8e083908f033529c30b1e4be protected: /// Find the address of the first element. For this pointer math to be valid -@@ -451,7 +446,7 @@ template +@@ -461,7 +456,7 @@ template T *SmallVectorTemplateBase::mallocForGrow( size_t MinSize, size_t &NewCapacity) { return static_cast( @@ -68,7 +89,7 @@ index b42438a9b16c273f9ef5b5cce6192873c78cb964..7775ed7e8e083908f033529c30b1e4be this->getFirstEl(), MinSize, sizeof(T), NewCapacity)); } -@@ -1324,12 +1319,6 @@ template SmallVector to_vector_of(R &&Range) { +@@ -1333,12 +1328,6 @@ template SmallVector to_vector_of(R &&Range) { return {std::begin(Range), std::end(Range)}; } @@ -82,7 +103,7 @@ index b42438a9b16c273f9ef5b5cce6192873c78cb964..7775ed7e8e083908f033529c30b1e4be namespace std { diff --git a/llvm/lib/Support/SmallVector.cpp b/llvm/lib/Support/SmallVector.cpp -index 6cefdff7c28060ca18b522acf5279af3a206e23a..ae64a36dcf4b9ceaf8767adbf8100f164f3738ac 100644 +index 4f6fee18b659adcbfd79822832f914170cbb1635..7ef023084d791cf746c346cb1655c9da36a6beb5 100644 --- a/llvm/lib/Support/SmallVector.cpp +++ b/llvm/lib/Support/SmallVector.cpp @@ -51,10 +51,6 @@ static_assert(sizeof(SmallVector) == @@ -144,9 +165,9 @@ index 6cefdff7c28060ca18b522acf5279af3a206e23a..ae64a36dcf4b9ceaf8767adbf8100f16 void *NewElts; if (BeginX == FirstEl) { NewElts = llvm::safe_malloc(NewCapacity * TSize); -@@ -155,20 +147,3 @@ void SmallVectorBase::grow_pod(void *FirstEl, size_t MinSize, - this->BeginX = NewElts; - this->Capacity = NewCapacity; +@@ -154,20 +146,3 @@ void SmallVectorBase::grow_pod(void *FirstEl, size_t MinSize, + + this->set_allocation_range(NewElts, NewCapacity); } - -template class llvm::SmallVectorBase; diff --git a/upstream_utils/llvm_patches/0011-Add-vectors-to-raw_ostream.patch b/upstream_utils/llvm_patches/0011-Add-vectors-to-raw_ostream.patch index cba909f2990..17e59aa3763 100644 --- a/upstream_utils/llvm_patches/0011-Add-vectors-to-raw_ostream.patch +++ b/upstream_utils/llvm_patches/0011-Add-vectors-to-raw_ostream.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sun, 8 May 2022 13:48:59 -0400 -Subject: [PATCH 11/31] Add vectors to raw_ostream +Subject: [PATCH 11/35] Add vectors to raw_ostream --- llvm/include/llvm/Support/raw_ostream.h | 115 ++++++++++++++++++++++++ @@ -155,10 +155,10 @@ index 95019180a9deb406ed4f2991c664a4cc4e956dac..e7526e016a858ad728feb7cf1c5014b9 class raw_null_ostream : public raw_pwrite_stream { /// See raw_ostream::write_impl. diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp -index 76c32155b4296fbbf3f4b164cd58d63f472ccd5e..dcdfdfd7a8e3fcc4019538a4fc9e158aeda0a8b8 100644 +index c65fb70a4d22db51f4140b910c308333289b6248..57d3091fd5cc5b416e814f9f33811f0fa7afe9cf 100644 --- a/llvm/lib/Support/raw_ostream.cpp +++ b/llvm/lib/Support/raw_ostream.cpp -@@ -670,6 +670,53 @@ void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size, +@@ -668,6 +668,53 @@ void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size, memcpy(OS.data() + Offset, Ptr, Size); } diff --git a/upstream_utils/llvm_patches/0012-Extra-collections-features.patch b/upstream_utils/llvm_patches/0012-Extra-collections-features.patch index 7da2c106a64..50da0be1b22 100644 --- a/upstream_utils/llvm_patches/0012-Extra-collections-features.patch +++ b/upstream_utils/llvm_patches/0012-Extra-collections-features.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Tue, 3 May 2022 22:16:10 -0400 -Subject: [PATCH 12/31] Extra collections features +Subject: [PATCH 12/35] Extra collections features --- llvm/include/llvm/ADT/StringMap.h | 103 +++++++++++++++++++++++++++++- @@ -142,10 +142,10 @@ index 34dfbf83c681f4e81a9dadd9382ddca6ef8d6c1d..c133e84f9b2e3a225cdac782c011fadb #endif // LLVM_ADT_STRINGMAP_H diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp -index dcdfdfd7a8e3fcc4019538a4fc9e158aeda0a8b8..b2a726633b48b179abfd24a5de110a2301e0f877 100644 +index 57d3091fd5cc5b416e814f9f33811f0fa7afe9cf..5bec803ccc76ce287b7ff3ea037d5e490a7af20c 100644 --- a/llvm/lib/Support/raw_ostream.cpp +++ b/llvm/lib/Support/raw_ostream.cpp -@@ -76,6 +76,14 @@ constexpr raw_ostream::Colors raw_ostream::WHITE; +@@ -77,6 +77,14 @@ constexpr raw_ostream::Colors raw_ostream::WHITE; constexpr raw_ostream::Colors raw_ostream::SAVEDCOLOR; constexpr raw_ostream::Colors raw_ostream::RESET; diff --git a/upstream_utils/llvm_patches/0013-EpochTracker-ABI-macro.patch b/upstream_utils/llvm_patches/0013-EpochTracker-ABI-macro.patch index a280defac3f..3c4ebfe9cc1 100644 --- a/upstream_utils/llvm_patches/0013-EpochTracker-ABI-macro.patch +++ b/upstream_utils/llvm_patches/0013-EpochTracker-ABI-macro.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Wed, 4 May 2022 00:01:00 -0400 -Subject: [PATCH 13/31] EpochTracker ABI macro +Subject: [PATCH 13/35] EpochTracker ABI macro --- llvm/include/llvm/ADT/EpochTracker.h | 2 +- diff --git a/upstream_utils/llvm_patches/0014-Delete-numbers-from-MathExtras.patch b/upstream_utils/llvm_patches/0014-Delete-numbers-from-MathExtras.patch index ea27672b2e4..9e66e4e448a 100644 --- a/upstream_utils/llvm_patches/0014-Delete-numbers-from-MathExtras.patch +++ b/upstream_utils/llvm_patches/0014-Delete-numbers-from-MathExtras.patch @@ -1,14 +1,14 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Thu, 5 May 2022 18:09:45 -0400 -Subject: [PATCH 14/31] Delete numbers from MathExtras +Subject: [PATCH 14/35] Delete numbers from MathExtras --- llvm/include/llvm/Support/MathExtras.h | 36 -------------------------- 1 file changed, 36 deletions(-) diff --git a/llvm/include/llvm/Support/MathExtras.h b/llvm/include/llvm/Support/MathExtras.h -index cd5a64a746b2eb7491e9b6cf8570bdf436d94a6d..cdf859ccfaca22a04b08a351d7c2c9789a70627e 100644 +index 7541447fa2db5e1634d952b1f39957eb725611f4..60b3b9012a32dda5e7c3ba1dc5923ffa68df8215 100644 --- a/llvm/include/llvm/Support/MathExtras.h +++ b/llvm/include/llvm/Support/MathExtras.h @@ -24,42 +24,6 @@ diff --git a/upstream_utils/llvm_patches/0015-Add-lerp-and-sgn.patch b/upstream_utils/llvm_patches/0015-Add-lerp-and-sgn.patch index c2fe9ed6430..5bad666c40a 100644 --- a/upstream_utils/llvm_patches/0015-Add-lerp-and-sgn.patch +++ b/upstream_utils/llvm_patches/0015-Add-lerp-and-sgn.patch @@ -1,17 +1,17 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Tue, 3 May 2022 22:50:24 -0400 -Subject: [PATCH 15/31] Add lerp and sgn +Subject: [PATCH 15/35] Add lerp and sgn --- llvm/include/llvm/Support/MathExtras.h | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/llvm/include/llvm/Support/MathExtras.h b/llvm/include/llvm/Support/MathExtras.h -index cdf859ccfaca22a04b08a351d7c2c9789a70627e..b82d9883c41008dcbbd933709c6e854ad74c5b58 100644 +index 60b3b9012a32dda5e7c3ba1dc5923ffa68df8215..daa79d99578e934ca001d1de5d2772ff961b8fc3 100644 --- a/llvm/include/llvm/Support/MathExtras.h +++ b/llvm/include/llvm/Support/MathExtras.h -@@ -614,6 +614,26 @@ std::enable_if_t, T> MulOverflow(T X, T Y, T &Result) { +@@ -617,6 +617,26 @@ std::enable_if_t, T> MulOverflow(T X, T Y, T &Result) { return UX > (static_cast((std::numeric_limits::max)())) / UY; } diff --git a/upstream_utils/llvm_patches/0016-Fixup-includes.patch b/upstream_utils/llvm_patches/0016-Fixup-includes.patch index 6d32c22203b..f72802f85a1 100644 --- a/upstream_utils/llvm_patches/0016-Fixup-includes.patch +++ b/upstream_utils/llvm_patches/0016-Fixup-includes.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sun, 8 May 2022 16:38:11 -0400 -Subject: [PATCH 16/31] Fixup includes +Subject: [PATCH 16/35] Fixup includes --- llvm/include/llvm/ADT/StringMap.h | 4 ++++ @@ -91,7 +91,7 @@ index 0b87b375de67dc18647e3ebe646bf323dd05e8c5..3a88178cfbbcf7062a958c7de820247b using namespace llvm; diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp -index b2a726633b48b179abfd24a5de110a2301e0f877..3b7d8d6db5f0df31e18b91be716a4fd21e7e3549 100644 +index 5bec803ccc76ce287b7ff3ea037d5e490a7af20c..ae5428825f7f62ad8e742490448d40aea7506990 100644 --- a/llvm/lib/Support/raw_ostream.cpp +++ b/llvm/lib/Support/raw_ostream.cpp @@ -15,6 +15,8 @@ @@ -102,8 +102,8 @@ index b2a726633b48b179abfd24a5de110a2301e0f877..3b7d8d6db5f0df31e18b91be716a4fd2 +#include "wpi/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Config/config.h" - #include "llvm/Support/Compiler.h" -@@ -32,12 +34,11 @@ + #include "llvm/Support/AutoConvert.h" +@@ -33,12 +35,11 @@ #include // may provide O_BINARY. @@ -119,7 +119,7 @@ index b2a726633b48b179abfd24a5de110a2301e0f877..3b7d8d6db5f0df31e18b91be716a4fd2 #endif #if defined(__CYGWIN__) -@@ -60,7 +61,7 @@ +@@ -61,7 +62,7 @@ #ifdef _WIN32 #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/Signals.h" diff --git a/upstream_utils/llvm_patches/0017-Use-std-is_trivially_copy_constructible.patch b/upstream_utils/llvm_patches/0017-Use-std-is_trivially_copy_constructible.patch index c78fd427756..f95870f3b93 100644 --- a/upstream_utils/llvm_patches/0017-Use-std-is_trivially_copy_constructible.patch +++ b/upstream_utils/llvm_patches/0017-Use-std-is_trivially_copy_constructible.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sun, 8 May 2022 16:42:09 -0400 -Subject: [PATCH 17/31] Use std::is_trivially_copy_constructible +Subject: [PATCH 17/35] Use std::is_trivially_copy_constructible --- llvm/include/llvm/Support/type_traits.h | 16 ---------------- diff --git a/upstream_utils/llvm_patches/0018-Use-std-is_trivially_copy_constructible.patch b/upstream_utils/llvm_patches/0018-Use-std-is_trivially_copy_constructible.patch deleted file mode 100644 index 47fdf0a91c6..00000000000 --- a/upstream_utils/llvm_patches/0018-Use-std-is_trivially_copy_constructible.patch +++ /dev/null @@ -1,60 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: PJ Reiniger -Date: Sun, 8 May 2022 16:42:09 -0400 -Subject: [PATCH 18/31] Use std::is_trivially_copy_constructible - ---- - llvm/include/llvm/Support/type_traits.h | 37 ++----------------------- - 1 file changed, 2 insertions(+), 35 deletions(-) - -diff --git a/llvm/include/llvm/Support/type_traits.h b/llvm/include/llvm/Support/type_traits.h -index a6046de87d1e3e1264a0040826ea347b870a8f9e..292a2cb78b93717647cf88d00f88c2eec14f52f6 100644 ---- a/llvm/include/llvm/Support/type_traits.h -+++ b/llvm/include/llvm/Support/type_traits.h -@@ -92,44 +92,11 @@ union trivial_helper { - - } // end namespace detail - --/// An implementation of `std::is_trivially_copy_constructible` since we have --/// users with STLs that don't yet include it. - template --struct is_trivially_copy_constructible -- : std::is_copy_constructible< -- ::llvm::detail::copy_construction_triviality_helper> {}; --template --struct is_trivially_copy_constructible : std::true_type {}; --template --struct is_trivially_copy_constructible : std::false_type {}; -+using is_trivially_move_constructible = std::is_trivially_move_constructible; - --/// An implementation of `std::is_trivially_move_constructible` since we have --/// users with STLs that don't yet include it. --template --struct is_trivially_move_constructible -- : std::is_move_constructible< -- ::llvm::detail::move_construction_triviality_helper> {}; - template --struct is_trivially_move_constructible : std::true_type {}; --template --struct is_trivially_move_constructible : std::true_type {}; -- -- --template --struct is_copy_assignable { -- template -- static auto get(F*) -> decltype(std::declval() = std::declval(), std::true_type{}); -- static std::false_type get(...); -- static constexpr bool value = decltype(get((T*)nullptr))::value; --}; -- --template --struct is_move_assignable { -- template -- static auto get(F*) -> decltype(std::declval() = std::declval(), std::true_type{}); -- static std::false_type get(...); -- static constexpr bool value = decltype(get((T*)nullptr))::value; --}; -+using is_trivially_copy_constructible = std::is_trivially_copy_constructible; - - } // end namespace llvm - diff --git a/upstream_utils/llvm_patches/0018-Windows-support.patch b/upstream_utils/llvm_patches/0018-Windows-support.patch index 43e0a071f72..af4a94f729b 100644 --- a/upstream_utils/llvm_patches/0018-Windows-support.patch +++ b/upstream_utils/llvm_patches/0018-Windows-support.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Tue, 3 May 2022 20:22:38 -0400 -Subject: [PATCH 18/31] Windows support +Subject: [PATCH 18/35] Windows support --- .../llvm/Support/Windows/WindowsSupport.h | 45 +++++---- @@ -204,10 +204,10 @@ index bc04c5ab5113563fb82d7b3b168985369b611f4b..57eb64a6017a6964ab14b40b8c6b3563 ConvertUTF_RESTORE_WARNINGS diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp -index 3b7d8d6db5f0df31e18b91be716a4fd21e7e3549..4769d34a14f3f2cbaaa4df50ea7111fe9fa2792f 100644 +index ae5428825f7f62ad8e742490448d40aea7506990..9ea41cad8fed864b53e2e463450c066fb4e00131 100644 --- a/llvm/lib/Support/raw_ostream.cpp +++ b/llvm/lib/Support/raw_ostream.cpp -@@ -534,7 +534,6 @@ void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) { +@@ -535,7 +535,6 @@ void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) { DWORD WinLastError = GetLastError(); if (WinLastError == ERROR_BROKEN_PIPE || (WinLastError == ERROR_NO_DATA && errno == EINVAL)) { diff --git a/upstream_utils/llvm_patches/0019-Prefer-fmtlib.patch b/upstream_utils/llvm_patches/0019-Prefer-fmtlib.patch index 4d5b81c3cc9..702fe5ec96a 100644 --- a/upstream_utils/llvm_patches/0019-Prefer-fmtlib.patch +++ b/upstream_utils/llvm_patches/0019-Prefer-fmtlib.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sun, 8 May 2022 16:46:20 -0400 -Subject: [PATCH 19/31] Prefer fmtlib +Subject: [PATCH 19/35] Prefer fmtlib --- llvm/lib/Support/ErrorHandling.cpp | 20 ++++++-------------- @@ -16,7 +16,7 @@ index 3a88178cfbbcf7062a958c7de820247bc913ab33..54137a331ca9e752b02c0f16ae996094 #include "llvm/Support/Threading.h" #include "llvm/Support/WindowsError.h" -#include "llvm/Support/raw_ostream.h" -+#include "fmt/format.h" ++#include "wpi/print.h" #include #include #include @@ -33,7 +33,7 @@ index 3a88178cfbbcf7062a958c7de820247bc913ab33..54137a331ca9e752b02c0f16ae996094 - std::string_view MessageStr = OS.str(); - ssize_t written = ::write(2, MessageStr.data(), MessageStr.size()); - (void)written; // If something went wrong, we deliberately just give up. -+ fmt::print(stderr, "LLVM ERROR: {}\n", Reason); ++ wpi::print(stderr, "LLVM ERROR: {}\n", Reason); } // If we reached here, we are failing ungracefully. Run the interrupt handlers @@ -43,13 +43,13 @@ index 3a88178cfbbcf7062a958c7de820247bc913ab33..54137a331ca9e752b02c0f16ae996094 if (msg) - dbgs() << msg << "\n"; - dbgs() << "UNREACHABLE executed"; -+ fmt::print(stderr, "{}\n", msg); ++ wpi::print(stderr, "{}\n", msg); + std::fputs("UNREACHABLE executed", stderr); if (file) - dbgs() << " at " << file << ":" << line; - dbgs() << "!\n"; -+ fmt::print(stderr, " at {}:{}", file, line); -+ fmt::print(stderr, "!\n"); ++ wpi::print(stderr, " at {}:{}", file, line); ++ wpi::print(stderr, "!\n"); abort(); #ifdef LLVM_BUILTIN_UNREACHABLE // Windows systems and possibly others don't declare abort() to be noreturn, diff --git a/upstream_utils/llvm_patches/0020-Prefer-wpi-s-fs.h.patch b/upstream_utils/llvm_patches/0020-Prefer-wpi-s-fs.h.patch index 18ae0e7b8c4..1d4ca32a571 100644 --- a/upstream_utils/llvm_patches/0020-Prefer-wpi-s-fs.h.patch +++ b/upstream_utils/llvm_patches/0020-Prefer-wpi-s-fs.h.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sun, 8 May 2022 16:49:36 -0400 -Subject: [PATCH 20/31] Prefer wpi's fs.h +Subject: [PATCH 20/35] Prefer wpi's fs.h --- llvm/include/llvm/Support/raw_ostream.h | 7 ++----- diff --git a/upstream_utils/llvm_patches/0021-Remove-unused-functions.patch b/upstream_utils/llvm_patches/0021-Remove-unused-functions.patch index 4f6ba93fffa..58544cada15 100644 --- a/upstream_utils/llvm_patches/0021-Remove-unused-functions.patch +++ b/upstream_utils/llvm_patches/0021-Remove-unused-functions.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sun, 8 May 2022 19:16:51 -0400 -Subject: [PATCH 21/31] Remove unused functions +Subject: [PATCH 21/35] Remove unused functions --- llvm/include/llvm/Support/raw_ostream.h | 5 +- @@ -62,10 +62,10 @@ index 54137a331ca9e752b02c0f16ae996094a6f2fafa..e253d6f7a5ca3aee75823efdb9717dcd #include diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp -index 4769d34a14f3f2cbaaa4df50ea7111fe9fa2792f..f9928ac969932b6baea60a80750477d78b6a5b02 100644 +index 9ea41cad8fed864b53e2e463450c066fb4e00131..44149e85876f089756dcce151670a6060eadfee1 100644 --- a/llvm/lib/Support/raw_ostream.cpp +++ b/llvm/lib/Support/raw_ostream.cpp -@@ -175,16 +175,6 @@ raw_ostream &raw_ostream::write_escaped(std::string_view Str, +@@ -176,16 +176,6 @@ raw_ostream &raw_ostream::write_escaped(std::string_view Str, return *this; } @@ -82,7 +82,7 @@ index 4769d34a14f3f2cbaaa4df50ea7111fe9fa2792f..f9928ac969932b6baea60a80750477d7 void raw_ostream::flush_nonempty() { assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty."); size_t Length = OutBufCur - OutBufStart; -@@ -327,15 +317,22 @@ static int getFD(std::string_view Filename, std::error_code &EC, +@@ -328,15 +318,22 @@ static int getFD(std::string_view Filename, std::error_code &EC, if (Filename == "-") { EC = std::error_code(); // Change stdout's text/binary mode based on the Flags. @@ -110,7 +110,7 @@ index 4769d34a14f3f2cbaaa4df50ea7111fe9fa2792f..f9928ac969932b6baea60a80750477d7 if (EC) return -1; -@@ -395,12 +392,8 @@ raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered, +@@ -396,12 +393,8 @@ raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered, // Get the starting position. off_t loc = ::lseek(FD, 0, SEEK_CUR); @@ -124,7 +124,7 @@ index 4769d34a14f3f2cbaaa4df50ea7111fe9fa2792f..f9928ac969932b6baea60a80750477d7 #else SupportsSeeking = !EC && loc != (off_t)-1; #endif -@@ -413,10 +406,8 @@ raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered, +@@ -414,10 +407,8 @@ raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered, raw_fd_ostream::~raw_fd_ostream() { if (FD >= 0) { flush(); @@ -137,7 +137,7 @@ index 4769d34a14f3f2cbaaa4df50ea7111fe9fa2792f..f9928ac969932b6baea60a80750477d7 } #ifdef __MINGW32__ -@@ -511,7 +502,11 @@ void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) { +@@ -512,7 +503,11 @@ void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) { do { size_t ChunkSize = std::min(Size, MaxWriteSize); @@ -149,7 +149,7 @@ index 4769d34a14f3f2cbaaa4df50ea7111fe9fa2792f..f9928ac969932b6baea60a80750477d7 if (ret < 0) { // If it's a recoverable error, swallow it and retry the write. -@@ -554,8 +549,8 @@ void raw_fd_ostream::close() { +@@ -555,8 +550,8 @@ void raw_fd_ostream::close() { assert(ShouldClose); ShouldClose = false; flush(); diff --git a/upstream_utils/llvm_patches/0022-OS-specific-changes.patch b/upstream_utils/llvm_patches/0022-OS-specific-changes.patch index 4b3b3b7e25e..6e5f9aa3169 100644 --- a/upstream_utils/llvm_patches/0022-OS-specific-changes.patch +++ b/upstream_utils/llvm_patches/0022-OS-specific-changes.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Sun, 8 May 2022 19:30:43 -0400 -Subject: [PATCH 22/31] OS-specific changes +Subject: [PATCH 22/35] OS-specific changes --- llvm/lib/Support/ErrorHandling.cpp | 16 +++++++--------- @@ -12,7 +12,7 @@ index e253d6f7a5ca3aee75823efdb9717dcd93fff5dc..5c08e469e2e44b27e69f4aa974bc59de --- a/llvm/lib/Support/ErrorHandling.cpp +++ b/llvm/lib/Support/ErrorHandling.cpp @@ -96,15 +96,7 @@ void llvm::report_fatal_error(std::string_view Reason, bool GenCrashDiag) { - fmt::print(stderr, "LLVM ERROR: {}\n", Reason); + wpi::print(stderr, "LLVM ERROR: {}\n", Reason); } - // If we reached here, we are failing ungracefully. Run the interrupt handlers diff --git a/upstream_utils/llvm_patches/0023-Use-SmallVector-for-UTF-conversion.patch b/upstream_utils/llvm_patches/0023-Use-SmallVector-for-UTF-conversion.patch index d04e93b476e..81806128be6 100644 --- a/upstream_utils/llvm_patches/0023-Use-SmallVector-for-UTF-conversion.patch +++ b/upstream_utils/llvm_patches/0023-Use-SmallVector-for-UTF-conversion.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Mon, 9 May 2022 00:04:30 -0400 -Subject: [PATCH 23/31] Use SmallVector for UTF conversion +Subject: [PATCH 23/35] Use SmallVector for UTF conversion --- llvm/include/llvm/Support/ConvertUTF.h | 6 +++--- diff --git a/upstream_utils/llvm_patches/0024-Prefer-to-use-static-pointers-in-raw_ostream.patch b/upstream_utils/llvm_patches/0024-Prefer-to-use-static-pointers-in-raw_ostream.patch index f5dce6b5230..f40be976c71 100644 --- a/upstream_utils/llvm_patches/0024-Prefer-to-use-static-pointers-in-raw_ostream.patch +++ b/upstream_utils/llvm_patches/0024-Prefer-to-use-static-pointers-in-raw_ostream.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger Date: Thu, 19 May 2022 00:58:36 -0400 -Subject: [PATCH 24/31] Prefer to use static pointers in raw_ostream +Subject: [PATCH 24/35] Prefer to use static pointers in raw_ostream See #1401 --- @@ -9,13 +9,13 @@ See #1401 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp -index f9928ac969932b6baea60a80750477d78b6a5b02..1de34976844d500970b833fca35324e2948733b7 100644 +index 44149e85876f089756dcce151670a6060eadfee1..8fe686142b8cdba76287a3b8b97569fde922f2bf 100644 --- a/llvm/lib/Support/raw_ostream.cpp +++ b/llvm/lib/Support/raw_ostream.cpp -@@ -613,15 +613,15 @@ void raw_fd_ostream::anchor() {} - raw_fd_ostream &llvm::outs() { - // Set buffer settings to model stdout behavior. - std::error_code EC; +@@ -615,9 +615,9 @@ raw_fd_ostream &llvm::outs() { + EC = enableAutoConversion(STDOUT_FILENO); + assert(!EC); + #endif - static raw_fd_ostream S("-", EC, sys::fs::OF_None); + static raw_fd_ostream* S = new raw_fd_ostream("-", EC, sys::fs::OF_None); assert(!EC); @@ -24,7 +24,10 @@ index f9928ac969932b6baea60a80750477d78b6a5b02..1de34976844d500970b833fca35324e2 } raw_fd_ostream &llvm::errs() { - // Set standard error to be unbuffered and tied to outs() by default. +@@ -626,8 +626,8 @@ raw_fd_ostream &llvm::errs() { + std::error_code EC = enableAutoConversion(STDERR_FILENO); + assert(!EC); + #endif - static raw_fd_ostream S(STDERR_FILENO, false, true); - return S; + static raw_fd_ostream* S = new raw_fd_ostream(STDERR_FILENO, false, true); diff --git a/upstream_utils/llvm_patches/0025-constexpr-endian-byte-swap.patch b/upstream_utils/llvm_patches/0025-constexpr-endian-byte-swap.patch index acbded14803..2e16d48ba2f 100644 --- a/upstream_utils/llvm_patches/0025-constexpr-endian-byte-swap.patch +++ b/upstream_utils/llvm_patches/0025-constexpr-endian-byte-swap.patch @@ -1,22 +1,22 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: PJ Reiniger -Date: Thu, 19 May 2022 01:12:41 -0400 -Subject: [PATCH 25/31] constexpr endian byte swap +Date: Fri, 1 Mar 2024 11:56:17 -0800 +Subject: [PATCH 25/35] constexpr endian byte swap --- llvm/include/llvm/Support/Endian.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/llvm/include/llvm/Support/Endian.h b/llvm/include/llvm/Support/Endian.h -index 5e7c1e961b9d1e0fd6bcd0c923f678a5e1596860..2e883ff05b7e287151b6031f66d3b4aefd1bf297 100644 +index 4c0405cf1e2f69c6268d708badc2aef6dd968b51..f31fbf70fb723d19634e61ea4f21549fc767e58c 100644 --- a/llvm/include/llvm/Support/Endian.h +++ b/llvm/include/llvm/Support/Endian.h -@@ -55,7 +55,9 @@ inline value_type byte_swap(value_type value, endianness endian) { +@@ -50,7 +50,9 @@ template /// Swap the bytes of value to match the given endianness. - template - inline value_type byte_swap(value_type value) { + template + [[nodiscard]] inline value_type byte_swap(value_type value) { - return byte_swap(value, endian); -+ if constexpr ((endian != native) && (endian != system_endianness())) ++ if constexpr (endian != llvm::endianness::native) + sys::swapByteOrder(value); + return value; } diff --git a/upstream_utils/llvm_patches/0026-Copy-type-traits-from-STLExtras.h-into-PointerUnion..patch b/upstream_utils/llvm_patches/0026-Copy-type-traits-from-STLExtras.h-into-PointerUnion..patch index efa9e6cc338..c824ea34e29 100644 --- a/upstream_utils/llvm_patches/0026-Copy-type-traits-from-STLExtras.h-into-PointerUnion..patch +++ b/upstream_utils/llvm_patches/0026-Copy-type-traits-from-STLExtras.h-into-PointerUnion..patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Wed, 10 Aug 2022 17:07:52 -0700 -Subject: [PATCH 26/31] Copy type traits from STLExtras.h into PointerUnion.h +Subject: [PATCH 26/35] Copy type traits from STLExtras.h into PointerUnion.h --- llvm/include/llvm/ADT/PointerUnion.h | 46 ++++++++++++++++++++++++++++ diff --git a/upstream_utils/llvm_patches/0027-Remove-StringMap-test-for-llvm-sort.patch b/upstream_utils/llvm_patches/0027-Remove-StringMap-test-for-llvm-sort.patch index 977dff33838..bed9cf3e584 100644 --- a/upstream_utils/llvm_patches/0027-Remove-StringMap-test-for-llvm-sort.patch +++ b/upstream_utils/llvm_patches/0027-Remove-StringMap-test-for-llvm-sort.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Wed, 10 Aug 2022 22:35:00 -0700 -Subject: [PATCH 27/31] Remove StringMap test for llvm::sort() +Subject: [PATCH 27/35] Remove StringMap test for llvm::sort() --- llvm/unittests/ADT/StringMapTest.cpp | 14 -------------- diff --git a/upstream_utils/llvm_patches/0028-Unused-variable-in-release-mode.patch b/upstream_utils/llvm_patches/0028-Unused-variable-in-release-mode.patch index 2492883e8b9..bbcf411ff39 100644 --- a/upstream_utils/llvm_patches/0028-Unused-variable-in-release-mode.patch +++ b/upstream_utils/llvm_patches/0028-Unused-variable-in-release-mode.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Leander Schulten Date: Mon, 10 Jul 2023 00:53:43 +0200 -Subject: [PATCH 28/31] Unused variable in release mode +Subject: [PATCH 28/35] Unused variable in release mode --- llvm/include/llvm/ADT/DenseMap.h | 2 +- diff --git a/upstream_utils/llvm_patches/0029-Use-C-20-bit-header.patch b/upstream_utils/llvm_patches/0029-Use-C-20-bit-header.patch index fad61d3e39a..6ba144a2bf2 100644 --- a/upstream_utils/llvm_patches/0029-Use-C-20-bit-header.patch +++ b/upstream_utils/llvm_patches/0029-Use-C-20-bit-header.patch @@ -1,14 +1,14 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Tue, 11 Jul 2023 22:56:09 -0700 -Subject: [PATCH 29/31] Use C++20 header +Subject: [PATCH 29/35] Use C++20 header --- llvm/include/llvm/ADT/DenseMap.h | 3 +- llvm/include/llvm/ADT/Hashing.h | 35 +-- - llvm/include/llvm/ADT/bit.h | 287 ------------------------- + llvm/include/llvm/ADT/bit.h | 313 ------------------------- llvm/include/llvm/Support/MathExtras.h | 21 +- - 4 files changed, 31 insertions(+), 315 deletions(-) + 4 files changed, 31 insertions(+), 341 deletions(-) diff --git a/llvm/include/llvm/ADT/DenseMap.h b/llvm/include/llvm/ADT/DenseMap.h index e9bd3bfa4a6fe0fa26ff20069bbadc816c8baa65..93b50c9e53af4ea3af5fd0329a8a03bdce659e9d 100644 @@ -32,7 +32,7 @@ index e9bd3bfa4a6fe0fa26ff20069bbadc816c8baa65..93b50c9e53af4ea3af5fd0329a8a03bd } diff --git a/llvm/include/llvm/ADT/Hashing.h b/llvm/include/llvm/ADT/Hashing.h -index 781bdb7416392e3f60a1ac3a38fbcf5324b5395f..28934add722f518ae1e9cb9c4a23d2212a47cbdf 100644 +index 08d6edb14eb3cd51405329aae61b9782266a2590..e84d53e6bf2f741be562b9d66bf0bdfe4a79f936 100644 --- a/llvm/include/llvm/ADT/Hashing.h +++ b/llvm/include/llvm/ADT/Hashing.h @@ -49,6 +49,7 @@ @@ -123,13 +123,39 @@ index 781bdb7416392e3f60a1ac3a38fbcf5324b5395f..28934add722f518ae1e9cb9c4a23d221 h4 = h0 + h5; mix_32_bytes(s, h3, h4); diff --git a/llvm/include/llvm/ADT/bit.h b/llvm/include/llvm/ADT/bit.h -index 2840c5f608d3ea896e1867dd4710685da9572f2d..0a4a3634820efbc0a8ca675e3ad7c98469260d0b 100644 +index c42b5e686bdc9cf3da71d8edaddc08216fe5fb2a..a19b6a9b80da2965f1308d3e7b0ade593b522a08 100644 --- a/llvm/include/llvm/ADT/bit.h +++ b/llvm/include/llvm/ADT/bit.h -@@ -27,18 +27,6 @@ +@@ -27,44 +27,6 @@ #include // for _byteswap_{ushort,ulong,uint64} #endif +-#if defined(__linux__) || defined(__GNU__) || defined(__HAIKU__) || \ +- defined(__Fuchsia__) || defined(__EMSCRIPTEN__) || defined(__NetBSD__) || \ +- defined(__OpenBSD__) || defined(__DragonFly__) +-#include +-#elif defined(_AIX) +-#include +-#elif defined(__sun) +-/* Solaris provides _BIG_ENDIAN/_LITTLE_ENDIAN selector in sys/types.h */ +-#include +-#define BIG_ENDIAN 4321 +-#define LITTLE_ENDIAN 1234 +-#if defined(_BIG_ENDIAN) +-#define BYTE_ORDER BIG_ENDIAN +-#else +-#define BYTE_ORDER LITTLE_ENDIAN +-#endif +-#elif defined(__MVS__) +-#define BIG_ENDIAN 4321 +-#define LITTLE_ENDIAN 1234 +-#define BYTE_ORDER BIG_ENDIAN +-#else +-#if !defined(BYTE_ORDER) && !defined(_WIN32) +-#include +-#endif +-#endif +- -#ifdef _MSC_VER -// Declare these intrinsics manually rather including intrin.h. It's very -// expensive, and bit.h is popular via MathExtras.h. @@ -144,8 +170,8 @@ index 2840c5f608d3ea896e1867dd4710685da9572f2d..0a4a3634820efbc0a8ca675e3ad7c984 - namespace llvm { - // This implementation of bit_cast is different from the C++20 one in two ways: -@@ -106,281 +94,6 @@ template >> + enum class endianness { +@@ -142,281 +104,6 @@ template >> } } @@ -428,7 +454,7 @@ index 2840c5f608d3ea896e1867dd4710685da9572f2d..0a4a3634820efbc0a8ca675e3ad7c984 #endif diff --git a/llvm/include/llvm/Support/MathExtras.h b/llvm/include/llvm/Support/MathExtras.h -index b82d9883c41008dcbbd933709c6e854ad74c5b58..5f034b694989d8ef24e0b249abd12a5c20146b97 100644 +index daa79d99578e934ca001d1de5d2772ff961b8fc3..f66e64b601d01f17dc6c7a4e568cc4eb1d9bb985 100644 --- a/llvm/include/llvm/Support/MathExtras.h +++ b/llvm/include/llvm/Support/MathExtras.h @@ -15,6 +15,7 @@ diff --git a/upstream_utils/llvm_patches/0030-Remove-DenseMap-GTest-printer-test.patch b/upstream_utils/llvm_patches/0030-Remove-DenseMap-GTest-printer-test.patch index 8ee47b8fff8..7648ab87435 100644 --- a/upstream_utils/llvm_patches/0030-Remove-DenseMap-GTest-printer-test.patch +++ b/upstream_utils/llvm_patches/0030-Remove-DenseMap-GTest-printer-test.patch @@ -1,7 +1,7 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Sun, 30 Jul 2023 14:17:37 -0700 -Subject: [PATCH 30/31] Remove DenseMap GTest printer test +Subject: [PATCH 30/35] Remove DenseMap GTest printer test LLVM modifies internal GTest headers to support it, which we can't do. --- diff --git a/upstream_utils/llvm_patches/0031-Replace-deprecated-std-aligned_storage_t.patch b/upstream_utils/llvm_patches/0031-Replace-deprecated-std-aligned_storage_t.patch index e074f273b66..add9be5db94 100644 --- a/upstream_utils/llvm_patches/0031-Replace-deprecated-std-aligned_storage_t.patch +++ b/upstream_utils/llvm_patches/0031-Replace-deprecated-std-aligned_storage_t.patch @@ -1,25 +1,25 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Tyler Veness Date: Fri, 15 Sep 2023 18:26:50 -0700 -Subject: [PATCH 31/31] Replace deprecated std::aligned_storage_t +Subject: [PATCH 31/35] Replace deprecated std::aligned_storage_t --- llvm/include/llvm/ADT/FunctionExtras.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/llvm/include/llvm/ADT/FunctionExtras.h b/llvm/include/llvm/ADT/FunctionExtras.h -index 1daeae915eb506b32a2d1296d2f0fe4e6dab606e..2e60e34d69914bd9b2197fc0a0e75a8e025674b2 100644 +index 043d8d90fff03d571a923c264b49be37a5dffa09..a62d5ce00d784def5ae21b8d91cea40cee7bf942 100644 --- a/llvm/include/llvm/ADT/FunctionExtras.h +++ b/llvm/include/llvm/ADT/FunctionExtras.h -@@ -37,6 +37,7 @@ - #include "llvm/ADT/STLForwardCompat.h" +@@ -38,6 +38,7 @@ + #include "llvm/Support/Compiler.h" #include "llvm/Support/MemAlloc.h" #include "llvm/Support/type_traits.h" +#include #include #include #include -@@ -167,8 +168,7 @@ protected: +@@ -168,8 +169,7 @@ protected: // provide four pointers worth of storage here. // This is mutable as an inlined `const unique_function` may // still modify its own mutable members. diff --git a/upstream_utils/llvm_patches/0032-Fix-compilation-of-MathExtras.h-on-Windows-with-sdl.patch b/upstream_utils/llvm_patches/0032-Fix-compilation-of-MathExtras.h-on-Windows-with-sdl.patch deleted file mode 100644 index 52956f95baa..00000000000 --- a/upstream_utils/llvm_patches/0032-Fix-compilation-of-MathExtras.h-on-Windows-with-sdl.patch +++ /dev/null @@ -1,26 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Benjamin Hall -Date: Mon, 23 Oct 2023 21:36:40 -0400 -Subject: [PATCH 32/32] Fix compilation of MathExtras.h on Windows with /sdl - -See https://github.com/llvm/llvm-project/pull/68978 ---- - llvm/include/llvm/Support/MathExtras.h | 5 ++++- - 1 file changed, 4 insertions(+), 1 deletion(-) - -diff --git a/llvm/include/llvm/Support/MathExtras.h b/llvm/include/llvm/Support/MathExtras.h -index 5f034b694989d8ef24e0b249abd12a5c20146b97..03db6e4d92cb3b62ac3d8b3cbd97783817c6326b 100644 ---- a/llvm/include/llvm/Support/MathExtras.h -+++ b/llvm/include/llvm/Support/MathExtras.h -@@ -356,7 +356,10 @@ inline uint64_t alignTo(uint64_t Value, uint64_t Align) { - inline uint64_t alignToPowerOf2(uint64_t Value, uint64_t Align) { - assert(Align != 0 && (Align & (Align - 1)) == 0 && - "Align must be a power of 2"); -- return (Value + Align - 1) & -Align; -+ // Replace unary minus to avoid compilation error on Windows: -+ // "unary minus operator applied to unsigned type, result still unsigned" -+ uint64_t negAlign = (~Align) + 1; -+ return (Value + Align - 1) & negAlign; - } - - /// If non-zero \p Skew is specified, the return value will be a minimal integer diff --git a/upstream_utils/llvm_patches/0033-raw_ostream-Add-SetNumBytesInBuffer.patch b/upstream_utils/llvm_patches/0032-raw_ostream-Add-SetNumBytesInBuffer.patch similarity index 84% rename from upstream_utils/llvm_patches/0033-raw_ostream-Add-SetNumBytesInBuffer.patch rename to upstream_utils/llvm_patches/0032-raw_ostream-Add-SetNumBytesInBuffer.patch index a36cfc66530..37c352331c8 100644 --- a/upstream_utils/llvm_patches/0033-raw_ostream-Add-SetNumBytesInBuffer.patch +++ b/upstream_utils/llvm_patches/0032-raw_ostream-Add-SetNumBytesInBuffer.patch @@ -1,14 +1,14 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Peter Johnson Date: Sun, 29 Oct 2023 23:00:08 -0700 -Subject: [PATCH 33/33] raw_ostream: Add SetNumBytesInBuffer +Subject: [PATCH 32/35] raw_ostream: Add SetNumBytesInBuffer --- llvm/include/llvm/Support/raw_ostream.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/llvm/include/llvm/Support/raw_ostream.h b/llvm/include/llvm/Support/raw_ostream.h -index 9a9a1f688313a5784a58a70f2cb4cc0d6ec70e79..39f98e4e7696e28587779e90a03995463767b02d 100644 +index 9a9a1f688313a5784a58a70f2cb4cc0d6ec70e79..d832bcb97b4131a08ba3692eb438455e4c9764e4 100644 --- a/llvm/include/llvm/Support/raw_ostream.h +++ b/llvm/include/llvm/Support/raw_ostream.h @@ -356,6 +356,11 @@ protected: diff --git a/upstream_utils/llvm_patches/0033-type_traits.h-Add-is_constexpr.patch b/upstream_utils/llvm_patches/0033-type_traits.h-Add-is_constexpr.patch new file mode 100644 index 00000000000..1a39b5ef3e4 --- /dev/null +++ b/upstream_utils/llvm_patches/0033-type_traits.h-Add-is_constexpr.patch @@ -0,0 +1,25 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Peter Johnson +Date: Sat, 2 Dec 2023 15:21:32 -0800 +Subject: [PATCH 33/35] type_traits.h: Add is_constexpr() + +--- + llvm/include/llvm/Support/type_traits.h | 5 +++++ + 1 file changed, 5 insertions(+) + +diff --git a/llvm/include/llvm/Support/type_traits.h b/llvm/include/llvm/Support/type_traits.h +index 3171af93fa7ffe4707c03289270cf5951e3db7c5..e1b094640876649709abc199f83942dbfef09771 100644 +--- a/llvm/include/llvm/Support/type_traits.h ++++ b/llvm/include/llvm/Support/type_traits.h +@@ -76,6 +76,11 @@ union trivial_helper { + + } // end namespace detail + ++// https://stackoverflow.com/questions/55288555/c-check-if-statement-can-be-evaluated-constexpr ++template ++constexpr bool is_constexpr(Lambda) { return true; } ++constexpr bool is_constexpr(...) { return false; } ++ + } // end namespace llvm + + #endif // LLVM_SUPPORT_TYPE_TRAITS_H diff --git a/upstream_utils/llvm_patches/0034-Add-back-removed-raw_string_ostream-write_impl.patch b/upstream_utils/llvm_patches/0034-Add-back-removed-raw_string_ostream-write_impl.patch new file mode 100644 index 00000000000..b5cf2072313 --- /dev/null +++ b/upstream_utils/llvm_patches/0034-Add-back-removed-raw_string_ostream-write_impl.patch @@ -0,0 +1,28 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Tyler Veness +Date: Fri, 1 Mar 2024 11:37:36 -0800 +Subject: [PATCH 34/35] Add back removed raw_string_ostream::write_impl() + +--- + llvm/lib/Support/raw_ostream.cpp | 8 ++++++++ + 1 file changed, 8 insertions(+) + +diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp +index 8fe686142b8cdba76287a3b8b97569fde922f2bf..9134f3d3db220ec5afb87b72cb9aed76c52a80ca 100644 +--- a/llvm/lib/Support/raw_ostream.cpp ++++ b/llvm/lib/Support/raw_ostream.cpp +@@ -656,6 +656,14 @@ bool raw_fd_stream::classof(const raw_ostream *OS) { + return OS->get_kind() == OStreamKind::OK_FDStream; + } + ++//===----------------------------------------------------------------------===// ++// raw_string_ostream ++//===----------------------------------------------------------------------===// ++ ++void raw_string_ostream::write_impl(const char *Ptr, size_t Size) { ++ OS.append(Ptr, Size); ++} ++ + //===----------------------------------------------------------------------===// + // raw_svector_ostream + //===----------------------------------------------------------------------===// diff --git a/upstream_utils/llvm_patches/0035-Remove-auto-conversion-from-raw_ostream.patch b/upstream_utils/llvm_patches/0035-Remove-auto-conversion-from-raw_ostream.patch new file mode 100644 index 00000000000..e992d6902c1 --- /dev/null +++ b/upstream_utils/llvm_patches/0035-Remove-auto-conversion-from-raw_ostream.patch @@ -0,0 +1,43 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Tyler Veness +Date: Sun, 17 Mar 2024 14:51:11 -0700 +Subject: [PATCH 35/35] Remove auto-conversion from raw_ostream + +--- + llvm/lib/Support/raw_ostream.cpp | 9 --------- + 1 file changed, 9 deletions(-) + +diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp +index 9134f3d3db220ec5afb87b72cb9aed76c52a80ca..efba615e1b77de335ab343cc56ce9b00ccf3f462 100644 +--- a/llvm/lib/Support/raw_ostream.cpp ++++ b/llvm/lib/Support/raw_ostream.cpp +@@ -19,7 +19,6 @@ + #include "wpi/SmallVector.h" + #include "llvm/ADT/StringExtras.h" + #include "llvm/Config/config.h" +-#include "llvm/Support/AutoConvert.h" + #include "llvm/Support/Compiler.h" + #include "llvm/Support/ErrorHandling.h" + #include "llvm/Support/FileSystem.h" +@@ -611,10 +610,6 @@ void raw_fd_ostream::anchor() {} + raw_fd_ostream &llvm::outs() { + // Set buffer settings to model stdout behavior. + std::error_code EC; +-#ifdef __MVS__ +- EC = enableAutoConversion(STDOUT_FILENO); +- assert(!EC); +-#endif + static raw_fd_ostream* S = new raw_fd_ostream("-", EC, sys::fs::OF_None); + assert(!EC); + return *S; +@@ -622,10 +617,6 @@ raw_fd_ostream &llvm::outs() { + + raw_fd_ostream &llvm::errs() { + // Set standard error to be unbuffered and tied to outs() by default. +-#ifdef __MVS__ +- std::error_code EC = enableAutoConversion(STDERR_FILENO); +- assert(!EC); +-#endif + static raw_fd_ostream* S = new raw_fd_ostream(STDERR_FILENO, false, true); + return *S; + } diff --git a/upstream_utils/sleipnir_patches/0001-Remove-using-enum-declarations.patch b/upstream_utils/sleipnir_patches/0001-Remove-using-enum-declarations.patch new file mode 100644 index 00000000000..45ea997600a --- /dev/null +++ b/upstream_utils/sleipnir_patches/0001-Remove-using-enum-declarations.patch @@ -0,0 +1,638 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Tyler Veness +Date: Wed, 24 Apr 2024 15:56:06 -0700 +Subject: [PATCH 1/2] Remove "using enum" declarations + +--- + include/sleipnir/autodiff/Expression.hpp | 161 +++++++----------- + .../optimization/SolverExitCondition.hpp | 22 ++- + 2 files changed, 73 insertions(+), 110 deletions(-) + +diff --git a/include/sleipnir/autodiff/Expression.hpp b/include/sleipnir/autodiff/Expression.hpp +index b60226ccffef9ac161727483ebca3d53df09dec2..fc503c10a209b4779e204e598d3bae45d27916cb 100644 +--- a/include/sleipnir/autodiff/Expression.hpp ++++ b/include/sleipnir/autodiff/Expression.hpp +@@ -192,8 +192,6 @@ struct SLEIPNIR_DLLEXPORT Expression { + */ + friend SLEIPNIR_DLLEXPORT ExpressionPtr operator*(const ExpressionPtr& lhs, + const ExpressionPtr& rhs) { +- using enum ExpressionType; +- + // Prune expression + if (lhs->IsConstant(0.0)) { + // Return zero +@@ -208,20 +206,22 @@ struct SLEIPNIR_DLLEXPORT Expression { + } + + // Evaluate constant +- if (lhs->type == kConstant && rhs->type == kConstant) { ++ if (lhs->type == ExpressionType::kConstant && ++ rhs->type == ExpressionType::kConstant) { + return MakeExpressionPtr(lhs->value * rhs->value); + } + + // Evaluate expression type + ExpressionType type; +- if (lhs->type == kConstant) { ++ if (lhs->type == ExpressionType::kConstant) { + type = rhs->type; +- } else if (rhs->type == kConstant) { ++ } else if (rhs->type == ExpressionType::kConstant) { + type = lhs->type; +- } else if (lhs->type == kLinear && rhs->type == kLinear) { +- type = kQuadratic; ++ } else if (lhs->type == ExpressionType::kLinear && ++ rhs->type == ExpressionType::kLinear) { ++ type = ExpressionType::kQuadratic; + } else { +- type = kNonlinear; ++ type = ExpressionType::kNonlinear; + } + + return MakeExpressionPtr( +@@ -247,8 +247,6 @@ struct SLEIPNIR_DLLEXPORT Expression { + */ + friend SLEIPNIR_DLLEXPORT ExpressionPtr operator/(const ExpressionPtr& lhs, + const ExpressionPtr& rhs) { +- using enum ExpressionType; +- + // Prune expression + if (lhs->IsConstant(0.0)) { + // Return zero +@@ -258,16 +256,17 @@ struct SLEIPNIR_DLLEXPORT Expression { + } + + // Evaluate constant +- if (lhs->type == kConstant && rhs->type == kConstant) { ++ if (lhs->type == ExpressionType::kConstant && ++ rhs->type == ExpressionType::kConstant) { + return MakeExpressionPtr(lhs->value / rhs->value); + } + + // Evaluate expression type + ExpressionType type; +- if (rhs->type == kConstant) { ++ if (rhs->type == ExpressionType::kConstant) { + type = lhs->type; + } else { +- type = kNonlinear; ++ type = ExpressionType::kNonlinear; + } + + return MakeExpressionPtr( +@@ -295,8 +294,6 @@ struct SLEIPNIR_DLLEXPORT Expression { + */ + friend SLEIPNIR_DLLEXPORT ExpressionPtr operator+(const ExpressionPtr& lhs, + const ExpressionPtr& rhs) { +- using enum ExpressionType; +- + // Prune expression + if (lhs == nullptr || lhs->IsConstant(0.0)) { + return rhs; +@@ -305,7 +302,8 @@ struct SLEIPNIR_DLLEXPORT Expression { + } + + // Evaluate constant +- if (lhs->type == kConstant && rhs->type == kConstant) { ++ if (lhs->type == ExpressionType::kConstant && ++ rhs->type == ExpressionType::kConstant) { + return MakeExpressionPtr(lhs->value + rhs->value); + } + +@@ -333,8 +331,6 @@ struct SLEIPNIR_DLLEXPORT Expression { + */ + friend SLEIPNIR_DLLEXPORT ExpressionPtr operator-(const ExpressionPtr& lhs, + const ExpressionPtr& rhs) { +- using enum ExpressionType; +- + // Prune expression + if (lhs->IsConstant(0.0)) { + if (rhs->IsConstant(0.0)) { +@@ -348,7 +344,8 @@ struct SLEIPNIR_DLLEXPORT Expression { + } + + // Evaluate constant +- if (lhs->type == kConstant && rhs->type == kConstant) { ++ if (lhs->type == ExpressionType::kConstant && ++ rhs->type == ExpressionType::kConstant) { + return MakeExpressionPtr(lhs->value - rhs->value); + } + +@@ -374,8 +371,6 @@ struct SLEIPNIR_DLLEXPORT Expression { + * @param lhs Operand of unary minus. + */ + friend SLEIPNIR_DLLEXPORT ExpressionPtr operator-(const ExpressionPtr& lhs) { +- using enum ExpressionType; +- + // Prune expression + if (lhs->IsConstant(0.0)) { + // Return zero +@@ -383,7 +378,7 @@ struct SLEIPNIR_DLLEXPORT Expression { + } + + // Evaluate constant +- if (lhs->type == kConstant) { ++ if (lhs->type == ExpressionType::kConstant) { + return MakeExpressionPtr(-lhs->value); + } + +@@ -465,8 +460,6 @@ inline void IntrusiveSharedPtrDecRefCount(Expression* expr) { + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr abs( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + // Return zero +@@ -474,12 +467,12 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr abs( // NOLINT + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::abs(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::abs(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::abs(x); }, + [](double x, double, double parentAdjoint) { + if (x < 0.0) { + return -parentAdjoint; +@@ -510,20 +503,18 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr abs( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr acos( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + return MakeExpressionPtr(std::numbers::pi / 2.0); + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::acos(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::acos(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::acos(x); }, + [](double x, double, double parentAdjoint) { + return -parentAdjoint / std::sqrt(1.0 - x * x); + }, +@@ -542,8 +533,6 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr acos( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr asin( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + // Return zero +@@ -551,12 +540,12 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr asin( // NOLINT + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::asin(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::asin(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::asin(x); }, + [](double x, double, double parentAdjoint) { + return parentAdjoint / std::sqrt(1.0 - x * x); + }, +@@ -575,8 +564,6 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr asin( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr atan( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + // Return zero +@@ -584,12 +571,12 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr atan( // NOLINT + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::atan(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::atan(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::atan(x); }, + [](double x, double, double parentAdjoint) { + return parentAdjoint / (1.0 + x * x); + }, +@@ -608,8 +595,6 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr atan( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr atan2( // NOLINT + const ExpressionPtr& y, const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (y->IsConstant(0.0)) { + // Return zero +@@ -619,12 +604,14 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr atan2( // NOLINT + } + + // Evaluate constant +- if (y->type == kConstant && x->type == kConstant) { ++ if (y->type == ExpressionType::kConstant && ++ x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::atan2(y->value, x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double y, double x) { return std::atan2(y, x); }, ++ ExpressionType::kNonlinear, ++ [](double y, double x) { return std::atan2(y, x); }, + [](double y, double x, double parentAdjoint) { + return parentAdjoint * x / (y * y + x * x); + }, +@@ -649,20 +636,18 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr atan2( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr cos( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + return MakeExpressionPtr(1.0); + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::cos(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::cos(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::cos(x); }, + [](double x, double, double parentAdjoint) { + return -parentAdjoint * std::sin(x); + }, +@@ -680,20 +665,18 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr cos( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr cosh( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + return MakeExpressionPtr(1.0); + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::cosh(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::cosh(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::cosh(x); }, + [](double x, double, double parentAdjoint) { + return parentAdjoint * std::sinh(x); + }, +@@ -711,8 +694,6 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr cosh( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr erf( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + // Return zero +@@ -720,12 +701,12 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr erf( // NOLINT + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::erf(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::erf(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::erf(x); }, + [](double x, double, double parentAdjoint) { + return parentAdjoint * 2.0 * std::numbers::inv_sqrtpi * + std::exp(-x * x); +@@ -746,20 +727,18 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr erf( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr exp( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + return MakeExpressionPtr(1.0); + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::exp(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::exp(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::exp(x); }, + [](double x, double, double parentAdjoint) { + return parentAdjoint * std::exp(x); + }, +@@ -778,8 +757,6 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr exp( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr hypot( // NOLINT + const ExpressionPtr& x, const ExpressionPtr& y) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + return y; +@@ -788,12 +765,14 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr hypot( // NOLINT + } + + // Evaluate constant +- if (x->type == kConstant && y->type == kConstant) { ++ if (x->type == ExpressionType::kConstant && ++ y->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::hypot(x->value, y->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double y) { return std::hypot(x, y); }, ++ ExpressionType::kNonlinear, ++ [](double x, double y) { return std::hypot(x, y); }, + [](double x, double y, double parentAdjoint) { + return parentAdjoint * x / std::hypot(x, y); + }, +@@ -818,8 +797,6 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr hypot( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr log( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + // Return zero +@@ -827,12 +804,12 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr log( // NOLINT + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::log(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::log(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::log(x); }, + [](double x, double, double parentAdjoint) { return parentAdjoint / x; }, + [](const ExpressionPtr& x, const ExpressionPtr&, + const ExpressionPtr& parentAdjoint) { return parentAdjoint / x; }, +@@ -846,8 +823,6 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr log( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr log10( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + // Return zero +@@ -855,12 +830,13 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr log10( // NOLINT + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::log10(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::log10(x); }, ++ ExpressionType::kNonlinear, ++ [](double x, double) { return std::log10(x); }, + [](double x, double, double parentAdjoint) { + return parentAdjoint / (std::numbers::ln10 * x); + }, +@@ -879,8 +855,6 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr log10( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr pow( // NOLINT + const ExpressionPtr& base, const ExpressionPtr& power) { +- using enum ExpressionType; +- + // Prune expression + if (base->IsConstant(0.0)) { + // Return zero +@@ -895,12 +869,15 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr pow( // NOLINT + } + + // Evaluate constant +- if (base->type == kConstant && power->type == kConstant) { ++ if (base->type == ExpressionType::kConstant && ++ power->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::pow(base->value, power->value)); + } + + return MakeExpressionPtr( +- base->type == kLinear && power->IsConstant(2.0) ? kQuadratic : kNonlinear, ++ base->type == ExpressionType::kLinear && power->IsConstant(2.0) ++ ? ExpressionType::kQuadratic ++ : ExpressionType::kNonlinear, + [](double base, double power) { return std::pow(base, power); }, + [](double base, double power, double parentAdjoint) { + return parentAdjoint * std::pow(base, power - 1) * power; +@@ -941,10 +918,8 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr pow( // NOLINT + * @param x The argument. + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr sign(const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + if (x->value < 0.0) { + return MakeExpressionPtr(-1.0); + } else if (x->value == 0.0) { +@@ -956,7 +931,7 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr sign(const ExpressionPtr& x) { + } + + return MakeExpressionPtr( +- kNonlinear, ++ ExpressionType::kNonlinear, + [](double x, double) { + if (x < 0.0) { + return -1.0; +@@ -982,8 +957,6 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr sign(const ExpressionPtr& x) { + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr sin( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + // Return zero +@@ -991,12 +964,12 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr sin( // NOLINT + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::sin(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::sin(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::sin(x); }, + [](double x, double, double parentAdjoint) { + return parentAdjoint * std::cos(x); + }, +@@ -1013,8 +986,6 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr sin( // NOLINT + * @param x The argument. + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr sinh(const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + // Return zero +@@ -1022,12 +993,12 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr sinh(const ExpressionPtr& x) { + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::sinh(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::sinh(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::sinh(x); }, + [](double x, double, double parentAdjoint) { + return parentAdjoint * std::cosh(x); + }, +@@ -1045,10 +1016,8 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr sinh(const ExpressionPtr& x) { + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr sqrt( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + if (x->value == 0.0) { + // Return zero + return x; +@@ -1060,7 +1029,7 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr sqrt( // NOLINT + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::sqrt(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::sqrt(x); }, + [](double x, double, double parentAdjoint) { + return parentAdjoint / (2.0 * std::sqrt(x)); + }, +@@ -1079,8 +1048,6 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr sqrt( // NOLINT + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr tan( // NOLINT + const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + // Return zero +@@ -1088,12 +1055,12 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr tan( // NOLINT + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::tan(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::tan(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::tan(x); }, + [](double x, double, double parentAdjoint) { + return parentAdjoint / (std::cos(x) * std::cos(x)); + }, +@@ -1111,8 +1078,6 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr tan( // NOLINT + * @param x The argument. + */ + SLEIPNIR_DLLEXPORT inline ExpressionPtr tanh(const ExpressionPtr& x) { +- using enum ExpressionType; +- + // Prune expression + if (x->IsConstant(0.0)) { + // Return zero +@@ -1120,12 +1085,12 @@ SLEIPNIR_DLLEXPORT inline ExpressionPtr tanh(const ExpressionPtr& x) { + } + + // Evaluate constant +- if (x->type == kConstant) { ++ if (x->type == ExpressionType::kConstant) { + return MakeExpressionPtr(std::tanh(x->value)); + } + + return MakeExpressionPtr( +- kNonlinear, [](double x, double) { return std::tanh(x); }, ++ ExpressionType::kNonlinear, [](double x, double) { return std::tanh(x); }, + [](double x, double, double parentAdjoint) { + return parentAdjoint / (std::cosh(x) * std::cosh(x)); + }, +diff --git a/include/sleipnir/optimization/SolverExitCondition.hpp b/include/sleipnir/optimization/SolverExitCondition.hpp +index 7d1445297e33e3c62bcdf9d03eebeaad20af9a1c..734cd3d127327e8ce01e1a42fe74ccc81fea1f90 100644 +--- a/include/sleipnir/optimization/SolverExitCondition.hpp ++++ b/include/sleipnir/optimization/SolverExitCondition.hpp +@@ -46,31 +46,29 @@ enum class SolverExitCondition : int8_t { + */ + SLEIPNIR_DLLEXPORT constexpr std::string_view ToMessage( + const SolverExitCondition& exitCondition) { +- using enum SolverExitCondition; +- + switch (exitCondition) { +- case kSuccess: ++ case SolverExitCondition::kSuccess: + return "solved to desired tolerance"; +- case kSolvedToAcceptableTolerance: ++ case SolverExitCondition::kSolvedToAcceptableTolerance: + return "solved to acceptable tolerance"; +- case kCallbackRequestedStop: ++ case SolverExitCondition::kCallbackRequestedStop: + return "callback requested stop"; +- case kTooFewDOFs: ++ case SolverExitCondition::kTooFewDOFs: + return "problem has too few degrees of freedom"; +- case kLocallyInfeasible: ++ case SolverExitCondition::kLocallyInfeasible: + return "problem is locally infeasible"; +- case kFeasibilityRestorationFailed: ++ case SolverExitCondition::kFeasibilityRestorationFailed: + return "solver failed to reach the desired tolerance, and feasibility " + "restoration failed to converge"; +- case kNonfiniteInitialCostOrConstraints: ++ case SolverExitCondition::kNonfiniteInitialCostOrConstraints: + return "solver encountered nonfinite initial cost or constraints and " + "gave up"; +- case kDivergingIterates: ++ case SolverExitCondition::kDivergingIterates: + return "solver encountered diverging primal iterates xₖ and/or sₖ and " + "gave up"; +- case kMaxIterationsExceeded: ++ case SolverExitCondition::kMaxIterationsExceeded: + return "solution returned after maximum iterations exceeded"; +- case kTimeout: ++ case SolverExitCondition::kTimeout: + return "solution returned after maximum wall clock time exceeded"; + default: + return "unknown"; diff --git a/upstream_utils/sleipnir_patches/0002-Add-implicit-typename.patch b/upstream_utils/sleipnir_patches/0002-Add-implicit-typename.patch new file mode 100644 index 00000000000..534c6c19bd9 --- /dev/null +++ b/upstream_utils/sleipnir_patches/0002-Add-implicit-typename.patch @@ -0,0 +1,24 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Tyler Veness +Date: Mon, 29 Apr 2024 19:17:18 -0700 +Subject: [PATCH 2/2] Add implicit typename + +--- + include/sleipnir/util/SmallVector.hpp | 4 ++-- + 1 file changed, 2 insertions(+), 2 deletions(-) + +diff --git a/include/sleipnir/util/SmallVector.hpp b/include/sleipnir/util/SmallVector.hpp +index a4fd51931bb86b2b689805b2c4c5e0125cc560fc..e301b973f1dcd1f662bd9c9f8fd567053e5ee578 100644 +--- a/include/sleipnir/util/SmallVector.hpp ++++ b/include/sleipnir/util/SmallVector.hpp +@@ -152,8 +152,8 @@ class small_vector + }; + + template +-constexpr small_vector::size_type erase_if(small_vector& c, +- Pred pred) { ++constexpr typename small_vector::size_type erase_if(small_vector& c, ++ Pred pred) { + auto it = std::remove_if(c.begin(), c.end(), pred); + auto r = c.end() - it; + c.erase(it, c.end()); diff --git a/upstream_utils/update_eigen.py b/upstream_utils/update_eigen.py index ce4c6203dd2..f031e44feff 100755 --- a/upstream_utils/update_eigen.py +++ b/upstream_utils/update_eigen.py @@ -95,7 +95,12 @@ def unsupported_inclusions(dp, f): def main(): - upstream_root = clone_repo("https://gitlab.com/libeigen/eigen.git", "3.4.0") + upstream_root = clone_repo( + "https://gitlab.com/libeigen/eigen.git", + # master on 2024-05-07 + "99c18bce6eb225fa5a4861af97189ada1bca3103", + shallow=False, + ) wpilib_root = get_repo_root() wpimath = os.path.join(wpilib_root, "wpimath") @@ -104,15 +109,13 @@ def main(): for f in [ "0001-Disable-warnings.patch", "0002-Intellisense-fix.patch", - "0003-Eigen-Sparse-fix-warnings-Wunused-but-set-variable.patch", + "0003-Suppress-C-23-deprecation-warnings-for-std-has_denor.patch", + "0004-Fix-compilation-failures-on-constexpr-matrices-with-.patch", ]: git_am(os.path.join(wpilib_root, "upstream_utils/eigen_patches", f)) # Delete old install - for d in [ - "src/main/native/thirdparty/eigen/include/Eigen", - "src/main/native/thirdparty/eigen/include/unsupported", - ]: + for d in ["src/main/native/thirdparty/eigen/include"]: shutil.rmtree(os.path.join(wpimath, d), ignore_errors=True) # Copy Eigen headers into allwpilib @@ -136,6 +139,11 @@ def main(): f, [os.path.join(wpimath, "src/main/native/thirdparty/eigen/include")] ) + shutil.copyfile( + os.path.join(upstream_root, ".clang-format"), + os.path.join(wpimath, "src/main/native/thirdparty/eigen/include/.clang-format"), + ) + if __name__ == "__main__": main() diff --git a/upstream_utils/update_expected.py b/upstream_utils/update_expected.py new file mode 100755 index 00000000000..1b459fe5ac3 --- /dev/null +++ b/upstream_utils/update_expected.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 + +import os +import re +import shutil + +from upstream_utils import ( + get_repo_root, + clone_repo, + comment_out_invalid_includes, + walk_cwd_and_copy_if, + git_am, +) + + +def main(): + upstream_root = clone_repo( + "https://github.com/TartanLlama/expected", + # master on 2024-01-25 + "3f0ca7b19253129700a073abfa6d8638d9f7c80c", + shallow=False, + ) + wpilib_root = get_repo_root() + wpiutil = os.path.join(wpilib_root, "wpiutil") + + # Copy expected header into allwpilib + dest_filename = os.path.join( + wpiutil, "src/main/native/thirdparty/expected/include/wpi/expected" + ) + shutil.copyfile( + os.path.join(upstream_root, "include/tl/expected.hpp"), dest_filename + ) + + # Rename namespace from tl to wpi + with open(dest_filename) as f: + content = f.read() + content = content.replace("namespace tl", "namespace wpi") + content = content.replace("tl::", "wpi::") + content = content.replace("TL_", "WPI_") + with open(dest_filename, "w") as f: + f.write(content) + + +if __name__ == "__main__": + main() diff --git a/upstream_utils/update_fmt.py b/upstream_utils/update_fmt.py index 746e879ad24..9fdff1ded20 100755 --- a/upstream_utils/update_fmt.py +++ b/upstream_utils/update_fmt.py @@ -13,15 +13,15 @@ def main(): - upstream_root = clone_repo("https://github.com/fmtlib/fmt", "10.1.1") + upstream_root = clone_repo("https://github.com/fmtlib/fmt", "10.2.1") wpilib_root = get_repo_root() wpiutil = os.path.join(wpilib_root, "wpiutil") # Apply patches to upstream Git repo os.chdir(upstream_root) for f in [ - "0001-Don-t-throw-on-write-failure.patch", - "0002-Suppress-warnings-we-can-t-fix.patch", + "0001-Suppress-warnings-we-can-t-fix.patch", + "0002-Fix-tautological-compare-warning.patch", ]: git_am(os.path.join(wpilib_root, "upstream_utils/fmt_patches", f)) diff --git a/upstream_utils/update_gcem.py b/upstream_utils/update_gcem.py index 0f3fe1f7b92..a198e9731c9 100755 --- a/upstream_utils/update_gcem.py +++ b/upstream_utils/update_gcem.py @@ -19,7 +19,10 @@ def main(): # Apply patches to upstream Git repo os.chdir(upstream_root) - for f in []: + for f in [ + "0001-Call-std-functions-if-not-constant-evaluated.patch", + "0002-Add-hypot-x-y-z.patch", + ]: git_am(os.path.join(wpilib_root, "upstream_utils/gcem_patches", f)) # Delete old install diff --git a/upstream_utils/update_libuv.py b/upstream_utils/update_libuv.py index e4c6b2b8bb2..f7d13b4db9b 100755 --- a/upstream_utils/update_libuv.py +++ b/upstream_utils/update_libuv.py @@ -25,11 +25,10 @@ def main(): "0003-Fix-warnings.patch", "0004-Preprocessor-cleanup.patch", "0005-Cleanup-problematic-language.patch", - "0006-Style-comments-cleanup.patch", - "0007-Fix-Win32-warning-suppression-pragma.patch", - "0008-Use-C-atomics.patch", - "0009-Remove-static-from-array-indices.patch", - "0010-Add-pragmas-for-missing-libraries-and-set-_WIN32_WIN.patch", + "0006-Fix-Win32-warning-suppression-pragma.patch", + "0007-Use-C-atomics.patch", + "0008-Remove-static-from-array-indices.patch", + "0009-Add-pragmas-for-missing-libraries-and-set-_WIN32_WIN.patch", ]: git_am(os.path.join(wpilib_root, "upstream_utils/libuv_patches", f)) diff --git a/upstream_utils/update_llvm.py b/upstream_utils/update_llvm.py index 5910396af91..d43527e3d18 100755 --- a/upstream_utils/update_llvm.py +++ b/upstream_utils/update_llvm.py @@ -171,7 +171,7 @@ def overwrite_tests(wpiutil_root, llvm_root): def main(): - upstream_root = clone_repo("https://github.com/llvm/llvm-project", "llvmorg-17.0.4") + upstream_root = clone_repo("https://github.com/llvm/llvm-project", "llvmorg-18.1.1") wpilib_root = get_repo_root() wpiutil = os.path.join(wpilib_root, "wpiutil") @@ -209,8 +209,10 @@ def main(): "0029-Use-C-20-bit-header.patch", "0030-Remove-DenseMap-GTest-printer-test.patch", "0031-Replace-deprecated-std-aligned_storage_t.patch", - "0032-Fix-compilation-of-MathExtras.h-on-Windows-with-sdl.patch", - "0033-raw_ostream-Add-SetNumBytesInBuffer.patch", + "0032-raw_ostream-Add-SetNumBytesInBuffer.patch", + "0033-type_traits.h-Add-is_constexpr.patch", + "0034-Add-back-removed-raw_string_ostream-write_impl.patch", + "0035-Remove-auto-conversion-from-raw_ostream.patch", ]: git_am( os.path.join(wpilib_root, "upstream_utils/llvm_patches", f), diff --git a/upstream_utils/update_sleipnir.py b/upstream_utils/update_sleipnir.py new file mode 100755 index 00000000000..3d58250abeb --- /dev/null +++ b/upstream_utils/update_sleipnir.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 + +import os +import shutil + +from upstream_utils import ( + get_repo_root, + clone_repo, + copy_to, + walk_cwd_and_copy_if, + git_am, +) + + +def main(): + upstream_root = clone_repo( + "https://github.com/SleipnirGroup/Sleipnir", + # main on 2024-04-29 + "9bac50e0f6c1b9ae20e1f611fb7db2cc305ca4fc", + shallow=False, + ) + wpilib_root = get_repo_root() + wpimath = os.path.join(wpilib_root, "wpimath") + + # Apply patches to upstream Git repo + os.chdir(upstream_root) + for f in [ + "0001-Remove-using-enum-declarations.patch", + "0002-Add-implicit-typename.patch", + ]: + git_am(os.path.join(wpilib_root, "upstream_utils/sleipnir_patches", f)) + + # Delete old install + for d in [ + "src/main/native/thirdparty/sleipnir/src", + "src/main/native/thirdparty/sleipnir/include", + ]: + shutil.rmtree(os.path.join(wpimath, d), ignore_errors=True) + + # Copy Sleipnir source files into allwpilib + os.chdir(upstream_root) + src_files = [os.path.join(dp, f) for dp, dn, fn in os.walk("src") for f in fn] + src_files = copy_to( + src_files, os.path.join(wpimath, "src/main/native/thirdparty/sleipnir") + ) + + # Copy Sleipnir header files into allwpilib + include_files = [ + os.path.join(dp, f) for dp, dn, fn in os.walk("include") for f in fn + ] + include_files = copy_to( + include_files, os.path.join(wpimath, "src/main/native/thirdparty/sleipnir") + ) + + for filename in [ + ".clang-format", + ".clang-tidy", + ".styleguide", + ".styleguide-license", + ]: + shutil.copyfile( + os.path.join(upstream_root, filename), + os.path.join(wpimath, "src/main/native/thirdparty/sleipnir", filename), + ) + + +if __name__ == "__main__": + main() diff --git a/vcpkg.json b/vcpkg.json index ea60ac26059..fc499d086bd 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -3,10 +3,9 @@ "version-string": "latest", "dependencies": [ "opencv", - "eigen3", "fmt", "libuv", "protobuf" ], - "builtin-baseline": "78b61582c9e093fda56a01ebb654be15a0033897" + "builtin-baseline": "37c3e63a1306562f7f59c4c3c8892ddd50fdf992" } diff --git a/wpigui/CMakeLists.txt b/wpigui/CMakeLists.txt index 68acbea643c..221977728f4 100644 --- a/wpigui/CMakeLists.txt +++ b/wpigui/CMakeLists.txt @@ -8,10 +8,10 @@ file(GLOB wpigui_windows_src src/main/native/directx11/*.cpp) file(GLOB wpigui_mac_src src/main/native/metal/*.mm) file(GLOB wpigui_unix_src src/main/native/opengl3/*.cpp) -if (MSVC) - add_library(wpigui STATIC ${wpigui_src}) +if(MSVC) + add_library(wpigui STATIC ${wpigui_src}) else() - add_library(wpigui ${wpigui_src}) + add_library(wpigui ${wpigui_src}) endif() set_target_properties(wpigui PROPERTIES DEBUG_POSTFIX "d") set_property(TARGET wpigui PROPERTY POSITION_INDEPENDENT_CODE ON) @@ -21,14 +21,17 @@ set_property(TARGET wpigui PROPERTY FOLDER "libraries") wpilib_target_warnings(wpigui) target_link_libraries(wpigui PUBLIC imgui) -target_include_directories(wpigui PUBLIC - $ - $) +target_include_directories( + wpigui + PUBLIC + $ + $ +) -if (MSVC) +if(MSVC) target_sources(wpigui PRIVATE ${wpigui_windows_src}) else() - if (APPLE) + if(APPLE) target_compile_options(wpigui PRIVATE -fobjc-arc) set_target_properties(wpigui PROPERTIES LINK_FLAGS "-framework Metal -framework QuartzCore") target_sources(wpigui PRIVATE ${wpigui_mac_src}) @@ -43,14 +46,5 @@ wpilib_target_warnings(wpiguidev) target_link_libraries(wpiguidev wpigui) install(TARGETS wpigui EXPORT wpigui) +export(TARGETS wpigui FILE wpigui.cmake NAMESPACE wpigui::) install(DIRECTORY src/main/native/include/ DESTINATION "${include_dest}/wpigui") - -#if (WITH_FLAT_INSTALL) -# set (wpigui_config_dir ${wpilib_dest}) -#else() -# set (wpigui_config_dir share/wpigui) -#endif() - -#configure_file(wpigui-config.cmake.in ${WPILIB_BINARY_DIR}/wpigui-config.cmake ) -#install(FILES ${WPILIB_BINARY_DIR}/wpigui-config.cmake DESTINATION ${wpigui_config_dir}) -#install(EXPORT wpigui DESTINATION ${wpigui_config_dir}) diff --git a/wpilib-config.cmake.in b/wpilib-config.cmake.in index aaf4bb84f85..c08e9d20012 100644 --- a/wpilib-config.cmake.in +++ b/wpilib-config.cmake.in @@ -4,11 +4,18 @@ set(THREADS_PREFER_PTHREAD_FLAG ON) find_dependency(Threads) @LIBUV_SYSTEM_REPLACE@ @EIGEN_SYSTEM_REPLACE@ -@WPIUTIL_DEP_REPLACE@ -@WPINET_DEP_REPLACE@ -@NTCORE_DEP_REPLACE@ -@CSCORE_DEP_REPLACE@ + +@APRILTAG_DEP_REPLACE@ @CAMERASERVER_DEP_REPLACE@ +@CSCORE_DEP_REPLACE@ @HAL_DEP_REPLACE@ +@NTCORE_DEP_REPLACE@ @WPILIBC_DEP_REPLACE@ @WPILIBNEWCOMMANDS_DEP_REPLACE@ +@WPIMATH_DEP_REPLACE@ +@WPINET_DEP_REPLACE@ +@WPIUTIL_DEP_REPLACE@ +if(@WITH_JAVA@) + @WPILIBJ_DEP_REPLACE@ + @WPIUNITS_DEP_REPLACE@ +endif() diff --git a/wpilibNewCommands/CMakeLists.txt b/wpilibNewCommands/CMakeLists.txt index 299b92a861b..e878e35abce 100644 --- a/wpilibNewCommands/CMakeLists.txt +++ b/wpilibNewCommands/CMakeLists.txt @@ -4,40 +4,55 @@ include(SubDirList) include(CompileWarnings) include(AddTest) -if (WITH_JAVA) - find_package(Java REQUIRED) - include(UseJava) - set(CMAKE_JAVA_COMPILE_FLAGS "-encoding" "UTF8" "-Xlint:unchecked") - - file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java) - add_jar(wpilibNewCommands_jar ${JAVA_SOURCES} INCLUDE_JARS hal_jar ntcore_jar cscore_jar cameraserver_jar wpimath_jar wpiunits_jar wpiutil_jar wpilibj_jar OUTPUT_NAME wpilibNewCommands) - - get_property(WPILIBNEWCOMMANDS_JAR_FILE TARGET wpilibNewCommands_jar PROPERTY JAR_FILE) - install(FILES ${WPILIBNEWCOMMANDS_JAR_FILE} DESTINATION "${java_lib_dest}") - - set_property(TARGET wpilibNewCommands_jar PROPERTY FOLDER "java") - - if (WITH_FLAT_INSTALL) - set (wpilibNewCommands_config_dir ${wpilib_dest}) - else() - set (wpilibNewCommands_config_dir share/wpilibNewCommands) - endif() +if(WITH_JAVA) + find_package(Java REQUIRED) + include(UseJava) + set(CMAKE_JAVA_COMPILE_FLAGS "-encoding" "UTF8" "-Xlint:unchecked") + + file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java) + add_jar( + wpilibNewCommands_jar + ${JAVA_SOURCES} + INCLUDE_JARS + hal_jar + ntcore_jar + cscore_jar + cameraserver_jar + wpimath_jar + wpiunits_jar + wpiutil_jar + wpilibj_jar + OUTPUT_NAME wpilibNewCommands + ) + + install_jar(wpilibNewCommands_jar DESTINATION ${java_lib_dest}) + install_jar_exports( + TARGETS wpilibNewCommands_jar + FILE wpilibNewCommands_jar.cmake + DESTINATION share/wpilibNewCommands + ) endif() -if (WITH_JAVA_SOURCE) - find_package(Java REQUIRED) - include(UseJava) - file(GLOB WPILIBNEWCOMMANDS_SOURCES src/main/java/edu/wpi/first/wpilibj2/command/*.java) - file(GLOB WPILIBNEWCOMMANDS_BUTTON_SOURCES src/main/java/edu/wpi/first/wpilibj2/command/button*.java) - add_jar(wpilibNewCommands_src_jar - RESOURCES NAMESPACE "edu/wpi/first/wpilibj2/command" ${WPILIBNEWCOMMANDS_SOURCES} - NAMESPACE "edu/wpi/first/wpilibj2/command/button" ${WPILIBNEWCOMMANDS_BUTTON_SOURCES} - OUTPUT_NAME wpilibNewCommands-sources) - - get_property(WPILIBNEWCOMMANDS_SRC_JAR_FILE TARGET wpilibNewCommands_src_jar PROPERTY JAR_FILE) - install(FILES ${WPILIBNEWCOMMANDS_SRC_JAR_FILE} DESTINATION "${java_lib_dest}") - - set_property(TARGET wpilibNewCommands_src_jar PROPERTY FOLDER "java") +if(WITH_JAVA_SOURCE) + find_package(Java REQUIRED) + include(UseJava) + file(GLOB WPILIBNEWCOMMANDS_SOURCES src/main/java/edu/wpi/first/wpilibj2/command/*.java) + file( + GLOB WPILIBNEWCOMMANDS_BUTTON_SOURCES + src/main/java/edu/wpi/first/wpilibj2/command/button*.java + ) + add_jar( + wpilibNewCommands_src_jar + RESOURCES + NAMESPACE "edu/wpi/first/wpilibj2/command" ${WPILIBNEWCOMMANDS_SOURCES} + NAMESPACE "edu/wpi/first/wpilibj2/command/button" ${WPILIBNEWCOMMANDS_BUTTON_SOURCES} + OUTPUT_NAME wpilibNewCommands-sources + ) + + get_property(WPILIBNEWCOMMANDS_SRC_JAR_FILE TARGET wpilibNewCommands_src_jar PROPERTY JAR_FILE) + install(FILES ${WPILIBNEWCOMMANDS_SRC_JAR_FILE} DESTINATION "${java_lib_dest}") + + set_property(TARGET wpilibNewCommands_src_jar PROPERTY FOLDER "java") endif() file(GLOB_RECURSE wpilibNewCommands_native_src src/main/native/cpp/*.cpp) @@ -49,25 +64,29 @@ target_compile_features(wpilibNewCommands PUBLIC cxx_std_20) wpilib_target_warnings(wpilibNewCommands) target_link_libraries(wpilibNewCommands wpilibc) -target_include_directories(wpilibNewCommands PUBLIC - $ - $) +target_include_directories( + wpilibNewCommands + PUBLIC + $ + $ +) -install(TARGETS wpilibNewCommands EXPORT wpilibNewCommands) +install(TARGETS wpilibNewCommands EXPORT wpilibnewcommands) +export(TARGETS wpilibNewCommands FILE wpilibnewcommands.cmake NAMESPACE wpilibnewcommands::) install(DIRECTORY src/main/native/include/ DESTINATION "${include_dest}/wpilibNewCommands") -if (FLAT_INSTALL_WPILIB) - set(wpilibNewCommands_config_dir ${wpilib_dest}) - else() - set(wpilibNewCommands_config_dir share/wpilibNewCommands) - endif() - - configure_file(wpilibNewCommands-config.cmake.in ${WPILIB_BINARY_DIR}/wpilibNewCommands-config.cmake) - install(FILES ${WPILIB_BINARY_DIR}/wpilibNewCommands-config.cmake DESTINATION ${wpilibNewCommands_config_dir}) - install(EXPORT wpilibNewCommands DESTINATION ${wpilibNewCommands_config_dir}) - - if (WITH_TESTS) - wpilib_add_test(wpilibNewCommands src/test/native/cpp) - target_include_directories(wpilibNewCommands_test PRIVATE src/test/native/include) - target_link_libraries(wpilibNewCommands_test wpilibNewCommands gmock_main) - endif() +configure_file( + wpilibnewcommands-config.cmake.in + ${WPILIB_BINARY_DIR}/wpilibnewcommands-config.cmake +) +install( + FILES ${WPILIB_BINARY_DIR}/wpilibnewcommands-config.cmake + DESTINATION share/wpilibNewCommands +) +install(EXPORT wpilibnewcommands DESTINATION share/wpilibNewCommands) + +if(WITH_TESTS) + wpilib_add_test(wpilibNewCommands src/test/native/cpp) + target_include_directories(wpilibNewCommands_test PRIVATE src/test/native/include) + target_link_libraries(wpilibNewCommands_test wpilibNewCommands gmock_main) +endif() diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/Command.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/Command.java index a913b554e63..255291b933e 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/Command.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/Command.java @@ -4,8 +4,11 @@ package edu.wpi.first.wpilibj2.command; +import static edu.wpi.first.units.Units.Second; import static edu.wpi.first.util.ErrorMessages.requireNonNullParam; +import edu.wpi.first.units.Measure; +import edu.wpi.first.units.Time; import edu.wpi.first.util.function.BooleanConsumer; import edu.wpi.first.util.sendable.Sendable; import edu.wpi.first.util.sendable.SendableBuilder; @@ -25,8 +28,11 @@ *

This class is provided by the NewCommands VendorDep */ public abstract class Command implements Sendable { + /** Requirements set. */ protected Set m_requirements = new HashSet<>(); + /** Default constructor. */ + @SuppressWarnings("this-escape") protected Command() { String name = getClass().getName(); SendableRegistry.add(this, name.substring(name.lastIndexOf('.') + 1)); @@ -146,6 +152,23 @@ public ParallelRaceGroup withTimeout(double seconds) { return raceWith(new WaitCommand(seconds)); } + /** + * Decorates this command with a timeout. If the specified timeout is exceeded before the command + * finishes normally, the command will be interrupted and un-scheduled. + * + *

Note: This decorator works by adding this command to a composition. The command the + * decorator was called on cannot be scheduled independently or be added to a different + * composition (namely, decorators), unless it is manually cleared from the list of composed + * commands with {@link CommandScheduler#removeComposedCommand(Command)}. The command composition + * returned from this method can be further decorated without issue. + * + * @param time the timeout duration + * @return the command with the timeout added + */ + public ParallelRaceGroup withTimeout(Measure

Note: This decorator works by adding this command to a composition. The command the + * decorator was called on cannot be scheduled independently or be added to a different + * composition (namely, decorators), unless it is manually cleared from the list of composed + * commands with {@link CommandScheduler#removeComposedCommand(Command)}. The command composition + * returned from this method can be further decorated without issue. + * + * @param parallel the commands to run in parallel. Note the parallel commands will be interupted + * when the deadline command ends + * @return the decorated command + */ + public ParallelDeadlineGroup deadlineFor(Command... parallel) { + return new ParallelDeadlineGroup(this, parallel); + } + /** * Decorates this command with a set of commands to run parallel to it, ending when the last * command ends. Often more convenient/less-verbose than constructing a new {@link @@ -326,11 +370,16 @@ public RepeatCommand repeatedly() { } /** - * Decorates this command to run "by proxy" by wrapping it in a {@link ProxyCommand}. This is - * useful for "forking off" from command compositions when the user does not wish to extend the - * command's requirements to the entire command composition. + * Decorates this command to run "by proxy" by wrapping it in a {@link ProxyCommand}. Use this for + * "forking off" from command compositions when the user does not wish to extend the command's + * requirements to the entire command composition. ProxyCommand has unique implications and + * semantics, see the WPILib docs for a full explanation. * * @return the decorated command + * @see ProxyCommand + * @see WPILib + * docs */ public ProxyCommand asProxy() { return new ProxyCommand(this); diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/CommandBase.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/CommandBase.java deleted file mode 100644 index 12243cb58b6..00000000000 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/CommandBase.java +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj2.command; - -import edu.wpi.first.util.sendable.Sendable; - -/** - * A {@link Sendable} base class for {@link Command}s. - * - *

This class is provided by the NewCommands VendorDep - * - * @deprecated All functionality provided by {@link CommandBase} has been merged into {@link - * Command}. Use {@link Command} instead. - */ -@Deprecated(since = "2024", forRemoval = true) -@SuppressWarnings("PMD.AbstractClassWithoutAnyMethod") -public abstract class CommandBase extends Command {} diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/CommandScheduler.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/CommandScheduler.java index c868539ff46..7e634cf5c92 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/CommandScheduler.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/CommandScheduler.java @@ -20,7 +20,10 @@ import edu.wpi.first.wpilibj.event.EventLoop; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj2.command.Command.InterruptionBehavior; +import java.io.PrintWriter; +import java.io.StringWriter; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; @@ -61,7 +64,7 @@ public static synchronized CommandScheduler getInstance() { private static final Optional kNoInterruptor = Optional.empty(); - private final Set m_composedCommands = Collections.newSetFromMap(new WeakHashMap<>()); + private final Map m_composedCommands = new WeakHashMap<>(); // A set of the currently-running commands. private final Set m_scheduledCommands = new LinkedHashSet<>(); @@ -261,7 +264,7 @@ public void run() { if (RobotBase.isSimulation()) { subsystem.simulationPeriodic(); } - m_watchdog.addEpoch(subsystem.getClass().getSimpleName() + ".periodic()"); + m_watchdog.addEpoch(subsystem.getName() + ".periodic()"); } // Cache the active instance to avoid concurrency problems if setActiveLoop() is called from @@ -527,6 +530,11 @@ public void enable() { m_disabled = false; } + /** Prints list of epochs added so far and their times. */ + public void printWatchdogEpochs() { + m_watchdog.printEpochs(); + } + /** * Adds an action to perform on the initialization of any command by the scheduler. * @@ -581,12 +589,25 @@ public void onCommandFinish(Consumer action) { * directly or added to a composition. * * @param commands the commands to register - * @throws IllegalArgumentException if the given commands have already been composed. + * @throws IllegalArgumentException if the given commands have already been composed, or the array + * of commands has duplicates. */ public void registerComposedCommands(Command... commands) { - var commandSet = Set.of(commands); - requireNotComposed(commandSet); - m_composedCommands.addAll(commandSet); + Set commandSet; + try { + commandSet = Set.of(commands); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException( + "Cannot compose a command twice in the same composition! (Original exception: " + + e + + ")"); + } + requireNotComposedOrScheduled(commandSet); + var exception = new Exception("Originally composed at:"); + exception.fillInStackTrace(); + for (var command : commands) { + m_composedCommands.put(command, exception); + } } /** @@ -613,30 +634,81 @@ public void removeComposedCommand(Command command) { } /** - * Requires that the specified command hasn't been already added to a composition. + * Strip additional leading stack trace elements that are in the framework package. * - * @param command The command to check + * @param stacktrace the original stacktrace + * @return the stacktrace stripped of leading elements so there is at max one leading element from + * the edu.wpi.first.wpilibj2.command package. + */ + private StackTraceElement[] stripFrameworkStackElements(StackTraceElement[] stacktrace) { + int i = stacktrace.length - 1; + for (; i > 0; i--) { + if (stacktrace[i].getClassName().startsWith("edu.wpi.first.wpilibj2.command.")) { + break; + } + } + return Arrays.copyOfRange(stacktrace, i, stacktrace.length); + } + + /** + * Requires that the specified command hasn't already been added to a composition. + * + * @param commands The commands to check * @throws IllegalArgumentException if the given commands have already been composed. */ - public void requireNotComposed(Command command) { - if (m_composedCommands.contains(command)) { - throw new IllegalArgumentException( - "Commands that have been composed may not be added to another composition or scheduled " - + "individually!"); + public void requireNotComposed(Command... commands) { + for (var command : commands) { + var exception = m_composedCommands.getOrDefault(command, null); + if (exception != null) { + exception.setStackTrace(stripFrameworkStackElements(exception.getStackTrace())); + var buffer = new StringWriter(); + var writer = new PrintWriter(buffer); + writer.println( + "Commands that have been composed may not be added to another composition or scheduled " + + "individually!"); + exception.printStackTrace(writer); + var thrownException = new IllegalArgumentException(buffer.toString()); + thrownException.setStackTrace(stripFrameworkStackElements(thrownException.getStackTrace())); + throw thrownException; + } } } /** - * Requires that the specified commands not have been already added to a composition. + * Requires that the specified commands have not already been added to a composition. * * @param commands The commands to check * @throws IllegalArgumentException if the given commands have already been composed. */ public void requireNotComposed(Collection commands) { - if (!Collections.disjoint(commands, getComposedCommands())) { + requireNotComposed(commands.toArray(Command[]::new)); + } + + /** + * Requires that the specified command hasn't already been added to a composition, and is not + * currently scheduled. + * + * @param command The command to check + * @throws IllegalArgumentException if the given command has already been composed or scheduled. + */ + public void requireNotComposedOrScheduled(Command command) { + if (isScheduled(command)) { throw new IllegalArgumentException( - "Commands that have been composed may not be added to another composition or scheduled " - + "individually!"); + "Commands that have been scheduled individually may not be added to a composition!"); + } + requireNotComposed(command); + } + + /** + * Requires that the specified commands have not already been added to a composition, and are not + * currently scheduled. + * + * @param commands The commands to check + * @throws IllegalArgumentException if the given commands have already been composed or scheduled. + */ + public void requireNotComposedOrScheduled(Collection commands) { + for (var command : commands) { + requireNotComposedOrScheduled(command); } } @@ -651,7 +723,7 @@ public boolean isComposed(Command command) { } Set getComposedCommands() { - return m_composedCommands; + return m_composedCommands.keySet(); } @Override @@ -683,9 +755,7 @@ public void initSendable(SendableBuilder builder) { null); builder.addIntegerArrayProperty( "Cancel", - () -> { - return new long[] {}; - }, + () -> new long[] {}, toCancel -> { Map ids = new LinkedHashMap<>(); for (Command command : m_scheduledCommands) { diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/Commands.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/Commands.java index 7295e3cd43c..0d2178f6b57 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/Commands.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/Commands.java @@ -6,6 +6,8 @@ import static edu.wpi.first.util.ErrorMessages.requireNonNullParam; +import edu.wpi.first.units.Measure; +import edu.wpi.first.units.Time; import java.util.Map; import java.util.Set; import java.util.function.BooleanSupplier; @@ -91,6 +93,19 @@ public static Command runEnd(Runnable run, Runnable end, Subsystem... requiremen () -> {}, run, interrupted -> end.run(), () -> false, requirements); } + /** + * Constructs a command that runs an action once, and then runs an action every iteration until + * interrupted. + * + * @param start the action to run on start + * @param run the action to run every iteration + * @param requirements subsystems the action requires + * @return the command + */ + public static Command startRun(Runnable start, Runnable run, Subsystem... requirements) { + return new FunctionalCommand(start, run, interrupted -> {}, () -> false, requirements); + } + /** * Constructs a command that prints a message and finishes. * @@ -115,6 +130,17 @@ public static Command waitSeconds(double seconds) { return new WaitCommand(seconds); } + /** + * Constructs a command that does nothing, finishing after a specified duration. + * + * @param time after how long the command finishes + * @return the command + * @see WaitCommand + */ + public static Command waitTime(Measure

Note that the supplier must create a new Command each call. For selecting one of a * preallocated set of commands, use {@link SelectCommand}. @@ -28,15 +28,17 @@ public class DeferredCommand extends Command { private Command m_command = m_nullCommand; /** - * Creates a new DeferredCommand that runs the supplied command when initialized, and ends when it - * ends. Useful for lazily creating commands at runtime. The {@link Supplier} will be called each - * time this command is initialized. The Supplier must create a new Command each call. + * Creates a new DeferredCommand that directly runs the supplied command when initialized, and + * ends when it ends. Useful for lazily creating commands when the DeferredCommand is initialized, + * such as if the supplied command depends on runtime state. The {@link Supplier} will be called + * each time this command is initialized. The Supplier must create a new Command each call. * * @param supplier The command supplier * @param requirements The command requirements. This is a {@link Set} to prevent accidental * omission of command requirements. Use {@link Set#of()} to easily construct a requirement * set. */ + @SuppressWarnings("this-escape") public DeferredCommand(Supplier supplier, Set requirements) { m_supplier = requireNonNullParam(supplier, "supplier", "DeferredCommand"); addRequirements(requirements.toArray(new Subsystem[0])); diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/FunctionalCommand.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/FunctionalCommand.java index dde5ae1f013..9f1d8a8130a 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/FunctionalCommand.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/FunctionalCommand.java @@ -18,10 +18,10 @@ *

This class is provided by the NewCommands VendorDep */ public class FunctionalCommand extends Command { - protected final Runnable m_onInit; - protected final Runnable m_onExecute; - protected final Consumer m_onEnd; - protected final BooleanSupplier m_isFinished; + private final Runnable m_onInit; + private final Runnable m_onExecute; + private final Consumer m_onEnd; + private final BooleanSupplier m_isFinished; /** * Creates a new FunctionalCommand. @@ -32,6 +32,7 @@ public class FunctionalCommand extends Command { * @param isFinished the function that determines whether the command has finished * @param requirements the subsystems required by this command */ + @SuppressWarnings("this-escape") public FunctionalCommand( Runnable onInit, Runnable onExecute, diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/MecanumControllerCommand.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/MecanumControllerCommand.java index 16d9c8a1ab2..06663c9a800 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/MecanumControllerCommand.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/MecanumControllerCommand.java @@ -86,6 +86,7 @@ public class MecanumControllerCommand extends Command { * voltages. * @param requirements The subsystems to require. */ + @SuppressWarnings("this-escape") public MecanumControllerCommand( Trajectory trajectory, Supplier pose, @@ -229,6 +230,7 @@ public MecanumControllerCommand( * @param outputWheelSpeeds A MecanumDriveWheelSpeeds object containing the output wheel speeds. * @param requirements The subsystems to require. */ + @SuppressWarnings("this-escape") public MecanumControllerCommand( Trajectory trajectory, Supplier pose, diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/NotifierCommand.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/NotifierCommand.java index ad1a12ad2dc..4109091cd11 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/NotifierCommand.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/NotifierCommand.java @@ -18,8 +18,8 @@ *

This class is provided by the NewCommands VendorDep */ public class NotifierCommand extends Command { - protected final Notifier m_notifier; - protected final double m_period; + private final Notifier m_notifier; + private final double m_period; /** * Creates a new NotifierCommand. @@ -28,6 +28,7 @@ public class NotifierCommand extends Command { * @param period the period at which the notifier should run, in seconds * @param requirements the subsystems required by this command */ + @SuppressWarnings("this-escape") public NotifierCommand(Runnable toRun, double period, Subsystem... requirements) { m_notifier = new Notifier(toRun); m_period = period; diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/PIDCommand.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/PIDCommand.java index c761f3f18df..26627fa30ff 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/PIDCommand.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/PIDCommand.java @@ -19,9 +19,16 @@ *

This class is provided by the NewCommands VendorDep */ public class PIDCommand extends Command { + /** PID controller. */ protected final PIDController m_controller; + + /** Measurement getter. */ protected DoubleSupplier m_measurement; + + /** Setpoint getter. */ protected DoubleSupplier m_setpoint; + + /** PID controller output consumer. */ protected DoubleConsumer m_useOutput; /** diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/PIDSubsystem.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/PIDSubsystem.java index 84318de14a2..8146ca4d7b0 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/PIDSubsystem.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/PIDSubsystem.java @@ -15,7 +15,10 @@ *

This class is provided by the NewCommands VendorDep */ public abstract class PIDSubsystem extends SubsystemBase { + /** PID controller. */ protected final PIDController m_controller; + + /** Whether PID controller output is enabled. */ protected boolean m_enabled; /** @@ -24,6 +27,7 @@ public abstract class PIDSubsystem extends SubsystemBase { * @param controller the PIDController to use * @param initialPosition the initial setpoint of the subsystem */ + @SuppressWarnings("this-escape") public PIDSubsystem(PIDController controller, double initialPosition) { m_controller = requireNonNullParam(controller, "controller", "PIDSubsystem"); setSetpoint(initialPosition); @@ -46,6 +50,11 @@ public void periodic() { } } + /** + * Returns the PIDController. + * + * @return The controller. + */ public PIDController getController() { return m_controller; } @@ -55,7 +64,7 @@ public PIDController getController() { * * @param setpoint the setpoint for the subsystem */ - public void setSetpoint(double setpoint) { + public final void setSetpoint(double setpoint) { m_controller.setSetpoint(setpoint); } diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ParallelDeadlineGroup.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ParallelDeadlineGroup.java index 6d263e88cf6..8acfea8a558 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ParallelDeadlineGroup.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ParallelDeadlineGroup.java @@ -29,20 +29,18 @@ public class ParallelDeadlineGroup extends Command { private InterruptionBehavior m_interruptBehavior = InterruptionBehavior.kCancelIncoming; /** - * Creates a new ParallelDeadlineGroup. The given commands (including the deadline) will be + * Creates a new ParallelDeadlineGroup. The given commands, including the deadline, will be * executed simultaneously. The composition will finish when the deadline finishes, interrupting * all other still-running commands. If the composition is interrupted, only the commands still * running will be interrupted. * * @param deadline the command that determines when the composition ends - * @param commands the commands to be executed + * @param otherCommands the other commands to be executed + * @throws IllegalArgumentException if the deadline command is also in the otherCommands argument */ - public ParallelDeadlineGroup(Command deadline, Command... commands) { - m_deadline = deadline; - addCommands(commands); - if (!m_commands.containsKey(deadline)) { - addCommands(deadline); - } + public ParallelDeadlineGroup(Command deadline, Command... otherCommands) { + addCommands(otherCommands); + setDeadline(deadline); } /** @@ -50,11 +48,19 @@ public ParallelDeadlineGroup(Command deadline, Command... commands) { * contained. * * @param deadline the command that determines when the group ends + * @throws IllegalArgumentException if the deadline command is already in the composition */ - public void setDeadline(Command deadline) { - if (!m_commands.containsKey(deadline)) { - addCommands(deadline); + public final void setDeadline(Command deadline) { + @SuppressWarnings("PMD.CompareObjectsWithEquals") + boolean isAlreadyDeadline = deadline == m_deadline; + if (isAlreadyDeadline) { + return; + } + if (m_commands.containsKey(deadline)) { + throw new IllegalArgumentException( + "The deadline command cannot also be in the other commands!"); } + addCommands(deadline); m_deadline = deadline; } @@ -74,7 +80,7 @@ public final void addCommands(Command... commands) { for (Command command : commands) { if (!Collections.disjoint(command.getRequirements(), m_requirements)) { throw new IllegalArgumentException( - "Multiple commands in a parallel group cannot" + "require the same subsystems"); + "Multiple commands in a parallel group cannot require the same subsystems"); } m_commands.put(command, false); m_requirements.addAll(command.getRequirements()); diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ProfiledPIDCommand.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ProfiledPIDCommand.java index f7175fc2ebe..4e82811739b 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ProfiledPIDCommand.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ProfiledPIDCommand.java @@ -21,9 +21,16 @@ *

This class is provided by the NewCommands VendorDep */ public class ProfiledPIDCommand extends Command { + /** Profiled PID controller. */ protected final ProfiledPIDController m_controller; + + /** Measurement getter. */ protected DoubleSupplier m_measurement; + + /** Goal getter. */ protected Supplier m_goal; + + /** Profiled PID controller output consumer. */ protected BiConsumer m_useOutput; /** diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ProfiledPIDSubsystem.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ProfiledPIDSubsystem.java index 283b4bfd466..05318edc611 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ProfiledPIDSubsystem.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ProfiledPIDSubsystem.java @@ -17,7 +17,10 @@ *

This class is provided by the NewCommands VendorDep */ public abstract class ProfiledPIDSubsystem extends SubsystemBase { + /** Profiled PID controller. */ protected final ProfiledPIDController m_controller; + + /** Whether the profiled PID controller output is enabled. */ protected boolean m_enabled; /** @@ -47,6 +50,11 @@ public void periodic() { } } + /** + * Returns the ProfiledPIDController. + * + * @return The controller. + */ public ProfiledPIDController getController() { return m_controller; } @@ -56,7 +64,7 @@ public ProfiledPIDController getController() { * * @param goal The goal state for the subsystem's motion profile. */ - public void setGoal(TrapezoidProfile.State goal) { + public final void setGoal(TrapezoidProfile.State goal) { m_controller.setGoal(goal); } @@ -65,7 +73,7 @@ public void setGoal(TrapezoidProfile.State goal) { * * @param goal The goal position for the subsystem's motion profile. */ - public void setGoal(double goal) { + public final void setGoal(double goal) { setGoal(new TrapezoidProfile.State(goal, 0)); } diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ProxyCommand.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ProxyCommand.java index d6e93e88ba7..7225dee1a97 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ProxyCommand.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/ProxyCommand.java @@ -10,8 +10,13 @@ import java.util.function.Supplier; /** - * Schedules the given command when this command is initialized, and ends when it ends. Useful for - * forking off from CommandGroups. If this command is interrupted, it will cancel the command. + * Schedules a given command when this command is initialized and ends when it ends, but does not + * directly run it. Use this for including a command in a composition without adding its + * requirements, but only if you know what you are doing. If you are unsure, see the + * WPILib docs for a complete explanation of proxy semantics. Do not proxy a command + * from a subsystem already required by the composition, or else the composition will cancel itself + * when the proxy is reached. If this command is interrupted, it will cancel the command. * *

This class is provided by the NewCommands VendorDep */ @@ -21,10 +26,19 @@ public class ProxyCommand extends Command { /** * Creates a new ProxyCommand that schedules the supplied command when initialized, and ends when - * it is no longer scheduled. Useful for lazily creating commands at runtime. + * it is no longer scheduled. Use this for lazily creating proxied commands at + * runtime. Proxying should only be done to escape from composition requirement semantics, so if + * only initialization time command construction is needed, use {@link DeferredCommand} instead. * * @param supplier the command supplier + * @deprecated This constructor's similarity to {@link DeferredCommand} is confusing and opens + * potential footguns for users who do not fully understand the semantics and implications of + * proxying, but who simply want runtime construction. Users who do know what they are doing + * and need a supplier-constructed proxied command should instead proxy a DeferredCommand + * using the asProxy decorator. + * @see DeferredCommand */ + @Deprecated(since = "2025", forRemoval = true) public ProxyCommand(Supplier supplier) { m_supplier = requireNonNullParam(supplier, "supplier", "ProxyCommand"); } @@ -35,9 +49,11 @@ public ProxyCommand(Supplier supplier) { * * @param command the command to run by proxy */ + @SuppressWarnings("this-escape") public ProxyCommand(Command command) { - this(() -> command); - setName("Proxy(" + command.getName() + ")"); + Command nullCheckedCommand = requireNonNullParam(command, "command", "ProxyCommand"); + m_supplier = () -> nullCheckedCommand; + setName("Proxy(" + nullCheckedCommand.getName() + ")"); } @Override diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/RamseteCommand.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/RamseteCommand.java index 9f19e4a792d..050e97048d8 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/RamseteCommand.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/RamseteCommand.java @@ -69,7 +69,10 @@ public class RamseteCommand extends Command { * @param outputVolts A function that consumes the computed left and right outputs (in volts) for * the robot drive. * @param requirements The subsystems to require. + * @deprecated Use LTVUnicycleController instead. */ + @Deprecated(since = "2024", forRemoval = true) + @SuppressWarnings("this-escape") public RamseteCommand( Trajectory trajectory, Supplier pose, @@ -108,7 +111,10 @@ public RamseteCommand( * @param kinematics The kinematics for the robot drivetrain. * @param outputMetersPerSecond A function that consumes the computed left and right wheel speeds. * @param requirements The subsystems to require. + * @deprecated Use LTVUnicycleController instead. */ + @Deprecated(since = "2024", forRemoval = true) + @SuppressWarnings("this-escape") public RamseteCommand( Trajectory trajectory, Supplier pose, diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/RepeatCommand.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/RepeatCommand.java index 5b49ae00277..70ff63c6103 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/RepeatCommand.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/RepeatCommand.java @@ -20,7 +20,7 @@ *

This class is provided by the NewCommands VendorDep */ public class RepeatCommand extends Command { - protected final Command m_command; + private final Command m_command; private boolean m_ended; /** @@ -29,6 +29,7 @@ public class RepeatCommand extends Command { * * @param command the command to run repeatedly */ + @SuppressWarnings("this-escape") public RepeatCommand(Command command) { m_command = requireNonNullParam(command, "command", "RepeatCommand"); CommandScheduler.getInstance().registerComposedCommands(command); diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/Subsystem.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/Subsystem.java index ac89dbdc218..c0e694774c3 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/Subsystem.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/Subsystem.java @@ -40,6 +40,15 @@ default void periodic() {} */ default void simulationPeriodic() {} + /** + * Gets the subsystem name of this Subsystem. + * + * @return Subsystem name + */ + default String getName() { + return this.getClass().getSimpleName(); + } + /** * Sets the default {@link Command} of the subsystem. The default command will be automatically * scheduled when no other commands are scheduled that require the subsystem. Default commands @@ -137,6 +146,18 @@ default Command runEnd(Runnable run, Runnable end) { return Commands.runEnd(run, end, this); } + /** + * Constructs a command that runs an action once and then runs another action every iteration + * until interrupted. Requires this subsystem. + * + * @param start the action to run on start + * @param run the action to run every iteration + * @return the command + */ + default Command startRun(Runnable start, Runnable run) { + return Commands.startRun(start, run, this); + } + /** * Constructs a {@link DeferredCommand} with the provided supplier. This subsystem is added as a * requirement. diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/SubsystemBase.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/SubsystemBase.java index 6cf926ee234..3a024e5f665 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/SubsystemBase.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/SubsystemBase.java @@ -15,7 +15,8 @@ *

This class is provided by the NewCommands VendorDep */ public abstract class SubsystemBase implements Subsystem, Sendable { - /** Constructor. */ + /** Constructor. Telemetry/log name defaults to the classname. */ + @SuppressWarnings("this-escape") public SubsystemBase() { String name = this.getClass().getSimpleName(); name = name.substring(name.lastIndexOf('.') + 1); @@ -23,11 +24,23 @@ public SubsystemBase() { CommandScheduler.getInstance().registerSubsystem(this); } + /** + * Constructor. + * + * @param name Name of the subsystem for telemetry and logging. + */ + @SuppressWarnings("this-escape") + public SubsystemBase(String name) { + SendableRegistry.addLW(this, name, name); + CommandScheduler.getInstance().registerSubsystem(this); + } + /** * Gets the name of this Subsystem. * * @return Name */ + @Override public String getName() { return SendableRegistry.getName(this); } diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/SwerveControllerCommand.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/SwerveControllerCommand.java index 3eacac3301d..424a288b03b 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/SwerveControllerCommand.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/SwerveControllerCommand.java @@ -186,6 +186,7 @@ public SwerveControllerCommand( * @param outputModuleStates The raw output module states from the position controllers. * @param requirements The subsystems to require. */ + @SuppressWarnings("this-escape") public SwerveControllerCommand( Trajectory trajectory, Supplier pose, diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/TrapezoidProfileCommand.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/TrapezoidProfileCommand.java index 50416b6c30f..8e49706958c 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/TrapezoidProfileCommand.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/TrapezoidProfileCommand.java @@ -22,7 +22,6 @@ public class TrapezoidProfileCommand extends Command { private final Consumer m_output; private final Supplier m_goal; private final Supplier m_currentState; - private final boolean m_newAPI; // TODO: Remove private final Timer m_timer = new Timer(); /** @@ -35,6 +34,7 @@ public class TrapezoidProfileCommand extends Command { * @param currentState The current state * @param requirements The subsystems required by this command. */ + @SuppressWarnings("this-escape") public TrapezoidProfileCommand( TrapezoidProfile profile, Consumer output, @@ -45,28 +45,6 @@ public TrapezoidProfileCommand( m_output = requireNonNullParam(output, "output", "TrapezoidProfileCommand"); m_goal = goal; m_currentState = currentState; - m_newAPI = true; - addRequirements(requirements); - } - - /** - * Creates a new TrapezoidProfileCommand that will execute the given {@link TrapezoidProfile}. - * Output will be piped to the provided consumer function. - * - * @param profile The motion profile to execute. - * @param output The consumer for the profile output. - * @param requirements The subsystems required by this command. - * @deprecated The new constructor allows you to pass in a supplier for desired and current state. - * This allows you to change goals at runtime. - */ - @Deprecated(since = "2024", forRemoval = true) - public TrapezoidProfileCommand( - TrapezoidProfile profile, Consumer output, Subsystem... requirements) { - m_profile = requireNonNullParam(profile, "profile", "TrapezoidProfileCommand"); - m_output = requireNonNullParam(output, "output", "TrapezoidProfileCommand"); - m_newAPI = false; - m_goal = null; - m_currentState = null; addRequirements(requirements); } @@ -78,11 +56,7 @@ public void initialize() { @Override @SuppressWarnings("removal") public void execute() { - if (m_newAPI) { - m_output.accept(m_profile.calculate(m_timer.get(), m_currentState.get(), m_goal.get())); - } else { - m_output.accept(m_profile.calculate(m_timer.get())); - } + m_output.accept(m_profile.calculate(m_timer.get(), m_currentState.get(), m_goal.get())); } @Override diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/TrapezoidProfileSubsystem.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/TrapezoidProfileSubsystem.java index 35c02e6ee63..44abdfc4db9 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/TrapezoidProfileSubsystem.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/TrapezoidProfileSubsystem.java @@ -63,7 +63,7 @@ public TrapezoidProfileSubsystem(TrapezoidProfile.Constraints constraints) { @Override public void periodic() { - m_state = m_profile.calculate(m_period, m_goal, m_state); + m_state = m_profile.calculate(m_period, m_state, m_goal); if (m_enabled) { useState(m_state); } @@ -74,7 +74,7 @@ public void periodic() { * * @param goal The goal state for the subsystem's motion profile. */ - public void setGoal(TrapezoidProfile.State goal) { + public final void setGoal(TrapezoidProfile.State goal) { m_goal = goal; } @@ -83,7 +83,7 @@ public void setGoal(TrapezoidProfile.State goal) { * * @param goal The goal position for the subsystem's motion profile. */ - public void setGoal(double goal) { + public final void setGoal(double goal) { setGoal(new TrapezoidProfile.State(goal, 0)); } diff --git a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/WaitCommand.java b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/WaitCommand.java index e7b32be8f68..a0851925137 100644 --- a/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/WaitCommand.java +++ b/wpilibNewCommands/src/main/java/edu/wpi/first/wpilibj2/command/WaitCommand.java @@ -4,6 +4,10 @@ package edu.wpi.first.wpilibj2.command; +import static edu.wpi.first.units.Units.Second; + +import edu.wpi.first.units.Measure; +import edu.wpi.first.units.Time; import edu.wpi.first.util.sendable.SendableBuilder; import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.Timer; @@ -14,7 +18,9 @@ *

This class is provided by the NewCommands VendorDep */ public class WaitCommand extends Command { + /** The timer used for waiting. */ protected Timer m_timer = new Timer(); + private final double m_duration; /** @@ -22,11 +28,21 @@ public class WaitCommand extends Command { * * @param seconds the time to wait, in seconds */ + @SuppressWarnings("this-escape") public WaitCommand(double seconds) { m_duration = seconds; SendableRegistry.setName(this, getName() + ": " + seconds + " seconds"); } + /** + * Creates a new WaitCommand. This command will do nothing, and end after the specified duration. + * + * @param time the time to wait + */ + public WaitCommand(Measure

A single subsystem may have multiple mechanisms, but mechanisms should not share test + * routines. Each complete test of a mechanism should have its own SysIdRoutine instance, since the + * log name of the recorded data is determined by the mechanism name. + * + *

The test state (e.g. "quasistatic-forward") is logged once per iteration during test + * execution, and once with state "none" when a test ends. Motor frames are logged every iteration + * during test execution. + * + *

Timestamps are not coordinated across data, so motor frames and test state tags may be + * recorded on different log frames. Because frame alignment is not guaranteed, SysId parses the log + * by using the test state flag to determine the timestamp range for each section of the test, and + * then extracts the motor frames within the valid timestamp ranges. If a given test was run + * multiple times in a single logfile, the user will need to select which of the tests to use for + * the fit in the analysis tool. + */ +public class SysIdRoutine extends SysIdRoutineLog { + private final Config m_config; + private final Mechanism m_mechanism; + private final MutableMeasure m_outputVolts = mutable(Volts.of(0)); + private final Consumer m_recordState; + + /** + * Create a new SysId characterization routine. + * + * @param config Hardware-independent parameters for the SysId routine. + * @param mechanism Hardware interface for the SysId routine. + */ + public SysIdRoutine(Config config, Mechanism mechanism) { + super(mechanism.m_name); + m_config = config; + m_mechanism = mechanism; + m_recordState = config.m_recordState != null ? config.m_recordState : this::recordState; + } + + /** Hardware-independent configuration for a SysId test routine. */ + public static class Config { + /** The voltage ramp rate used for quasistatic test routines. */ + public final Measure> m_rampRate; + + /** The step voltage output used for dynamic test routines. */ + public final Measure m_stepVoltage; + + /** Safety timeout for the test routine commands. */ + public final Measure

rampRate: 1 volt/sec + * + *

stepVoltage: 7 volts + * + *

timeout: 10 seconds + */ + public Config() { + this(null, null, null, null); + } + } + + /** + * A mechanism to be characterized by a SysId routine. Defines callbacks needed for the SysId test + * routine to control and record data from the mechanism. + */ + public static class Mechanism { + /** Sends the SysId-specified drive signal to the mechanism motors during test routines. */ + public final Consumer> m_drive; + + /** + * Returns measured data (voltages, positions, velocities) of the mechanism motors during test + * routines. + */ + public final Consumer m_log; + + /** The subsystem containing the motor(s) that is (or are) being characterized. */ + public final Subsystem m_subsystem; + + /** The name of the mechanism being tested. */ + public final String m_name; + + /** + * Create a new mechanism specification for a SysId routine. + * + * @param drive Sends the SysId-specified drive signal to the mechanism motors during test + * routines. + * @param log Returns measured data of the mechanism motors during test routines. To return + * data, call `motor(string motorName)` on the supplied `SysIdRoutineLog` instance, and then + * call one or more of the chainable logging handles (e.g. `voltage`) on the returned + * `MotorLog`. Multiple motors can be logged in a single callback by calling `motor` + * multiple times. + * @param subsystem The subsystem containing the motor(s) that is (or are) being characterized. + * Will be declared as a requirement for the returned test commands. + * @param name The name of the mechanism being tested. Will be appended to the log entry title + * for the routine's test state, e.g. "sysid-test-state-mechanism". Defaults to the name of + * the subsystem if left null. + */ + public Mechanism( + Consumer> drive, + Consumer log, + Subsystem subsystem, + String name) { + m_drive = drive; + m_log = log != null ? log : l -> {}; + m_subsystem = subsystem; + m_name = name != null ? name : subsystem.getName(); + } + + /** + * Create a new mechanism specification for a SysId routine. Defaults the mechanism name to the + * subsystem name. + * + * @param drive Sends the SysId-specified drive signal to the mechanism motors during test + * routines. + * @param log Returns measured data of the mechanism motors during test routines. To return + * data, call `motor(string motorName)` on the supplied `SysIdRoutineLog` instance, and then + * call one or more of the chainable logging handles (e.g. `voltage`) on the returned + * `MotorLog`. Multiple motors can be logged in a single callback by calling `motor` + * multiple times. + * @param subsystem The subsystem containing the motor(s) that is (or are) being characterized. + * Will be declared as a requirement for the returned test commands. The subsystem's `name` + * will be appended to the log entry title for the routine's test state, e.g. + * "sysid-test-state-subsystem". + */ + public Mechanism( + Consumer> drive, Consumer log, Subsystem subsystem) { + this(drive, log, subsystem, null); + } + } + + /** Motor direction for a SysId test. */ + public enum Direction { + /** Forward. */ + kForward, + /** Reverse. */ + kReverse + } + + /** + * Returns a command to run a quasistatic test in the specified direction. + * + *

The command will call the `drive` and `log` callbacks supplied at routine construction once + * per iteration. Upon command end or interruption, the `drive` callback is called with a value of + * 0 volts. + * + * @param direction The direction in which to run the test. + * @return A command to run the test. + */ + public Command quasistatic(Direction direction) { + State state; + if (direction == Direction.kForward) { + state = State.kQuasistaticForward; + } else { // if (direction == Direction.kReverse) { + state = State.kQuasistaticReverse; + } + + double outputSign = direction == Direction.kForward ? 1.0 : -1.0; + + Timer timer = new Timer(); + return m_mechanism + .m_subsystem + .runOnce(timer::restart) + .andThen( + m_mechanism.m_subsystem.run( + () -> { + m_mechanism.m_drive.accept( + m_outputVolts.mut_replace( + outputSign * timer.get() * m_config.m_rampRate.in(Volts.per(Second)), + Volts)); + m_mechanism.m_log.accept(this); + m_recordState.accept(state); + })) + .finallyDo( + () -> { + m_mechanism.m_drive.accept(Volts.of(0)); + m_recordState.accept(State.kNone); + timer.stop(); + }) + .withName("sysid-" + state.toString() + "-" + m_mechanism.m_name) + .withTimeout(m_config.m_timeout.in(Seconds)); + } + + /** + * Returns a command to run a dynamic test in the specified direction. + * + *

The command will call the `drive` and `log` callbacks supplied at routine construction once + * per iteration. Upon command end or interruption, the `drive` callback is called with a value of + * 0 volts. + * + * @param direction The direction in which to run the test. + * @return A command to run the test. + */ + public Command dynamic(Direction direction) { + double outputSign = direction == Direction.kForward ? 1.0 : -1.0; + State state = + Map.ofEntries( + entry(Direction.kForward, State.kDynamicForward), + entry(Direction.kReverse, State.kDynamicReverse)) + .get(direction); + + return m_mechanism + .m_subsystem + .runOnce( + () -> m_outputVolts.mut_replace(m_config.m_stepVoltage.in(Volts) * outputSign, Volts)) + .andThen( + m_mechanism.m_subsystem.run( + () -> { + m_mechanism.m_drive.accept(m_outputVolts); + m_mechanism.m_log.accept(this); + m_recordState.accept(state); + })) + .finallyDo( + () -> { + m_mechanism.m_drive.accept(Volts.of(0)); + m_recordState.accept(State.kNone); + }) + .withName("sysid-" + state.toString() + "-" + m_mechanism.m_name) + .withTimeout(m_config.m_timeout.in(Seconds)); + } +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/Command.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/Command.cpp index 66de555ca9f..b9183146c00 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/Command.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/Command.cpp @@ -4,6 +4,7 @@ #include "frc2/command/Command.h" +#include #include #include @@ -31,7 +32,7 @@ Command::~Command() { } Command& Command::operator=(const Command& rhs) { - m_isComposed = false; + SetComposed(false); return *this; } @@ -156,17 +157,24 @@ bool Command::HasRequirement(Subsystem* requirement) const { } bool Command::IsComposed() const { - return m_isComposed; + return GetPreviousCompositionSite().has_value(); } void Command::SetComposed(bool isComposed) { - m_isComposed = isComposed; + if (isComposed) { + m_previousComposition = wpi::GetStackTrace(1); + } else { + m_previousComposition.reset(); + } +} + +std::optional Command::GetPreviousCompositionSite() const { + return m_previousComposition; } void Command::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("Command"); - builder.AddStringProperty( - ".name", [this] { return GetName(); }, nullptr); + builder.AddStringProperty(".name", [this] { return GetName(); }, nullptr); builder.AddBooleanProperty( "running", [this] { return IsScheduled(); }, [this](bool value) { diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandPtr.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandPtr.cpp index 6f7e41837a1..4cd0cbee9d6 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandPtr.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandPtr.cpp @@ -22,10 +22,22 @@ using namespace frc2; +CommandPtr::CommandPtr(std::unique_ptr&& command) + : m_ptr(std::move(command)) { + AssertValid(); +} + +CommandPtr::CommandPtr(CommandPtr&& rhs) { + m_ptr = std::move(rhs.m_ptr); + AssertValid(); + rhs.m_moveOutSite = wpi::GetStackTrace(1); +} + void CommandPtr::AssertValid() const { if (!m_ptr) { throw FRC_MakeError(frc::err::CommandIllegalUse, - "Moved-from CommandPtr object used!"); + "Moved-from CommandPtr object used!\nMoved out at:\n{}", + m_moveOutSite); } } @@ -162,6 +174,15 @@ CommandPtr CommandPtr::DeadlineWith(CommandPtr&& parallel) && { return std::move(*this); } +CommandPtr CommandPtr::DeadlineFor(CommandPtr&& parallel) && { + AssertValid(); + std::vector> vec; + vec.emplace_back(std::move(parallel).Unwrap()); + m_ptr = + std::make_unique(std::move(m_ptr), std::move(vec)); + return std::move(*this); +} + CommandPtr CommandPtr::AlongWith(CommandPtr&& parallel) && { AssertValid(); std::vector> vec; diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandScheduler.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandScheduler.cpp index d61ffbda3e4..f845cbc0533 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandScheduler.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandScheduler.cpp @@ -183,7 +183,7 @@ void CommandScheduler::Run() { if constexpr (frc::RobotBase::IsSimulation()) { subsystem.getFirst()->SimulationPeriodic(); } - m_watchdog.AddEpoch("Subsystem Periodic()"); + m_watchdog.AddEpoch(subsystem.getFirst()->GetName() + ".Periodic()"); } // Cache the active instance to avoid concurrency problems if SetActiveLoop() @@ -428,6 +428,10 @@ void CommandScheduler::Enable() { m_impl->disabled = false; } +void CommandScheduler::PrintWatchdogEpochs() { + m_watchdog.PrintEpochs(); +} + void CommandScheduler::OnCommandInitialize(Action action) { m_impl->initActions.emplace_back(std::move(action)); } @@ -453,11 +457,13 @@ void CommandScheduler::OnCommandFinish(Action action) { } void CommandScheduler::RequireUngrouped(const Command* command) { - if (command->IsComposed()) { + auto stacktrace = command->GetPreviousCompositionSite(); + if (stacktrace.has_value()) { throw FRC_MakeError(frc::err::CommandIllegalUse, "Commands that have been composed may not be added to " - "another composition or scheduled " - "individually!"); + "another composition or scheduled individually!" + "\nOriginally composed at:\n{}", + stacktrace.value()); } } @@ -475,6 +481,29 @@ void CommandScheduler::RequireUngrouped( } } +void CommandScheduler::RequireUngroupedAndUnscheduled(const Command* command) { + if (IsScheduled(command)) { + throw FRC_MakeError(frc::err::CommandIllegalUse, + "Commands that have been scheduled individually may " + "not be added to another composition!"); + } + RequireUngrouped(command); +} + +void CommandScheduler::RequireUngroupedAndUnscheduled( + std::span> commands) { + for (auto&& command : commands) { + RequireUngroupedAndUnscheduled(command.get()); + } +} + +void CommandScheduler::RequireUngroupedAndUnscheduled( + std::initializer_list commands) { + for (auto&& command : commands) { + RequireUngroupedAndUnscheduled(command); + } +} + void CommandScheduler::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("Scheduler"); builder.AddStringArrayProperty( diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/Commands.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/Commands.cpp index 31a4b1fe1c3..15458083d69 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/Commands.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/Commands.cpp @@ -4,6 +4,8 @@ #include "frc2/command/Commands.h" +#include + #include "frc2/command/ConditionalCommand.h" #include "frc2/command/DeferredCommand.h" #include "frc2/command/FunctionalCommand.h" @@ -56,10 +58,19 @@ CommandPtr cmd::RunEnd(std::function run, std::function end, .ToPtr(); } +CommandPtr cmd::StartRun(std::function start, std::function run, + Requirements requirements) { + return FunctionalCommand( + std::move(start), std::move(run), [](bool interrupted) {}, + [] { return false; }, requirements) + .ToPtr(); +} + CommandPtr cmd::Print(std::string_view msg) { return PrintCommand(msg).ToPtr(); } +WPI_IGNORE_DEPRECATED CommandPtr cmd::DeferredProxy(wpi::unique_function supplier) { return ProxyCommand(std::move(supplier)).ToPtr(); } @@ -67,6 +78,7 @@ CommandPtr cmd::DeferredProxy(wpi::unique_function supplier) { CommandPtr cmd::DeferredProxy(wpi::unique_function supplier) { return ProxyCommand(std::move(supplier)).ToPtr(); } +WPI_UNIGNORE_DEPRECATED CommandPtr cmd::Wait(units::second_t duration) { return WaitCommand(duration).ToPtr(); diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/ConditionalCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/ConditionalCommand.cpp index 4c07c7ae241..6ce33b75486 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/ConditionalCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/ConditionalCommand.cpp @@ -12,7 +12,7 @@ ConditionalCommand::ConditionalCommand(std::unique_ptr&& onTrue, std::unique_ptr&& onFalse, std::function condition) : m_condition{std::move(condition)} { - CommandScheduler::GetInstance().RequireUngrouped( + CommandScheduler::GetInstance().RequireUngroupedAndUnscheduled( {onTrue.get(), onFalse.get()}); m_onTrue = std::move(onTrue); diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/MecanumControllerCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/MecanumControllerCommand.cpp index 902c26b30eb..6059db4ecee 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/MecanumControllerCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/MecanumControllerCommand.cpp @@ -6,7 +6,12 @@ #include +#include +#include + using namespace frc2; +using kv_unit = units::compound_unit>; MecanumControllerCommand::MecanumControllerCommand( frc::Trajectory trajectory, std::function pose, @@ -95,6 +100,7 @@ MecanumControllerCommand::MecanumControllerCommand( Requirements requirements) : m_trajectory(std::move(trajectory)), m_pose(std::move(pose)), + m_feedforward(0_V, units::unit_t{0}), m_kinematics(kinematics), m_controller(xController, yController, thetaController), m_desiredRotation(std::move(desiredRotation)), @@ -116,6 +122,7 @@ MecanumControllerCommand::MecanumControllerCommand( Requirements requirements) : m_trajectory(std::move(trajectory)), m_pose(std::move(pose)), + m_feedforward(0_V, units::unit_t{0}), m_kinematics(kinematics), m_controller(xController, yController, thetaController), m_maxWheelVelocity(maxWheelVelocity), diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelCommandGroup.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelCommandGroup.cpp index 99e0845c8d7..4a234b14756 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelCommandGroup.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelCommandGroup.cpp @@ -63,7 +63,7 @@ Command::InterruptionBehavior ParallelCommandGroup::GetInterruptionBehavior() void ParallelCommandGroup::AddCommands( std::vector>&& commands) { - CommandScheduler::GetInstance().RequireUngrouped(commands); + CommandScheduler::GetInstance().RequireUngroupedAndUnscheduled(commands); if (isRunning) { throw FRC_MakeError(frc::err::CommandIllegalUse, diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelDeadlineGroup.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelDeadlineGroup.cpp index a6b5c1c264b..1c9b7005345 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelDeadlineGroup.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelDeadlineGroup.cpp @@ -62,7 +62,7 @@ Command::InterruptionBehavior ParallelDeadlineGroup::GetInterruptionBehavior() void ParallelDeadlineGroup::AddCommands( std::vector>&& commands) { - CommandScheduler::GetInstance().RequireUngrouped(commands); + CommandScheduler::GetInstance().RequireUngroupedAndUnscheduled(commands); if (!m_finished) { throw FRC_MakeError(frc::err::CommandIllegalUse, diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelRaceGroup.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelRaceGroup.cpp index df658bcc732..334286f8e37 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelRaceGroup.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/ParallelRaceGroup.cpp @@ -50,7 +50,7 @@ Command::InterruptionBehavior ParallelRaceGroup::GetInterruptionBehavior() void ParallelRaceGroup::AddCommands( std::vector>&& commands) { - CommandScheduler::GetInstance().RequireUngrouped(commands); + CommandScheduler::GetInstance().RequireUngroupedAndUnscheduled(commands); if (isRunning) { throw FRC_MakeError(frc::err::CommandIllegalUse, diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/PrintCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/PrintCommand.cpp index 8d7c855602f..8032dada7ea 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/PrintCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/PrintCommand.cpp @@ -4,12 +4,12 @@ #include "frc2/command/PrintCommand.h" -#include +#include using namespace frc2; PrintCommand::PrintCommand(std::string_view message) - : CommandHelper{[str = std::string(message)] { fmt::print("{}\n", str); }, + : CommandHelper{[str = std::string(message)] { wpi::print("{}\n", str); }, {}} {} bool PrintCommand::RunsWhenDisabled() const { diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/ProxyCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/ProxyCommand.cpp index eb4fb7cab1f..9f903845eef 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/ProxyCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/ProxyCommand.cpp @@ -4,10 +4,13 @@ #include "frc2/command/ProxyCommand.h" +#include +#include #include using namespace frc2; +WPI_IGNORE_DEPRECATED ProxyCommand::ProxyCommand(wpi::unique_function supplier) : m_supplier(std::move(supplier)) {} @@ -17,14 +20,15 @@ ProxyCommand::ProxyCommand(wpi::unique_function supplier) holder = supplier(); return holder->get(); }) {} +WPI_UNIGNORE_DEPRECATED ProxyCommand::ProxyCommand(Command* command) - : ProxyCommand([command] { return command; }) { - SetName(std::string{"Proxy("}.append(command->GetName()).append(")")); + : m_supplier([command] { return command; }) { + SetName(fmt::format("Proxy({})", command->GetName())); } ProxyCommand::ProxyCommand(std::unique_ptr command) { - SetName(std::string{"Proxy("}.append(command->GetName()).append(")")); + SetName(fmt::format("Proxy({})", command->GetName())); m_supplier = [command = std::move(command)] { return command.get(); }; } diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/RamseteCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/RamseteCommand.cpp index 91459858dd6..b78b6ad4c1c 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/RamseteCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/RamseteCommand.cpp @@ -6,9 +6,13 @@ #include +#include +#include #include using namespace frc2; +using kv_unit = units::compound_unit>; RamseteCommand::RamseteCommand( frc::Trajectory trajectory, std::function pose, @@ -42,6 +46,7 @@ RamseteCommand::RamseteCommand( : m_trajectory(std::move(trajectory)), m_pose(std::move(pose)), m_controller(controller), + m_feedforward(0_V, units::unit_t{0}), m_kinematics(std::move(kinematics)), m_outputVel(std::move(output)), m_usePID(false) { diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/RepeatCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/RepeatCommand.cpp index 2e74c8c72fd..2a08f1b0438 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/RepeatCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/RepeatCommand.cpp @@ -9,7 +9,7 @@ using namespace frc2; RepeatCommand::RepeatCommand(std::unique_ptr&& command) { - CommandScheduler::GetInstance().RequireUngrouped(command.get()); + CommandScheduler::GetInstance().RequireUngroupedAndUnscheduled(command.get()); m_command = std::move(command); m_command->SetComposed(true); AddRequirements(m_command->GetRequirements()); diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/SequentialCommandGroup.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/SequentialCommandGroup.cpp index b9ea3d56ecb..173b9d93c8e 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/SequentialCommandGroup.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/SequentialCommandGroup.cpp @@ -62,7 +62,7 @@ Command::InterruptionBehavior SequentialCommandGroup::GetInterruptionBehavior() void SequentialCommandGroup::AddCommands( std::vector>&& commands) { - CommandScheduler::GetInstance().RequireUngrouped(commands); + CommandScheduler::GetInstance().RequireUngroupedAndUnscheduled(commands); if (m_currentCommandIndex != invalid_index) { throw FRC_MakeError(frc::err::CommandIllegalUse, diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/Subsystem.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/Subsystem.cpp index 4c06f1f4ead..5800c440692 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/Subsystem.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/Subsystem.cpp @@ -4,6 +4,8 @@ #include "frc2/command/Subsystem.h" +#include + #include "frc2/command/CommandPtr.h" #include "frc2/command/Commands.h" @@ -16,6 +18,10 @@ void Subsystem::Periodic() {} void Subsystem::SimulationPeriodic() {} +std::string Subsystem::GetName() const { + return wpi::GetTypeName(*this); +} + void Subsystem::SetDefaultCommand(CommandPtr&& defaultCommand) { CommandScheduler::GetInstance().SetDefaultCommand(this, std::move(defaultCommand)); @@ -55,6 +61,11 @@ CommandPtr Subsystem::RunEnd(std::function run, return cmd::RunEnd(std::move(run), std::move(end), {this}); } +CommandPtr Subsystem::StartRun(std::function start, + std::function run) { + return cmd::StartRun(std::move(start), std::move(run), {this}); +} + CommandPtr Subsystem::Defer(wpi::unique_function supplier) { return cmd::Defer(std::move(supplier), {this}); } diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/SubsystemBase.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/SubsystemBase.cpp index 8216a075828..e5a40388e4a 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/SubsystemBase.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/SubsystemBase.cpp @@ -17,6 +17,11 @@ SubsystemBase::SubsystemBase() { CommandScheduler::GetInstance().RegisterSubsystem({this}); } +SubsystemBase::SubsystemBase(std::string_view name) { + wpi::SendableRegistry::AddLW(this, name); + CommandScheduler::GetInstance().RegisterSubsystem({this}); +} + void SubsystemBase::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("Subsystem"); builder.AddBooleanProperty( diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/WrapperCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/WrapperCommand.cpp index f7928c964e6..2e1b280d693 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/WrapperCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/WrapperCommand.cpp @@ -9,7 +9,7 @@ using namespace frc2; WrapperCommand::WrapperCommand(std::unique_ptr&& command) { - CommandScheduler::GetInstance().RequireUngrouped(command.get()); + CommandScheduler::GetInstance().RequireUngroupedAndUnscheduled(command.get()); m_command = std::move(command); m_command->SetComposed(true); // copy the wrapped command's name @@ -43,3 +43,7 @@ Command::InterruptionBehavior WrapperCommand::GetInterruptionBehavior() const { wpi::SmallSet WrapperCommand::GetRequirements() const { return m_command->GetRequirements(); } + +void WrapperCommand::InitSendable(wpi::SendableBuilder& builder) { + m_command->InitSendable(builder); +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/button/CommandStadiaController.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/button/CommandStadiaController.cpp new file mode 100644 index 00000000000..86c34bad219 --- /dev/null +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/button/CommandStadiaController.cpp @@ -0,0 +1,72 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc2/command/button/CommandStadiaController.h" + +using namespace frc2; + +Trigger CommandStadiaController::Button(int button, + frc::EventLoop* loop) const { + return GenericHID::Button(button, loop).CastTo(); +} + +Trigger CommandStadiaController::LeftBumper(frc::EventLoop* loop) const { + return StadiaController::LeftBumper(loop).CastTo(); +} + +Trigger CommandStadiaController::RightBumper(frc::EventLoop* loop) const { + return StadiaController::RightBumper(loop).CastTo(); +} + +Trigger CommandStadiaController::LeftStick(frc::EventLoop* loop) const { + return StadiaController::LeftStick(loop).CastTo(); +} + +Trigger CommandStadiaController::RightStick(frc::EventLoop* loop) const { + return StadiaController::RightStick(loop).CastTo(); +} + +Trigger CommandStadiaController::A(frc::EventLoop* loop) const { + return StadiaController::A(loop).CastTo(); +} + +Trigger CommandStadiaController::B(frc::EventLoop* loop) const { + return StadiaController::B(loop).CastTo(); +} + +Trigger CommandStadiaController::X(frc::EventLoop* loop) const { + return StadiaController::X(loop).CastTo(); +} + +Trigger CommandStadiaController::Y(frc::EventLoop* loop) const { + return StadiaController::Y(loop).CastTo(); +} + +Trigger CommandStadiaController::Ellipses(frc::EventLoop* loop) const { + return StadiaController::Ellipses(loop).CastTo(); +} + +Trigger CommandStadiaController::Hamburger(frc::EventLoop* loop) const { + return StadiaController::Hamburger(loop).CastTo(); +} + +Trigger CommandStadiaController::Stadia(frc::EventLoop* loop) const { + return StadiaController::Stadia(loop).CastTo(); +} + +Trigger CommandStadiaController::Google(frc::EventLoop* loop) const { + return StadiaController::Google(loop).CastTo(); +} + +Trigger CommandStadiaController::Frame(frc::EventLoop* loop) const { + return StadiaController::Frame(loop).CastTo(); +} + +Trigger CommandStadiaController::LeftTrigger(frc::EventLoop* loop) const { + return StadiaController::LeftTrigger(loop).CastTo(); +} + +Trigger CommandStadiaController::RightTrigger(frc::EventLoop* loop) const { + return StadiaController::RightTrigger(loop).CastTo(); +} diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/button/Trigger.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/button/Trigger.cpp index 190a5448177..78fd0b3f769 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/button/Trigger.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/button/Trigger.cpp @@ -13,6 +13,34 @@ using namespace frc2; Trigger::Trigger(const Trigger& other) = default; +Trigger Trigger::OnChange(Command* command) { + m_loop->Bind( + [condition = m_condition, previous = m_condition(), command]() mutable { + bool current = condition(); + + if (previous != current) { + command->Schedule(); + } + + previous = current; + }); + return *this; +} + +Trigger Trigger::OnChange(CommandPtr&& command) { + m_loop->Bind([condition = m_condition, previous = m_condition(), + command = std::move(command)]() mutable { + bool current = condition(); + + if (previous != current) { + command.Schedule(); + } + + previous = current; + }); + return *this; +} + Trigger Trigger::OnTrue(Command* command) { m_loop->Bind( [condition = m_condition, previous = m_condition(), command]() mutable { diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/sysid/SysIdRoutine.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/sysid/SysIdRoutine.cpp new file mode 100644 index 00000000000..359c8d824d4 --- /dev/null +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/sysid/SysIdRoutine.cpp @@ -0,0 +1,66 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc2/command/sysid/SysIdRoutine.h" + +#include + +using namespace frc2::sysid; + +frc2::CommandPtr SysIdRoutine::Quasistatic(Direction direction) { + frc::sysid::State state; + if (direction == Direction::kForward) { + state = frc::sysid::State::kQuasistaticForward; + } else { // if (direction == Direction::kReverse) { + state = frc::sysid::State::kQuasistaticReverse; + } + + double outputSign = direction == Direction::kForward ? 1.0 : -1.0; + + return m_mechanism.m_subsystem->RunOnce([this] { timer.Restart(); }) + .AndThen( + m_mechanism.m_subsystem + ->Run([this, state, outputSign] { + m_outputVolts = outputSign * timer.Get() * m_config.m_rampRate; + m_mechanism.m_drive(m_outputVolts); + m_mechanism.m_log(this); + m_recordState(state); + }) + .FinallyDo([this] { + m_mechanism.m_drive(0_V); + m_recordState(frc::sysid::State::kNone); + timer.Stop(); + }) + .WithName("sysid-" + + frc::sysid::SysIdRoutineLog::StateEnumToString(state) + + "-" + m_mechanism.m_name) + .WithTimeout(m_config.m_timeout)); +} + +frc2::CommandPtr SysIdRoutine::Dynamic(Direction direction) { + frc::sysid::State state; + if (direction == Direction::kForward) { + state = frc::sysid::State::kDynamicForward; + } else { // if (direction == Direction::kReverse) { + state = frc::sysid::State::kDynamicReverse; + } + + double outputSign = direction == Direction::kForward ? 1.0 : -1.0; + + return m_mechanism.m_subsystem + ->RunOnce([this] { m_outputVolts = m_config.m_stepVoltage; }) + .AndThen(m_mechanism.m_subsystem->Run([this, state, outputSign] { + m_mechanism.m_drive(m_outputVolts * outputSign); + m_mechanism.m_log(this); + m_recordState(state); + })) + .FinallyDo([this] { + m_mechanism.m_drive(0_V); + m_recordState(frc::sysid::State::kNone); + }) + .WithName("sysid-" + + frc::sysid::SysIdRoutineLog::StateEnumToString(state) + "-" + + m_mechanism.m_name) + .WithTimeout(m_config.m_timeout); +} diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/Command.h b/wpilibNewCommands/src/main/native/include/frc2/command/Command.h index 9a48b2ecc40..27ac7f35828 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/Command.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/Command.h @@ -6,11 +6,13 @@ #include #include +#include #include #include #include #include +#include #include #include "frc2/command/Requirements.h" @@ -18,11 +20,6 @@ namespace frc2 { -template -std::string GetTypeName(const T& type) { - return wpi::Demangle(typeid(type).name()); -} - /** * A state machine representing a complete action to be performed by the robot. * Commands are run by the CommandScheduler, and can be composed into @@ -252,14 +249,17 @@ class Command : public wpi::Sendable, public wpi::SendableHelper { CommandPtr Repeatedly() &&; /** - * Decorates this command to run "by proxy" by wrapping it in a - * ProxyCommand. This is useful for "forking off" from command groups - * when the user does not wish to extend the command's requirements to the - * entire command group. + * Decorates this command to run "by proxy" by wrapping it in a ProxyCommand. + * Use this for "forking off" from command compositions when the user does not + * wish to extend the command's requirements to the entire command + * composition. ProxyCommand has unique implications and semantics, see the + * WPILib docs for a full explanation. * *

This overload transfers command ownership to the returned CommandPtr. * * @return the decorated command + * @see ProxyCommand */ [[nodiscard]] CommandPtr AsProxy() &&; @@ -392,6 +392,14 @@ class Command : public wpi::Sendable, public wpi::SendableHelper { */ void SetComposed(bool isComposed); + /** + * Get the stacktrace of where this command was composed, or an empty + * optional. Intended for internal use. + * + * @return optional string representation of the composition site stack trace. + */ + std::optional GetPreviousCompositionSite() const; + /** * Whether the given command should run when the robot is disabled. Override * to return true if the command should run when disabled. @@ -421,15 +429,17 @@ class Command : public wpi::Sendable, public wpi::SendableHelper { protected: Command(); + /// Requirements set. wpi::SmallSet m_requirements; /** * Transfers ownership of this command to a unique pointer. Used for * decorator methods. */ + [[deprecated("Use ToPtr() instead")]] virtual std::unique_ptr TransferOwnership() && = 0; - bool m_isComposed = false; + std::optional m_previousComposition; }; /** diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/CommandBase.h b/wpilibNewCommands/src/main/native/include/frc2/command/CommandBase.h deleted file mode 100644 index ea24e42d97a..00000000000 --- a/wpilibNewCommands/src/main/native/include/frc2/command/CommandBase.h +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include - -#include "frc2/command/Command.h" - -namespace frc2 { -/** - * A Sendable base class for Commands. - * - * This class is provided by the NewCommands VendorDep - * - * @deprecated All functionality provided by CommandBase has been merged into - * Command. Use Command instead. - */ -class [[deprecated("Use Command instead")]] CommandBase : public Command { - protected: - WPI_DEPRECATED("Use Command instead") - CommandBase(); -}; -} // namespace frc2 diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/CommandHelper.h b/wpilibNewCommands/src/main/native/include/frc2/command/CommandHelper.h index ed93b655f99..83451fe8dc2 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/CommandHelper.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/CommandHelper.h @@ -34,7 +34,9 @@ class CommandHelper : public Base { } protected: - std::unique_ptr TransferOwnership() && override { + [[deprecated("Use ToPtr() instead")]] + std::unique_ptr TransferOwnership() && + override { return std::make_unique(std::move(*static_cast(this))); } }; diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/CommandPtr.h b/wpilibNewCommands/src/main/native/include/frc2/command/CommandPtr.h index ae8c11819f4..e2f534f7547 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/CommandPtr.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/CommandPtr.h @@ -27,8 +27,7 @@ namespace frc2 { */ class CommandPtr final { public: - explicit CommandPtr(std::unique_ptr&& command) - : m_ptr(std::move(command)) {} + explicit CommandPtr(std::unique_ptr&& command); template T> // NOLINTNEXTLINE(bugprone-forwarding-reference-overload) @@ -36,9 +35,11 @@ class CommandPtr final { : CommandPtr( std::make_unique>(std::forward(command))) {} - CommandPtr(CommandPtr&&) = default; + CommandPtr(CommandPtr&&); CommandPtr& operator=(CommandPtr&&) = default; + explicit CommandPtr(std::nullptr_t) = delete; + /** * Decorates this command to run repeatedly, restarting it when it ends, until * this command is interrupted. The decorated command can still be canceled. @@ -49,12 +50,15 @@ class CommandPtr final { CommandPtr Repeatedly() &&; /** - * Decorates this command to run "by proxy" by wrapping it in a - * ProxyCommand. This is useful for "forking off" from command groups - * when the user does not wish to extend the command's requirements to the - * entire command group. + * Decorates this command to run "by proxy" by wrapping it in a ProxyCommand. + * Use this for "forking off" from command compositions when the user does not + * wish to extend the command's requirements to the entire command + * composition. ProxyCommand has unique implications and semantics, see the + * WPILib docs for a full explanation. * * @return the decorated command + * @see ProxyCommand */ [[nodiscard]] CommandPtr AsProxy() &&; @@ -187,9 +191,21 @@ class CommandPtr final { * @param parallel the commands to run in parallel * @return the decorated command */ - [[nodiscard]] + [[nodiscard]] [[deprecated("Replace with DeadlineFor")]] CommandPtr DeadlineWith(CommandPtr&& parallel) &&; + /** + * Decorates this command with a set of commands to run parallel to it, ending + * when the calling command ends and interrupting all the others. Often more + * convenient/less-verbose than constructing a new {@link + * ParallelDeadlineGroup} explicitly. + * + * @param parallel the commands to run in parallel. Note the parallel commands + * will be interupted when the deadline command ends + * @return the decorated command + */ + [[nodiscard]] + CommandPtr DeadlineFor(CommandPtr&& parallel) &&; /** * Decorates this command with a set of commands to run parallel to it, ending * when the last command ends. Often more convenient/less-verbose than @@ -326,6 +342,7 @@ class CommandPtr final { private: std::unique_ptr m_ptr; + std::string m_moveOutSite{""}; void AssertValid() const; }; diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/CommandScheduler.h b/wpilibNewCommands/src/main/native/include/frc2/command/CommandScheduler.h index ce4dc914c25..fde2c6d3e3f 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/CommandScheduler.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/CommandScheduler.h @@ -333,6 +333,11 @@ class CommandScheduler final : public wpi::Sendable, */ void Enable(); + /** + * Prints list of epochs added so far and their times. + */ + void PrintWatchdogEpochs(); + /** * Adds an action to perform on the initialization of any command by the * scheduler. @@ -374,7 +379,7 @@ class CommandScheduler final : public wpi::Sendable, void OnCommandFinish(Action action); /** - * Requires that the specified command hasn't been already added to a + * Requires that the specified command hasn't already been added to a * composition. * * @param command The command to check @@ -383,7 +388,7 @@ class CommandScheduler final : public wpi::Sendable, void RequireUngrouped(const Command* command); /** - * Requires that the specified commands not have been already added to a + * Requires that the specified commands have not already been added to a * composition. * * @param commands The commands to check @@ -392,7 +397,7 @@ class CommandScheduler final : public wpi::Sendable, void RequireUngrouped(std::span> commands); /** - * Requires that the specified commands not have been already added to a + * Requires that the specified commands have not already been added to a * composition. * * @param commands The commands to check @@ -401,6 +406,38 @@ class CommandScheduler final : public wpi::Sendable, */ void RequireUngrouped(std::initializer_list commands); + /** + * Requires that the specified command has not already been added to a + * composition and is not currently scheduled. + * + * @param command The command to check + * @throws IllegalArgumentException if the given command has already been + * composed or scheduled. + */ + void RequireUngroupedAndUnscheduled(const Command* command); + + /** + * Requires that the specified commands have not already been added to a + * composition and are not currently scheduled. + * + * @param commands The commands to check + * @throws IllegalArgumentException if the given commands have already been + * composed. + */ + void RequireUngroupedAndUnscheduled( + std::span> commands); + + /** + * Requires that the specified commands have not already been added to a + * composition and are not currently scheduled. + * + * @param commands The commands to check + * @throws IllegalArgumentException if the given commands have already been + * composed or scheduled. + */ + void RequireUngroupedAndUnscheduled( + std::initializer_list commands); + void InitSendable(wpi::SendableBuilder& builder) override; private: diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/Commands.h b/wpilibNewCommands/src/main/native/include/frc2/command/Commands.h index 5c1d49a2570..6cfad01b1f0 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/Commands.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/Commands.h @@ -12,6 +12,8 @@ #include #include +#include + #include "frc2/command/CommandPtr.h" #include "frc2/command/Requirements.h" #include "frc2/command/SelectCommand.h" @@ -84,6 +86,18 @@ CommandPtr StartEnd(std::function start, std::function end, CommandPtr RunEnd(std::function run, std::function end, Requirements requirements = {}); +/** + * Constructs a command that runs an action once, and then runs an action every + * iteration until interrupted. + * + * @param start the action to run on start + * @param run the action to run every iteration + * @param requirements subsystems the action requires + */ +[[nodiscard]] +CommandPtr StartRun(std::function start, std::function run, + Requirements requirements = {}); + /** * Constructs a command that prints a message and finishes. * @@ -155,11 +169,15 @@ CommandPtr Defer(wpi::unique_function supplier, /** * Constructs a command that schedules the command returned from the supplier * when initialized, and ends when it is no longer scheduled. The supplier is - * called when the command is initialized. + * called when the command is initialized. As a replacement, consider using + * `Defer(supplier).AsProxy()`. * * @param supplier the command supplier */ -[[nodiscard]] +WPI_IGNORE_DEPRECATED +[[nodiscard]] [[deprecated( + "The ProxyCommand supplier constructor has been deprecated. Use " + "Defer(supplier).AsProxy() instead.")]] CommandPtr DeferredProxy(wpi::unique_function supplier); /** @@ -169,9 +187,11 @@ CommandPtr DeferredProxy(wpi::unique_function supplier); * * @param supplier the command supplier */ -[[nodiscard]] +[[nodiscard]] [[deprecated( + "The ProxyCommand supplier constructor has been deprecated. Use " + "Defer(supplier).AsProxy() instead.")]] CommandPtr DeferredProxy(wpi::unique_function supplier); - +WPI_UNIGNORE_DEPRECATED // Command Groups namespace impl { diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/DeferredCommand.h b/wpilibNewCommands/src/main/native/include/frc2/command/DeferredCommand.h index 442076d8f27..28460fdf9b5 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/DeferredCommand.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/DeferredCommand.h @@ -16,7 +16,7 @@ namespace frc2 { /** - * Defers Command construction to runtime. Runs the command returned by the + * Defers Command construction to runtime. Runs the command returned by a * supplier when this command is initialized, and ends when it ends. Useful for * performing runtime tasks before creating a new command. If this command is * interrupted, it will cancel the command. @@ -29,9 +29,10 @@ namespace frc2 { class DeferredCommand : public CommandHelper { public: /** - * Creates a new DeferredCommand that runs the supplied command when - * initialized, and ends when it ends. Useful for lazily - * creating commands at runtime. The supplier will be called each time this + * Creates a new DeferredCommand that directly runs the supplied command when + * initialized, and ends when it ends. Useful for lazily creating commands + * when the DeferredCommand is initialized, such as if the supplied command + * depends on runtime state. The supplier will be called each time this * command is initialized. The supplier must create a new Command each * call. * diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/MecanumControllerCommand.h b/wpilibNewCommands/src/main/native/include/frc2/command/MecanumControllerCommand.h index e189ef1b95e..c305054d1ac 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/MecanumControllerCommand.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/MecanumControllerCommand.h @@ -2,7 +2,6 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -#include #include #include diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/PIDCommand.h b/wpilibNewCommands/src/main/native/include/frc2/command/PIDCommand.h index bede6d0d514..ab16e7dd25d 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/PIDCommand.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/PIDCommand.h @@ -74,9 +74,16 @@ class PIDCommand : public CommandHelper { frc::PIDController& GetController(); protected: + /// PID controller. frc::PIDController m_controller; + + /// Measurement getter. std::function m_measurement; + + /// Setpoint getter. std::function m_setpoint; + + /// PID controller output consumer. std::function m_useOutput; }; } // namespace frc2 diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/PIDSubsystem.h b/wpilibNewCommands/src/main/native/include/frc2/command/PIDSubsystem.h index af61430e8a9..af7d2980874 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/PIDSubsystem.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/PIDSubsystem.h @@ -69,7 +69,10 @@ class PIDSubsystem : public SubsystemBase { frc::PIDController& GetController(); protected: + /// PID controller. frc::PIDController m_controller; + + /// Whether PID controller output is enabled. bool m_enabled{false}; /** diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/ParallelCommandGroup.h b/wpilibNewCommands/src/main/native/include/frc2/command/ParallelCommandGroup.h index bb33a059fad..05768223606 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/ParallelCommandGroup.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/ParallelCommandGroup.h @@ -9,7 +9,6 @@ #pragma warning(disable : 4521) #endif -#include #include #include #include @@ -17,7 +16,6 @@ #include -#include "frc2/command/CommandBase.h" #include "frc2/command/CommandHelper.h" namespace frc2 { diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/ParallelDeadlineGroup.h b/wpilibNewCommands/src/main/native/include/frc2/command/ParallelDeadlineGroup.h index 9e253fbffdf..4cbf878d11b 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/ParallelDeadlineGroup.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/ParallelDeadlineGroup.h @@ -9,7 +9,6 @@ #pragma warning(disable : 4521) #endif -#include #include #include #include @@ -17,7 +16,6 @@ #include -#include "frc2/command/CommandBase.h" #include "frc2/command/CommandHelper.h" namespace frc2 { diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/ParallelRaceGroup.h b/wpilibNewCommands/src/main/native/include/frc2/command/ParallelRaceGroup.h index caefa48fa35..1091d177c7d 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/ParallelRaceGroup.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/ParallelRaceGroup.h @@ -9,7 +9,6 @@ #pragma warning(disable : 4521) #endif -#include #include #include #include @@ -17,7 +16,6 @@ #include -#include "frc2/command/CommandBase.h" #include "frc2/command/CommandHelper.h" namespace frc2 { diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/ProfiledPIDCommand.h b/wpilibNewCommands/src/main/native/include/frc2/command/ProfiledPIDCommand.h index 9ea5db5c7e3..6fbb12b1994 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/ProfiledPIDCommand.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/ProfiledPIDCommand.h @@ -139,9 +139,16 @@ class ProfiledPIDCommand frc::ProfiledPIDController& GetController() { return m_controller; } protected: + /// Profiled PID controller. frc::ProfiledPIDController m_controller; + + /// Measurement getter. std::function m_measurement; + + /// Goal getter. std::function m_goal; + + /// Profiled PID controller output consumer. std::function m_useOutput; }; } // namespace frc2 diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/ProfiledPIDSubsystem.h b/wpilibNewCommands/src/main/native/include/frc2/command/ProfiledPIDSubsystem.h index cfdfc6b6313..1dac7fab276 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/ProfiledPIDSubsystem.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/ProfiledPIDSubsystem.h @@ -91,7 +91,10 @@ class ProfiledPIDSubsystem : public SubsystemBase { frc::ProfiledPIDController& GetController() { return m_controller; } protected: + /// Profiled PID controller. frc::ProfiledPIDController m_controller; + + /// Whether the profiled PID controller output is enabled. bool m_enabled{false}; /** diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/ProxyCommand.h b/wpilibNewCommands/src/main/native/include/frc2/command/ProxyCommand.h index 3b7eecc6741..714427d1045 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/ProxyCommand.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/ProxyCommand.h @@ -7,15 +7,22 @@ #include #include +#include #include "frc2/command/Command.h" #include "frc2/command/CommandHelper.h" namespace frc2 { /** - * Schedules the given command when this command is initialized, and ends when - * it ends. Useful for forking off from CommandGroups. If this command is - * interrupted, it will cancel the command. + * Schedules a given command when this command is initialized and ends when it + * ends, but does not directly run it. Use this for including a command in a + * composition without adding its requirements, but only if you know + * what you are doing. If you are unsure, see the + * WPILib docs for a complete explanation of proxy semantics. Do + * not proxy a command from a subsystem already required by the composition, or + * else the composition will cancel itself when the proxy is reached. If this + * command is interrupted, it will cancel the command. * *

This class is provided by the NewCommands VendorDep */ @@ -23,21 +30,45 @@ class ProxyCommand : public CommandHelper { public: /** * Creates a new ProxyCommand that schedules the supplied command when - * initialized, and ends when it is no longer scheduled. Useful for lazily - * creating commands at runtime. + * initialized, and ends when it is no longer scheduled. Use this for lazily + * creating proxied commands at runtime. Proxying should only + * be done to escape from composition requirement semantics, so if only + * initialization time command construction is needed, use {@link + * DeferredCommand} instead. * * @param supplier the command supplier + * @deprecated This constructor's similarity to {@link DeferredCommand} is + * confusing and opens potential footguns for users who do not fully + * understand the semantics and implications of proxying, but who simply want + * runtime construction. Users who do know what they are doing and need a + * supplier-constructed proxied command should instead proxy a DeferredCommand + * using the AsProxy decorator. + * @see DeferredCommand */ + WPI_IGNORE_DEPRECATED + [[deprecated("Proxy a DeferredCommand instead")]] explicit ProxyCommand(wpi::unique_function supplier); /** * Creates a new ProxyCommand that schedules the supplied command when - * initialized, and ends when it is no longer scheduled. Useful for lazily - * creating commands at runtime. + * initialized, and ends when it is no longer scheduled. Use this for lazily + * creating proxied commands at runtime. Proxying should only + * be done to escape from composition requirement semantics, so if only + * initialization time command construction is needed, use {@link + * DeferredCommand} instead. * * @param supplier the command supplier + * @deprecated This constructor's similarity to {@link DeferredCommand} is + * confusing and opens potential footguns for users who do not fully + * understand the semantics and implications of proxying, but who simply want + * runtime construction. Users who do know what they are doing and need a + * supplier-constructed proxied command should instead proxy a DeferredCommand + * using the AsProxy decorator. + * @see DeferredCommand */ + [[deprecated("Proxy a DeferredCommand instead")]] explicit ProxyCommand(wpi::unique_function supplier); + WPI_UNIGNORE_DEPRECATED /** * Creates a new ProxyCommand that schedules the given command when diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/RamseteCommand.h b/wpilibNewCommands/src/main/native/include/frc2/command/RamseteCommand.h index 56fb8ff92dd..5a15f548830 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/RamseteCommand.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/RamseteCommand.h @@ -69,7 +69,9 @@ class RamseteCommand : public CommandHelper { * @param output A function that consumes the computed left and right * outputs (in volts) for the robot drive. * @param requirements The subsystems to require. + * @deprecated Use LTVUnicycleController instead. */ + [[deprecated("Use LTVUnicycleController instead.")]] RamseteCommand(frc::Trajectory trajectory, std::function pose, frc::RamseteController controller, frc::SimpleMotorFeedforward feedforward, @@ -95,13 +97,14 @@ class RamseteCommand : public CommandHelper { * @param output A function that consumes the computed left and right * wheel speeds. * @param requirements The subsystems to require. + * @deprecated Use LTVUnicycleController instead. */ + [[deprecated("Use LTVUnicycleController instead.")]] RamseteCommand(frc::Trajectory trajectory, std::function pose, frc::RamseteController controller, frc::DifferentialDriveKinematics kinematics, std::function - output, + units::meters_per_second_t)> output, Requirements requirements = {}); void Initialize() override; diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/SelectCommand.h b/wpilibNewCommands/src/main/native/include/frc2/command/SelectCommand.h index d425d76c563..5eb8733219c 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/SelectCommand.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/SelectCommand.h @@ -56,7 +56,8 @@ class SelectCommand : public CommandHelper> { m_defaultCommand.SetComposed(true); for (auto&& command : foo) { - CommandScheduler::GetInstance().RequireUngrouped(command.second.get()); + CommandScheduler::GetInstance().RequireUngroupedAndUnscheduled( + command.second.get()); command.second.get()->SetComposed(true); } @@ -77,7 +78,8 @@ class SelectCommand : public CommandHelper> { : m_selector{std::move(selector)} { m_defaultCommand.SetComposed(true); for (auto&& command : commands) { - CommandScheduler::GetInstance().RequireUngrouped(command.second.get()); + CommandScheduler::GetInstance().RequireUngroupedAndUnscheduled( + command.second.get()); command.second.get()->SetComposed(true); } @@ -132,7 +134,9 @@ class SelectCommand : public CommandHelper> { } protected: - std::unique_ptr TransferOwnership() && override { + [[deprecated("Use ToPtr() instead")]] + std::unique_ptr TransferOwnership() && + override { return std::make_unique(std::move(*this)); } diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/SequentialCommandGroup.h b/wpilibNewCommands/src/main/native/include/frc2/command/SequentialCommandGroup.h index fdcd1bc22fc..956dc29b1ec 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/SequentialCommandGroup.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/SequentialCommandGroup.h @@ -9,7 +9,6 @@ #pragma warning(disable : 4521) #endif -#include #include #include #include @@ -18,7 +17,6 @@ #include -#include "frc2/command/CommandBase.h" #include "frc2/command/CommandHelper.h" namespace frc2 { diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/Subsystem.h b/wpilibNewCommands/src/main/native/include/frc2/command/Subsystem.h index cdac0c04661..d62f69ca356 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/Subsystem.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/Subsystem.h @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -59,6 +60,13 @@ class Subsystem { */ virtual void SimulationPeriodic(); + /** + * Gets the name of this Subsystem. + * + * @return Name + */ + virtual std::string GetName() const; + /** * Sets the default Command of the subsystem. The default command will be * automatically scheduled when no other commands are scheduled that require @@ -151,6 +159,16 @@ class Subsystem { [[nodiscard]] CommandPtr RunEnd(std::function run, std::function end); + /** + * Constructs a command that runs an action once, and then runs an action + * every iteration until interrupted. Requires this subsystem. + * + * @param start the action to run on start + * @param run the action to run every iteration + */ + [[nodiscard]] + CommandPtr StartRun(std::function start, std::function run); + /** * Constructs a DeferredCommand with the provided supplier. This subsystem is * added as a requirement. diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/SubsystemBase.h b/wpilibNewCommands/src/main/native/include/frc2/command/SubsystemBase.h index 86fb026fc1c..444aca5d78c 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/SubsystemBase.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/SubsystemBase.h @@ -30,7 +30,7 @@ class SubsystemBase : public Subsystem, * * @return Name */ - std::string GetName() const; + std::string GetName() const override; /** * Sets the name of this Subsystem. @@ -63,6 +63,15 @@ class SubsystemBase : public Subsystem, void AddChild(std::string name, wpi::Sendable* child); protected: + /** + * Constructor. Telemetry/log name defaults to the classname. + */ SubsystemBase(); + /** + * Constructor. + * + * @param name Name of the subsystem for telemetry and logging. + */ + explicit SubsystemBase(std::string_view name); }; } // namespace frc2 diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.h b/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.h index ae928b8b4a9..388730f89c3 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.h @@ -2,9 +2,7 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -#include #include -#include #include #include diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/TrapezoidProfileCommand.h b/wpilibNewCommands/src/main/native/include/frc2/command/TrapezoidProfileCommand.h index 289b1cb455e..30ad9b70872 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/TrapezoidProfileCommand.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/TrapezoidProfileCommand.h @@ -52,28 +52,6 @@ class TrapezoidProfileCommand m_goal(goal), m_currentState(currentState) { this->AddRequirements(requirements); - m_newAPI = true; - } - - /** - * Creates a new TrapezoidProfileCommand that will execute the given - * TrapezoidalProfile. Output will be piped to the provided consumer function. - * - * @param profile The motion profile to execute. - * @param output The consumer for the profile output. - * @param requirements The list of requirements. - * @deprecated The new constructor allows you to pass in a supplier for - * desired and current state. This allows you to change goals at runtime. - */ - WPI_DEPRECATED( - "The new constructor allows you to pass in a supplier for desired and " - "current state. This allows you to change goals at runtime.") - TrapezoidProfileCommand(frc::TrapezoidProfile profile, - std::function output, - Requirements requirements = {}) - : m_profile(profile), m_output(output) { - this->AddRequirements(requirements); - m_newAPI = false; } void Initialize() override { m_timer.Restart(); } @@ -93,7 +71,6 @@ class TrapezoidProfileCommand std::function m_output; std::function m_goal; std::function m_currentState; - bool m_newAPI; // TODO: Remove frc::Timer m_timer; }; diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/TrapezoidProfileSubsystem.h b/wpilibNewCommands/src/main/native/include/frc2/command/TrapezoidProfileSubsystem.h index 344aefc77ea..56680103122 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/TrapezoidProfileSubsystem.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/TrapezoidProfileSubsystem.h @@ -45,7 +45,7 @@ class TrapezoidProfileSubsystem : public SubsystemBase { m_period(period) {} void Periodic() override { - m_state = m_profile.Calculate(m_period, m_goal, m_state); + m_state = m_profile.Calculate(m_period, m_state, m_goal); if (m_enabled) { UseState(m_state); } diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/WaitCommand.h b/wpilibNewCommands/src/main/native/include/frc2/command/WaitCommand.h index e28615e468b..6f6db40667c 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/WaitCommand.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/WaitCommand.h @@ -41,6 +41,7 @@ class WaitCommand : public CommandHelper { void InitSendable(wpi::SendableBuilder& builder) override; protected: + /// The timer used for waiting. frc::Timer m_timer; private: diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/WrapperCommand.h b/wpilibNewCommands/src/main/native/include/frc2/command/WrapperCommand.h index 98e8b200820..e6a2b9ffa73 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/WrapperCommand.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/WrapperCommand.h @@ -68,7 +68,10 @@ class WrapperCommand : public CommandHelper { wpi::SmallSet GetRequirements() const override; + void InitSendable(wpi::SendableBuilder& builder) override; + protected: + /// Command being wrapped. std::unique_ptr m_command; }; } // namespace frc2 diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/button/CommandStadiaController.h b/wpilibNewCommands/src/main/native/include/frc2/command/button/CommandStadiaController.h new file mode 100644 index 00000000000..7a1b54934cd --- /dev/null +++ b/wpilibNewCommands/src/main/native/include/frc2/command/button/CommandStadiaController.h @@ -0,0 +1,201 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once +#include + +#include "Trigger.h" +#include "frc2/command/CommandScheduler.h" + +namespace frc2 { +/** + * A version of {@link StadiaController} with {@link Trigger} factories for + * command-based. + * + * @see StadiaController + */ +class CommandStadiaController : public frc::StadiaController { + public: + using StadiaController::StadiaController; + + /** + * Constructs an event instance around this button's digital signal. + * + * @param button the button index + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the button's digital signal attached + * to the given loop. + */ + Trigger Button(int button, + frc::EventLoop* loop = CommandScheduler::GetInstance() + .GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the left bumper's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the left bumper's digital signal + * attached to the given loop. + */ + Trigger LeftBumper(frc::EventLoop* loop = CommandScheduler::GetInstance() + .GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the right bumper's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the right bumper's digital signal + * attached to the given loop. + */ + Trigger RightBumper(frc::EventLoop* loop = CommandScheduler::GetInstance() + .GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the left stick's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the left stick's digital signal + * attached to the given loop. + */ + Trigger LeftStick(frc::EventLoop* loop = CommandScheduler::GetInstance() + .GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the right stick's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the right stick's digital signal + * attached to the given loop. + */ + Trigger RightStick(frc::EventLoop* loop = CommandScheduler::GetInstance() + .GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the A button's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the A button's digital signal + * attached to the given loop. + */ + Trigger A(frc::EventLoop* loop = + CommandScheduler::GetInstance().GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the B button's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the B button's digital signal + * attached to the given loop. + */ + Trigger B(frc::EventLoop* loop = + CommandScheduler::GetInstance().GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the X button's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the X button's digital signal + * attached to the given loop. + */ + Trigger X(frc::EventLoop* loop = + CommandScheduler::GetInstance().GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the Y button's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the Y button's digital signal + * attached to the given loop. + */ + Trigger Y(frc::EventLoop* loop = + CommandScheduler::GetInstance().GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the ellipses button's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the ellipses button's digital signal + * attached to the given loop. + */ + Trigger Ellipses(frc::EventLoop* loop = CommandScheduler::GetInstance() + .GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the hamburger button's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the hamburger button's digital + * signal attached to the given loop. + */ + Trigger Hamburger(frc::EventLoop* loop = CommandScheduler::GetInstance() + .GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the stadia button's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the stadia button's digital signal + * attached to the given loop. + */ + Trigger Stadia(frc::EventLoop* loop = CommandScheduler::GetInstance() + .GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the google button's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the google button's digital signal + * attached to the given loop. + */ + Trigger Google(frc::EventLoop* loop = CommandScheduler::GetInstance() + .GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the frame button's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the frame button's digital signal + * attached to the given loop. + */ + Trigger Frame(frc::EventLoop* loop = CommandScheduler::GetInstance() + .GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the left trigger's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the left trigger's digital signal + * attached to the given loop. + */ + Trigger LeftTrigger(frc::EventLoop* loop = CommandScheduler::GetInstance() + .GetDefaultButtonLoop()) const; + + /** + * Constructs an event instance around the right trigger's digital signal. + * + * @param loop the event loop instance to attach the event to. Defaults to the + * CommandScheduler's default loop. + * @return an event instance representing the right trigger's digital signal + * attached to the given loop. + */ + Trigger RightTrigger( + frc::EventLoop* loop = + CommandScheduler::GetInstance().GetDefaultButtonLoop()) const; +}; +} // namespace frc2 diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/button/Trigger.h b/wpilibNewCommands/src/main/native/include/frc2/command/button/Trigger.h index 4438aacdf90..2ef93b9c1b5 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/button/Trigger.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/button/Trigger.h @@ -4,9 +4,7 @@ #pragma once -#include #include -#include #include #include @@ -59,6 +57,23 @@ class Trigger { Trigger(const Trigger& other); + /** + * Starts the command when the condition changes. + * + * @param command the command to start + * @return this trigger, so calls can be chained + */ + Trigger OnChange(Command* command); + + /** + * Starts the command when the condition changes. Moves command ownership to + * the button scheduler. + * + * @param command the command to start + * @return this trigger, so calls can be chained + */ + Trigger OnChange(CommandPtr&& command); + /** * Starts the given command whenever the condition changes from `false` to * `true`. diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/sysid/SysIdRoutine.h b/wpilibNewCommands/src/main/native/include/frc2/command/sysid/SysIdRoutine.h new file mode 100644 index 00000000000..4ccfd41328d --- /dev/null +++ b/wpilibNewCommands/src/main/native/include/frc2/command/sysid/SysIdRoutine.h @@ -0,0 +1,198 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include +#include +#include + +#include +#include + +#include "frc2/command/CommandPtr.h" +#include "frc2/command/Subsystem.h" + +namespace frc2::sysid { + +using ramp_rate_t = units::unit_t< + units::compound_unit>>; + +/** Hardware-independent configuration for a SysId test routine. */ +class Config { + public: + /// The voltage ramp rate used for quasistatic test routines. + ramp_rate_t m_rampRate{1_V / 1_s}; + + /// The step voltage output used for dynamic test routines. + units::volt_t m_stepVoltage{7_V}; + + /// Safety timeout for the test routine commands. + units::second_t m_timeout{10_s}; + + /// Optional handle for recording test state in a third-party logging + /// solution. + std::function m_recordState; + + /** + * Create a new configuration for a SysId test routine. + * + * @param rampRate The voltage ramp rate used for quasistatic test routines. + * Defaults to 1 volt per second if left null. + * @param stepVoltage The step voltage output used for dynamic test routines. + * Defaults to 7 volts if left null. + * @param timeout Safety timeout for the test routine commands. Defaults to 10 + * seconds if left null. + * @param recordState Optional handle for recording test state in a + * third-party logging solution. If provided, the test routine state will be + * passed to this callback instead of logged in WPILog. + */ + Config(std::optional rampRate, + std::optional stepVoltage, + std::optional timeout, + std::function recordState) + : m_recordState{recordState} { + if (rampRate) { + m_rampRate = rampRate.value(); + } + if (stepVoltage) { + m_stepVoltage = stepVoltage.value(); + } + if (timeout) { + m_timeout = timeout.value(); + } + } +}; + +class Mechanism { + public: + /// Sends the SysId-specified drive signal to the mechanism motors during test + /// routines. + std::function m_drive; + + /// Returns measured data (voltages, positions, velocities) of the mechanism + /// motors during test routines. + std::function m_log; + + /// The subsystem containing the motor(s) that is (or are) being + /// characterized. + frc2::Subsystem* m_subsystem; + + /// The name of the mechanism being tested. Will be appended to the log entry + /// title for the routine's test state, e.g. "sysid-test-state-mechanism". + std::string m_name; + + /** + * Create a new mechanism specification for a SysId routine. + * + * @param drive Sends the SysId-specified drive signal to the mechanism motors + * during test routines. + * @param log Returns measured data of the mechanism motors during test + * routines. To return data, call `Motor(string motorName)` on the supplied + * `SysIdRoutineLog` instance, and then call one or more of the chainable + * logging handles (e.g. `voltage`) on the returned `MotorLog`. Multiple + * motors can be logged in a single callback by calling `Motor` multiple + * times. + * @param subsystem The subsystem containing the motor(s) that is (or are) + * being characterized. Will be declared as a requirement for the returned + * test commands. + * @param name The name of the mechanism being tested. Will be appended to the + * log entry * title for the routine's test state, e.g. + * "sysid-test-state-mechanism". Defaults to the name of the subsystem if + * left null. + */ + Mechanism(std::function drive, + std::function log, + frc2::Subsystem* subsystem, std::string_view name) + : m_drive{std::move(drive)}, + m_log{log ? std::move(log) : [](frc::sysid::SysIdRoutineLog* log) {}}, + m_subsystem{subsystem}, + m_name{name} {} + + /** + * Create a new mechanism specification for a SysId routine. Defaults the + * mechanism name to the subsystem name. + * + * @param drive Sends the SysId-specified drive signal to the mechanism motors + * during test routines. + * @param log Returns measured data of the mechanism motors during test + * routines. To return data, call `Motor(string motorName)` on the supplied + * `SysIdRoutineLog` instance, and then call one or more of the chainable + * logging handles (e.g. `voltage`) on the returned `MotorLog`. Multiple + * motors can be logged in a single callback by calling `Motor` multiple + * times. + * @param subsystem The subsystem containing the motor(s) that is (or are) + * being characterized. Will be declared as a requirement for the returned + * test commands. The subsystem's `name` will be appended to the log entry + * title for the routine's test state, e.g. "sysid-test-state-subsystem". + */ + Mechanism(std::function drive, + std::function log, + frc2::Subsystem* subsystem) + : m_drive{std::move(drive)}, + m_log{log ? std::move(log) : [](frc::sysid::SysIdRoutineLog* log) {}}, + m_subsystem{subsystem}, + m_name{m_subsystem->GetName()} {} +}; + +/** + * Motor direction for a SysId test. + */ +enum Direction { + /// Forward. + kForward, + /// Reverse. + kReverse +}; + +/** + * A SysId characterization routine for a single mechanism. Mechanisms may have + * multiple motors. + * + * A single subsystem may have multiple mechanisms, but mechanisms should not + * share test routines. Each complete test of a mechanism should have its own + * SysIdRoutine instance, since the log name of the recorded data is determined + * by the mechanism name. + * + * The test state (e.g. "quasistatic-forward") is logged once per iteration + * during test execution, and once with state "none" when a test ends. Motor + * frames are logged every iteration during test execution. + * + * Timestamps are not coordinated across data, so motor frames and test state + * tags may be recorded on different log frames. Because frame alignment is not + * guaranteed, SysId parses the log by using the test state flag to determine + * the timestamp range for each section of the test, and then extracts the motor + * frames within the valid timestamp ranges. If a given test was run multiple + * times in a single logfile, the user will need to select which of the tests to + * use for the fit in the analysis tool. + */ +class SysIdRoutine : public frc::sysid::SysIdRoutineLog { + public: + /** + * Create a new SysId characterization routine. + * + * @param config Hardware-independent parameters for the SysId routine. + * @param mechanism Hardware interface for the SysId routine. + */ + SysIdRoutine(Config config, Mechanism mechanism) + : SysIdRoutineLog(mechanism.m_name), + m_config(config), + m_mechanism(mechanism), + m_recordState(config.m_recordState ? config.m_recordState + : [this](frc::sysid::State state) { + this->RecordState(state); + }) {} + + frc2::CommandPtr Quasistatic(Direction direction); + frc2::CommandPtr Dynamic(Direction direction); + + private: + Config m_config; + Mechanism m_mechanism; + units::volt_t m_outputVolts{0}; + std::function m_recordState; + frc::Timer timer; +}; +} // namespace frc2::sysid diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/CommandDecoratorTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/CommandDecoratorTest.java index 0f66acdef24..582c176596b 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/CommandDecoratorTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/CommandDecoratorTest.java @@ -148,7 +148,7 @@ void deadlineWithTest() { Command endsBefore = new InstantCommand(); Command endsAfter = new WaitUntilCommand(() -> false); - Command group = dictator.deadlineWith(endsBefore, endsAfter); + Command group = dictator.deadlineFor(endsBefore, endsAfter); scheduler.schedule(group); scheduler.run(); diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/CommandGroupErrorTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/CommandGroupErrorTest.java deleted file mode 100644 index ba4a77b8294..00000000000 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/CommandGroupErrorTest.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj2.command; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.junit.jupiter.api.Test; - -class CommandGroupErrorTest extends CommandTestBase { - @Test - void commandInMultipleGroupsTest() { - MockCommandHolder command1Holder = new MockCommandHolder(true); - Command command1 = command1Holder.getMock(); - MockCommandHolder command2Holder = new MockCommandHolder(true); - Command command2 = command2Holder.getMock(); - - new ParallelCommandGroup(command1, command2); - assertThrows( - IllegalArgumentException.class, () -> new ParallelCommandGroup(command1, command2)); - } - - @Test - void commandInGroupExternallyScheduledTest() { - MockCommandHolder command1Holder = new MockCommandHolder(true); - Command command1 = command1Holder.getMock(); - MockCommandHolder command2Holder = new MockCommandHolder(true); - Command command2 = command2Holder.getMock(); - - new ParallelCommandGroup(command1, command2); - - assertThrows( - IllegalArgumentException.class, () -> CommandScheduler.getInstance().schedule(command1)); - } - - @Test - void redecoratedCommandErrorTest() { - Command command = new InstantCommand(); - - assertDoesNotThrow(() -> command.withTimeout(10).until(() -> false)); - assertThrows(IllegalArgumentException.class, () -> command.withTimeout(10)); - CommandScheduler.getInstance().removeComposedCommand(command); - assertDoesNotThrow(() -> command.withTimeout(10)); - } -} diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/MecanumControllerCommandTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/MecanumControllerCommandTest.java index 3ca11010c3b..9ac412ce50b 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/MecanumControllerCommandTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/MecanumControllerCommandTest.java @@ -41,7 +41,7 @@ void cleanupAll() { } private final Timer m_timer = new Timer(); - private Rotation2d m_angle = new Rotation2d(0); + private Rotation2d m_angle = Rotation2d.kZero; private double m_frontLeftSpeed; private double m_frontLeftDistance; @@ -71,10 +71,7 @@ void cleanupAll() { private final MecanumDriveOdometry m_odometry = new MecanumDriveOdometry( - m_kinematics, - new Rotation2d(0), - new MecanumDriveWheelPositions(), - new Pose2d(0, 0, new Rotation2d(0))); + m_kinematics, Rotation2d.kZero, new MecanumDriveWheelPositions(), Pose2d.kZero); public void setWheelSpeeds(MecanumDriveWheelSpeeds wheelSpeeds) { this.m_frontLeftSpeed = wheelSpeeds.frontLeftMetersPerSecond; @@ -99,7 +96,7 @@ void testReachesReference() { final var subsystem = new Subsystem() {}; final var waypoints = new ArrayList(); - waypoints.add(new Pose2d(0, 0, new Rotation2d(0))); + waypoints.add(Pose2d.kZero); waypoints.add(new Pose2d(1, 5, new Rotation2d(3))); var config = new TrajectoryConfig(8.8, 0.1); final var trajectory = TrajectoryGenerator.generateTrajectory(waypoints, config); diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/MultiCompositionTestBase.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/MultiCompositionTestBase.java index 2b79550cb74..9fafc5905c3 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/MultiCompositionTestBase.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/MultiCompositionTestBase.java @@ -5,6 +5,7 @@ package edu.wpi.first.wpilibj2.command; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.params.provider.Arguments.arguments; import edu.wpi.first.wpilibj2.command.Command.InterruptionBehavior; @@ -13,11 +14,11 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -interface MultiCompositionTestBase extends SingleCompositionTestBase { - T compose(Command... members); +abstract class MultiCompositionTestBase extends SingleCompositionTestBase { + abstract T compose(Command... members); @Override - default T composeSingle(Command member) { + T composeSingle(Command member) { return compose(member); } @@ -63,7 +64,7 @@ static Stream interruptible() { @MethodSource @ParameterizedTest(name = "interruptible[{index}]: {0}") - default void interruptible( + void interruptible( @SuppressWarnings("unused") String name, InterruptionBehavior expected, Command command1, @@ -103,7 +104,7 @@ static Stream runsWhenDisabled() { @MethodSource @ParameterizedTest(name = "runsWhenDisabled[{index}]: {0}") - default void runsWhenDisabled( + void runsWhenDisabled( @SuppressWarnings("unused") String name, boolean expected, Command command1, @@ -112,4 +113,19 @@ default void runsWhenDisabled( var command = compose(command1, command2, command3); assertEquals(expected, command.runsWhenDisabled()); } + + static Stream composeDuplicates() { + Command a = new InstantCommand(() -> {}); + Command b = new InstantCommand(() -> {}); + return Stream.of( + arguments("AA", new Command[] {a, a}), + arguments("ABA", new Command[] {a, b, a}), + arguments("BAA", new Command[] {b, a, a})); + } + + @MethodSource + @ParameterizedTest(name = "composeDuplicates[{index}]: {0}") + void composeDuplicates(@SuppressWarnings("unused") String name, Command[] commands) { + assertThrows(IllegalArgumentException.class, () -> compose(commands)); + } } diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelCommandGroupTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelCommandGroupTest.java index 7dc91106eeb..a837baac8aa 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelCommandGroupTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelCommandGroupTest.java @@ -14,8 +14,7 @@ import org.junit.jupiter.api.Test; -class ParallelCommandGroupTest extends CommandTestBase - implements MultiCompositionTestBase { +class ParallelCommandGroupTest extends MultiCompositionTestBase { @Test void parallelGroupScheduleTest() { try (CommandScheduler scheduler = new CommandScheduler()) { diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelDeadlineGroupTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelDeadlineGroupTest.java index 6fa644bb245..206d801015b 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelDeadlineGroupTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelDeadlineGroupTest.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj2.command; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -14,8 +15,7 @@ import java.util.Arrays; import org.junit.jupiter.api.Test; -class ParallelDeadlineGroupTest extends CommandTestBase - implements MultiCompositionTestBase { +class ParallelDeadlineGroupTest extends MultiCompositionTestBase { @Test void parallelDeadlineScheduleTest() { try (CommandScheduler scheduler = new CommandScheduler()) { @@ -125,6 +125,21 @@ void parallelDeadlineRequirementErrorTest() { IllegalArgumentException.class, () -> new ParallelDeadlineGroup(command1, command2)); } + @Test + void parallelDeadlineSetDeadlineToDeadlineTest() { + Command a = new InstantCommand(() -> {}); + ParallelDeadlineGroup group = new ParallelDeadlineGroup(a); + assertDoesNotThrow(() -> group.setDeadline(a)); + } + + @Test + void parallelDeadlineSetDeadlineDuplicateTest() { + Command a = new InstantCommand(() -> {}); + Command b = new InstantCommand(() -> {}); + ParallelDeadlineGroup group = new ParallelDeadlineGroup(a, b); + assertThrows(IllegalArgumentException.class, () -> group.setDeadline(b)); + } + @Override public ParallelDeadlineGroup compose(Command... members) { return new ParallelDeadlineGroup(members[0], Arrays.copyOfRange(members, 1, members.length)); diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelRaceGroupTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelRaceGroupTest.java index 67524960ca3..ea780c6216e 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelRaceGroupTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/ParallelRaceGroupTest.java @@ -16,8 +16,7 @@ import org.junit.jupiter.api.Test; -class ParallelRaceGroupTest extends CommandTestBase - implements MultiCompositionTestBase { +class ParallelRaceGroupTest extends MultiCompositionTestBase { @Test void parallelRaceScheduleTest() { try (CommandScheduler scheduler = new CommandScheduler()) { @@ -153,7 +152,7 @@ void parallelRaceOnlyCallsEndOnceTest() { scheduler.run(); command2Holder.setFinished(true); // at this point the sequential group should be done - assertDoesNotThrow(() -> scheduler.run()); + assertDoesNotThrow(scheduler::run); assertFalse(scheduler.isScheduled(group2)); } } diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/RepeatCommandTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/RepeatCommandTest.java index 53abdd8dc9e..2aaecc6d933 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/RepeatCommandTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/RepeatCommandTest.java @@ -10,8 +10,7 @@ import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; -class RepeatCommandTest extends CommandTestBase - implements SingleCompositionTestBase { +class RepeatCommandTest extends SingleCompositionTestBase { @Test void callsMethodsCorrectly() { try (CommandScheduler scheduler = new CommandScheduler()) { diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SchedulingRecursionTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SchedulingRecursionTest.java index 5e8fd392e46..a253740c028 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SchedulingRecursionTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SchedulingRecursionTest.java @@ -288,7 +288,7 @@ void cancelFromEndLoopWhileInRunLoop() { scheduler.schedule(cCancelsD); scheduler.schedule(dCancelsAll); - assertDoesNotThrow(() -> scheduler.run()); + assertDoesNotThrow(scheduler::run); assertEquals(4, counter.get()); assertFalse(scheduler.isScheduled(aCancelsB)); assertFalse(scheduler.isScheduled(bCancelsC)); diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SelectCommandTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SelectCommandTest.java index 0ce3b790577..e364468186c 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SelectCommandTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SelectCommandTest.java @@ -13,8 +13,7 @@ import java.util.Map; import org.junit.jupiter.api.Test; -class SelectCommandTest extends CommandTestBase - implements MultiCompositionTestBase> { +class SelectCommandTest extends MultiCompositionTestBase> { @Test void selectCommandTest() { try (CommandScheduler scheduler = new CommandScheduler()) { diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SequentialCommandGroupTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SequentialCommandGroupTest.java index ff578f45d4e..abbc49062c7 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SequentialCommandGroupTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SequentialCommandGroupTest.java @@ -12,8 +12,7 @@ import org.junit.jupiter.api.Test; -class SequentialCommandGroupTest extends CommandTestBase - implements MultiCompositionTestBase { +class SequentialCommandGroupTest extends MultiCompositionTestBase { @Test void sequentialGroupScheduleTest() { try (CommandScheduler scheduler = new CommandScheduler()) { diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SingleCompositionTestBase.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SingleCompositionTestBase.java index 4e54e3ec009..a063a1de638 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SingleCompositionTestBase.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SingleCompositionTestBase.java @@ -5,17 +5,19 @@ package edu.wpi.first.wpilibj2.command; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; -public interface SingleCompositionTestBase { - T composeSingle(Command member); +public abstract class SingleCompositionTestBase extends CommandTestBase { + abstract T composeSingle(Command member); @EnumSource(Command.InterruptionBehavior.class) @ParameterizedTest - default void interruptible(Command.InterruptionBehavior interruptionBehavior) { + void interruptible(Command.InterruptionBehavior interruptionBehavior) { var command = composeSingle( new WaitUntilCommand(() -> false).withInterruptBehavior(interruptionBehavior)); @@ -24,9 +26,38 @@ default void interruptible(Command.InterruptionBehavior interruptionBehavior) { @ValueSource(booleans = {true, false}) @ParameterizedTest - default void runWhenDisabled(boolean runsWhenDisabled) { + void runWhenDisabled(boolean runsWhenDisabled) { var command = composeSingle(new WaitUntilCommand(() -> false).ignoringDisable(runsWhenDisabled)); assertEquals(runsWhenDisabled, command.runsWhenDisabled()); } + + @Test + void commandInOtherCompositionTest() { + var command = new InstantCommand(); + new WrapperCommand(command) {}; + assertThrows(IllegalArgumentException.class, () -> composeSingle(command)); + } + + @Test + void commandInMultipleCompositionsTest() { + var command = new InstantCommand(); + composeSingle(command); + assertThrows(IllegalArgumentException.class, () -> composeSingle(command)); + } + + @Test + void composeThenScheduleTest() { + var command = new InstantCommand(); + composeSingle(command); + assertThrows( + IllegalArgumentException.class, () -> CommandScheduler.getInstance().schedule(command)); + } + + @Test + void scheduleThenComposeTest() { + var command = new RunCommand(() -> {}); + CommandScheduler.getInstance().schedule(command); + assertThrows(IllegalArgumentException.class, () -> composeSingle(command)); + } } diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SwerveControllerCommandTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SwerveControllerCommandTest.java index 9dd03aee337..2f6c6965656 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SwerveControllerCommandTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/SwerveControllerCommandTest.java @@ -41,22 +41,22 @@ void cleanup() { } private final Timer m_timer = new Timer(); - private Rotation2d m_angle = new Rotation2d(0); + private Rotation2d m_angle = Rotation2d.kZero; private SwerveModuleState[] m_moduleStates = new SwerveModuleState[] { - new SwerveModuleState(0, new Rotation2d(0)), - new SwerveModuleState(0, new Rotation2d(0)), - new SwerveModuleState(0, new Rotation2d(0)), - new SwerveModuleState(0, new Rotation2d(0)) + new SwerveModuleState(0, Rotation2d.kZero), + new SwerveModuleState(0, Rotation2d.kZero), + new SwerveModuleState(0, Rotation2d.kZero), + new SwerveModuleState(0, Rotation2d.kZero) }; private SwerveModulePosition[] m_modulePositions = new SwerveModulePosition[] { - new SwerveModulePosition(0, new Rotation2d(0)), - new SwerveModulePosition(0, new Rotation2d(0)), - new SwerveModulePosition(0, new Rotation2d(0)), - new SwerveModulePosition(0, new Rotation2d(0)) + new SwerveModulePosition(0, Rotation2d.kZero), + new SwerveModulePosition(0, Rotation2d.kZero), + new SwerveModulePosition(0, Rotation2d.kZero), + new SwerveModulePosition(0, Rotation2d.kZero) }; private final ProfiledPIDController m_rotController = @@ -77,8 +77,7 @@ void cleanup() { new Translation2d(-kWheelBase / 2, -kTrackWidth / 2)); private final SwerveDriveOdometry m_odometry = - new SwerveDriveOdometry( - m_kinematics, new Rotation2d(0), m_modulePositions, new Pose2d(0, 0, new Rotation2d(0))); + new SwerveDriveOdometry(m_kinematics, Rotation2d.kZero, m_modulePositions, Pose2d.kZero); @SuppressWarnings("PMD.ArrayIsStoredDirectly") public void setModuleStates(SwerveModuleState[] moduleStates) { @@ -96,7 +95,7 @@ void testReachesReference() { final var subsystem = new Subsystem() {}; final var waypoints = new ArrayList(); - waypoints.add(new Pose2d(0, 0, new Rotation2d(0))); + waypoints.add(Pose2d.kZero); waypoints.add(new Pose2d(1, 5, new Rotation2d(3))); var config = new TrajectoryConfig(8.8, 0.1); final var trajectory = TrajectoryGenerator.generateTrajectory(waypoints, config); diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/button/RobotModeTriggersTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/button/RobotModeTriggersTest.java index b2b41c4dfb6..f7df7f0bcb6 100644 --- a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/button/RobotModeTriggersTest.java +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/button/RobotModeTriggersTest.java @@ -6,7 +6,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; -import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.simulation.DriverStationSim; import edu.wpi.first.wpilibj2.command.CommandTestBase; import org.junit.jupiter.api.Test; @@ -18,7 +17,7 @@ void autonomousTest() { DriverStationSim.setAutonomous(true); DriverStationSim.setTest(false); DriverStationSim.setEnabled(true); - DriverStation.refreshData(); + DriverStationSim.notifyNewData(); Trigger auto = RobotModeTriggers.autonomous(); assertTrue(auto.getAsBoolean()); } @@ -29,7 +28,7 @@ void teleopTest() { DriverStationSim.setAutonomous(false); DriverStationSim.setTest(false); DriverStationSim.setEnabled(true); - DriverStation.refreshData(); + DriverStationSim.notifyNewData(); Trigger teleop = RobotModeTriggers.teleop(); assertTrue(teleop.getAsBoolean()); } @@ -40,7 +39,7 @@ void testModeTest() { DriverStationSim.setAutonomous(false); DriverStationSim.setTest(true); DriverStationSim.setEnabled(true); - DriverStation.refreshData(); + DriverStationSim.notifyNewData(); Trigger test = RobotModeTriggers.test(); assertTrue(test.getAsBoolean()); } @@ -51,7 +50,7 @@ void disabledTest() { DriverStationSim.setAutonomous(false); DriverStationSim.setTest(false); DriverStationSim.setEnabled(false); - DriverStation.refreshData(); + DriverStationSim.notifyNewData(); Trigger disabled = RobotModeTriggers.disabled(); assertTrue(disabled.getAsBoolean()); } diff --git a/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/sysid/SysIdRoutineTest.java b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/sysid/SysIdRoutineTest.java new file mode 100644 index 00000000000..3d885b21bd9 --- /dev/null +++ b/wpilibNewCommands/src/test/java/edu/wpi/first/wpilibj2/command/sysid/SysIdRoutineTest.java @@ -0,0 +1,144 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.wpilibj2.command.sysid; + +import static edu.wpi.first.units.Units.Volts; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import edu.wpi.first.hal.HAL; +import edu.wpi.first.units.Measure; +import edu.wpi.first.units.Voltage; +import edu.wpi.first.wpilibj.simulation.SimHooks; +import edu.wpi.first.wpilibj.sysid.SysIdRoutineLog; +import edu.wpi.first.wpilibj2.command.Command; +import edu.wpi.first.wpilibj2.command.Subsystem; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class SysIdRoutineTest { + interface Mechanism extends Subsystem { + void recordState(SysIdRoutineLog.State state); + + void drive(Measure voltage); + + void log(SysIdRoutineLog log); + } + + Mechanism m_mechanism; + SysIdRoutine m_sysidRoutine; + Command m_quasistaticForward; + Command m_quasistaticReverse; + Command m_dynamicForward; + Command m_dynamicReverse; + + void runCommand(Command command) { + command.initialize(); + command.execute(); + command.execute(); + SimHooks.stepTiming(1); + command.execute(); + command.end(true); + } + + @BeforeEach + void setup() { + HAL.initialize(500, 0); + SimHooks.pauseTiming(); + m_mechanism = mock(Mechanism.class); + m_sysidRoutine = + new SysIdRoutine( + new SysIdRoutine.Config(null, null, null, m_mechanism::recordState), + new SysIdRoutine.Mechanism(m_mechanism::drive, m_mechanism::log, new Subsystem() {})); + m_quasistaticForward = m_sysidRoutine.quasistatic(SysIdRoutine.Direction.kForward); + m_quasistaticReverse = m_sysidRoutine.quasistatic(SysIdRoutine.Direction.kReverse); + m_dynamicForward = m_sysidRoutine.dynamic(SysIdRoutine.Direction.kForward); + m_dynamicReverse = m_sysidRoutine.dynamic(SysIdRoutine.Direction.kReverse); + } + + @AfterEach + void cleanupAll() { + SimHooks.resumeTiming(); + } + + @Test + void recordStateBookendsMotorLogging() { + runCommand(m_quasistaticForward); + + var orderCheck = inOrder(m_mechanism); + + orderCheck.verify(m_mechanism).recordState(SysIdRoutineLog.State.kQuasistaticForward); + orderCheck.verify(m_mechanism).drive(any()); + orderCheck.verify(m_mechanism).log(any()); + orderCheck.verify(m_mechanism).recordState(SysIdRoutineLog.State.kNone); + orderCheck.verifyNoMoreInteractions(); + + clearInvocations(m_mechanism); + orderCheck = inOrder(m_mechanism); + runCommand(m_dynamicForward); + + orderCheck.verify(m_mechanism).recordState(SysIdRoutineLog.State.kDynamicForward); + orderCheck.verify(m_mechanism).drive(any()); + orderCheck.verify(m_mechanism).log(any()); + orderCheck.verify(m_mechanism).recordState(SysIdRoutineLog.State.kNone); + orderCheck.verifyNoMoreInteractions(); + } + + @Test + void testsDeclareCorrectState() { + runCommand(m_quasistaticForward); + verify(m_mechanism, atLeastOnce()).recordState(SysIdRoutineLog.State.kQuasistaticForward); + + runCommand(m_quasistaticReverse); + verify(m_mechanism, atLeastOnce()).recordState(SysIdRoutineLog.State.kQuasistaticReverse); + + runCommand(m_dynamicForward); + verify(m_mechanism, atLeastOnce()).recordState(SysIdRoutineLog.State.kDynamicForward); + + runCommand(m_dynamicReverse); + verify(m_mechanism, atLeastOnce()).recordState(SysIdRoutineLog.State.kDynamicReverse); + } + + @Test + void testsOutputCorrectVoltage() { + runCommand(m_quasistaticForward); + var orderCheck = inOrder(m_mechanism); + + orderCheck.verify(m_mechanism, atLeastOnce()).drive(Volts.of(1)); + orderCheck.verify(m_mechanism).drive(Volts.of(0)); + orderCheck.verify(m_mechanism, never()).drive(any()); + + clearInvocations(m_mechanism); + runCommand(m_quasistaticReverse); + orderCheck = inOrder(m_mechanism); + + orderCheck.verify(m_mechanism, atLeastOnce()).drive(Volts.of(-1)); + orderCheck.verify(m_mechanism).drive(Volts.of(0)); + orderCheck.verify(m_mechanism, never()).drive(any()); + + clearInvocations(m_mechanism); + runCommand(m_dynamicForward); + orderCheck = inOrder(m_mechanism); + + orderCheck.verify(m_mechanism, atLeastOnce()).drive(Volts.of(7)); + orderCheck.verify(m_mechanism).drive(Volts.of(0)); + orderCheck.verify(m_mechanism, never()).drive(any()); + + clearInvocations(m_mechanism); + runCommand(m_dynamicForward); + orderCheck = inOrder(m_mechanism); + + runCommand(m_dynamicReverse); + orderCheck.verify(m_mechanism, atLeastOnce()).drive(Volts.of(-7)); + orderCheck.verify(m_mechanism).drive(Volts.of(0)); + orderCheck.verify(m_mechanism, never()).drive(any()); + } +} diff --git a/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandDecoratorTest.cpp b/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandDecoratorTest.cpp index 884d5043469..7c342476fb1 100644 --- a/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandDecoratorTest.cpp +++ b/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandDecoratorTest.cpp @@ -5,12 +5,9 @@ #include #include "CommandTestBase.h" -#include "frc2/command/ConditionalCommand.h" #include "frc2/command/FunctionalCommand.h" #include "frc2/command/InstantCommand.h" -#include "frc2/command/ParallelRaceGroup.h" #include "frc2/command/RunCommand.h" -#include "frc2/command/SequentialCommandGroup.h" using namespace frc2; class CommandDecoratorTest : public CommandTestBase {}; diff --git a/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandPtrTest.cpp b/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandPtrTest.cpp index 6c57c7f9fac..75ec0409649 100644 --- a/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandPtrTest.cpp +++ b/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandPtrTest.cpp @@ -34,3 +34,7 @@ TEST_F(CommandPtrTest, MovedFrom) { EXPECT_EQ(1, counter); } + +TEST_F(CommandPtrTest, NullInitialization) { + EXPECT_THROW(CommandPtr{std::unique_ptr{}}, frc::RuntimeError); +} diff --git a/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandTestBase.h b/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandTestBase.h index 586432dff05..16d0cdc8b2c 100644 --- a/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandTestBase.h +++ b/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandTestBase.h @@ -5,7 +5,6 @@ #pragma once #include -#include #include #include @@ -16,14 +15,13 @@ #include "frc2/command/Requirements.h" #include "frc2/command/SubsystemBase.h" #include "gmock/gmock.h" -#include "make_vector.h" namespace frc2 { class TestSubsystem : public SubsystemBase { public: explicit TestSubsystem(std::function periodic = [] {}) - : m_periodic{periodic} {} + : m_periodic{std::move(periodic)} {} void Periodic() override { m_periodic(); } private: diff --git a/wpilibNewCommands/src/test/native/cpp/frc2/command/button/RobotModeTriggersTest.cpp b/wpilibNewCommands/src/test/native/cpp/frc2/command/button/RobotModeTriggersTest.cpp index cb9e9664ba0..adc9ec7732c 100644 --- a/wpilibNewCommands/src/test/native/cpp/frc2/command/button/RobotModeTriggersTest.cpp +++ b/wpilibNewCommands/src/test/native/cpp/frc2/command/button/RobotModeTriggersTest.cpp @@ -18,7 +18,7 @@ TEST(RobotModeTriggersTest, Autonomous) { DriverStationSim::SetAutonomous(true); DriverStationSim::SetTest(false); DriverStationSim::SetEnabled(true); - frc::DriverStation::RefreshData(); + DriverStationSim::NotifyNewData(); Trigger autonomous = RobotModeTriggers::Autonomous(); EXPECT_TRUE(autonomous.Get()); } @@ -28,7 +28,7 @@ TEST(RobotModeTriggersTest, Teleop) { DriverStationSim::SetAutonomous(false); DriverStationSim::SetTest(false); DriverStationSim::SetEnabled(true); - frc::DriverStation::RefreshData(); + DriverStationSim::NotifyNewData(); Trigger teleop = RobotModeTriggers::Teleop(); EXPECT_TRUE(teleop.Get()); } @@ -38,7 +38,7 @@ TEST(RobotModeTriggersTest, Disabled) { DriverStationSim::SetAutonomous(false); DriverStationSim::SetTest(false); DriverStationSim::SetEnabled(false); - frc::DriverStation::RefreshData(); + DriverStationSim::NotifyNewData(); Trigger disabled = RobotModeTriggers::Disabled(); EXPECT_TRUE(disabled.Get()); } @@ -48,7 +48,7 @@ TEST(RobotModeTriggersTest, TestMode) { DriverStationSim::SetAutonomous(false); DriverStationSim::SetTest(true); DriverStationSim::SetEnabled(true); - frc::DriverStation::RefreshData(); + DriverStationSim::NotifyNewData(); Trigger test = RobotModeTriggers::Test(); EXPECT_TRUE(test.Get()); } diff --git a/wpilibNewCommands/src/test/native/cpp/frc2/command/make_vector.h b/wpilibNewCommands/src/test/native/cpp/frc2/command/make_vector.h index 295eba76458..8dbf7544aca 100644 --- a/wpilibNewCommands/src/test/native/cpp/frc2/command/make_vector.h +++ b/wpilibNewCommands/src/test/native/cpp/frc2/command/make_vector.h @@ -24,8 +24,8 @@ std::vector make_vector(Args&&... args) { vec.reserve(sizeof...(Args)); using arr_t = int[]; - [[maybe_unused]] arr_t arr{ - 0, (vec.emplace_back(std::forward(args)), 0)...}; + [[maybe_unused]] + arr_t arr{0, (vec.emplace_back(std::forward(args)), 0)...}; return vec; } diff --git a/wpilibNewCommands/src/test/native/cpp/frc2/command/sysid/SysIdRoutineTest.cpp b/wpilibNewCommands/src/test/native/cpp/frc2/command/sysid/SysIdRoutineTest.cpp new file mode 100644 index 00000000000..1cfe39c6ee8 --- /dev/null +++ b/wpilibNewCommands/src/test/native/cpp/frc2/command/sysid/SysIdRoutineTest.cpp @@ -0,0 +1,184 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include +#include + +#include + +#include +#include +#include +#include + +#define EXPECT_NEAR_UNITS(val1, val2, eps) \ + EXPECT_LE(units::math::abs(val1 - val2), eps) + +enum StateTest { + Invalid, + InRecordStateQf, + InRecordStateQr, + InRecordStateDf, + InRecordStateDr, + InDrive, + InLog, + DoneWithRecordState +}; + +class SysIdRoutineTest : public ::testing::Test { + protected: + std::vector currentStateList{}; + std::vector sentVoltages{}; + frc2::Subsystem m_subsystem{}; + frc2::sysid::SysIdRoutine m_sysidRoutine{ + frc2::sysid::Config{ + std::nullopt, std::nullopt, std::nullopt, + [this](frc::sysid::State state) { + switch (state) { + case frc::sysid::State::kQuasistaticForward: + currentStateList.emplace_back(StateTest::InRecordStateQf); + break; + case frc::sysid::State::kQuasistaticReverse: + currentStateList.emplace_back(StateTest::InRecordStateQr); + break; + case frc::sysid::State::kDynamicForward: + currentStateList.emplace_back(StateTest::InRecordStateDf); + break; + case frc::sysid::State::kDynamicReverse: + currentStateList.emplace_back(StateTest::InRecordStateDr); + break; + case frc::sysid::State::kNone: + currentStateList.emplace_back(StateTest::DoneWithRecordState); + break; + } + }}, + frc2::sysid::Mechanism{ + [this](units::volt_t driveVoltage) { + sentVoltages.emplace_back(driveVoltage); + currentStateList.emplace_back(StateTest::InDrive); + }, + [this](frc::sysid::SysIdRoutineLog* log) { + currentStateList.emplace_back(StateTest::InLog); + log->Motor("Mock Motor").position(0_m).velocity(0_mps).voltage(0_V); + }, + &m_subsystem}}; + + frc2::CommandPtr m_quasistaticForward{ + m_sysidRoutine.Quasistatic(frc2::sysid::Direction::kForward)}; + frc2::CommandPtr m_quasistaticReverse{ + m_sysidRoutine.Quasistatic(frc2::sysid::Direction::kReverse)}; + frc2::CommandPtr m_dynamicForward{ + m_sysidRoutine.Dynamic(frc2::sysid::Direction::kForward)}; + frc2::CommandPtr m_dynamicReverse{ + m_sysidRoutine.Dynamic(frc2::sysid::Direction::kReverse)}; + + frc2::sysid::SysIdRoutine m_emptySysidRoutine{ + frc2::sysid::Config{std::nullopt, std::nullopt, std::nullopt, nullptr}, + frc2::sysid::Mechanism{[](units::volt_t driveVoltage) {}, nullptr, + &m_subsystem}}; + + frc2::CommandPtr m_emptyRoutineForward{ + m_emptySysidRoutine.Quasistatic(frc2::sysid::Direction::kForward)}; + + void RunCommand(frc2::CommandPtr command) { + command.get()->Initialize(); + command.get()->Execute(); + frc::sim::StepTiming(1_s); + command.get()->Execute(); + command.get()->End(true); + } + + void SetUp() override { + frc::sim::PauseTiming(); + frc2::CommandPtr m_quasistaticForward{ + m_sysidRoutine.Quasistatic(frc2::sysid::Direction::kForward)}; + frc2::CommandPtr m_quasistaticReverse{ + m_sysidRoutine.Quasistatic(frc2::sysid::Direction::kReverse)}; + frc2::CommandPtr m_dynamicForward{ + m_sysidRoutine.Dynamic(frc2::sysid::Direction::kForward)}; + frc2::CommandPtr m_dynamicReverse{ + m_sysidRoutine.Dynamic(frc2::sysid::Direction::kReverse)}; + } + + void TearDown() override { frc::sim::ResumeTiming(); } +}; + +TEST_F(SysIdRoutineTest, RecordStateBookendsMotorLogging) { + RunCommand(std::move(m_quasistaticForward)); + std::vector expectedOrder{ + StateTest::InDrive, StateTest::InLog, StateTest::InRecordStateQf, + StateTest::InDrive, StateTest::DoneWithRecordState}; + EXPECT_TRUE(expectedOrder == currentStateList); + currentStateList.clear(); + sentVoltages.clear(); + + expectedOrder = std::vector{ + StateTest::InDrive, StateTest::InLog, StateTest::InRecordStateDf, + StateTest::InDrive, StateTest::DoneWithRecordState}; + RunCommand(std::move(m_dynamicForward)); + EXPECT_TRUE(expectedOrder == currentStateList); + currentStateList.clear(); + sentVoltages.clear(); +} + +TEST_F(SysIdRoutineTest, DeclareCorrectState) { + RunCommand(std::move(m_quasistaticForward)); + EXPECT_TRUE(std::find(currentStateList.begin(), currentStateList.end(), + StateTest::InRecordStateQf) != currentStateList.end()); + currentStateList.clear(); + sentVoltages.clear(); + + RunCommand(std::move(m_quasistaticReverse)); + EXPECT_TRUE(std::find(currentStateList.begin(), currentStateList.end(), + StateTest::InRecordStateQr) != currentStateList.end()); + currentStateList.clear(); + sentVoltages.clear(); + + RunCommand(std::move(m_dynamicForward)); + EXPECT_TRUE(std::find(currentStateList.begin(), currentStateList.end(), + StateTest::InRecordStateDf) != currentStateList.end()); + currentStateList.clear(); + sentVoltages.clear(); + + RunCommand(std::move(m_dynamicReverse)); + EXPECT_TRUE(std::find(currentStateList.begin(), currentStateList.end(), + StateTest::InRecordStateDr) != currentStateList.end()); + currentStateList.clear(); + sentVoltages.clear(); +} + +TEST_F(SysIdRoutineTest, OutputCorrectVoltage) { + RunCommand(std::move(m_quasistaticForward)); + std::vector expectedVoltages{1_V, 0_V}; + EXPECT_NEAR_UNITS(expectedVoltages[0], sentVoltages[0], 1e-6_V); + EXPECT_NEAR_UNITS(expectedVoltages[1], sentVoltages[1], 1e-6_V); + currentStateList.clear(); + sentVoltages.clear(); + + RunCommand(std::move(m_quasistaticReverse)); + expectedVoltages = std::vector{-1_V, 0_V}; + EXPECT_NEAR_UNITS(expectedVoltages[0], sentVoltages[0], 1e-6_V); + EXPECT_NEAR_UNITS(expectedVoltages[1], sentVoltages[1], 1e-6_V); + currentStateList.clear(); + sentVoltages.clear(); + + RunCommand(std::move(m_dynamicForward)); + expectedVoltages = std::vector{7_V, 0_V}; + EXPECT_NEAR_UNITS(expectedVoltages[0], sentVoltages[0], 1e-6_V); + EXPECT_NEAR_UNITS(expectedVoltages[1], sentVoltages[1], 1e-6_V); + currentStateList.clear(); + sentVoltages.clear(); + + RunCommand(std::move(m_dynamicReverse)); + expectedVoltages = std::vector{-7_V, 0_V}; + EXPECT_NEAR_UNITS(expectedVoltages[0], sentVoltages[0], 1e-6_V); + EXPECT_NEAR_UNITS(expectedVoltages[1], sentVoltages[1], 1e-6_V); + currentStateList.clear(); + sentVoltages.clear(); +} + +TEST_F(SysIdRoutineTest, EmptyLogFunc) { + RunCommand(std::move(m_emptyRoutineForward)); + SUCCEED(); +} diff --git a/wpilibNewCommands/wpilibNewCommands-config.cmake.in b/wpilibNewCommands/wpilibNewCommands-config.cmake.in deleted file mode 100644 index 8a8d8d8ecba..00000000000 --- a/wpilibNewCommands/wpilibNewCommands-config.cmake.in +++ /dev/null @@ -1,11 +0,0 @@ -include(CMakeFindDependencyMacro) - @WPIUTIL_DEP_REPLACE@ - @NTCORE_DEP_REPLACE@ - @CSCORE_DEP_REPLACE@ - @CAMERASERVER_DEP_REPLACE@ - @HAL_DEP_REPLACE@ - @WPILIBC_DEP_REPLACE@ - @WPIMATH_DEP_REPLACE@ - - @FILENAME_DEP_REPLACE@ - include(${SELF_DIR}/wpilibNewCommands.cmake) diff --git a/wpilibNewCommands/wpilibnewcommands-config.cmake.in b/wpilibNewCommands/wpilibnewcommands-config.cmake.in new file mode 100644 index 00000000000..b26b9a7a555 --- /dev/null +++ b/wpilibNewCommands/wpilibnewcommands-config.cmake.in @@ -0,0 +1,14 @@ +include(CMakeFindDependencyMacro) +@WPIUTIL_DEP_REPLACE@ +@NTCORE_DEP_REPLACE@ +@CSCORE_DEP_REPLACE@ +@CAMERASERVER_DEP_REPLACE@ +@HAL_DEP_REPLACE@ +@WPILIBC_DEP_REPLACE@ +@WPIMATH_DEP_REPLACE@ + +@FILENAME_DEP_REPLACE@ +include(${SELF_DIR}/wpilibnewcommands.cmake) +if(@WITH_JAVA@) + include(${SELF_DIR}/wpilibNewCommands_jar.cmake) +endif() diff --git a/wpilibc/CMakeLists.txt b/wpilibc/CMakeLists.txt index ed8583497c4..17e7c991ad2 100644 --- a/wpilibc/CMakeLists.txt +++ b/wpilibc/CMakeLists.txt @@ -5,51 +5,53 @@ include(AddTest) configure_file(src/generate/WPILibVersion.cpp.in WPILibVersion.cpp) -file(GLOB_RECURSE - wpilibc_native_src src/main/native/cpp/*.cpp src/main/native/cppcs/*.cpp) +file(GLOB_RECURSE wpilibc_native_src src/main/native/cpp/*.cpp src/main/native/cppcs/*.cpp) add_library(wpilibc ${wpilibc_native_src} ${CMAKE_CURRENT_BINARY_DIR}/WPILibVersion.cpp) set_target_properties(wpilibc PROPERTIES DEBUG_POSTFIX "d") -target_include_directories(wpilibc PUBLIC - $ - $) +target_include_directories( + wpilibc + PUBLIC + $ + $ +) wpilib_target_warnings(wpilibc) -if (WITH_CSCORE) - find_package( OpenCV ) +if(WITH_CSCORE) + find_package(OpenCV) target_link_libraries(wpilibc PUBLIC cameraserver cscore ${OpenCV_LIBS}) else() target_compile_definitions(wpilibc PRIVATE DYNAMIC_CAMERA_SERVER) # Add just the camera server include directory - target_include_directories(wpilibc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../cameraserver/src/main/native/include) + target_include_directories( + wpilibc + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../cameraserver/src/main/native/include + ) endif() target_link_libraries(wpilibc PUBLIC hal ntcore wpimath wpiutil) - set_property(TARGET wpilibc PROPERTY FOLDER "libraries") install(TARGETS wpilibc EXPORT wpilibc) +export(TARGETS wpilibc FILE wpilibc.cmake NAMESPACE wpilibc::) install(DIRECTORY src/main/native/include/ DESTINATION "${include_dest}/wpilibc") -if (WITH_FLAT_INSTALL) - set (wpilibc_config_dir ${wpilib_dest}) -else() - set (wpilibc_config_dir share/wpilibc) -endif() - -configure_file(wpilibc-config.cmake.in ${WPILIB_BINARY_DIR}/wpilibc-config.cmake ) -install(FILES ${WPILIB_BINARY_DIR}/wpilibc-config.cmake DESTINATION ${wpilibc_config_dir}) -install(EXPORT wpilibc DESTINATION ${wpilibc_config_dir}) +configure_file(wpilibc-config.cmake.in ${WPILIB_BINARY_DIR}/wpilibc-config.cmake) +install(FILES ${WPILIB_BINARY_DIR}/wpilibc-config.cmake DESTINATION share/wpilibc) +install(EXPORT wpilibc DESTINATION share/wpilibc) -if (WITH_TESTS) +if(WITH_TESTS) wpilib_add_test(wpilibc src/test/native/cpp) target_include_directories(wpilibc_test PRIVATE src/test/native/include) target_link_libraries(wpilibc_test wpilibc gmock_main) - if (NOT WITH_CSCORE) + if(NOT WITH_CSCORE) target_compile_definitions(wpilibc_test PRIVATE DYNAMIC_CAMERA_SERVER) # Add just the camera server include directory - target_include_directories(wpilibc_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../cameraserver/src/main/native/include) + target_include_directories( + wpilibc_test + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../cameraserver/src/main/native/include + ) endif() endif() diff --git a/wpilibc/src/dev/native/cpp/main.cpp b/wpilibc/src/dev/native/cpp/main.cpp index fcc55b1a4fc..b2ceb9deb79 100644 --- a/wpilibc/src/dev/native/cpp/main.cpp +++ b/wpilibc/src/dev/native/cpp/main.cpp @@ -4,11 +4,12 @@ #include #include +#include #include "WPILibVersion.h" int main() { - fmt::print("Hello World\n"); - fmt::print("{}\n", static_cast(HAL_GetRuntimeType())); - fmt::print("{}\n", GetWPILibVersion()); + wpi::print("Hello World\n"); + wpi::print("{}\n", static_cast(HAL_GetRuntimeType())); + wpi::print("{}\n", GetWPILibVersion()); } diff --git a/wpilibc/src/generate/WPILibVersion.cpp.in b/wpilibc/src/generate/WPILibVersion.cpp.in index b0a44905207..cfe24411588 100644 --- a/wpilibc/src/generate/WPILibVersion.cpp.in +++ b/wpilibc/src/generate/WPILibVersion.cpp.in @@ -1,4 +1,4 @@ -/* +/** * Autogenerated file! Do not manually edit this file. This version is regenerated * any time the publish task is run, or when this file is deleted. */ diff --git a/wpilibc/src/main/native/cpp/ADIS16448_IMU.cpp b/wpilibc/src/main/native/cpp/ADIS16448_IMU.cpp index 14fd37fedc1..8ba4a96c404 100644 --- a/wpilibc/src/main/native/cpp/ADIS16448_IMU.cpp +++ b/wpilibc/src/main/native/cpp/ADIS16448_IMU.cpp @@ -23,7 +23,6 @@ #include #include #include -#include #include #include @@ -114,23 +113,86 @@ ADIS16448_IMU::ADIS16448_IMU(IMUAxis yaw_axis, SPI::Port port, return; } - // Set IMU internal decimation to 819.2 SPS - WriteRegister(SMPL_PRD, 0x0001); - // Enable Data Ready (LOW = Good Data) on DIO1 (PWM0 on MXP) - WriteRegister(MSC_CTRL, 0x0016); - // Disable IMU internal Bartlett filter - WriteRegister(SENS_AVG, 0x0400); + // Set up flash state variable + bool m_needs_flash = false; + + // Set IMU internal decimation to 1 (output data rate of 819.2 SPS / (1 + 1) + // = 409.6Hz), output bandwidth = 204.8Hz + if (ReadRegister(SMPL_PRD) != 0x0001) { + WriteRegister(SMPL_PRD, 0x0001); + m_needs_flash = true; + REPORT_WARNING( + "ADIS16448: SMPL_PRD register configuration inconsistent! Scheduling " + "flash update."); + } + + // Set data ready polarity (LOW = Good Data) on DIO1 (PWM0 on MXP) + if (ReadRegister(MSC_CTRL) != 0x0016) { + WriteRegister(MSC_CTRL, 0x0016); + m_needs_flash = true; + REPORT_WARNING( + "ADIS16448: MSC_CTRL register configuration inconsistent! Scheduling " + "flash update."); + } + + // Disable IMU internal Bartlett filter (204Hz bandwidth is sufficient) and + // set IMU scale factor (range) + if (ReadRegister(SENS_AVG) != 0x0400) { + WriteRegister(SENS_AVG, 0x0400); + m_needs_flash = true; + REPORT_WARNING( + "ADIS16448: SENS_AVG register configuration inconsistent! Scheduling " + "flash update."); + } // Clear offset registers - WriteRegister(XGYRO_OFF, 0x0000); - WriteRegister(YGYRO_OFF, 0x0000); - WriteRegister(ZGYRO_OFF, 0x0000); + if (ReadRegister(XGYRO_OFF) != 0x0000) { + WriteRegister(XGYRO_OFF, 0x0000); + m_needs_flash = true; + REPORT_WARNING( + "ADIS16448: XGYRO_OFF register configuration inconsistent! " + "Scheduling flash update."); + } + + if (ReadRegister(YGYRO_OFF) != 0x0000) { + WriteRegister(YGYRO_OFF, 0x0000); + m_needs_flash = true; + REPORT_WARNING( + "ADIS16448: YGYRO_OFF register configuration inconsistent! " + "Scheduling flash update."); + } + + if (ReadRegister(ZGYRO_OFF) != 0x0000) { + WriteRegister(ZGYRO_OFF, 0x0000); + m_needs_flash = true; + REPORT_WARNING( + "ADIS16448: ZGYRO_OFF register configuration inconsistent! " + "Scheduling flash update."); + } + + // If any registers on the IMU don't match the config, trigger a flash + // update + if (m_needs_flash) { + REPORT_WARNING( + "ADIS16448: Register configuration changed! Starting IMU flash " + "update."); + WriteRegister(GLOB_CMD, 0x0008); + // Wait long enough for the flash update to finish (72ms minimum as per + // the datasheet) + Wait(0.5_s); + REPORT_WARNING("ADIS16448: Flash update finished!"); + m_needs_flash = false; + } else { + REPORT_WARNING( + "ADIS16448: Flash and RAM configuration consistent. No flash update " + "required!"); + } + // Configure and enable auto SPI if (!SwitchToAutoSPI()) { return; } // Notify DS that IMU calibration delay is active - REPORT_WARNING( - "ADIS16448 IMU Detected. Starting initial calibration delay."); + REPORT_WARNING("ADIS16448: Starting initial calibration delay."); // Wait for whatever time the user set as the start-up delay Wait(static_cast(m_calibration_time) * 1.2_s); // Execute calibration routine @@ -155,6 +217,122 @@ ADIS16448_IMU::ADIS16448_IMU(IMUAxis yaw_axis, SPI::Port port, m_connected = true; } +ADIS16448_IMU::ADIS16448_IMU(ADIS16448_IMU&& other) + : m_reset_in{std::move(other.m_reset_in)}, + m_status_led{std::move(other.m_status_led)}, + m_yaw_axis{std::move(other.m_yaw_axis)}, + m_gyro_rate_x{std::move(other.m_gyro_rate_x)}, + m_gyro_rate_y{std::move(other.m_gyro_rate_y)}, + m_gyro_rate_z{std::move(other.m_gyro_rate_z)}, + m_accel_x{std::move(other.m_accel_x)}, + m_accel_y{std::move(other.m_accel_y)}, + m_accel_z{std::move(other.m_accel_z)}, + m_mag_x{std::move(other.m_mag_x)}, + m_mag_y{std::move(other.m_mag_y)}, + m_mag_z{std::move(other.m_mag_z)}, + m_baro{std::move(other.m_baro)}, + m_temp{std::move(other.m_temp)}, + m_tau{std::move(other.m_tau)}, + m_dt{std::move(other.m_dt)}, + m_alpha{std::move(other.m_alpha)}, + m_compAngleX{std::move(other.m_compAngleX)}, + m_compAngleY{std::move(other.m_compAngleY)}, + m_accelAngleX{std::move(other.m_accelAngleX)}, + m_accelAngleY{std::move(other.m_accelAngleY)}, + m_offset_buffer{other.m_offset_buffer}, + m_gyro_rate_offset_x{std::move(other.m_gyro_rate_offset_x)}, + m_gyro_rate_offset_y{std::move(other.m_gyro_rate_offset_y)}, + m_gyro_rate_offset_z{std::move(other.m_gyro_rate_offset_z)}, + m_avg_size{std::move(other.m_avg_size)}, + m_accum_count{std::move(other.m_accum_count)}, + m_integ_gyro_angle_x{std::move(other.m_integ_gyro_angle_x)}, + m_integ_gyro_angle_y{std::move(other.m_integ_gyro_angle_y)}, + m_integ_gyro_angle_z{std::move(other.m_integ_gyro_angle_z)}, + m_thread_active{other.m_thread_active.load()}, + m_first_run{other.m_first_run.load()}, + m_thread_idle{other.m_thread_idle.load()}, + m_start_up_mode{other.m_start_up_mode.load()}, + m_auto_configured{std::move(other.m_auto_configured)}, + m_spi_port{std::move(other.m_spi_port)}, + m_calibration_time{std::move(other.m_calibration_time)}, + m_spi{std::move(other.m_spi)}, + m_auto_interrupt{std::move(other.m_auto_interrupt)}, + m_connected{std::move(other.m_connected)}, + m_acquire_task{std::move(other.m_acquire_task)}, + m_simDevice{std::move(other.m_simDevice)}, + m_simConnected{std::move(other.m_simConnected)}, + m_simGyroAngleX{std::move(other.m_simGyroAngleX)}, + m_simGyroAngleY{std::move(other.m_simGyroAngleZ)}, + m_simGyroAngleZ{std::move(other.m_simGyroAngleZ)}, + m_simGyroRateX{std::move(other.m_simGyroRateX)}, + m_simGyroRateY{std::move(other.m_simGyroRateY)}, + m_simGyroRateZ{std::move(other.m_simGyroRateZ)}, + m_simAccelX{std::move(other.m_simAccelX)}, + m_simAccelY{std::move(other.m_simAccelY)}, + m_simAccelZ{std::move(other.m_simAccelZ)}, + m_mutex{std::move(other.m_mutex)} {} + +ADIS16448_IMU& ADIS16448_IMU::operator=(ADIS16448_IMU&& other) { + if (this == &other) { + return *this; + } + + std::swap(this->m_reset_in, other.m_reset_in); + std::swap(this->m_status_led, other.m_status_led); + std::swap(this->m_yaw_axis, other.m_yaw_axis); + std::swap(this->m_gyro_rate_x, other.m_gyro_rate_x); + std::swap(this->m_gyro_rate_y, other.m_gyro_rate_y); + std::swap(this->m_gyro_rate_z, other.m_gyro_rate_z); + std::swap(this->m_accel_x, other.m_accel_x); + std::swap(this->m_accel_y, other.m_accel_y); + std::swap(this->m_accel_z, other.m_accel_z); + std::swap(this->m_mag_x, other.m_mag_x); + std::swap(this->m_mag_y, other.m_mag_y); + std::swap(this->m_mag_z, other.m_mag_z); + std::swap(this->m_baro, other.m_baro); + std::swap(this->m_temp, other.m_temp); + std::swap(this->m_tau, other.m_tau); + std::swap(this->m_dt, other.m_dt); + std::swap(this->m_alpha, other.m_alpha); + std::swap(this->m_compAngleX, other.m_compAngleX); + std::swap(this->m_compAngleY, other.m_compAngleY); + std::swap(this->m_accelAngleX, other.m_accelAngleX); + std::swap(this->m_accelAngleY, other.m_accelAngleY); + std::swap(this->m_offset_buffer, other.m_offset_buffer); + std::swap(this->m_gyro_rate_offset_x, other.m_gyro_rate_offset_x); + std::swap(this->m_gyro_rate_offset_y, other.m_gyro_rate_offset_y); + std::swap(this->m_gyro_rate_offset_z, other.m_gyro_rate_offset_z); + std::swap(this->m_avg_size, other.m_avg_size); + std::swap(this->m_accum_count, other.m_accum_count); + std::swap(this->m_integ_gyro_angle_x, other.m_integ_gyro_angle_x); + std::swap(this->m_integ_gyro_angle_y, other.m_integ_gyro_angle_y); + std::swap(this->m_integ_gyro_angle_z, other.m_integ_gyro_angle_z); + this->m_thread_active = other.m_thread_active.load(); + this->m_first_run = other.m_first_run.load(); + this->m_thread_idle = other.m_thread_idle.load(); + this->m_start_up_mode = other.m_start_up_mode.load(); + std::swap(this->m_auto_configured, other.m_auto_configured); + std::swap(this->m_spi_port, other.m_spi_port); + std::swap(this->m_calibration_time, other.m_calibration_time); + std::swap(this->m_spi, other.m_spi); + std::swap(this->m_auto_interrupt, other.m_auto_interrupt); + std::swap(this->m_connected, other.m_connected); + std::swap(this->m_acquire_task, other.m_acquire_task); + std::swap(this->m_simDevice, other.m_simDevice); + std::swap(this->m_simConnected, other.m_simConnected); + std::swap(this->m_simGyroAngleX, other.m_simGyroAngleX); + std::swap(this->m_simGyroAngleY, other.m_simGyroAngleY); + std::swap(this->m_simGyroAngleZ, other.m_simGyroAngleZ); + std::swap(this->m_simGyroRateX, other.m_simGyroRateX); + std::swap(this->m_simGyroRateY, other.m_simGyroRateY); + std::swap(this->m_simGyroRateZ, other.m_simGyroRateZ); + std::swap(this->m_simAccelX, other.m_simAccelX); + std::swap(this->m_simAccelY, other.m_simAccelY); + std::swap(this->m_simAccelZ, other.m_simAccelZ); + std::swap(this->m_mutex, other.m_mutex); + return *this; +} + bool ADIS16448_IMU::IsConnected() const { if (m_simConnected) { return m_simConnected.Get(); @@ -679,8 +857,13 @@ double ADIS16448_IMU::CompFilterProcess(double compAngle, double accelAngle, return compAngle; } -int ADIS16448_IMU::ConfigDecRate(uint16_t DecimationSetting) { - uint16_t writeValue = DecimationSetting; +int ADIS16448_IMU::ConfigDecRate(uint16_t decimationRate) { + // Switches the active SPI port to standard SPI mode, writes a new value to + // the DECIMATE register in the IMU, and re-enables auto SPI. + // + // This function enters standard SPI mode, writes a new DECIMATE setting to + // the IMU, adjusts the sample scale factor, and re-enters auto SPI mode. + uint16_t writeValue = decimationRate; uint16_t readbackValue; if (!SwitchToStandardSPI()) { REPORT_ERROR("Failed to configure/reconfigure standard SPI."); @@ -688,14 +871,14 @@ int ADIS16448_IMU::ConfigDecRate(uint16_t DecimationSetting) { } /* Check max */ - if (DecimationSetting > 9) { + if (decimationRate > 9) { REPORT_ERROR( "Attempted to write an invalid decimation value. Capping at 9"); - DecimationSetting = 9; + decimationRate = 9; } /* Shift decimation setting to correct position and select internal sync */ - writeValue = (DecimationSetting << 8) | 0x1; + writeValue = (decimationRate << 8) | 0x1; /* Apply to IMU */ WriteRegister(SMPL_PRD, writeValue); diff --git a/wpilibc/src/main/native/cpp/ADIS16470_IMU.cpp b/wpilibc/src/main/native/cpp/ADIS16470_IMU.cpp index 05dac7893d8..0f8da84a21f 100644 --- a/wpilibc/src/main/native/cpp/ADIS16470_IMU.cpp +++ b/wpilibc/src/main/native/cpp/ADIS16470_IMU.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include #include @@ -63,14 +63,35 @@ inline void ADISReportError(int32_t status, const char* file, int line, * Constructor. */ ADIS16470_IMU::ADIS16470_IMU() - : ADIS16470_IMU(kZ, SPI::Port::kOnboardCS0, CalibrationTime::_4s) {} + : ADIS16470_IMU(kZ, kY, kX, SPI::Port::kOnboardCS0, CalibrationTime::_1s) {} -ADIS16470_IMU::ADIS16470_IMU(IMUAxis yaw_axis, SPI::Port port, +ADIS16470_IMU::ADIS16470_IMU(IMUAxis yaw_axis, IMUAxis pitch_axis, + IMUAxis roll_axis) + : ADIS16470_IMU(yaw_axis, pitch_axis, roll_axis, SPI::Port::kOnboardCS0, + CalibrationTime::_1s) {} + +ADIS16470_IMU::ADIS16470_IMU(IMUAxis yaw_axis, IMUAxis pitch_axis, + IMUAxis roll_axis, SPI::Port port, CalibrationTime cal_time) : m_yaw_axis(yaw_axis), + m_pitch_axis(pitch_axis), + m_roll_axis(roll_axis), m_spi_port(port), m_calibration_time(static_cast(cal_time)), m_simDevice("Gyro:ADIS16470", port) { + if (yaw_axis == kYaw || yaw_axis == kPitch || yaw_axis == kRoll || + pitch_axis == kYaw || pitch_axis == kPitch || pitch_axis == kRoll || + roll_axis == kYaw || roll_axis == kPitch || roll_axis == kRoll) { + REPORT_ERROR( + "ADIS16470 constructor only allows IMUAxis.kX, IMUAxis.kY or " + "IMUAxis.kZ as arguments."); + REPORT_ERROR( + "Constructing ADIS with default axes. (IMUAxis.kZ is defined as Yaw)"); + yaw_axis = kZ; + pitch_axis = kY; + roll_axis = kX; + } + if (m_simDevice) { m_connected = m_simDevice.CreateBoolean("connected", hal::SimDevice::kInput, true); @@ -111,20 +132,60 @@ ADIS16470_IMU::ADIS16470_IMU(IMUAxis yaw_axis, SPI::Port port, return; } + // Set up flash state variable + bool m_needs_flash = false; + // Set IMU internal decimation to 4 (output data rate of 2000 SPS / (4 + 1) // = 400Hz) - WriteRegister(DEC_RATE, 0x0004); + if (ReadRegister(DEC_RATE) != 0x0004) { + WriteRegister(DEC_RATE, 0x0004); + m_needs_flash = true; + REPORT_WARNING( + "ADIS16470: DEC_RATE register configuration inconsistent! Scheduling " + "flash update."); + } // Set data ready polarity (HIGH = Good Data), Disable gSense Compensation // and PoP - WriteRegister(MSC_CTRL, 0x0001); - // Configure IMU internal Bartlett filter - WriteRegister(FILT_CTRL, 0x0000); + if (ReadRegister(MSC_CTRL) != 0x0001) { + WriteRegister(MSC_CTRL, 0x0001); + m_needs_flash = true; + REPORT_WARNING( + "ADIS16470: MSC_CTRL register configuration inconsistent! Scheduling " + "flash update."); + } + + // Disable IMU internal Bartlett filter (200Hz bandwidth is sufficient) + if (ReadRegister(FILT_CTRL) != 0x0000) { + WriteRegister(FILT_CTRL, 0x0000); + m_needs_flash = true; + REPORT_WARNING( + "ADIS16470: FILT_CTRL register configuration inconsistent! " + "Scheduling flash update."); + } + + // If any registers on the IMU don't match the config, trigger a flash + // update + if (m_needs_flash) { + REPORT_WARNING( + "ADIS16470: Register configuration changed! Starting IMU flash " + "update."); + WriteRegister(GLOB_CMD, 0x0008); + // Wait long enough for the flash update to finish (72ms minimum as per + // the datasheet) + Wait(0.3_s); + REPORT_WARNING("ADIS16470: Flash update finished!"); + m_needs_flash = false; + } else { + REPORT_WARNING( + "ADIS16470: Flash and RAM configuration consistent. No flash update " + "required!"); + } + // Configure continuous bias calibration time based on user setting WriteRegister(NULL_CNFG, m_calibration_time | 0x700); // Notify DS that IMU calibration delay is active - REPORT_WARNING( - "ADIS16470 IMU Detected. Starting initial calibration delay."); + REPORT_WARNING("ADIS16470: Starting initial calibration delay."); // Wait for samples to accumulate internal to the IMU (110% of user-defined // time) @@ -152,6 +213,104 @@ ADIS16470_IMU::ADIS16470_IMU(IMUAxis yaw_axis, SPI::Port port, m_connected = true; } +ADIS16470_IMU::ADIS16470_IMU(ADIS16470_IMU&& other) + : m_yaw_axis{std::move(other.m_yaw_axis)}, + m_pitch_axis{std::move(other.m_pitch_axis)}, + m_roll_axis{std::move(other.m_roll_axis)}, + m_reset_in{std::move(other.m_reset_in)}, + m_status_led{std::move(other.m_status_led)}, + m_integ_angle_x{std::move(other.m_integ_angle_x)}, + m_integ_angle_y{std::move(other.m_integ_angle_y)}, + m_integ_angle_z{std::move(other.m_integ_angle_z)}, + m_gyro_rate_x{std::move(other.m_gyro_rate_x)}, + m_gyro_rate_y{std::move(other.m_gyro_rate_y)}, + m_gyro_rate_z{std::move(other.m_gyro_rate_z)}, + m_accel_x{std::move(other.m_accel_x)}, + m_accel_y{std::move(other.m_accel_y)}, + m_accel_z{std::move(other.m_accel_z)}, + m_tau{std::move(other.m_tau)}, + m_dt{std::move(other.m_dt)}, + m_alpha{std::move(other.m_alpha)}, + m_compAngleX{std::move(other.m_compAngleX)}, + m_compAngleY{std::move(other.m_compAngleY)}, + m_accelAngleX{std::move(other.m_accelAngleX)}, + m_accelAngleY{std::move(other.m_accelAngleY)}, + m_thread_active{other.m_thread_active.load()}, + m_first_run{other.m_first_run.load()}, + m_thread_idle{other.m_thread_idle.load()}, + m_auto_configured{std::move(other.m_auto_configured)}, + m_spi_port{std::move(other.m_spi_port)}, + m_calibration_time{std::move(other.m_calibration_time)}, + m_spi{std::move(other.m_spi)}, + m_auto_interrupt{std::move(other.m_auto_interrupt)}, + m_scaled_sample_rate{std::move(other.m_scaled_sample_rate)}, + m_connected{std::move(other.m_connected)}, + m_acquire_task{std::move(other.m_acquire_task)}, + m_simDevice{std::move(other.m_simDevice)}, + m_simConnected{std::move(other.m_simConnected)}, + m_simGyroAngleX{std::move(other.m_simGyroAngleX)}, + m_simGyroAngleY{std::move(other.m_simGyroAngleZ)}, + m_simGyroAngleZ{std::move(other.m_simGyroAngleZ)}, + m_simGyroRateX{std::move(other.m_simGyroRateX)}, + m_simGyroRateY{std::move(other.m_simGyroRateY)}, + m_simGyroRateZ{std::move(other.m_simGyroRateZ)}, + m_simAccelX{std::move(other.m_simAccelX)}, + m_simAccelY{std::move(other.m_simAccelY)}, + m_simAccelZ{std::move(other.m_simAccelZ)}, + m_mutex{std::move(other.m_mutex)} {} + +ADIS16470_IMU& ADIS16470_IMU::operator=(ADIS16470_IMU&& other) { + if (this == &other) { + return *this; + } + + std::swap(this->m_yaw_axis, other.m_yaw_axis); + std::swap(this->m_pitch_axis, other.m_pitch_axis); + std::swap(this->m_roll_axis, other.m_roll_axis); + std::swap(this->m_reset_in, other.m_reset_in); + std::swap(this->m_status_led, other.m_status_led); + std::swap(this->m_integ_angle_x, other.m_integ_angle_x); + std::swap(this->m_integ_angle_y, other.m_integ_angle_y); + std::swap(this->m_integ_angle_z, other.m_integ_angle_z); + std::swap(this->m_gyro_rate_x, other.m_gyro_rate_x); + std::swap(this->m_gyro_rate_y, other.m_gyro_rate_y); + std::swap(this->m_gyro_rate_z, other.m_gyro_rate_z); + std::swap(this->m_accel_x, other.m_accel_x); + std::swap(this->m_accel_y, other.m_accel_y); + std::swap(this->m_accel_z, other.m_accel_z); + std::swap(this->m_tau, other.m_tau); + std::swap(this->m_dt, other.m_dt); + std::swap(this->m_alpha, other.m_alpha); + std::swap(this->m_compAngleX, other.m_compAngleX); + std::swap(this->m_compAngleY, other.m_compAngleY); + std::swap(this->m_accelAngleX, other.m_accelAngleX); + std::swap(this->m_accelAngleY, other.m_accelAngleY); + this->m_thread_active = other.m_thread_active.load(); + this->m_first_run = other.m_first_run.load(); + this->m_thread_idle = other.m_thread_idle.load(); + std::swap(this->m_auto_configured, other.m_auto_configured); + std::swap(this->m_spi_port, other.m_spi_port); + std::swap(this->m_calibration_time, other.m_calibration_time); + std::swap(this->m_spi, other.m_spi); + std::swap(this->m_auto_interrupt, other.m_auto_interrupt); + std::swap(this->m_scaled_sample_rate, other.m_scaled_sample_rate); + std::swap(this->m_connected, other.m_connected); + std::swap(this->m_acquire_task, other.m_acquire_task); + std::swap(this->m_simDevice, other.m_simDevice); + std::swap(this->m_simConnected, other.m_simConnected); + std::swap(this->m_simGyroAngleX, other.m_simGyroAngleX); + std::swap(this->m_simGyroAngleY, other.m_simGyroAngleZ); + std::swap(this->m_simGyroAngleZ, other.m_simGyroAngleZ); + std::swap(this->m_simGyroRateX, other.m_simGyroRateX); + std::swap(this->m_simGyroRateY, other.m_simGyroRateY); + std::swap(this->m_simGyroRateZ, other.m_simGyroRateZ); + std::swap(this->m_simAccelX, other.m_simAccelX); + std::swap(this->m_simAccelY, other.m_simAccelY); + std::swap(this->m_simAccelZ, other.m_simAccelZ); + std::swap(this->m_mutex, other.m_mutex); + return *this; +} + bool ADIS16470_IMU::IsConnected() const { if (m_simConnected) { return m_simConnected.Get(); @@ -266,17 +425,8 @@ bool ADIS16470_IMU::SwitchToAutoSPI() { m_auto_configured = true; } // Do we need to change auto SPI settings? - switch (m_yaw_axis) { - case kX: - m_spi->SetAutoTransmitData(m_autospi_x_packet, 2); - break; - case kY: - m_spi->SetAutoTransmitData(m_autospi_y_packet, 2); - break; - default: - m_spi->SetAutoTransmitData(m_autospi_z_packet, 2); - break; - } + m_spi->SetAutoTransmitData(m_autospi_allangle_packet, 2); + // Configure auto stall time m_spi->ConfigureAutoStall(HAL_SPI_kOnboardCS0, 5, 1000, 1); // Kick off DMA SPI (Note: Device configuration impossible after SPI DMA is @@ -336,31 +486,22 @@ int ADIS16470_IMU::ConfigCalTime(CalibrationTime new_cal_time) { return 0; } -/** - * @brief Switches the active SPI port to standard SPI mode, writes a new value - *to the DECIMATE register in the IMU, and re-enables auto SPI. - * - * @param reg Decimation value to be set. - * - * @return An int indicating the success or failure of writing the new DECIMATE - *setting and returning to auto SPI mode. 0 = Success, 1 = No Change, 2 = - *Failure - * - * This function enters standard SPI mode, writes a new DECIMATE setting to the - *IMU, adjusts the sample scale factor, and re-enters auto SPI mode. - **/ -int ADIS16470_IMU::ConfigDecRate(uint16_t reg) { - uint16_t m_reg = reg; +int ADIS16470_IMU::ConfigDecRate(uint16_t decimationRate) { + // Switches the active SPI port to standard SPI mode, writes a new value to + // the DECIMATE register in the IMU, and re-enables auto SPI. + // + // This function enters standard SPI mode, writes a new DECIMATE setting to + // the IMU, adjusts the sample scale factor, and re-enters auto SPI mode. if (!SwitchToStandardSPI()) { REPORT_ERROR("Failed to configure/reconfigure standard SPI."); return 2; } - if (m_reg > 1999) { + if (decimationRate > 1999) { REPORT_ERROR("Attempted to write an invalid decimation value."); - m_reg = 1999; + decimationRate = 1999; } - m_scaled_sample_rate = (((m_reg + 1.0) / 2000.0) * 1000000.0); - WriteRegister(DEC_RATE, m_reg); + m_scaled_sample_rate = (((decimationRate + 1.0) / 2000.0) * 1000000.0); + WriteRegister(DEC_RATE, decimationRate); if (!SwitchToAutoSPI()) { REPORT_ERROR("Failed to configure/reconfigure auto SPI."); return 2; @@ -445,7 +586,9 @@ void ADIS16470_IMU::WriteRegister(uint8_t reg, uint16_t val) { **/ void ADIS16470_IMU::Reset() { std::scoped_lock sync(m_mutex); - m_integ_angle = 0.0; + m_integ_angle_x = 0.0; + m_integ_angle_y = 0.0; + m_integ_angle_z = 0.0; } void ADIS16470_IMU::Close() { @@ -502,7 +645,7 @@ ADIS16470_IMU::~ADIS16470_IMU() { **/ void ADIS16470_IMU::Acquire() { // Set data packet length - const int dataset_len = 19; // 18 data points + timestamp + const int dataset_len = 27; // 26 data points + timestamp /* Fixed buffer size */ const int BUFFER_SIZE = 4000; @@ -513,7 +656,9 @@ void ADIS16470_IMU::Acquire() { int data_remainder = 0; int data_to_read = 0; uint32_t previous_timestamp = 0; - double delta_angle = 0.0; + double delta_angle_x = 0.0; + double delta_angle_y = 0.0; + double delta_angle_z = 0.0; double gyro_rate_x = 0.0; double gyro_rate_y = 0.0; double gyro_rate_z = 0.0; @@ -562,14 +707,22 @@ void ADIS16470_IMU::Acquire() { m_dt = (buffer[i] - previous_timestamp) / 1000000.0; /* Get delta angle value for selected yaw axis and scale by the elapsed * time (based on timestamp) */ - delta_angle = (ToInt(&buffer[i + 3]) * delta_angle_sf) / - (m_scaled_sample_rate / (buffer[i] - previous_timestamp)); - gyro_rate_x = (BuffToShort(&buffer[i + 7]) / 10.0); - gyro_rate_y = (BuffToShort(&buffer[i + 9]) / 10.0); - gyro_rate_z = (BuffToShort(&buffer[i + 11]) / 10.0); - accel_x = (BuffToShort(&buffer[i + 13]) / 800.0); - accel_y = (BuffToShort(&buffer[i + 15]) / 800.0); - accel_z = (BuffToShort(&buffer[i + 17]) / 800.0); + delta_angle_x = + (ToInt(&buffer[i + 3]) * delta_angle_sf) / + (m_scaled_sample_rate / (buffer[i] - previous_timestamp)); + delta_angle_y = + (ToInt(&buffer[i + 7]) * delta_angle_sf) / + (m_scaled_sample_rate / (buffer[i] - previous_timestamp)); + delta_angle_z = + (ToInt(&buffer[i + 11]) * delta_angle_sf) / + (m_scaled_sample_rate / (buffer[i] - previous_timestamp)); + + gyro_rate_x = (BuffToShort(&buffer[i + 15]) / 10.0); + gyro_rate_y = (BuffToShort(&buffer[i + 17]) / 10.0); + gyro_rate_z = (BuffToShort(&buffer[i + 19]) / 10.0); + accel_x = (BuffToShort(&buffer[i + 21]) / 800.0); + accel_y = (BuffToShort(&buffer[i + 23]) / 800.0); + accel_z = (BuffToShort(&buffer[i + 25]) / 800.0); // Convert scaled sensor data to SI units gyro_rate_x_si = gyro_rate_x * deg_to_rad; @@ -611,9 +764,13 @@ void ADIS16470_IMU::Acquire() { if (m_first_run) { /* Don't accumulate first run. previous_timestamp will be "very" old * and the integration will end up way off */ - m_integ_angle = 0.0; + m_integ_angle_x = 0.0; + m_integ_angle_y = 0.0; + m_integ_angle_z = 0.0; } else { - m_integ_angle += delta_angle; + m_integ_angle_x += delta_angle_x; + m_integ_angle_y += delta_angle_y; + m_integ_angle_z += delta_angle_z; } m_gyro_rate_x = gyro_rate_x; m_gyro_rate_y = gyro_rate_y; @@ -634,7 +791,9 @@ void ADIS16470_IMU::Acquire() { data_remainder = 0; data_to_read = 0; previous_timestamp = 0.0; - delta_angle = 0.0; + delta_angle_x = 0.0; + delta_angle_y = 0.0; + delta_angle_z = 0.0; gyro_rate_x = 0.0; gyro_rate_y = 0.0; gyro_rate_z = 0.0; @@ -696,50 +855,143 @@ double ADIS16470_IMU::CompFilterProcess(double compAngle, double accelAngle, return compAngle; } -units::degree_t ADIS16470_IMU::GetAngle() const { - switch (m_yaw_axis) { +void ADIS16470_IMU::SetGyroAngle(IMUAxis axis, units::degree_t angle) { + switch (axis) { + case kYaw: + axis = m_yaw_axis; + break; + case kPitch: + axis = m_pitch_axis; + break; + case kRoll: + axis = m_roll_axis; + break; + default: + break; + } + + switch (axis) { + case kX: + SetGyroAngleX(angle); + break; + case kY: + SetGyroAngleY(angle); + break; + case kZ: + SetGyroAngleZ(angle); + break; + default: + break; + } +} + +void ADIS16470_IMU::SetGyroAngleX(units::degree_t angle) { + std::scoped_lock sync(m_mutex); + m_integ_angle_x = angle.value(); +} + +void ADIS16470_IMU::SetGyroAngleY(units::degree_t angle) { + std::scoped_lock sync(m_mutex); + m_integ_angle_y = angle.value(); +} + +void ADIS16470_IMU::SetGyroAngleZ(units::degree_t angle) { + std::scoped_lock sync(m_mutex); + m_integ_angle_z = angle.value(); +} + +units::degree_t ADIS16470_IMU::GetAngle(IMUAxis axis) const { + switch (axis) { + case kYaw: + axis = m_yaw_axis; + break; + case kPitch: + axis = m_pitch_axis; + break; + case kRoll: + axis = m_roll_axis; + break; + default: + break; + } + + switch (axis) { case kX: if (m_simGyroAngleX) { return units::degree_t{m_simGyroAngleX.Get()}; } - break; + { + std::scoped_lock sync(m_mutex); + return units::degree_t{m_integ_angle_x}; + } case kY: if (m_simGyroAngleY) { return units::degree_t{m_simGyroAngleY.Get()}; } - break; + { + std::scoped_lock sync(m_mutex); + return units::degree_t{m_integ_angle_y}; + } case kZ: if (m_simGyroAngleZ) { return units::degree_t{m_simGyroAngleZ.Get()}; } + { + std::scoped_lock sync(m_mutex); + return units::degree_t{m_integ_angle_z}; + } + default: break; } - std::scoped_lock sync(m_mutex); - return units::degree_t{m_integ_angle}; + + return units::degree_t{0.0}; } -units::degrees_per_second_t ADIS16470_IMU::GetRate() const { - if (m_yaw_axis == kX) { - if (m_simGyroRateX) { - return units::degrees_per_second_t{m_simGyroRateX.Get()}; - } - std::scoped_lock sync(m_mutex); - return units::degrees_per_second_t{m_gyro_rate_x}; - } else if (m_yaw_axis == kY) { - if (m_simGyroRateY) { - return units::degrees_per_second_t{m_simGyroRateY.Get()}; - } - std::scoped_lock sync(m_mutex); - return units::degrees_per_second_t{m_gyro_rate_y}; - } else if (m_yaw_axis == kZ) { - if (m_simGyroRateZ) { - return units::degrees_per_second_t{m_simGyroRateZ.Get()}; - } - std::scoped_lock sync(m_mutex); - return units::degrees_per_second_t{m_gyro_rate_z}; - } else { - return 0_deg_per_s; +units::degrees_per_second_t ADIS16470_IMU::GetRate(IMUAxis axis) const { + switch (axis) { + case kYaw: + axis = m_yaw_axis; + break; + case kPitch: + axis = m_pitch_axis; + break; + case kRoll: + axis = m_roll_axis; + break; + default: + break; } + + switch (axis) { + case kX: + if (m_simGyroRateX) { + return units::degrees_per_second_t{m_simGyroRateX.Get()}; + } + { + std::scoped_lock sync(m_mutex); + return units::degrees_per_second_t{m_gyro_rate_x}; + } + case kY: + if (m_simGyroRateY) { + return units::degrees_per_second_t{m_simGyroRateY.Get()}; + } + { + std::scoped_lock sync(m_mutex); + return units::degrees_per_second_t{m_gyro_rate_y}; + } + case kZ: + if (m_simGyroRateZ) { + return units::degrees_per_second_t{m_simGyroRateZ.Get()}; + } + { + std::scoped_lock sync(m_mutex); + return units::degrees_per_second_t{m_gyro_rate_z}; + } + default: + break; + } + + return 0_deg_per_s; } units::meters_per_second_squared_t ADIS16470_IMU::GetAccelX() const { @@ -790,20 +1042,12 @@ ADIS16470_IMU::IMUAxis ADIS16470_IMU::GetYawAxis() const { return m_yaw_axis; } -int ADIS16470_IMU::SetYawAxis(IMUAxis yaw_axis) { - if (m_yaw_axis == yaw_axis) { - return 1; - } - if (!SwitchToStandardSPI()) { - REPORT_ERROR("Failed to configure/reconfigure standard SPI."); - return 2; - } - m_yaw_axis = yaw_axis; - if (!SwitchToAutoSPI()) { - REPORT_ERROR("Failed to configure/reconfigure auto SPI."); - return 2; - } - return 0; +ADIS16470_IMU::IMUAxis ADIS16470_IMU::GetPitchAxis() const { + return m_pitch_axis; +} + +ADIS16470_IMU::IMUAxis ADIS16470_IMU::GetRollAxis() const { + return m_roll_axis; } int ADIS16470_IMU::GetPort() const { @@ -819,5 +1063,5 @@ int ADIS16470_IMU::GetPort() const { void ADIS16470_IMU::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("ADIS16470 IMU"); builder.AddDoubleProperty( - "Yaw Angle", [=, this] { return GetAngle().value(); }, nullptr); + "Yaw Angle", [=, this] { return GetAngle(kYaw).value(); }, nullptr); } diff --git a/wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp b/wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp index c134b5c1ee2..21e98e2ee3b 100644 --- a/wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp +++ b/wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp @@ -150,6 +150,5 @@ int ADXRS450_Gyro::GetPort() const { void ADXRS450_Gyro::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("Gyro"); - builder.AddDoubleProperty( - "Value", [=, this] { return GetAngle(); }, nullptr); + builder.AddDoubleProperty("Value", [=, this] { return GetAngle(); }, nullptr); } diff --git a/wpilibc/src/main/native/cpp/AnalogGyro.cpp b/wpilibc/src/main/native/cpp/AnalogGyro.cpp index df6d33f458d..8c0c4709c40 100644 --- a/wpilibc/src/main/native/cpp/AnalogGyro.cpp +++ b/wpilibc/src/main/native/cpp/AnalogGyro.cpp @@ -143,6 +143,5 @@ std::shared_ptr AnalogGyro::GetAnalogInput() const { void AnalogGyro::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("Gyro"); - builder.AddDoubleProperty( - "Value", [=, this] { return GetAngle(); }, nullptr); + builder.AddDoubleProperty("Value", [=, this] { return GetAngle(); }, nullptr); } diff --git a/wpilibc/src/main/native/cpp/AnalogPotentiometer.cpp b/wpilibc/src/main/native/cpp/AnalogPotentiometer.cpp index d43c84fe752..d8b8b1e0a88 100644 --- a/wpilibc/src/main/native/cpp/AnalogPotentiometer.cpp +++ b/wpilibc/src/main/native/cpp/AnalogPotentiometer.cpp @@ -45,6 +45,5 @@ double AnalogPotentiometer::Get() const { void AnalogPotentiometer::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("Analog Input"); - builder.AddDoubleProperty( - "Value", [=, this] { return Get(); }, nullptr); + builder.AddDoubleProperty("Value", [=, this] { return Get(); }, nullptr); } diff --git a/wpilibc/src/main/native/cpp/BuiltInAccelerometer.cpp b/wpilibc/src/main/native/cpp/BuiltInAccelerometer.cpp index 857643b6587..2189863241f 100644 --- a/wpilibc/src/main/native/cpp/BuiltInAccelerometer.cpp +++ b/wpilibc/src/main/native/cpp/BuiltInAccelerometer.cpp @@ -41,10 +41,7 @@ double BuiltInAccelerometer::GetZ() { void BuiltInAccelerometer::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("3AxisAccelerometer"); - builder.AddDoubleProperty( - "X", [=, this] { return GetX(); }, nullptr); - builder.AddDoubleProperty( - "Y", [=, this] { return GetY(); }, nullptr); - builder.AddDoubleProperty( - "Z", [=, this] { return GetZ(); }, nullptr); + builder.AddDoubleProperty("X", [=, this] { return GetX(); }, nullptr); + builder.AddDoubleProperty("Y", [=, this] { return GetY(); }, nullptr); + builder.AddDoubleProperty("Z", [=, this] { return GetZ(); }, nullptr); } diff --git a/wpilibc/src/main/native/cpp/Counter.cpp b/wpilibc/src/main/native/cpp/Counter.cpp index c33b69bef3c..ab69f4ffde0 100644 --- a/wpilibc/src/main/native/cpp/Counter.cpp +++ b/wpilibc/src/main/native/cpp/Counter.cpp @@ -320,6 +320,5 @@ bool Counter::GetDirection() const { void Counter::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("Counter"); - builder.AddDoubleProperty( - "Value", [=, this] { return Get(); }, nullptr); + builder.AddDoubleProperty("Value", [=, this] { return Get(); }, nullptr); } diff --git a/wpilibc/src/main/native/cpp/DMA.cpp b/wpilibc/src/main/native/cpp/DMA.cpp index ce6c5328a64..da45aa3562e 100644 --- a/wpilibc/src/main/native/cpp/DMA.cpp +++ b/wpilibc/src/main/native/cpp/DMA.cpp @@ -40,9 +40,9 @@ void DMA::SetPause(bool pause) { FRC_CheckErrorStatus(status, "SetPause"); } -void DMA::SetTimedTrigger(units::second_t seconds) { +void DMA::SetTimedTrigger(units::second_t period) { int32_t status = 0; - HAL_SetDMATimedTrigger(dmaHandle, seconds.value(), &status); + HAL_SetDMATimedTrigger(dmaHandle, period.value(), &status); FRC_CheckErrorStatus(status, "SetTimedTrigger"); } diff --git a/wpilibc/src/main/native/cpp/DataLogManager.cpp b/wpilibc/src/main/native/cpp/DataLogManager.cpp index 156b4054cc4..43870728d48 100644 --- a/wpilibc/src/main/native/cpp/DataLogManager.cpp +++ b/wpilibc/src/main/native/cpp/DataLogManager.cpp @@ -11,12 +11,13 @@ #include #include -#include #include #include +#include #include #include #include +#include #include #include "frc/DriverStation.h" @@ -39,7 +40,7 @@ struct Thread final : public wpi::SafeThread { std::string m_logDir; bool m_filenameOverride; - wpi::log::DataLog m_log; + wpi::log::DataLogBackgroundWriter m_log; bool m_ntLoggerEnabled = false; NT_DataLogger m_ntEntryLogger = 0; NT_ConnectionDataLogger m_ntConnLogger = 0; @@ -64,12 +65,12 @@ static std::string MakeLogDir(std::string_view dir) { } #ifdef __FRC_ROBORIO__ // prefer a mounted USB drive if one is accessible - constexpr std::string_view usbDir{"/u"}; std::error_code ec; - auto s = fs::status(usbDir, ec); + auto s = fs::status("/u", ec); if (!ec && fs::is_directory(s) && (s.permissions() & fs::perms::others_write) != fs::perms::none) { - return std::string{usbDir}; + fs::create_directory("/u/logs", ec); + return "/u/logs"; } if (RobotBase::GetRuntimeType() == kRoboRIO) { FRC_ReportError(warn::Warning, @@ -79,7 +80,10 @@ static std::string MakeLogDir(std::string_view dir) { fs::create_directory("/home/lvuser/logs", ec); return "/home/lvuser/logs"; #else - return filesystem::GetOperatingDirectory(); + std::string logDir = filesystem::GetOperatingDirectory() + "/logs"; + std::error_code ec; + fs::create_directory(logDir, ec); + return logDir; #endif } @@ -154,7 +158,7 @@ void Thread::Main() { break; } } else { - fmt::print(stderr, "DataLogManager: could not delete {}\n", + wpi::print(stderr, "DataLogManager: could not delete {}\n", entry.path().string()); } } @@ -304,7 +308,7 @@ Instance::Instance(std::string_view dir, std::string_view filename, if (wpi::starts_with(entry.path().stem().string(), "FRC_TBD_") && entry.path().extension() == ".wpilog") { if (!fs::remove(entry, ec)) { - fmt::print(stderr, "DataLogManager: could not delete {}\n", + wpi::print(stderr, "DataLogManager: could not delete {}\n", entry.path().string()); } } @@ -336,7 +340,7 @@ void DataLogManager::Stop() { void DataLogManager::Log(std::string_view message) { GetInstance().owner.GetThread()->m_messageLog.Append(message); - fmt::print("{}\n", message); + wpi::print("{}\n", message); } wpi::log::DataLog& DataLogManager::GetLog() { diff --git a/wpilibc/src/main/native/cpp/DigitalInput.cpp b/wpilibc/src/main/native/cpp/DigitalInput.cpp index 02757415de3..e3f183dc658 100644 --- a/wpilibc/src/main/native/cpp/DigitalInput.cpp +++ b/wpilibc/src/main/native/cpp/DigitalInput.cpp @@ -68,6 +68,5 @@ int DigitalInput::GetChannel() const { void DigitalInput::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("Digital Input"); - builder.AddBooleanProperty( - "Value", [=, this] { return Get(); }, nullptr); + builder.AddBooleanProperty("Value", [=, this] { return Get(); }, nullptr); } diff --git a/wpilibc/src/main/native/cpp/DigitalOutput.cpp b/wpilibc/src/main/native/cpp/DigitalOutput.cpp index fc69e359da5..9f65faf3fca 100644 --- a/wpilibc/src/main/native/cpp/DigitalOutput.cpp +++ b/wpilibc/src/main/native/cpp/DigitalOutput.cpp @@ -78,7 +78,7 @@ int DigitalOutput::GetChannel() const { void DigitalOutput::Pulse(units::second_t pulseLength) { int32_t status = 0; - HAL_Pulse(m_handle, pulseLength.to(), &status); + HAL_Pulse(m_handle, pulseLength.value(), &status); FRC_CheckErrorStatus(status, "Channel {}", m_channel); } diff --git a/wpilibc/src/main/native/cpp/Encoder.cpp b/wpilibc/src/main/native/cpp/Encoder.cpp index c6440709ef9..1e15ed87bb6 100644 --- a/wpilibc/src/main/native/cpp/Encoder.cpp +++ b/wpilibc/src/main/native/cpp/Encoder.cpp @@ -216,8 +216,7 @@ void Encoder::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("Encoder"); } - builder.AddDoubleProperty( - "Speed", [=, this] { return GetRate(); }, nullptr); + builder.AddDoubleProperty("Speed", [=, this] { return GetRate(); }, nullptr); builder.AddDoubleProperty( "Distance", [=, this] { return GetDistance(); }, nullptr); builder.AddDoubleProperty( diff --git a/wpilibc/src/main/native/cpp/I2C.cpp b/wpilibc/src/main/native/cpp/I2C.cpp index da26c0c9cee..232a47f0f12 100644 --- a/wpilibc/src/main/native/cpp/I2C.cpp +++ b/wpilibc/src/main/native/cpp/I2C.cpp @@ -4,6 +4,7 @@ #include "frc/I2C.h" +#include #include #include @@ -96,7 +97,7 @@ bool I2C::VerifySensor(int registerAddress, int count, uint8_t deviceData[4]; for (int i = 0, curRegisterAddress = registerAddress; i < count; i += 4, curRegisterAddress += 4) { - int toRead = count - i < 4 ? count - i : 4; + int toRead = std::min(count - i, 4); // Read the chunk of data. Return false if the sensor does not respond. if (Read(curRegisterAddress, toRead, deviceData)) { return false; diff --git a/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp b/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp index ee941b61cc0..78a3067b388 100644 --- a/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp +++ b/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp @@ -6,9 +6,10 @@ #include -#include #include +#include #include +#include #include "frc/DSControlWord.h" #include "frc/Errors.h" @@ -39,7 +40,7 @@ void IterativeRobotBase::TestInit() {} void IterativeRobotBase::RobotPeriodic() { static bool firstRun = true; if (firstRun) { - fmt::print("Default {}() method... Override me!\n", __FUNCTION__); + wpi::print("Default {}() method... Override me!\n", __FUNCTION__); firstRun = false; } } @@ -47,7 +48,7 @@ void IterativeRobotBase::RobotPeriodic() { void IterativeRobotBase::SimulationPeriodic() { static bool firstRun = true; if (firstRun) { - fmt::print("Default {}() method... Override me!\n", __FUNCTION__); + wpi::print("Default {}() method... Override me!\n", __FUNCTION__); firstRun = false; } } @@ -55,7 +56,7 @@ void IterativeRobotBase::SimulationPeriodic() { void IterativeRobotBase::DisabledPeriodic() { static bool firstRun = true; if (firstRun) { - fmt::print("Default {}() method... Override me!\n", __FUNCTION__); + wpi::print("Default {}() method... Override me!\n", __FUNCTION__); firstRun = false; } } @@ -63,7 +64,7 @@ void IterativeRobotBase::DisabledPeriodic() { void IterativeRobotBase::AutonomousPeriodic() { static bool firstRun = true; if (firstRun) { - fmt::print("Default {}() method... Override me!\n", __FUNCTION__); + wpi::print("Default {}() method... Override me!\n", __FUNCTION__); firstRun = false; } } @@ -71,7 +72,7 @@ void IterativeRobotBase::AutonomousPeriodic() { void IterativeRobotBase::TeleopPeriodic() { static bool firstRun = true; if (firstRun) { - fmt::print("Default {}() method... Override me!\n", __FUNCTION__); + wpi::print("Default {}() method... Override me!\n", __FUNCTION__); firstRun = false; } } @@ -79,7 +80,7 @@ void IterativeRobotBase::TeleopPeriodic() { void IterativeRobotBase::TestPeriodic() { static bool firstRun = true; if (firstRun) { - fmt::print("Default {}() method... Override me!\n", __FUNCTION__); + wpi::print("Default {}() method... Override me!\n", __FUNCTION__); firstRun = false; } } @@ -97,10 +98,16 @@ void IterativeRobotBase::SetNetworkTablesFlushEnabled(bool enabled) { } void IterativeRobotBase::EnableLiveWindowInTest(bool testLW) { + static bool hasReported; if (IsTestEnabled()) { throw FRC_MakeError(err::IncompatibleMode, "Can't configure test mode while in test mode!"); } + if (!hasReported && testLW) { + HAL_Report(HALUsageReporting::kResourceType_SmartDashboard, + HALUsageReporting::kSmartDashboard_LiveWindow); + hasReported = true; + } m_lwEnabledInTest = testLW; } @@ -225,3 +232,7 @@ void IterativeRobotBase::LoopFunc() { void IterativeRobotBase::PrintLoopOverrunMessage() { FRC_ReportError(err::Error, "Loop time of {:.6f}s overrun", m_period.value()); } + +void IterativeRobotBase::PrintWatchdogEpochs() { + m_watchdog.PrintEpochs(); +} diff --git a/wpilibc/src/main/native/cpp/Joystick.cpp b/wpilibc/src/main/native/cpp/Joystick.cpp index 8a378c59eee..851e25c1277 100644 --- a/wpilibc/src/main/native/cpp/Joystick.cpp +++ b/wpilibc/src/main/native/cpp/Joystick.cpp @@ -122,16 +122,6 @@ double Joystick::GetMagnitude() const { return std::hypot(GetX(), GetY()); } -double Joystick::GetDirectionRadians() const { - return std::atan2(GetX(), -GetY()); -} - -double Joystick::GetDirectionDegrees() const { - WPI_IGNORE_DEPRECATED - return (180 / std::numbers::pi) * GetDirectionRadians(); - WPI_UNIGNORE_DEPRECATED -} - units::radian_t Joystick::GetDirection() const { return units::math::atan2(units::dimensionless::scalar_t{GetX()}, units::dimensionless::scalar_t{-GetY()}); diff --git a/wpilibc/src/main/native/cpp/Notifier.cpp b/wpilibc/src/main/native/cpp/Notifier.cpp index 147beb40035..81cd017c24e 100644 --- a/wpilibc/src/main/native/cpp/Notifier.cpp +++ b/wpilibc/src/main/native/cpp/Notifier.cpp @@ -161,11 +161,6 @@ void Notifier::SetName(std::string_view name) { HAL_SetNotifierName(m_notifier, buf.data(), &status); } -void Notifier::SetHandler(std::function callback) { - std::scoped_lock lock(m_processMutex); - m_callback = callback; -} - void Notifier::SetCallback(std::function callback) { std::scoped_lock lock(m_processMutex); m_callback = callback; diff --git a/wpilibc/src/main/native/cpp/PS4Controller.cpp b/wpilibc/src/main/native/cpp/PS4Controller.cpp index 5ac3420756c..e59e18cd3b3 100644 --- a/wpilibc/src/main/native/cpp/PS4Controller.cpp +++ b/wpilibc/src/main/native/cpp/PS4Controller.cpp @@ -11,8 +11,7 @@ using namespace frc; PS4Controller::PS4Controller(int port) : GenericHID(port) { - // re-enable when PS4Controller is added to Usage Reporting - // HAL_Report(HALUsageReporting::kResourceType_PS4Controller, port + 1); + HAL_Report(HALUsageReporting::kResourceType_PS4Controller, port + 1); } double PS4Controller::GetLeftX() const { diff --git a/wpilibc/src/main/native/cpp/PneumaticHub.cpp b/wpilibc/src/main/native/cpp/PneumaticHub.cpp index bcbbd558026..91014735a62 100644 --- a/wpilibc/src/main/native/cpp/PneumaticHub.cpp +++ b/wpilibc/src/main/native/cpp/PneumaticHub.cpp @@ -23,15 +23,15 @@ using namespace frc; /** Converts volts to PSI per the REV Analog Pressure Sensor datasheet. */ units::pounds_per_square_inch_t VoltsToPSI(units::volt_t sensorVoltage, units::volt_t supplyVoltage) { - auto pressure = 250 * (sensorVoltage.value() / supplyVoltage.value()) - 25; - return units::pounds_per_square_inch_t{pressure}; + return units::pounds_per_square_inch_t{ + 250 * (sensorVoltage.value() / supplyVoltage.value()) - 25}; } /** Converts PSI to volts per the REV Analog Pressure Sensor datasheet. */ units::volt_t PSIToVolts(units::pounds_per_square_inch_t pressure, units::volt_t supplyVoltage) { - auto voltage = supplyVoltage.value() * (0.004 * pressure.value() + 0.1); - return units::volt_t{voltage}; + return units::volt_t{supplyVoltage.value() * + (0.004 * pressure.value() + 0.1)}; } wpi::mutex PneumaticHub::m_handleLock; @@ -339,6 +339,46 @@ PneumaticHub::StickyFaults PneumaticHub::GetStickyFaults() const { return stickyFaults; } +bool PneumaticHub::Faults::GetChannelFault(int channel) const { + switch (channel) { + case 0: + return Channel0Fault != 0; + case 1: + return Channel1Fault != 0; + case 2: + return Channel2Fault != 0; + case 3: + return Channel3Fault != 0; + case 4: + return Channel4Fault != 0; + case 5: + return Channel5Fault != 0; + case 6: + return Channel6Fault != 0; + case 7: + return Channel7Fault != 0; + case 8: + return Channel8Fault != 0; + case 9: + return Channel9Fault != 0; + case 10: + return Channel10Fault != 0; + case 11: + return Channel11Fault != 0; + case 12: + return Channel12Fault != 0; + case 13: + return Channel13Fault != 0; + case 14: + return Channel14Fault != 0; + case 15: + return Channel15Fault != 0; + default: + throw FRC_MakeError(err::ChannelIndexOutOfRange, + "Pneumatics fault channel out of bounds!"); + } +} + void PneumaticHub::ClearStickyFaults() { int32_t status = 0; HAL_ClearREVPHStickyFaults(m_handle, &status); diff --git a/wpilibc/src/main/native/cpp/PowerDistribution.cpp b/wpilibc/src/main/native/cpp/PowerDistribution.cpp index ba4cb383c30..d6451780bb1 100644 --- a/wpilibc/src/main/native/cpp/PowerDistribution.cpp +++ b/wpilibc/src/main/native/cpp/PowerDistribution.cpp @@ -172,6 +172,118 @@ PowerDistribution::Faults PowerDistribution::GetFaults() const { return faults; } +bool PowerDistribution::Faults::GetBreakerFault(int channel) const { + switch (channel) { + case 0: + return Channel0BreakerFault != 0; + case 1: + return Channel1BreakerFault != 0; + case 2: + return Channel2BreakerFault != 0; + case 3: + return Channel3BreakerFault != 0; + case 4: + return Channel4BreakerFault != 0; + case 5: + return Channel5BreakerFault != 0; + case 6: + return Channel6BreakerFault != 0; + case 7: + return Channel7BreakerFault != 0; + case 8: + return Channel8BreakerFault != 0; + case 9: + return Channel9BreakerFault != 0; + case 10: + return Channel10BreakerFault != 0; + case 11: + return Channel11BreakerFault != 0; + case 12: + return Channel12BreakerFault != 0; + case 13: + return Channel13BreakerFault != 0; + case 14: + return Channel14BreakerFault != 0; + case 15: + return Channel15BreakerFault != 0; + case 16: + return Channel16BreakerFault != 0; + case 17: + return Channel17BreakerFault != 0; + case 18: + return Channel18BreakerFault != 0; + case 19: + return Channel19BreakerFault != 0; + case 20: + return Channel20BreakerFault != 0; + case 21: + return Channel21BreakerFault != 0; + case 22: + return Channel22BreakerFault != 0; + case 23: + return Channel23BreakerFault != 0; + default: + throw FRC_MakeError(err::ChannelIndexOutOfRange, + "Power distribution fault channel out of bounds!"); + } +} + +bool PowerDistribution::StickyFaults::GetBreakerFault(int channel) const { + switch (channel) { + case 0: + return Channel0BreakerFault != 0; + case 1: + return Channel1BreakerFault != 0; + case 2: + return Channel2BreakerFault != 0; + case 3: + return Channel3BreakerFault != 0; + case 4: + return Channel4BreakerFault != 0; + case 5: + return Channel5BreakerFault != 0; + case 6: + return Channel6BreakerFault != 0; + case 7: + return Channel7BreakerFault != 0; + case 8: + return Channel8BreakerFault != 0; + case 9: + return Channel9BreakerFault != 0; + case 10: + return Channel10BreakerFault != 0; + case 11: + return Channel11BreakerFault != 0; + case 12: + return Channel12BreakerFault != 0; + case 13: + return Channel13BreakerFault != 0; + case 14: + return Channel14BreakerFault != 0; + case 15: + return Channel15BreakerFault != 0; + case 16: + return Channel16BreakerFault != 0; + case 17: + return Channel17BreakerFault != 0; + case 18: + return Channel18BreakerFault != 0; + case 19: + return Channel19BreakerFault != 0; + case 20: + return Channel20BreakerFault != 0; + case 21: + return Channel21BreakerFault != 0; + case 22: + return Channel22BreakerFault != 0; + case 23: + return Channel23BreakerFault != 0; + default: + throw FRC_MakeError(err::ChannelIndexOutOfRange, + "Power distribution fault channel out of bounds!"); + } +} + PowerDistribution::StickyFaults PowerDistribution::GetStickyFaults() const { int32_t status = 0; HAL_PowerDistributionStickyFaults halStickyFaults; diff --git a/wpilibc/src/main/native/cpp/RobotController.cpp b/wpilibc/src/main/native/cpp/RobotController.cpp index 8b2b4964a8d..48da72372af 100644 --- a/wpilibc/src/main/native/cpp/RobotController.cpp +++ b/wpilibc/src/main/native/cpp/RobotController.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include "frc/Errors.h" @@ -29,16 +30,19 @@ int64_t RobotController::GetFPGARevision() { } std::string RobotController::GetSerialNumber() { - // Serial number is 8 characters - char serialNum[9]; - size_t len = HAL_GetSerialNumber(serialNum, sizeof(serialNum)); - return std::string(serialNum, len); + WPI_String serialNum; + HAL_GetSerialNumber(&serialNum); + std::string ret{wpi::to_string_view(&serialNum)}; + WPI_FreeString(&serialNum); + return ret; } std::string RobotController::GetComments() { - char comments[65]; - size_t len = HAL_GetComments(comments, sizeof(comments)); - return std::string(comments, len); + WPI_String comments; + HAL_GetComments(&comments); + std::string ret{wpi::to_string_view(&comments)}; + WPI_FreeString(&comments); + return ret; } int32_t RobotController::GetTeamNumber() { @@ -230,6 +234,30 @@ units::celsius_t RobotController::GetCPUTemp() { return units::celsius_t{retVal}; } +static_assert(RadioLEDState::kOff == + static_cast(HAL_RadioLEDState::HAL_RadioLED_kOff)); +static_assert( + RadioLEDState::kGreen == + static_cast(HAL_RadioLEDState::HAL_RadioLED_kGreen)); +static_assert(RadioLEDState::kRed == + static_cast(HAL_RadioLEDState::HAL_RadioLED_kRed)); +static_assert( + RadioLEDState::kOrange == + static_cast(HAL_RadioLEDState::HAL_RadioLED_kOrange)); + +void RobotController::SetRadioLEDState(RadioLEDState state) { + int32_t status = 0; + HAL_SetRadioLEDState(static_cast(state), &status); + FRC_CheckErrorStatus(status, "SetRadioLEDState"); +} + +RadioLEDState RobotController::GetRadioLEDState() { + int32_t status = 0; + auto retVal = static_cast(HAL_GetRadioLEDState(&status)); + FRC_CheckErrorStatus(status, "GetRadioLEDState"); + return retVal; +} + CANStatus RobotController::GetCANStatus() { int32_t status = 0; float percentBusUtilization = 0; diff --git a/wpilibc/src/main/native/cpp/StadiaController.cpp b/wpilibc/src/main/native/cpp/StadiaController.cpp new file mode 100644 index 00000000000..4f8d666c54c --- /dev/null +++ b/wpilibc/src/main/native/cpp/StadiaController.cpp @@ -0,0 +1,272 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/StadiaController.h" + +#include + +#include "frc/event/BooleanEvent.h" + +using namespace frc; + +StadiaController::StadiaController(int port) : GenericHID(port) { + // re-enable when StadiaController is added to Usage Reporting + // HAL_Report(HALUsageReporting::kResourceType_StadiaController, port + 1); +} + +double StadiaController::GetLeftX() const { + return GetRawAxis(Axis::kLeftX); +} + +double StadiaController::GetRightX() const { + return GetRawAxis(Axis::kRightX); +} + +double StadiaController::GetLeftY() const { + return GetRawAxis(Axis::kLeftY); +} + +double StadiaController::GetRightY() const { + return GetRawAxis(Axis::kRightY); +} + +bool StadiaController::GetLeftBumper() const { + return GetRawButton(Button::kLeftBumper); +} + +bool StadiaController::GetRightBumper() const { + return GetRawButton(Button::kRightBumper); +} + +bool StadiaController::GetLeftBumperPressed() { + return GetRawButtonPressed(Button::kLeftBumper); +} + +bool StadiaController::GetRightBumperPressed() { + return GetRawButtonPressed(Button::kRightBumper); +} + +bool StadiaController::GetLeftBumperReleased() { + return GetRawButtonReleased(Button::kLeftBumper); +} + +bool StadiaController::GetRightBumperReleased() { + return GetRawButtonReleased(Button::kRightBumper); +} + +BooleanEvent StadiaController::LeftBumper(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetLeftBumper(); }); +} + +BooleanEvent StadiaController::RightBumper(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetRightBumper(); }); +} + +bool StadiaController::GetLeftStickButton() const { + return GetRawButton(Button::kLeftStick); +} + +bool StadiaController::GetRightStickButton() const { + return GetRawButton(Button::kRightStick); +} + +bool StadiaController::GetLeftStickButtonPressed() { + return GetRawButtonPressed(Button::kLeftStick); +} + +bool StadiaController::GetRightStickButtonPressed() { + return GetRawButtonPressed(Button::kRightStick); +} + +bool StadiaController::GetLeftStickButtonReleased() { + return GetRawButtonReleased(Button::kLeftStick); +} + +bool StadiaController::GetRightStickButtonReleased() { + return GetRawButtonReleased(Button::kRightStick); +} + +BooleanEvent StadiaController::LeftStick(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetLeftStickButton(); }); +} + +BooleanEvent StadiaController::RightStick(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetRightStickButton(); }); +} + +bool StadiaController::GetAButton() const { + return GetRawButton(Button::kA); +} + +bool StadiaController::GetAButtonPressed() { + return GetRawButtonPressed(Button::kA); +} + +bool StadiaController::GetAButtonReleased() { + return GetRawButtonReleased(Button::kA); +} + +BooleanEvent StadiaController::A(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetAButton(); }); +} + +bool StadiaController::GetBButton() const { + return GetRawButton(Button::kB); +} + +bool StadiaController::GetBButtonPressed() { + return GetRawButtonPressed(Button::kB); +} + +bool StadiaController::GetBButtonReleased() { + return GetRawButtonReleased(Button::kB); +} + +BooleanEvent StadiaController::B(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetBButton(); }); +} + +bool StadiaController::GetXButton() const { + return GetRawButton(Button::kX); +} + +bool StadiaController::GetXButtonPressed() { + return GetRawButtonPressed(Button::kX); +} + +bool StadiaController::GetXButtonReleased() { + return GetRawButtonReleased(Button::kX); +} + +BooleanEvent StadiaController::X(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetXButton(); }); +} + +bool StadiaController::GetYButton() const { + return GetRawButton(Button::kY); +} + +bool StadiaController::GetYButtonPressed() { + return GetRawButtonPressed(Button::kY); +} + +bool StadiaController::GetYButtonReleased() { + return GetRawButtonReleased(Button::kY); +} + +BooleanEvent StadiaController::Y(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetYButton(); }); +} + +bool StadiaController::GetEllipsesButton() const { + return GetRawButton(Button::kEllipses); +} + +bool StadiaController::GetEllipsesButtonPressed() { + return GetRawButtonPressed(Button::kEllipses); +} + +bool StadiaController::GetEllipsesButtonReleased() { + return GetRawButtonReleased(Button::kEllipses); +} + +BooleanEvent StadiaController::Ellipses(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetEllipsesButton(); }); +} + +bool StadiaController::GetHamburgerButton() const { + return GetRawButton(Button::kHamburger); +} + +bool StadiaController::GetHamburgerButtonPressed() { + return GetRawButtonPressed(Button::kHamburger); +} + +bool StadiaController::GetHamburgerButtonReleased() { + return GetRawButtonReleased(Button::kHamburger); +} + +BooleanEvent StadiaController::Hamburger(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetHamburgerButton(); }); +} + +bool StadiaController::GetStadiaButton() const { + return GetRawButton(Button::kStadia); +} + +bool StadiaController::GetStadiaButtonPressed() { + return GetRawButtonPressed(Button::kStadia); +} + +bool StadiaController::GetStadiaButtonReleased() { + return GetRawButtonReleased(Button::kStadia); +} + +BooleanEvent StadiaController::Stadia(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetStadiaButton(); }); +} + +bool StadiaController::GetGoogleButton() const { + return GetRawButton(Button::kGoogle); +} + +bool StadiaController::GetGoogleButtonPressed() { + return GetRawButtonPressed(Button::kGoogle); +} + +bool StadiaController::GetGoogleButtonReleased() { + return GetRawButtonReleased(Button::kGoogle); +} + +BooleanEvent StadiaController::Google(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetGoogleButton(); }); +} + +bool StadiaController::GetFrameButton() const { + return GetRawButton(Button::kFrame); +} + +bool StadiaController::GetFrameButtonPressed() { + return GetRawButtonPressed(Button::kFrame); +} + +bool StadiaController::GetFrameButtonReleased() { + return GetRawButtonReleased(Button::kFrame); +} + +BooleanEvent StadiaController::Frame(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetFrameButton(); }); +} + +bool StadiaController::GetLeftTriggerButton() const { + return GetRawButton(Button::kLeftTrigger); +} + +bool StadiaController::GetLeftTriggerButtonPressed() { + return GetRawButtonPressed(Button::kLeftTrigger); +} + +bool StadiaController::GetLeftTriggerButtonReleased() { + return GetRawButtonReleased(Button::kLeftTrigger); +} + +BooleanEvent StadiaController::LeftTrigger(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetLeftTriggerButton(); }); +} + +bool StadiaController::GetRightTriggerButton() const { + return GetRawButton(Button::kRightTrigger); +} + +bool StadiaController::GetRightTriggerButtonPressed() { + return GetRawButtonPressed(Button::kRightTrigger); +} + +bool StadiaController::GetRightTriggerButtonReleased() { + return GetRawButtonReleased(Button::kRightTrigger); +} + +BooleanEvent StadiaController::RightTrigger(EventLoop* loop) const { + return BooleanEvent(loop, [this]() { return this->GetRightTriggerButton(); }); +} diff --git a/wpilibc/src/main/native/cpp/counter/ExternalDirectionCounter.cpp b/wpilibc/src/main/native/cpp/counter/ExternalDirectionCounter.cpp index 24709aab321..071d55063be 100644 --- a/wpilibc/src/main/native/cpp/counter/ExternalDirectionCounter.cpp +++ b/wpilibc/src/main/native/cpp/counter/ExternalDirectionCounter.cpp @@ -98,6 +98,5 @@ void ExternalDirectionCounter::SetEdgeConfiguration( void ExternalDirectionCounter::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("External Direction Counter"); - builder.AddDoubleProperty( - "Count", [&] { return GetCount(); }, nullptr); + builder.AddDoubleProperty("Count", [&] { return GetCount(); }, nullptr); } diff --git a/wpilibc/src/main/native/cpp/counter/Tachometer.cpp b/wpilibc/src/main/native/cpp/counter/Tachometer.cpp index 90324f59c9a..90688d2c386 100644 --- a/wpilibc/src/main/native/cpp/counter/Tachometer.cpp +++ b/wpilibc/src/main/native/cpp/counter/Tachometer.cpp @@ -44,7 +44,7 @@ Tachometer::~Tachometer() { units::hertz_t Tachometer::GetFrequency() const { auto period = GetPeriod(); - if (period.to() == 0) { + if (period.value() == 0) { return units::hertz_t{0.0}; } return 1 / period; @@ -66,7 +66,7 @@ void Tachometer::SetEdgesPerRevolution(int edges) { units::turns_per_second_t Tachometer::GetRevolutionsPerSecond() const { auto period = GetPeriod(); - if (period.to() == 0) { + if (period.value() == 0) { return units::turns_per_second_t{0.0}; } int edgesPerRevolution = GetEdgesPerRevolution(); @@ -74,7 +74,7 @@ units::turns_per_second_t Tachometer::GetRevolutionsPerSecond() const { return units::turns_per_second_t{0.0}; } auto rotationHz = ((1.0 / edgesPerRevolution) / period); - return units::turns_per_second_t{rotationHz.to()}; + return units::turns_per_second_t{rotationHz.value()}; } units::revolutions_per_minute_t Tachometer::GetRevolutionsPerMinute() const { @@ -103,7 +103,7 @@ void Tachometer::SetSamplesToAverage(int samples) { void Tachometer::SetMaxPeriod(units::second_t maxPeriod) { int32_t status = 0; - HAL_SetCounterMaxPeriod(m_handle, maxPeriod.to(), &status); + HAL_SetCounterMaxPeriod(m_handle, maxPeriod.value(), &status); FRC_CheckErrorStatus(status, "Channel {}", m_source->GetChannel()); } @@ -116,7 +116,7 @@ void Tachometer::SetUpdateWhenEmpty(bool updateWhenEmpty) { void Tachometer::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("Tachometer"); builder.AddDoubleProperty( - "RPS", [&] { return GetRevolutionsPerSecond().to(); }, nullptr); + "RPS", [&] { return GetRevolutionsPerSecond().value(); }, nullptr); builder.AddDoubleProperty( - "RPM", [&] { return GetRevolutionsPerMinute().to(); }, nullptr); + "RPM", [&] { return GetRevolutionsPerMinute().value(); }, nullptr); } diff --git a/wpilibc/src/main/native/cpp/counter/UpDownCounter.cpp b/wpilibc/src/main/native/cpp/counter/UpDownCounter.cpp index 62537ee882c..706b2d96733 100644 --- a/wpilibc/src/main/native/cpp/counter/UpDownCounter.cpp +++ b/wpilibc/src/main/native/cpp/counter/UpDownCounter.cpp @@ -101,6 +101,5 @@ void UpDownCounter::SetDownEdgeConfiguration(EdgeConfiguration configuration) { void UpDownCounter::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("UpDown Counter"); - builder.AddDoubleProperty( - "Count", [&] { return GetCount(); }, nullptr); + builder.AddDoubleProperty("Count", [&] { return GetCount(); }, nullptr); } diff --git a/wpilibc/src/main/native/cpp/drive/DifferentialDrive.cpp b/wpilibc/src/main/native/cpp/drive/DifferentialDrive.cpp index 8cce62eeb02..e3a0a8c4945 100644 --- a/wpilibc/src/main/native/cpp/drive/DifferentialDrive.cpp +++ b/wpilibc/src/main/native/cpp/drive/DifferentialDrive.cpp @@ -16,11 +16,21 @@ using namespace frc; +WPI_IGNORE_DEPRECATED + DifferentialDrive::DifferentialDrive(MotorController& leftMotor, MotorController& rightMotor) - : m_leftMotor(&leftMotor), m_rightMotor(&rightMotor) { - wpi::SendableRegistry::AddChild(this, m_leftMotor); - wpi::SendableRegistry::AddChild(this, m_rightMotor); + : DifferentialDrive{[&](double output) { leftMotor.Set(output); }, + [&](double output) { rightMotor.Set(output); }} { + wpi::SendableRegistry::AddChild(this, &leftMotor); + wpi::SendableRegistry::AddChild(this, &rightMotor); +} + +WPI_UNIGNORE_DEPRECATED + +DifferentialDrive::DifferentialDrive(std::function leftMotor, + std::function rightMotor) + : m_leftMotor{std::move(leftMotor)}, m_rightMotor{std::move(rightMotor)} { static int instances = 0; ++instances; wpi::SendableRegistry::AddLW(this, "DifferentialDrive", instances); @@ -40,8 +50,11 @@ void DifferentialDrive::ArcadeDrive(double xSpeed, double zRotation, auto [left, right] = ArcadeDriveIK(xSpeed, zRotation, squareInputs); - m_leftMotor->Set(left); - m_rightMotor->Set(right); + m_leftOutput = left * m_maxOutput; + m_rightOutput = right * m_maxOutput; + + m_leftMotor(m_leftOutput); + m_rightMotor(m_rightOutput); Feed(); } @@ -60,8 +73,11 @@ void DifferentialDrive::CurvatureDrive(double xSpeed, double zRotation, auto [left, right] = CurvatureDriveIK(xSpeed, zRotation, allowTurnInPlace); - m_leftMotor->Set(left * m_maxOutput); - m_rightMotor->Set(right * m_maxOutput); + m_leftOutput = left * m_maxOutput; + m_rightOutput = right * m_maxOutput; + + m_leftMotor(m_leftOutput); + m_rightMotor(m_rightOutput); Feed(); } @@ -80,8 +96,11 @@ void DifferentialDrive::TankDrive(double leftSpeed, double rightSpeed, auto [left, right] = TankDriveIK(leftSpeed, rightSpeed, squareInputs); - m_leftMotor->Set(left * m_maxOutput); - m_rightMotor->Set(right * m_maxOutput); + m_leftOutput = left * m_maxOutput; + m_rightOutput = right * m_maxOutput; + + m_leftMotor(m_leftOutput); + m_rightMotor(m_rightOutput); Feed(); } @@ -157,8 +176,12 @@ DifferentialDrive::WheelSpeeds DifferentialDrive::TankDriveIK( } void DifferentialDrive::StopMotor() { - m_leftMotor->StopMotor(); - m_rightMotor->StopMotor(); + m_leftOutput = 0.0; + m_rightOutput = 0.0; + + m_leftMotor(0.0); + m_rightMotor(0.0); + Feed(); } @@ -171,9 +194,7 @@ void DifferentialDrive::InitSendable(wpi::SendableBuilder& builder) { builder.SetActuator(true); builder.SetSafeState([=, this] { StopMotor(); }); builder.AddDoubleProperty( - "Left Motor Speed", [=, this] { return m_leftMotor->Get(); }, - [=, this](double value) { m_leftMotor->Set(value); }); + "Left Motor Speed", [&] { return m_leftOutput; }, m_leftMotor); builder.AddDoubleProperty( - "Right Motor Speed", [=, this] { return m_rightMotor->Get(); }, - [=, this](double value) { m_rightMotor->Set(value); }); + "Right Motor Speed", [&] { return m_rightOutput; }, m_rightMotor); } diff --git a/wpilibc/src/main/native/cpp/drive/MecanumDrive.cpp b/wpilibc/src/main/native/cpp/drive/MecanumDrive.cpp index 2bf6a3f3c49..aeec27d0ded 100644 --- a/wpilibc/src/main/native/cpp/drive/MecanumDrive.cpp +++ b/wpilibc/src/main/native/cpp/drive/MecanumDrive.cpp @@ -16,18 +16,32 @@ using namespace frc; +WPI_IGNORE_DEPRECATED + MecanumDrive::MecanumDrive(MotorController& frontLeftMotor, MotorController& rearLeftMotor, MotorController& frontRightMotor, MotorController& rearRightMotor) - : m_frontLeftMotor(&frontLeftMotor), - m_rearLeftMotor(&rearLeftMotor), - m_frontRightMotor(&frontRightMotor), - m_rearRightMotor(&rearRightMotor) { - wpi::SendableRegistry::AddChild(this, m_frontLeftMotor); - wpi::SendableRegistry::AddChild(this, m_rearLeftMotor); - wpi::SendableRegistry::AddChild(this, m_frontRightMotor); - wpi::SendableRegistry::AddChild(this, m_rearRightMotor); + : MecanumDrive{[&](double output) { frontLeftMotor.Set(output); }, + [&](double output) { rearLeftMotor.Set(output); }, + [&](double output) { frontRightMotor.Set(output); }, + [&](double output) { rearRightMotor.Set(output); }} { + wpi::SendableRegistry::AddChild(this, &frontLeftMotor); + wpi::SendableRegistry::AddChild(this, &rearLeftMotor); + wpi::SendableRegistry::AddChild(this, &frontRightMotor); + wpi::SendableRegistry::AddChild(this, &rearRightMotor); +} + +WPI_UNIGNORE_DEPRECATED + +MecanumDrive::MecanumDrive(std::function frontLeftMotor, + std::function rearLeftMotor, + std::function frontRightMotor, + std::function rearRightMotor) + : m_frontLeftMotor{std::move(frontLeftMotor)}, + m_rearLeftMotor{std::move(rearLeftMotor)}, + m_frontRightMotor{std::move(frontRightMotor)}, + m_rearRightMotor{std::move(rearRightMotor)} { static int instances = 0; ++instances; wpi::SendableRegistry::AddLW(this, "MecanumDrive", instances); @@ -47,10 +61,15 @@ void MecanumDrive::DriveCartesian(double xSpeed, double ySpeed, auto [frontLeft, frontRight, rearLeft, rearRight] = DriveCartesianIK(xSpeed, ySpeed, zRotation, gyroAngle); - m_frontLeftMotor->Set(frontLeft * m_maxOutput); - m_frontRightMotor->Set(frontRight * m_maxOutput); - m_rearLeftMotor->Set(rearLeft * m_maxOutput); - m_rearRightMotor->Set(rearRight * m_maxOutput); + m_frontLeftOutput = frontLeft * m_maxOutput; + m_rearLeftOutput = rearLeft * m_maxOutput; + m_frontRightOutput = frontRight * m_maxOutput; + m_rearRightOutput = rearRight * m_maxOutput; + + m_frontLeftMotor(m_frontLeftOutput); + m_frontRightMotor(m_frontRightOutput); + m_rearLeftMotor(m_rearLeftOutput); + m_rearRightMotor(m_rearRightOutput); Feed(); } @@ -68,10 +87,16 @@ void MecanumDrive::DrivePolar(double magnitude, Rotation2d angle, } void MecanumDrive::StopMotor() { - m_frontLeftMotor->StopMotor(); - m_frontRightMotor->StopMotor(); - m_rearLeftMotor->StopMotor(); - m_rearRightMotor->StopMotor(); + m_frontLeftOutput = 0.0; + m_frontRightOutput = 0.0; + m_rearLeftOutput = 0.0; + m_rearRightOutput = 0.0; + + m_frontLeftMotor(0.0); + m_frontRightMotor(0.0); + m_rearLeftMotor(0.0); + m_rearRightMotor(0.0); + Feed(); } @@ -108,15 +133,15 @@ void MecanumDrive::InitSendable(wpi::SendableBuilder& builder) { builder.SetActuator(true); builder.SetSafeState([=, this] { StopMotor(); }); builder.AddDoubleProperty( - "Front Left Motor Speed", [=, this] { return m_frontLeftMotor->Get(); }, - [=, this](double value) { m_frontLeftMotor->Set(value); }); + "Front Left Motor Speed", [&] { return m_frontLeftOutput; }, + m_frontLeftMotor); builder.AddDoubleProperty( - "Front Right Motor Speed", [=, this] { return m_frontRightMotor->Get(); }, - [=, this](double value) { m_frontRightMotor->Set(value); }); + "Front Right Motor Speed", [&] { return m_frontRightOutput; }, + m_frontRightMotor); builder.AddDoubleProperty( - "Rear Left Motor Speed", [=, this] { return m_rearLeftMotor->Get(); }, - [=, this](double value) { m_rearLeftMotor->Set(value); }); + "Rear Left Motor Speed", [&] { return m_rearLeftOutput; }, + m_rearLeftMotor); builder.AddDoubleProperty( - "Rear Right Motor Speed", [=, this] { return m_rearRightMotor->Get(); }, - [=, this](double value) { m_rearRightMotor->Set(value); }); + "Rear Right Motor Speed", [&] { return m_rearRightOutput; }, + m_rearRightMotor); } diff --git a/wpilibc/src/main/native/cpp/event/EventLoop.cpp b/wpilibc/src/main/native/cpp/event/EventLoop.cpp index 5af79c96d36..c85286ba371 100644 --- a/wpilibc/src/main/native/cpp/event/EventLoop.cpp +++ b/wpilibc/src/main/native/cpp/event/EventLoop.cpp @@ -4,20 +4,41 @@ #include "frc/event/EventLoop.h" +#include "frc/Errors.h" + using namespace frc; +namespace { +struct RunningSetter { + bool& m_running; + explicit RunningSetter(bool& running) noexcept : m_running{running} { + m_running = true; + } + ~RunningSetter() noexcept { m_running = false; } +}; +} // namespace + EventLoop::EventLoop() {} void EventLoop::Bind(wpi::unique_function action) { + if (m_running) { + throw FRC_MakeError(err::Error, + "Cannot bind EventLoop while it is running"); + } m_bindings.emplace_back(std::move(action)); } void EventLoop::Poll() { + RunningSetter runSetter{m_running}; for (wpi::unique_function& action : m_bindings) { action(); } } void EventLoop::Clear() { + if (m_running) { + throw FRC_MakeError(err::Error, + "Cannot clear EventLoop while it is running"); + } m_bindings.clear(); } diff --git a/wpilibc/src/main/native/cpp/internal/DriverStationModeThread.cpp b/wpilibc/src/main/native/cpp/internal/DriverStationModeThread.cpp index 40856580f06..78d580e36c0 100644 --- a/wpilibc/src/main/native/cpp/internal/DriverStationModeThread.cpp +++ b/wpilibc/src/main/native/cpp/internal/DriverStationModeThread.cpp @@ -23,13 +23,14 @@ DriverStationModeThread::~DriverStationModeThread() { } } -void DriverStationModeThread::InAutonomous(bool entering) { - m_userInAutonomous = entering; -} void DriverStationModeThread::InDisabled(bool entering) { m_userInDisabled = entering; } +void DriverStationModeThread::InAutonomous(bool entering) { + m_userInAutonomous = entering; +} + void DriverStationModeThread::InTeleop(bool entering) { m_userInTeleop = entering; } diff --git a/wpilibc/src/main/native/cpp/motorcontrol/MotorController.cpp b/wpilibc/src/main/native/cpp/motorcontrol/MotorController.cpp index 9d20144ca83..2b64da27a23 100644 --- a/wpilibc/src/main/native/cpp/motorcontrol/MotorController.cpp +++ b/wpilibc/src/main/native/cpp/motorcontrol/MotorController.cpp @@ -9,5 +9,6 @@ using namespace frc; void MotorController::SetVoltage(units::volt_t output) { + // NOLINTNEXTLINE(bugprone-integer-division) Set(output / RobotController::GetBatteryVoltage()); } diff --git a/wpilibc/src/main/native/cpp/motorcontrol/MotorControllerGroup.cpp b/wpilibc/src/main/native/cpp/motorcontrol/MotorControllerGroup.cpp index f855d14b0ee..cf57f7c55b2 100644 --- a/wpilibc/src/main/native/cpp/motorcontrol/MotorControllerGroup.cpp +++ b/wpilibc/src/main/native/cpp/motorcontrol/MotorControllerGroup.cpp @@ -12,6 +12,8 @@ using namespace frc; // Can't use a delegated constructor here because of an MSVC bug. // https://developercommunity.visualstudio.com/content/problem/583/compiler-bug-with-delegating-a-constructor.html +WPI_IGNORE_DEPRECATED + MotorControllerGroup::MotorControllerGroup( std::vector>&& motorControllers) : m_motorControllers(std::move(motorControllers)) { @@ -74,3 +76,5 @@ void MotorControllerGroup::InitSendable(wpi::SendableBuilder& builder) { "Value", [=, this] { return Get(); }, [=, this](double value) { Set(value); }); } + +WPI_UNIGNORE_DEPRECATED diff --git a/wpilibc/src/main/native/cpp/motorcontrol/NidecBrushless.cpp b/wpilibc/src/main/native/cpp/motorcontrol/NidecBrushless.cpp index f25aa9180bf..a05b7cc8416 100644 --- a/wpilibc/src/main/native/cpp/motorcontrol/NidecBrushless.cpp +++ b/wpilibc/src/main/native/cpp/motorcontrol/NidecBrushless.cpp @@ -11,6 +11,8 @@ using namespace frc; +WPI_IGNORE_DEPRECATED + NidecBrushless::NidecBrushless(int pwmChannel, int dioChannel) : m_dio(dioChannel), m_pwm(pwmChannel) { wpi::SendableRegistry::AddChild(this, &m_dio); @@ -26,6 +28,8 @@ NidecBrushless::NidecBrushless(int pwmChannel, int dioChannel) wpi::SendableRegistry::AddLW(this, "Nidec Brushless", pwmChannel); } +WPI_UNIGNORE_DEPRECATED + void NidecBrushless::Set(double speed) { if (!m_disabled) { m_speed = speed; diff --git a/wpilibc/src/main/native/cpp/motorcontrol/PWMMotorController.cpp b/wpilibc/src/main/native/cpp/motorcontrol/PWMMotorController.cpp index 3692f757b12..924e4fd3053 100644 --- a/wpilibc/src/main/native/cpp/motorcontrol/PWMMotorController.cpp +++ b/wpilibc/src/main/native/cpp/motorcontrol/PWMMotorController.cpp @@ -8,13 +8,31 @@ #include #include +#include "frc/RobotController.h" + using namespace frc; void PWMMotorController::Set(double speed) { - m_pwm.SetSpeed(m_isInverted ? -speed : speed); + if (m_isInverted) { + speed = -speed; + } + m_pwm.SetSpeed(speed); + + for (auto& follower : m_nonowningFollowers) { + follower->Set(speed); + } + for (auto& follower : m_owningFollowers) { + follower->Set(speed); + } + Feed(); } +void PWMMotorController::SetVoltage(units::volt_t output) { + // NOLINTNEXTLINE(bugprone-integer-division) + Set(output / RobotController::GetBatteryVoltage()); +} + double PWMMotorController::Get() const { return m_pwm.GetSpeed() * (m_isInverted ? -1.0 : 1.0); } @@ -48,11 +66,19 @@ void PWMMotorController::EnableDeadbandElimination(bool eliminateDeadband) { m_pwm.EnableDeadbandElimination(eliminateDeadband); } +void PWMMotorController::AddFollower(PWMMotorController& follower) { + m_nonowningFollowers.emplace_back(&follower); +} + +WPI_IGNORE_DEPRECATED + PWMMotorController::PWMMotorController(std::string_view name, int channel) : m_pwm(channel, false) { wpi::SendableRegistry::AddLW(this, name, channel); } +WPI_UNIGNORE_DEPRECATED + void PWMMotorController::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("Motor Controller"); builder.SetActuator(true); diff --git a/wpilibc/src/main/native/cpp/motorcontrol/PWMSparkFlex.cpp b/wpilibc/src/main/native/cpp/motorcontrol/PWMSparkFlex.cpp new file mode 100644 index 00000000000..945a70e22ec --- /dev/null +++ b/wpilibc/src/main/native/cpp/motorcontrol/PWMSparkFlex.cpp @@ -0,0 +1,20 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/motorcontrol/PWMSparkFlex.h" + +#include + +using namespace frc; + +PWMSparkFlex::PWMSparkFlex(int channel) + : PWMMotorController("PWMSparkFlex", channel) { + m_pwm.SetBounds(2.003_ms, 1.55_ms, 1.50_ms, 1.46_ms, 0.999_ms); + m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X); + m_pwm.SetSpeed(0.0); + m_pwm.SetZeroLatch(); + + HAL_Report(HALUsageReporting::kResourceType_RevSparkFlexPWM, + GetChannel() + 1); +} diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardInstance.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardInstance.cpp index a19cc6a3f06..8c0880a5884 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardInstance.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardInstance.cpp @@ -30,12 +30,17 @@ ShuffleboardInstance::ShuffleboardInstance(nt::NetworkTableInstance ntInstance) m_impl->selectedTabPub = m_impl->rootMetaTable->GetStringTopic("Selected") .Publish(nt::PubSubOptions{.keepDuplicates = true}); - HAL_Report(HALUsageReporting::kResourceType_Shuffleboard, 0); } ShuffleboardInstance::~ShuffleboardInstance() = default; +static bool gReported = false; + frc::ShuffleboardTab& ShuffleboardInstance::GetTab(std::string_view title) { + if (!gReported) { + HAL_Report(HALUsageReporting::kResourceType_Shuffleboard, 0); + gReported = true; + } if (m_impl->tabs.find(title) == m_impl->tabs.end()) { m_impl->tabs.try_emplace(title, std::make_unique(*this, title)); diff --git a/wpilibc/src/main/native/cpp/simulation/DCMotorSim.cpp b/wpilibc/src/main/native/cpp/simulation/DCMotorSim.cpp index c0448ead591..f14564449ab 100644 --- a/wpilibc/src/main/native/cpp/simulation/DCMotorSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/DCMotorSim.cpp @@ -41,11 +41,12 @@ units::ampere_t DCMotorSim::GetCurrentDraw() const { // I = V / R - omega / (Kv * R) // Reductions are greater than 1, so a reduction of 10:1 would mean the motor // is spinning 10x faster than the output. - return m_gearbox.Current(GetAngularVelocity() * m_gearing, + return m_gearbox.Current(units::radians_per_second_t{m_x(1)} * m_gearing, units::volt_t{m_u(0)}) * wpi::sgn(m_u(0)); } void DCMotorSim::SetInputVoltage(units::volt_t voltage) { SetInput(Vectord<1>{voltage.value()}); + ClampInput(frc::RobotController::GetBatteryVoltage().value()); } diff --git a/wpilibc/src/main/native/cpp/simulation/DifferentialDrivetrainSim.cpp b/wpilibc/src/main/native/cpp/simulation/DifferentialDrivetrainSim.cpp index 4d2720f5a6f..d5addb23389 100644 --- a/wpilibc/src/main/native/cpp/simulation/DifferentialDrivetrainSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/DifferentialDrivetrainSim.cpp @@ -92,26 +92,22 @@ Pose2d DifferentialDrivetrainSim::GetPose() const { } units::ampere_t DifferentialDrivetrainSim::GetLeftCurrentDraw() const { - auto loadIleft = - m_motor.Current( - units::radians_per_second_t{m_x(State::kLeftVelocity) * - m_currentGearing / m_wheelRadius.value()}, - units::volt_t{m_u(0)}) * - wpi::sgn(m_u(0)); - - return loadIleft; + return m_motor.Current(units::radians_per_second_t{m_x(State::kLeftVelocity) * + m_currentGearing / + m_wheelRadius.value()}, + units::volt_t{m_u(0)}) * + wpi::sgn(m_u(0)); } units::ampere_t DifferentialDrivetrainSim::GetRightCurrentDraw() const { - auto loadIRight = - m_motor.Current( - units::radians_per_second_t{m_x(State::kRightVelocity) * - m_currentGearing / m_wheelRadius.value()}, - units::volt_t{m_u(1)}) * - wpi::sgn(m_u(1)); - - return loadIRight; + return m_motor.Current( + units::radians_per_second_t{m_x(State::kRightVelocity) * + m_currentGearing / + m_wheelRadius.value()}, + units::volt_t{m_u(1)}) * + wpi::sgn(m_u(1)); } + units::ampere_t DifferentialDrivetrainSim::GetCurrentDraw() const { return GetLeftCurrentDraw() + GetRightCurrentDraw(); } diff --git a/wpilibc/src/main/native/cpp/simulation/DriverStationSim.cpp b/wpilibc/src/main/native/cpp/simulation/DriverStationSim.cpp index 345204a82a4..bdefda9002a 100644 --- a/wpilibc/src/main/native/cpp/simulation/DriverStationSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/DriverStationSim.cpp @@ -235,7 +235,8 @@ void DriverStationSim::SetJoystickType(int stick, int type) { } void DriverStationSim::SetJoystickName(int stick, std::string_view name) { - HALSIM_SetJoystickName(stick, name.data(), name.size()); + auto str = wpi::make_string(name); + HALSIM_SetJoystickName(stick, &str); } void DriverStationSim::SetJoystickAxisType(int stick, int axis, int type) { @@ -243,11 +244,13 @@ void DriverStationSim::SetJoystickAxisType(int stick, int axis, int type) { } void DriverStationSim::SetGameSpecificMessage(std::string_view message) { - HALSIM_SetGameSpecificMessage(message.data(), message.size()); + auto str = wpi::make_string(message); + HALSIM_SetGameSpecificMessage(&str); } void DriverStationSim::SetEventName(std::string_view name) { - HALSIM_SetEventName(name.data(), name.size()); + auto str = wpi::make_string(name); + HALSIM_SetEventName(&str); } void DriverStationSim::SetMatchType(DriverStation::MatchType type) { diff --git a/wpilibc/src/main/native/cpp/simulation/ElevatorSim.cpp b/wpilibc/src/main/native/cpp/simulation/ElevatorSim.cpp index 02817302147..13b3d2e4a3e 100644 --- a/wpilibc/src/main/native/cpp/simulation/ElevatorSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/ElevatorSim.cpp @@ -12,11 +12,11 @@ using namespace frc; using namespace frc::sim; -ElevatorSim::ElevatorSim(const LinearSystem<2, 1, 1>& plant, +ElevatorSim::ElevatorSim(const LinearSystem<2, 1, 2>& plant, const DCMotor& gearbox, units::meter_t minHeight, units::meter_t maxHeight, bool simulateGravity, units::meter_t startingHeight, - const std::array& measurementStdDevs) + const std::array& measurementStdDevs) : LinearSystemSim(plant, measurementStdDevs), m_gearbox(gearbox), m_minHeight(minHeight), @@ -30,7 +30,7 @@ ElevatorSim::ElevatorSim(const DCMotor& gearbox, double gearing, units::meter_t drumRadius, units::meter_t minHeight, units::meter_t maxHeight, bool simulateGravity, units::meter_t startingHeight, - const std::array& measurementStdDevs) + const std::array& measurementStdDevs) : ElevatorSim(LinearSystemId::ElevatorSystem(gearbox, carriageMass, drumRadius, gearing), gearbox, minHeight, maxHeight, simulateGravity, @@ -44,7 +44,7 @@ ElevatorSim::ElevatorSim(decltype(1_V / Velocity_t(1)) kV, const DCMotor& gearbox, units::meter_t minHeight, units::meter_t maxHeight, bool simulateGravity, units::meter_t startingHeight, - const std::array& measurementStdDevs) + const std::array& measurementStdDevs) : ElevatorSim(LinearSystemId::IdentifyPositionSystem(kV, kA), gearbox, minHeight, maxHeight, simulateGravity, startingHeight, measurementStdDevs) {} @@ -98,6 +98,7 @@ units::ampere_t ElevatorSim::GetCurrentDraw() const { void ElevatorSim::SetInputVoltage(units::volt_t voltage) { SetInput(Vectord<1>{voltage.value()}); + ClampInput(frc::RobotController::GetBatteryVoltage().value()); } Vectord<2> ElevatorSim::UpdateX(const Vectord<2>& currentXhat, diff --git a/wpilibc/src/main/native/cpp/simulation/FlywheelSim.cpp b/wpilibc/src/main/native/cpp/simulation/FlywheelSim.cpp index f4b9a81556c..31024c3ae8a 100644 --- a/wpilibc/src/main/native/cpp/simulation/FlywheelSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/FlywheelSim.cpp @@ -36,11 +36,12 @@ units::ampere_t FlywheelSim::GetCurrentDraw() const { // I = V / R - omega / (Kv * R) // Reductions are greater than 1, so a reduction of 10:1 would mean the motor // is spinning 10x faster than the output. - return m_gearbox.Current(GetAngularVelocity() * m_gearing, + return m_gearbox.Current(units::radians_per_second_t{m_x(0)} * m_gearing, units::volt_t{m_u(0)}) * wpi::sgn(m_u(0)); } void FlywheelSim::SetInputVoltage(units::volt_t voltage) { SetInput(Vectord<1>{voltage.value()}); + ClampInput(frc::RobotController::GetBatteryVoltage().value()); } diff --git a/wpilibc/src/main/native/cpp/simulation/PneumaticsBaseSim.cpp b/wpilibc/src/main/native/cpp/simulation/PneumaticsBaseSim.cpp index 476d07ae735..04aef3a6699 100644 --- a/wpilibc/src/main/native/cpp/simulation/PneumaticsBaseSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/PneumaticsBaseSim.cpp @@ -12,11 +12,6 @@ using namespace frc; using namespace frc::sim; -PneumaticsBaseSim::PneumaticsBaseSim(int module) : m_index{module} {} - -PneumaticsBaseSim::PneumaticsBaseSim(const PneumaticsBase& module) - : m_index{module.GetModuleNumber()} {} - std::shared_ptr PneumaticsBaseSim::GetForType( int module, PneumaticsModuleType type) { switch (type) { @@ -31,3 +26,8 @@ std::shared_ptr PneumaticsBaseSim::GetForType( static_cast(module)); } } + +PneumaticsBaseSim::PneumaticsBaseSim(int module) : m_index{module} {} + +PneumaticsBaseSim::PneumaticsBaseSim(const PneumaticsBase& module) + : m_index{module.GetModuleNumber()} {} diff --git a/wpilibc/src/main/native/cpp/simulation/RoboRioSim.cpp b/wpilibc/src/main/native/cpp/simulation/RoboRioSim.cpp index 90d9651d39f..3717128d99e 100644 --- a/wpilibc/src/main/native/cpp/simulation/RoboRioSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/RoboRioSim.cpp @@ -319,23 +319,46 @@ void RoboRioSim::SetTeamNumber(int32_t teamNumber) { } std::string RoboRioSim::GetSerialNumber() { - char serialNum[9]; - size_t len = HALSIM_GetRoboRioSerialNumber(serialNum, sizeof(serialNum)); - return std::string(serialNum, len); + WPI_String serialNum; + HALSIM_GetRoboRioSerialNumber(&serialNum); + std::string serial{wpi::to_string_view(&serialNum)}; + WPI_FreeString(&serialNum); + return serial; } void RoboRioSim::SetSerialNumber(std::string_view serialNumber) { - HALSIM_SetRoboRioSerialNumber(serialNumber.data(), serialNumber.size()); + auto str = wpi::make_string(serialNumber); + HALSIM_SetRoboRioSerialNumber(&str); } std::string RoboRioSim::GetComments() { - char comments[65]; - size_t len = HALSIM_GetRoboRioComments(comments, sizeof(comments)); - return std::string(comments, len); + WPI_String comments; + HALSIM_GetRoboRioComments(&comments); + std::string serial{wpi::to_string_view(&comments)}; + WPI_FreeString(&comments); + return serial; } void RoboRioSim::SetComments(std::string_view comments) { - HALSIM_SetRoboRioComments(comments.data(), comments.size()); + auto str = wpi::make_string(comments); + HALSIM_SetRoboRioComments(&str); +} + +std::unique_ptr RoboRioSim::RegisterRadioLEDStateCallback( + NotifyCallback callback, bool initialNotify) { + auto store = std::make_unique( + -1, callback, &HALSIM_CancelRoboRioRadioLEDStateCallback); + store->SetUid(HALSIM_RegisterRoboRioRadioLEDStateCallback( + &CallbackStoreThunk, store.get(), initialNotify)); + return store; +} + +RadioLEDState RoboRioSim::GetRadioLEDState() { + return static_cast(HALSIM_GetRoboRioRadioLEDState()); +} + +void RoboRioSim::SetRadioLEDState(RadioLEDState state) { + HALSIM_SetRoboRioRadioLEDState(static_cast(state)); } void RoboRioSim::ResetData() { diff --git a/wpilibc/src/main/native/cpp/simulation/SingleJointedArmSim.cpp b/wpilibc/src/main/native/cpp/simulation/SingleJointedArmSim.cpp index d9969ca15a5..945decc3201 100644 --- a/wpilibc/src/main/native/cpp/simulation/SingleJointedArmSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/SingleJointedArmSim.cpp @@ -16,12 +16,12 @@ using namespace frc; using namespace frc::sim; SingleJointedArmSim::SingleJointedArmSim( - const LinearSystem<2, 1, 1>& system, const DCMotor& gearbox, double gearing, + const LinearSystem<2, 1, 2>& system, const DCMotor& gearbox, double gearing, units::meter_t armLength, units::radian_t minAngle, units::radian_t maxAngle, bool simulateGravity, units::radian_t startingAngle, - const std::array& measurementStdDevs) - : LinearSystemSim<2, 1, 1>(system, measurementStdDevs), + const std::array& measurementStdDevs) + : LinearSystemSim<2, 1, 2>(system, measurementStdDevs), m_armLen(armLength), m_minAngle(minAngle), m_maxAngle(maxAngle), @@ -36,7 +36,7 @@ SingleJointedArmSim::SingleJointedArmSim( units::meter_t armLength, units::radian_t minAngle, units::radian_t maxAngle, bool simulateGravity, units::radian_t startingAngle, - const std::array& measurementStdDevs) + const std::array& measurementStdDevs) : SingleJointedArmSim( LinearSystemId::SingleJointedArmSystem(gearbox, moi, gearing), gearbox, gearing, armLength, minAngle, maxAngle, simulateGravity, @@ -81,6 +81,7 @@ units::ampere_t SingleJointedArmSim::GetCurrentDraw() const { void SingleJointedArmSim::SetInputVoltage(units::volt_t voltage) { SetInput(Vectord<1>{voltage.value()}); + ClampInput(frc::RobotController::GetBatteryVoltage().value()); } Vectord<2> SingleJointedArmSim::UpdateX(const Vectord<2>& currentXhat, diff --git a/wpilibc/src/main/native/cpp/simulation/UltrasonicSim.cpp b/wpilibc/src/main/native/cpp/simulation/UltrasonicSim.cpp index 30a565039c0..1016c4bccbc 100644 --- a/wpilibc/src/main/native/cpp/simulation/UltrasonicSim.cpp +++ b/wpilibc/src/main/native/cpp/simulation/UltrasonicSim.cpp @@ -18,8 +18,8 @@ UltrasonicSim::UltrasonicSim(int ping, int echo) { m_simRange = deviceSim.GetDouble("Range (in)"); } -void UltrasonicSim::SetRangeValid(bool isValid) { - m_simRangeValid.Set(isValid); +void UltrasonicSim::SetRangeValid(bool valid) { + m_simRangeValid.Set(valid); } void UltrasonicSim::SetRange(units::inch_t range) { diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp index e6991d44faa..d57473fbe04 100644 --- a/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp +++ b/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp @@ -19,8 +19,6 @@ using namespace frc; namespace { struct Instance { - Instance() { HAL_Report(HALUsageReporting::kResourceType_SmartDashboard, 0); } - detail::ListenerExecutor listenerExecutor; std::shared_ptr table = nt::NetworkTableInstance::GetDefault().GetTable("SmartDashboard"); @@ -46,6 +44,8 @@ void ResetSmartDashboardInstance() { } // namespace frc::impl #endif +static bool gReported = false; + void SmartDashboard::init() { GetInstance(); } @@ -59,18 +59,23 @@ std::vector SmartDashboard::GetKeys(int types) { } void SmartDashboard::SetPersistent(std::string_view key) { - GetInstance().table->GetEntry(key).SetPersistent(); + GetEntry(key).SetPersistent(); } void SmartDashboard::ClearPersistent(std::string_view key) { - GetInstance().table->GetEntry(key).ClearPersistent(); + GetEntry(key).ClearPersistent(); } bool SmartDashboard::IsPersistent(std::string_view key) { - return GetInstance().table->GetEntry(key).IsPersistent(); + return GetEntry(key).IsPersistent(); } nt::NetworkTableEntry SmartDashboard::GetEntry(std::string_view key) { + if (!gReported) { + HAL_Report(HALUsageReporting::kResourceType_SmartDashboard, + HALUsageReporting::kSmartDashboard_Instance); + gReported = true; + } return GetInstance().table->GetEntry(key); } @@ -78,6 +83,11 @@ void SmartDashboard::PutData(std::string_view key, wpi::Sendable* data) { if (!data) { throw FRC_MakeError(err::NullParameter, "value"); } + if (!gReported) { + HAL_Report(HALUsageReporting::kResourceType_SmartDashboard, + HALUsageReporting::kSmartDashboard_Instance); + gReported = true; + } auto& inst = GetInstance(); std::scoped_lock lock(inst.tablesToDataMutex); auto& uid = inst.tablesToData[key]; @@ -120,7 +130,7 @@ bool SmartDashboard::PutBoolean(std::string_view keyName, bool value) { bool SmartDashboard::SetDefaultBoolean(std::string_view key, bool defaultValue) { - return GetInstance().table->GetEntry(key).SetDefaultBoolean(defaultValue); + return GetEntry(key).SetDefaultBoolean(defaultValue); } bool SmartDashboard::GetBoolean(std::string_view keyName, bool defaultValue) { @@ -133,7 +143,7 @@ bool SmartDashboard::PutNumber(std::string_view keyName, double value) { bool SmartDashboard::SetDefaultNumber(std::string_view key, double defaultValue) { - return GetInstance().table->GetEntry(key).SetDefaultDouble(defaultValue); + return GetEntry(key).SetDefaultDouble(defaultValue); } double SmartDashboard::GetNumber(std::string_view keyName, @@ -148,7 +158,7 @@ bool SmartDashboard::PutString(std::string_view keyName, bool SmartDashboard::SetDefaultString(std::string_view key, std::string_view defaultValue) { - return GetInstance().table->GetEntry(key).SetDefaultString(defaultValue); + return GetEntry(key).SetDefaultString(defaultValue); } std::string SmartDashboard::GetString(std::string_view keyName, @@ -158,63 +168,62 @@ std::string SmartDashboard::GetString(std::string_view keyName, bool SmartDashboard::PutBooleanArray(std::string_view key, std::span value) { - return GetInstance().table->GetEntry(key).SetBooleanArray(value); + return GetEntry(key).SetBooleanArray(value); } bool SmartDashboard::SetDefaultBooleanArray(std::string_view key, std::span defaultValue) { - return GetInstance().table->GetEntry(key).SetDefaultBooleanArray( - defaultValue); + return GetEntry(key).SetDefaultBooleanArray(defaultValue); } std::vector SmartDashboard::GetBooleanArray( std::string_view key, std::span defaultValue) { - return GetInstance().table->GetEntry(key).GetBooleanArray(defaultValue); + return GetEntry(key).GetBooleanArray(defaultValue); } bool SmartDashboard::PutNumberArray(std::string_view key, std::span value) { - return GetInstance().table->GetEntry(key).SetDoubleArray(value); + return GetEntry(key).SetDoubleArray(value); } bool SmartDashboard::SetDefaultNumberArray( std::string_view key, std::span defaultValue) { - return GetInstance().table->GetEntry(key).SetDefaultDoubleArray(defaultValue); + return GetEntry(key).SetDefaultDoubleArray(defaultValue); } std::vector SmartDashboard::GetNumberArray( std::string_view key, std::span defaultValue) { - return GetInstance().table->GetEntry(key).GetDoubleArray(defaultValue); + return GetEntry(key).GetDoubleArray(defaultValue); } bool SmartDashboard::PutStringArray(std::string_view key, std::span value) { - return GetInstance().table->GetEntry(key).SetStringArray(value); + return GetEntry(key).SetStringArray(value); } bool SmartDashboard::SetDefaultStringArray( std::string_view key, std::span defaultValue) { - return GetInstance().table->GetEntry(key).SetDefaultStringArray(defaultValue); + return GetEntry(key).SetDefaultStringArray(defaultValue); } std::vector SmartDashboard::GetStringArray( std::string_view key, std::span defaultValue) { - return GetInstance().table->GetEntry(key).GetStringArray(defaultValue); + return GetEntry(key).GetStringArray(defaultValue); } bool SmartDashboard::PutRaw(std::string_view key, std::span value) { - return GetInstance().table->GetEntry(key).SetRaw(value); + return GetEntry(key).SetRaw(value); } bool SmartDashboard::SetDefaultRaw(std::string_view key, std::span defaultValue) { - return GetInstance().table->GetEntry(key).SetDefaultRaw(defaultValue); + return GetEntry(key).SetDefaultRaw(defaultValue); } std::vector SmartDashboard::GetRaw( std::string_view key, std::span defaultValue) { - return GetInstance().table->GetEntry(key).GetRaw(defaultValue); + return GetEntry(key).GetRaw(defaultValue); } bool SmartDashboard::PutValue(std::string_view keyName, @@ -224,7 +233,7 @@ bool SmartDashboard::PutValue(std::string_view keyName, bool SmartDashboard::SetDefaultValue(std::string_view key, const nt::Value& defaultValue) { - return GetInstance().table->GetEntry(key).SetDefaultValue(defaultValue); + return GetEntry(key).SetDefaultValue(defaultValue); } nt::Value SmartDashboard::GetValue(std::string_view keyName) { diff --git a/wpilibc/src/main/native/cpp/sysid/SysIdRoutineLog.cpp b/wpilibc/src/main/native/cpp/sysid/SysIdRoutineLog.cpp new file mode 100644 index 00000000000..1ee35b8863b --- /dev/null +++ b/wpilibc/src/main/native/cpp/sysid/SysIdRoutineLog.cpp @@ -0,0 +1,67 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/sysid/SysIdRoutineLog.h" + +#include + +#include "frc/DataLogManager.h" + +using namespace frc::sysid; + +SysIdRoutineLog::SysIdRoutineLog(std::string_view logName) + : m_logName(logName) {} + +SysIdRoutineLog::MotorLog::MotorLog(std::string_view motorName, + std::string_view logName, + LogEntries* logEntries) + : m_motorName(motorName), m_logName(logName), m_logEntries(logEntries) { + (*logEntries)[motorName] = MotorEntries(); +} + +SysIdRoutineLog::MotorLog& SysIdRoutineLog::MotorLog::value( + std::string_view name, double value, std::string_view unit) { + auto& motorEntries = (*m_logEntries)[m_motorName]; + + if (!motorEntries.contains(name)) { + wpi::log::DataLog& log = frc::DataLogManager::GetLog(); + + motorEntries[name] = wpi::log::DoubleLogEntry( + log, fmt::format("{}-{}-{}", name, m_motorName, m_logName), unit); + } + + motorEntries[name].Append(value); + return *this; +} + +SysIdRoutineLog::MotorLog SysIdRoutineLog::Motor(std::string_view motorName) { + return MotorLog{motorName, m_logName, &m_logEntries}; +} + +void SysIdRoutineLog::RecordState(State state) { + if (!m_stateInitialized) { + m_state = + wpi::log::StringLogEntry{frc::DataLogManager::GetLog(), + fmt::format("sysid-test-state-{}", m_logName)}; + m_stateInitialized = true; + } + m_state.Append(StateEnumToString(state)); +} + +std::string SysIdRoutineLog::StateEnumToString(State state) { + switch (state) { + case State::kQuasistaticForward: + return "quasistatic-forward"; + case State::kQuasistaticReverse: + return "quasistatic-reverse"; + case State::kDynamicForward: + return "dynamic-forward"; + case State::kDynamicReverse: + return "dynamic-reverse"; + case State::kNone: + return "none"; + default: + return "none"; + } +} diff --git a/wpilibc/src/main/native/cpp/util/Color.cpp b/wpilibc/src/main/native/cpp/util/Color.cpp deleted file mode 100644 index e3adaf2db3f..00000000000 --- a/wpilibc/src/main/native/cpp/util/Color.cpp +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "frc/util/Color.h" - -#include - -using namespace frc; - -std::string Color::HexString() const { - return fmt::format("#{:02X}{:02X}{:02X}", static_cast(255.0 * red), - static_cast(255.0 * green), - static_cast(255.0 * blue)); -} diff --git a/wpilibc/src/main/native/cpp/util/Color8Bit.cpp b/wpilibc/src/main/native/cpp/util/Color8Bit.cpp deleted file mode 100644 index af200a294b5..00000000000 --- a/wpilibc/src/main/native/cpp/util/Color8Bit.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "frc/util/Color8Bit.h" - -#include - -using namespace frc; - -std::string Color8Bit::HexString() const { - return fmt::format("#{:02X}{:02X}{:02X}", red, green, blue); -} diff --git a/wpilibc/src/main/native/cppcs/RobotBase.cpp b/wpilibc/src/main/native/cppcs/RobotBase.cpp index c3616b924b3..c4052ac6e05 100644 --- a/wpilibc/src/main/native/cppcs/RobotBase.cpp +++ b/wpilibc/src/main/native/cppcs/RobotBase.cpp @@ -11,10 +11,10 @@ #include #include -#include #include #include #include +#include #include #include @@ -244,7 +244,7 @@ RobotBase::RobotBase() { std::this_thread::sleep_for(10ms); ++count; if (count > 100) { - fmt::print(stderr, "timed out while waiting for NT server to start\n"); + wpi::print(stderr, "timed out while waiting for NT server to start\n"); break; } } diff --git a/wpilibc/src/main/native/include/frc/ADIS16448_IMU.h b/wpilibc/src/main/native/include/frc/ADIS16448_IMU.h index 3f4a1c2ebda..0b16782b8ab 100644 --- a/wpilibc/src/main/native/include/frc/ADIS16448_IMU.h +++ b/wpilibc/src/main/native/include/frc/ADIS16448_IMU.h @@ -16,7 +16,6 @@ #include #include -#include #include #include @@ -33,7 +32,6 @@ #include "frc/DigitalInput.h" #include "frc/DigitalOutput.h" -#include "frc/DigitalSource.h" #include "frc/SPI.h" namespace frc { @@ -56,23 +54,47 @@ namespace frc { class ADIS16448_IMU : public wpi::Sendable, public wpi::SendableHelper { public: - /* ADIS16448 Calibration Time Enum Class */ + /** + * ADIS16448 calibration times. + */ enum class CalibrationTime { + /// 32 ms calibration time. _32ms = 0, + /// 64 ms calibration time. _64ms = 1, + /// 128 ms calibration time. _128ms = 2, + /// 256 ms calibration time. _256ms = 3, + /// 512 ms calibration time. _512ms = 4, + /// 1 s calibration time. _1s = 5, + /// 2 s calibration time. _2s = 6, + /// 4 s calibration time. _4s = 7, + /// 8 s calibration time. _8s = 8, + /// 16 s calibration time. _16s = 9, + /// 32 s calibration time. _32s = 10, + /// 64 s calibration time. _64s = 11 }; - enum IMUAxis { kX, kY, kZ }; + /** + * IMU axes. + */ + enum IMUAxis { + /// The IMU's X axis. + kX, + /// The IMU's Y axis. + kY, + /// The IMU's Z axis. + kZ + }; /** * IMU constructor on onboard MXP CS0, Z-up orientation, and complementary @@ -93,8 +115,8 @@ class ADIS16448_IMU : public wpi::Sendable, ~ADIS16448_IMU() override; - ADIS16448_IMU(ADIS16448_IMU&&) = default; - ADIS16448_IMU& operator=(ADIS16448_IMU&&) = default; + ADIS16448_IMU(ADIS16448_IMU&&); + ADIS16448_IMU& operator=(ADIS16448_IMU&&); /** * Initialize the IMU. @@ -183,31 +205,71 @@ class ADIS16448_IMU : public wpi::Sendable, */ units::meters_per_second_squared_t GetAccelZ() const; + /** + * Returns the complementary angle around the X axis computed from + * accelerometer and gyro rate measurements. + */ units::degree_t GetXComplementaryAngle() const; + /** + * Returns the complementary angle around the Y axis computed from + * accelerometer and gyro rate measurements. + */ units::degree_t GetYComplementaryAngle() const; + /** + * Returns the X-axis filtered acceleration angle. + */ units::degree_t GetXFilteredAccelAngle() const; + /** + * Returns the Y-axis filtered acceleration angle. + */ units::degree_t GetYFilteredAccelAngle() const; + /** + * Returns the magnetic field strength in the X axis. + */ units::tesla_t GetMagneticFieldX() const; + /** + * Returns the magnetic field strength in the Y axis. + */ units::tesla_t GetMagneticFieldY() const; + /** + * Returns the magnetic field strength in the Z axis. + */ units::tesla_t GetMagneticFieldZ() const; + /** + * Returns the barometric pressure. + */ units::pounds_per_square_inch_t GetBarometricPressure() const; + /** + * Returns the temperature. + */ units::celsius_t GetTemperature() const; IMUAxis GetYawAxis() const; int SetYawAxis(IMUAxis yaw_axis); + /** + * Checks the connection status of the IMU. + * + * @return True if the IMU is connected, false otherwise. + */ bool IsConnected() const; - int ConfigDecRate(uint16_t DecimationRate); + /** + * Configures the decimation rate of the IMU. + * + * @param decimationRate The new decimation value. + * @return 0 if success, 1 if no change, 2 if error. + */ + int ConfigDecRate(uint16_t decimationRate); /** * Get the SPI port number. @@ -288,8 +350,8 @@ class ADIS16448_IMU : public wpi::Sendable, }; /** @brief Internal Resources **/ - DigitalInput* m_reset_in; - DigitalOutput* m_status_led; + DigitalInput* m_reset_in = nullptr; + DigitalOutput* m_status_led = nullptr; bool SwitchToStandardSPI(); @@ -353,10 +415,10 @@ class ADIS16448_IMU : public wpi::Sendable, double CompFilterProcess(double compAngle, double accelAngle, double omega); // State and resource variables - volatile bool m_thread_active = false; - volatile bool m_first_run = true; - volatile bool m_thread_idle = false; - volatile bool m_start_up_mode = true; + std::atomic m_thread_active = false; + std::atomic m_first_run = true; + std::atomic m_thread_idle = false; + std::atomic m_start_up_mode = true; bool m_auto_configured = false; SPI::Port m_spi_port; diff --git a/wpilibc/src/main/native/include/frc/ADIS16470_IMU.h b/wpilibc/src/main/native/include/frc/ADIS16470_IMU.h index e3b521c2b33..f4f4145e177 100644 --- a/wpilibc/src/main/native/include/frc/ADIS16470_IMU.h +++ b/wpilibc/src/main/native/include/frc/ADIS16470_IMU.h @@ -16,7 +16,6 @@ #include #include -#include #include #include @@ -30,7 +29,6 @@ #include "frc/DigitalInput.h" #include "frc/DigitalOutput.h" -#include "frc/DigitalSource.h" #include "frc/SPI.h" namespace frc { @@ -53,55 +51,109 @@ namespace frc { class ADIS16470_IMU : public wpi::Sendable, public wpi::SendableHelper { public: - /* ADIS16470 Calibration Time Enum Class */ + /** + * ADIS16470 calibration times. + */ enum class CalibrationTime { + /// 32 ms calibration time. _32ms = 0, + /// 64 ms calibration time. _64ms = 1, + /// 128 ms calibration time. _128ms = 2, + /// 256 ms calibration time. _256ms = 3, + /// 512 ms calibration time. _512ms = 4, + /// 1 s calibration time. _1s = 5, + /// 2 s calibration time. _2s = 6, + /// 4 s calibration time. _4s = 7, + /// 8 s calibration time. _8s = 8, + /// 16 s calibration time. _16s = 9, + /// 32 s calibration time. _32s = 10, + /// 64 s calibration time. _64s = 11 }; - enum IMUAxis { kX, kY, kZ }; + /** + * IMU axes. + * + * kX, kY, and kZ refer to the IMU's X, Y, and Z axes respectively. kYaw, + * kPitch, and kRoll are configured by the user to refer to an X, Y, or Z + * axis. + */ + enum IMUAxis { + /// The IMU's X axis. + kX, + /// The IMU's Y axis. + kY, + /// The IMU's Z axis. + kZ, + /// The user-configured yaw axis. + kYaw, + /// The user-configured pitch axis. + kPitch, + /// The user-configured roll axis. + kRoll + }; /** - * @brief Default constructor. Uses CS0 on the 10-pin SPI port, the yaw axis - * is set to the IMU Z axis, and calibration time is defaulted to 4 seconds. + * Creates a new ADIS16740 IMU object. + * + * The default setup is the onboard SPI port with a calibration time of 1 + * second. Yaw, pitch, and roll are kZ, kX, and kY respectively. */ ADIS16470_IMU(); /** - * @brief Customizable constructor. Allows the SPI port and CS to be - * customized, the yaw axis used for GetAngle() is adjustable, and initial - * calibration time can be modified. + * Creates a new ADIS16740 IMU object. * - * @param yaw_axis Selects the "default" axis to use for GetAngle() and - * GetRate() + * The default setup is the onboard SPI port with a calibration time of 1 + * second. * - * @param port The SPI port and CS where the IMU is connected. + * Input axes limited to kX, kY and kZ. Specifying kYaw, kPitch,or kRoll + * will result in an error. * - * @param cal_time The calibration time that should be used on start-up. + * @param yaw_axis The axis that measures the yaw + * @param pitch_axis The axis that measures the pitch + * @param roll_axis The axis that measures the roll */ - explicit ADIS16470_IMU(IMUAxis yaw_axis, SPI::Port port, - CalibrationTime cal_time); + ADIS16470_IMU(IMUAxis yaw_axis, IMUAxis pitch_axis, IMUAxis roll_axis); /** - * @brief Destructor. Kills the acquisition loop and closes the SPI - * peripheral. + * Creates a new ADIS16740 IMU object. + * + * Input axes limited to kX, kY and kZ. Specifying kYaw, kPitch, or + * kRoll will result in an error. + * + * @param yaw_axis The axis that measures the yaw + * @param pitch_axis The axis that measures the pitch + * @param roll_axis The axis that measures the roll + * @param port The SPI Port the gyro is plugged into + * @param cal_time Calibration time */ + explicit ADIS16470_IMU(IMUAxis yaw_axis, IMUAxis pitch_axis, + IMUAxis roll_axis, frc::SPI::Port port, + CalibrationTime cal_time); + ~ADIS16470_IMU() override; - ADIS16470_IMU(ADIS16470_IMU&&) = default; - ADIS16470_IMU& operator=(ADIS16470_IMU&&) = default; + ADIS16470_IMU(ADIS16470_IMU&& other); + ADIS16470_IMU& operator=(ADIS16470_IMU&& other); - int ConfigDecRate(uint16_t reg); + /** + * Configures the decimation rate of the IMU. + * + * @param decimationRate The new decimation value. + * @return 0 if success, 1 if no change, 2 if error. + */ + int ConfigDecRate(uint16_t decimationRate); /** * @brief Switches the active SPI port to standard SPI mode, writes the @@ -116,22 +168,68 @@ class ADIS16470_IMU : public wpi::Sendable, int ConfigCalTime(CalibrationTime new_cal_time); /** - * @brief Resets (zeros) the xgyro, ygyro, and zgyro angle integrations. + * Reset the gyro. * * Resets the gyro accumulations to a heading of zero. This can be used if - * the "zero" orientation of the sensor needs to be changed in runtime. + * there is significant drift in the gyro and it needs to be recalibrated + * after running. */ void Reset(); /** - * Returns the yaw axis angle in degrees (CCW positive). + * Allow the designated gyro angle to be set to a given value. This may happen + * with unread values in the buffer, it is suggested that the IMU is not + * moving when this method is run. + * + * @param axis IMUAxis that will be changed + * @param angle The new angle (CCW positive) + */ + void SetGyroAngle(IMUAxis axis, units::degree_t angle); + + /** + * Allow the gyro angle X to be set to a given value. This may happen with + * unread values in the buffer, it is suggested that the IMU is not moving + * when this method is run. + * + * @param angle The new angle (CCW positive) + */ + void SetGyroAngleX(units::degree_t angle); + + /** + * Allow the gyro angle Y to be set to a given value. This may happen with + * unread values in the buffer, it is suggested that the IMU is not moving + * when this method is run. + * + * @param angle The new angle (CCW positive) */ - units::degree_t GetAngle() const; + void SetGyroAngleY(units::degree_t angle); /** - * Returns the yaw axis angular rate in degrees per second (CCW positive). + * Allow the gyro angle Z to be set to a given value. This may happen with + * unread values in the buffer, it is suggested that the IMU is not moving + * when this method is run. + * + * @param angle The new angle (CCW positive) */ - units::degrees_per_second_t GetRate() const; + void SetGyroAngleZ(units::degree_t angle); + + /** + * Returns the axis angle (CCW positive). + * + * @param axis The IMUAxis whose angle to return. Defaults to user configured + * Yaw. + * @return The axis angle (CCW positive). + */ + units::degree_t GetAngle(IMUAxis axis = IMUAxis::kYaw) const; + + /** + * Returns the axis angular rate (CCW positive). + * + * @param axis The IMUAxis whose rate to return. Defaults to user configured + * Yaw. + * @return Axis angular rate (CCW positive). + */ + units::degrees_per_second_t GetRate(IMUAxis axis = IMUAxis::kYaw) const; /** * Returns the acceleration in the X axis. @@ -148,25 +246,60 @@ class ADIS16470_IMU : public wpi::Sendable, */ units::meters_per_second_squared_t GetAccelZ() const; + /** + * Returns the X-axis complementary angle. + */ units::degree_t GetXComplementaryAngle() const; + /** + * Returns the Y-axis complementary angle. + */ units::degree_t GetYComplementaryAngle() const; + /** + * Returns the X-axis filtered acceleration angle. + */ units::degree_t GetXFilteredAccelAngle() const; + /** + * Returns the Y-axis filtered acceleration angle. + */ units::degree_t GetYFilteredAccelAngle() const; + /** + * Returns which axis, kX, kY, or kZ, is set to the yaw axis. + * + * @return IMUAxis Yaw Axis + */ IMUAxis GetYawAxis() const; - int SetYawAxis(IMUAxis yaw_axis); + /** + * Returns which axis, kX, kY, or kZ, is set to the pitch axis. + * + * @return IMUAxis Pitch Axis + */ + IMUAxis GetPitchAxis() const; + /** + * Returns which axis, kX, kY, or kZ, is set to the roll axis. + * + * @return IMUAxis Roll Axis + */ + IMUAxis GetRollAxis() const; + + /** + * Checks the connection status of the IMU. + * + * @return True if the IMU is connected, false otherwise. + */ bool IsConnected() const; - // IMU yaw axis IMUAxis m_yaw_axis; + IMUAxis m_pitch_axis; + IMUAxis m_roll_axis; /** - * Get the SPI port number. + * Gets the SPI port number. * * @return The SPI port number. */ @@ -175,7 +308,7 @@ class ADIS16470_IMU : public wpi::Sendable, void InitSendable(wpi::SendableBuilder& builder) override; private: - /* ADIS16470 Register Map Declaration */ + // Register Map Declaration static constexpr uint8_t FLASH_CNT = 0x00; // Flash memory write count static constexpr uint8_t DIAG_STAT = 0x02; // Diagnostic and operational status @@ -276,32 +409,22 @@ class ADIS16470_IMU : public wpi::Sendable, static constexpr uint8_t FLSHCNT_HIGH = 0x7E; // Flash update count, upper word - /* ADIS16470 Auto SPI Data Packets */ - static constexpr uint8_t m_autospi_x_packet[16] = { - X_DELTANG_OUT, FLASH_CNT, X_DELTANG_LOW, FLASH_CNT, X_GYRO_OUT, FLASH_CNT, - Y_GYRO_OUT, FLASH_CNT, Z_GYRO_OUT, FLASH_CNT, X_ACCL_OUT, FLASH_CNT, - Y_ACCL_OUT, FLASH_CNT, Z_ACCL_OUT, FLASH_CNT}; - - static constexpr uint8_t m_autospi_y_packet[16] = { - Y_DELTANG_OUT, FLASH_CNT, Y_DELTANG_LOW, FLASH_CNT, X_GYRO_OUT, FLASH_CNT, - Y_GYRO_OUT, FLASH_CNT, Z_GYRO_OUT, FLASH_CNT, X_ACCL_OUT, FLASH_CNT, - Y_ACCL_OUT, FLASH_CNT, Z_ACCL_OUT, FLASH_CNT}; - - static constexpr uint8_t m_autospi_z_packet[16] = { - Z_DELTANG_OUT, FLASH_CNT, Z_DELTANG_LOW, FLASH_CNT, X_GYRO_OUT, FLASH_CNT, - Y_GYRO_OUT, FLASH_CNT, Z_GYRO_OUT, FLASH_CNT, X_ACCL_OUT, FLASH_CNT, - Y_ACCL_OUT, FLASH_CNT, Z_ACCL_OUT, FLASH_CNT}; - - /* ADIS16470 Constants */ - static constexpr double delta_angle_sf = - 2160.0 / 2147483648.0; /* 2160 / (2^31) */ + // Auto SPI Data Packet to read all thrre gyro axes. + static constexpr uint8_t m_autospi_allangle_packet[24] = { + X_DELTANG_OUT, FLASH_CNT, X_DELTANG_LOW, FLASH_CNT, Y_DELTANG_OUT, + FLASH_CNT, Y_DELTANG_LOW, FLASH_CNT, Z_DELTANG_OUT, FLASH_CNT, + Z_DELTANG_LOW, FLASH_CNT, X_GYRO_OUT, FLASH_CNT, Y_GYRO_OUT, + FLASH_CNT, Z_GYRO_OUT, FLASH_CNT, X_ACCL_OUT, FLASH_CNT, + Y_ACCL_OUT, FLASH_CNT, Z_ACCL_OUT, FLASH_CNT}; + + static constexpr double delta_angle_sf = 2160.0 / 2147483648.0; static constexpr double rad_to_deg = 57.2957795; static constexpr double deg_to_rad = 0.0174532; static constexpr double grav = 9.81; /** @brief Resources **/ - DigitalInput* m_reset_in; - DigitalOutput* m_status_led; + DigitalInput* m_reset_in = nullptr; + DigitalOutput* m_status_led = nullptr; /** * @brief Switches to standard SPI operation. Primarily used when exiting auto @@ -350,8 +473,10 @@ class ADIS16470_IMU : public wpi::Sendable, void Close(); - // Integrated gyro value - double m_integ_angle = 0.0; + // Integrated gyro angles. + double m_integ_angle_x = 0.0; + double m_integ_angle_y = 0.0; + double m_integ_angle_z = 0.0; // Instant raw outputs double m_gyro_rate_x = 0.0; @@ -376,9 +501,9 @@ class ADIS16470_IMU : public wpi::Sendable, double CompFilterProcess(double compAngle, double accelAngle, double omega); // State and resource variables - volatile bool m_thread_active = false; - volatile bool m_first_run = true; - volatile bool m_thread_idle = false; + std::atomic m_thread_active = false; + std::atomic m_first_run = true; + std::atomic m_thread_idle = false; bool m_auto_configured = false; SPI::Port m_spi_port; uint16_t m_calibration_time = 0; diff --git a/wpilibc/src/main/native/include/frc/ADXL345_I2C.h b/wpilibc/src/main/native/include/frc/ADXL345_I2C.h index 2fe0da4a350..4c6d9dffe2e 100644 --- a/wpilibc/src/main/native/include/frc/ADXL345_I2C.h +++ b/wpilibc/src/main/native/include/frc/ADXL345_I2C.h @@ -26,16 +26,47 @@ namespace frc { class ADXL345_I2C : public nt::NTSendable, public wpi::SendableHelper { public: - enum Range { kRange_2G = 0, kRange_4G = 1, kRange_8G = 2, kRange_16G = 3 }; + /** + * Accelerometer range. + */ + enum Range { + /// 2 Gs max. + kRange_2G = 0, + /// 4 Gs max. + kRange_4G = 1, + /// 8 Gs max. + kRange_8G = 2, + /// 16 Gs max. + kRange_16G = 3 + }; - enum Axes { kAxis_X = 0x00, kAxis_Y = 0x02, kAxis_Z = 0x04 }; + /** + * Accelerometer axes. + */ + enum Axes { + /// X axis. + kAxis_X = 0x00, + /// Y axis. + kAxis_Y = 0x02, + /// Z axis. + kAxis_Z = 0x04 + }; + /** + * Container type for accelerations from all axes. + */ struct AllAxes { - double XAxis; - double YAxis; - double ZAxis; + /// Acceleration along the X axis in g-forces. + double XAxis = 0.0; + /// Acceleration along the Y axis in g-forces. + double YAxis = 0.0; + /// Acceleration along the Z axis in g-forces. + double ZAxis = 0.0; }; + /// Default I2C device address. + static constexpr int kAddress = 0x1D; + /** * Constructs the ADXL345 Accelerometer over I2C. * @@ -100,7 +131,7 @@ class ADXL345_I2C : public nt::NTSendable, void InitSendable(nt::NTSendableBuilder& builder) override; - protected: + private: I2C m_i2c; hal::SimDevice m_simDevice; @@ -109,7 +140,6 @@ class ADXL345_I2C : public nt::NTSendable, hal::SimDouble m_simY; hal::SimDouble m_simZ; - static constexpr int kAddress = 0x1D; static constexpr int kPowerCtlRegister = 0x2D; static constexpr int kDataFormatRegister = 0x31; static constexpr int kDataRegister = 0x32; diff --git a/wpilibc/src/main/native/include/frc/ADXL345_SPI.h b/wpilibc/src/main/native/include/frc/ADXL345_SPI.h index 3f2d8aebab4..305be9280a2 100644 --- a/wpilibc/src/main/native/include/frc/ADXL345_SPI.h +++ b/wpilibc/src/main/native/include/frc/ADXL345_SPI.h @@ -21,14 +21,42 @@ namespace frc { class ADXL345_SPI : public nt::NTSendable, public wpi::SendableHelper { public: - enum Range { kRange_2G = 0, kRange_4G = 1, kRange_8G = 2, kRange_16G = 3 }; + /** + * Accelerometer range. + */ + enum Range { + /// 2 Gs max. + kRange_2G = 0, + /// 4 Gs max. + kRange_4G = 1, + /// 8 Gs max. + kRange_8G = 2, + /// 16 Gs max. + kRange_16G = 3 + }; - enum Axes { kAxis_X = 0x00, kAxis_Y = 0x02, kAxis_Z = 0x04 }; + /** + * Accelerometer axes. + */ + enum Axes { + /// X axis. + kAxis_X = 0x00, + /// Y axis. + kAxis_Y = 0x02, + /// Z axis. + kAxis_Z = 0x04 + }; + /** + * Container type for accelerations from all axes. + */ struct AllAxes { - double XAxis; - double YAxis; - double ZAxis; + /// Acceleration along the X axis in g-forces. + double XAxis = 0.0; + /// Acceleration along the Y axis in g-forces. + double YAxis = 0.0; + /// Acceleration along the Z axis in g-forces. + double ZAxis = 0.0; }; /** @@ -93,7 +121,7 @@ class ADXL345_SPI : public nt::NTSendable, void InitSendable(nt::NTSendableBuilder& builder) override; - protected: + private: SPI m_spi; hal::SimDevice m_simDevice; diff --git a/wpilibc/src/main/native/include/frc/ADXL362.h b/wpilibc/src/main/native/include/frc/ADXL362.h index ddf6ebed1a2..0332b3103fe 100644 --- a/wpilibc/src/main/native/include/frc/ADXL362.h +++ b/wpilibc/src/main/native/include/frc/ADXL362.h @@ -19,13 +19,40 @@ namespace frc { */ class ADXL362 : public nt::NTSendable, public wpi::SendableHelper { public: - enum Range { kRange_2G = 0, kRange_4G = 1, kRange_8G = 2 }; + /** + * Accelerometer range. + */ + enum Range { + /// 2 Gs max. + kRange_2G = 0, + /// 4 Gs max. + kRange_4G = 1, + /// 8 Gs max. + kRange_8G = 2 + }; - enum Axes { kAxis_X = 0x00, kAxis_Y = 0x02, kAxis_Z = 0x04 }; + /** + * Accelerometer axes. + */ + enum Axes { + /// X axis. + kAxis_X = 0x00, + /// Y axis. + kAxis_Y = 0x02, + /// Z axis. + kAxis_Z = 0x04 + }; + + /** + * Container type for accelerations from all axes. + */ struct AllAxes { - double XAxis; - double YAxis; - double ZAxis; + /// Acceleration along the X axis in g-forces. + double XAxis = 0.0; + /// Acceleration along the Y axis in g-forces. + double YAxis = 0.0; + /// Acceleration along the Z axis in g-forces. + double ZAxis = 0.0; }; public: diff --git a/wpilibc/src/main/native/include/frc/AddressableLED.h b/wpilibc/src/main/native/include/frc/AddressableLED.h index 198eb6770c0..26738bbbfdd 100644 --- a/wpilibc/src/main/native/include/frc/AddressableLED.h +++ b/wpilibc/src/main/native/include/frc/AddressableLED.h @@ -22,7 +22,9 @@ namespace frc { * By default, the timing supports WS2812B LEDs, but is configurable using * SetBitTiming() * - *

Only 1 LED driver is currently supported by the roboRIO. + *

Only 1 LED driver is currently supported by the roboRIO. However, + * multiple LED strips can be connected in series and controlled from the + * single driver. */ class AddressableLED { public: diff --git a/wpilibc/src/main/native/include/frc/AnalogGyro.h b/wpilibc/src/main/native/include/frc/AnalogGyro.h index 0c472fbf7f8..3913b404884 100644 --- a/wpilibc/src/main/native/include/frc/AnalogGyro.h +++ b/wpilibc/src/main/native/include/frc/AnalogGyro.h @@ -218,10 +218,8 @@ class AnalogGyro : public wpi::Sendable, void InitSendable(wpi::SendableBuilder& builder) override; - protected: - std::shared_ptr m_analog; - private: + std::shared_ptr m_analog; hal::Handle m_gyroHandle; }; diff --git a/wpilibc/src/main/native/include/frc/AnalogOutput.h b/wpilibc/src/main/native/include/frc/AnalogOutput.h index ccb3c9c91fe..4151ae67557 100644 --- a/wpilibc/src/main/native/include/frc/AnalogOutput.h +++ b/wpilibc/src/main/native/include/frc/AnalogOutput.h @@ -33,14 +33,14 @@ class AnalogOutput : public wpi::Sendable, /** * Set the value of the analog output. * - * @param voltage The output value in Volts, from 0.0 to +5.0 + * @param voltage The output value in Volts, from 0.0 to +5.0. */ void SetVoltage(double voltage); /** - * Get the voltage of the analog output + * Get the voltage of the analog output. * - * @return The value in Volts, from 0.0 to +5.0 + * @return The value in Volts, from 0.0 to +5.0. */ double GetVoltage() const; diff --git a/wpilibc/src/main/native/include/frc/AnalogTriggerType.h b/wpilibc/src/main/native/include/frc/AnalogTriggerType.h index c706c344337..0db114d598a 100644 --- a/wpilibc/src/main/native/include/frc/AnalogTriggerType.h +++ b/wpilibc/src/main/native/include/frc/AnalogTriggerType.h @@ -6,10 +6,15 @@ namespace frc { +/** Defines the state in which the AnalogTrigger triggers. */ enum class AnalogTriggerType { + /// In window. kInWindow = 0, + /// State. kState = 1, + /// Rising Pulse. kRisingPulse = 2, + /// Falling pulse. kFallingPulse = 3 }; diff --git a/wpilibc/src/main/native/include/frc/BuiltInAccelerometer.h b/wpilibc/src/main/native/include/frc/BuiltInAccelerometer.h index a8f0adc4deb..270ed80d55c 100644 --- a/wpilibc/src/main/native/include/frc/BuiltInAccelerometer.h +++ b/wpilibc/src/main/native/include/frc/BuiltInAccelerometer.h @@ -17,7 +17,17 @@ namespace frc { class BuiltInAccelerometer : public wpi::Sendable, public wpi::SendableHelper { public: - enum Range { kRange_2G = 0, kRange_4G = 1, kRange_8G = 2 }; + /** + * Accelerometer range. + */ + enum Range { + /// 2 Gs max. + kRange_2G = 0, + /// 4 Gs max. + kRange_4G = 1, + /// 8 Gs max. + kRange_8G = 2 + }; /** * Constructor. diff --git a/wpilibc/src/main/native/include/frc/CAN.h b/wpilibc/src/main/native/include/frc/CAN.h index dc04988f1f3..1f5d1682a0f 100644 --- a/wpilibc/src/main/native/include/frc/CAN.h +++ b/wpilibc/src/main/native/include/frc/CAN.h @@ -170,7 +170,10 @@ class CAN { */ static uint64_t GetTimestampBaseTime(); + /// Team manufacturer. static constexpr HAL_CANManufacturer kTeamManufacturer = HAL_CAN_Man_kTeamUse; + + /// Team device type. static constexpr HAL_CANDeviceType kTeamDeviceType = HAL_CAN_Dev_kMiscellaneous; diff --git a/wpilibc/src/main/native/include/frc/CompressorConfigType.h b/wpilibc/src/main/native/include/frc/CompressorConfigType.h index 5a5a1c13a1f..b9338042b6b 100644 --- a/wpilibc/src/main/native/include/frc/CompressorConfigType.h +++ b/wpilibc/src/main/native/include/frc/CompressorConfigType.h @@ -5,10 +5,17 @@ #pragma once namespace frc { +/** + * Compressor config type. + */ enum class CompressorConfigType { + /// Disabled. Disabled = 0, + /// Digital. Digital = 1, + /// Analog. Analog = 2, + /// Hybrid. Hybrid = 3 }; diff --git a/wpilibc/src/main/native/include/frc/Counter.h b/wpilibc/src/main/native/include/frc/Counter.h index 71eebcab5a3..3720dde31b3 100644 --- a/wpilibc/src/main/native/include/frc/Counter.h +++ b/wpilibc/src/main/native/include/frc/Counter.h @@ -451,17 +451,20 @@ class Counter : public CounterBase, void InitSendable(wpi::SendableBuilder& builder) override; protected: - // Makes the counter count up. + /// Makes the counter count up. std::shared_ptr m_upSource; - // Makes the counter count down. + /// Makes the counter count down. std::shared_ptr m_downSource; - // The FPGA counter object + /// The FPGA counter object hal::Handle m_counter; private: - int m_index = 0; // The index of this counter. + /// The index of this counter. + int m_index = 0; + + /// Distance of travel for each tick. double m_distancePerPulse = 1; friend class DigitalGlitchFilter; diff --git a/wpilibc/src/main/native/include/frc/DMA.h b/wpilibc/src/main/native/include/frc/DMA.h index 1bbf268f774..d09368fb37f 100644 --- a/wpilibc/src/main/native/include/frc/DMA.h +++ b/wpilibc/src/main/native/include/frc/DMA.h @@ -17,6 +17,9 @@ class DMASample; class PWM; class PWMMotorController; +/** + * Class for configuring Direct Memory Access (DMA) of FPGA inputs. + */ class DMA { friend class DMASample; @@ -27,32 +30,162 @@ class DMA { DMA& operator=(DMA&& other) = default; DMA(DMA&& other) = default; + /** + * Sets whether DMA is paused. + * + * @param pause True pauses DMA. + */ void SetPause(bool pause); - void SetTimedTrigger(units::second_t seconds); + + /** + * Sets DMA to trigger at an interval. + * + * @param period Period at which to trigger DMA. + */ + void SetTimedTrigger(units::second_t period); + + /** + * Sets number of DMA cycles to trigger. + * + * @param cycles Number of cycles. + */ void SetTimedTriggerCycles(int cycles); + /** + * Adds position data for an encoder to be collected by DMA. + * + * This can only be called if DMA is not started. + * + * @param encoder Encoder to add to DMA. + */ void AddEncoder(const Encoder* encoder); + + /** + * Adds timer data for an encoder to be collected by DMA. + * + * This can only be called if DMA is not started. + * + * @param encoder Encoder to add to DMA. + */ void AddEncoderPeriod(const Encoder* encoder); + /** + * Adds position data for an counter to be collected by DMA. + * + * This can only be called if DMA is not started. + * + * @param counter Counter to add to DMA. + */ void AddCounter(const Counter* counter); + + /** + * Adds timer data for an counter to be collected by DMA. + * + * This can only be called if DMA is not started. + * + * @param counter Counter to add to DMA. + */ void AddCounterPeriod(const Counter* counter); + /** + * Adds a digital source to be collected by DMA. + * + * This can only be called if DMA is not started. + * + * @param digitalSource DigitalSource to add to DMA. + */ void AddDigitalSource(const DigitalSource* digitalSource); + /** + * Adds a digital source to be collected by DMA. + * + * This can only be called if DMA is not started. + * + * @param digitalSource DigitalSource to add to DMA. + */ void AddDutyCycle(const DutyCycle* digitalSource); + /** + * Adds an analog input to be collected by DMA. + * + * This can only be called if DMA is not started. + * + * @param analogInput AnalogInput to add to DMA. + */ void AddAnalogInput(const AnalogInput* analogInput); + + /** + * Adds averaged data of an analog input to be collected by DMA. + * + * This can only be called if DMA is not started. + * + * @param analogInput AnalogInput to add to DMA. + */ void AddAveragedAnalogInput(const AnalogInput* analogInput); + + /** + * Adds accumulator data of an analog input to be collected by DMA. + * + * This can only be called if DMA is not started. + * + * @param analogInput AnalogInput to add to DMA. + */ void AddAnalogAccumulator(const AnalogInput* analogInput); + /** + * Sets an external DMA trigger. + * + * @param source the source to trigger from. + * @param rising trigger on rising edge. + * @param falling trigger on falling edge. + * @return the index of the trigger + */ int SetExternalTrigger(DigitalSource* source, bool rising, bool falling); + + /** + * Sets a DMA PWM edge trigger. + * + * @param pwm the PWM to trigger from. + * @param rising trigger on rising edge. + * @param falling trigger on falling edge. + * @return the index of the trigger + */ int SetPwmEdgeTrigger(PWM* pwm, bool rising, bool falling); + + /** + * Sets a DMA PWMMotorController edge trigger. + * + * @param pwm the PWMMotorController to trigger from. + * @param rising trigger on rising edge. + * @param falling trigger on falling edge. + * @return the index of the trigger + */ int SetPwmEdgeTrigger(PWMMotorController* pwm, bool rising, bool falling); + /** + * Clear all sensors from the DMA collection list. + * + * This can only be called if DMA is not started. + */ void ClearSensors(); + + /** + * Clear all external triggers from the DMA trigger list. + * + * This can only be called if DMA is not started. + */ void ClearExternalTriggers(); + /** + * Starts DMA Collection. + * + * @param queueDepth The number of objects to be able to queue. + */ void Start(int queueDepth); + + /** + * Stops DMA Collection. + */ void Stop(); private: diff --git a/wpilibc/src/main/native/include/frc/DMASample.h b/wpilibc/src/main/native/include/frc/DMASample.h index 48a0a9e9cac..b2bed41fc75 100644 --- a/wpilibc/src/main/native/include/frc/DMASample.h +++ b/wpilibc/src/main/native/include/frc/DMASample.h @@ -17,30 +17,71 @@ #include "frc/Encoder.h" namespace frc { +/** + * DMA sample. + */ class DMASample : public HAL_DMASample { public: + /** + * DMA read status. + */ enum class DMAReadStatus { + /// OK status. kOk = HAL_DMA_OK, + /// Timeout status. kTimeout = HAL_DMA_TIMEOUT, + /// Error status. kError = HAL_DMA_ERROR }; + /** + * Retrieves a new DMA sample. + * + * @param dma DMA object. + * @param timeout Timeout for retrieval. + * @param remaining Number of remaining samples. + * @param status DMA read status. + */ DMAReadStatus Update(const DMA* dma, units::second_t timeout, int32_t* remaining, int32_t* status) { return static_cast( HAL_ReadDMA(dma->dmaHandle, this, timeout.value(), remaining, status)); } + /** + * Returns the DMA sample time in microseconds. + * + * @return The DMA sample time in microseconds. + */ uint64_t GetTime() const { return timeStamp; } + /** + * Returns the DMA sample timestamp. + * + * @return The DMA sample timestamp. + */ units::second_t GetTimeStamp() const { return units::second_t{static_cast(GetTime()) * 1.0e-6}; } + /** + * Returns raw encoder value from DMA. + * + * @param encoder Encoder used for DMA. + * @param status DMA read status. + * @return Raw encoder value from DMA. + */ int32_t GetEncoderRaw(const Encoder* encoder, int32_t* status) const { return HAL_GetDMASampleEncoderRaw(this, encoder->m_encoder, status); } + /** + * Returns encoder distance from DMA. + * + * @param encoder Encoder used for DMA. + * @param status DMA read status. + * @return Encoder distance from DMA. + */ double GetEncoderDistance(const Encoder* encoder, int32_t* status) const { double val = GetEncoderRaw(encoder, status); val *= encoder->DecodingScaleFactor(); @@ -48,41 +89,97 @@ class DMASample : public HAL_DMASample { return val; } + /** + * Returns raw encoder period from DMA. + * + * @param encoder Encoder used for DMA. + * @param status DMA read status. + * @return Raw encoder period from DMA. + */ int32_t GetEncoderPeriodRaw(const Encoder* encoder, int32_t* status) const { return HAL_GetDMASampleEncoderPeriodRaw(this, encoder->m_encoder, status); } + /** + * Returns counter value from DMA. + * + * @param counter Counter used for DMA. + * @param status DMA read status. + * @return Counter value from DMA. + */ int32_t GetCounter(const Counter* counter, int32_t* status) const { return HAL_GetDMASampleCounter(this, counter->m_counter, status); } + /** + * Returns counter period from DMA. + * + * @param counter Counter used for DMA. + * @param status DMA read status. + * @return Counter period from DMA. + */ int32_t GetCounterPeriod(const Counter* counter, int32_t* status) const { return HAL_GetDMASampleCounterPeriod(this, counter->m_counter, status); } + /** + * Returns digital source value from DMA. + * + * @param digitalSource DigitalSource used for DMA. + * @param status DMA read status. + * @return DigitalSource value from DMA. + */ bool GetDigitalSource(const DigitalSource* digitalSource, int32_t* status) const { return HAL_GetDMASampleDigitalSource( this, digitalSource->GetPortHandleForRouting(), status); } + /** + * Returns raw analog input value from DMA. + * + * @param analogInput AnalogInput used for DMA. + * @param status DMA read status. + * @return Raw analog input value from DMA. + */ int32_t GetAnalogInputRaw(const AnalogInput* analogInput, int32_t* status) const { return HAL_GetDMASampleAnalogInputRaw(this, analogInput->m_port, status); } + /** + * Returns analog input voltage from DMA. + * + * @param analogInput AnalogInput used for DMA. + * @param status DMA read status. + * @return Analog input voltage from DMA. + */ double GetAnalogInputVoltage(const AnalogInput* analogInput, int32_t* status) { return HAL_GetAnalogValueToVolts( analogInput->m_port, GetAnalogInputRaw(analogInput, status), status); } + /** + * Returns averaged analog input raw value from DMA. + * + * @param analogInput AnalogInput used for DMA. + * @param status DMA read status. + * @return Averaged analog input raw value from DMA. + */ int32_t GetAveragedAnalogInputRaw(const AnalogInput* analogInput, int32_t* status) const { return HAL_GetDMASampleAveragedAnalogInputRaw(this, analogInput->m_port, status); } + /** + * Returns averaged analog input voltage from DMA. + * + * @param analogInput AnalogInput used for DMA. + * @param status DMA read status. + * @return Averaged analog input voltage from DMA. + */ double GetAveragedAnalogInputVoltage(const AnalogInput* analogInput, int32_t* status) { return HAL_GetAnalogValueToVolts( @@ -90,18 +187,40 @@ class DMASample : public HAL_DMASample { status); } + /** + * Returns analog accumulator value from DMA. + * + * @param analogInput AnalogInput used for DMA. + * @param count Accumulator sample count. + * @param value Accumulator value. + * @param status DMA read status. + */ void GetAnalogAccumulator(const AnalogInput* analogInput, int64_t* count, int64_t* value, int32_t* status) const { return HAL_GetDMASampleAnalogAccumulator(this, analogInput->m_port, count, value, status); } + /** + * Returns raw duty cycle output from DMA. + * + * @param dutyCycle DutyCycle used for DMA. + * @param status DMA read status. + * @return Raw duty cycle output from DMA. + */ int32_t GetDutyCycleOutputRaw(const DutyCycle* dutyCycle, int32_t* status) const { return HAL_GetDMASampleDutyCycleOutputRaw(this, dutyCycle->m_handle, status); } + /** + * Returns duty cycle output (0-1) from DMA. + * + * @param dutyCycle DutyCycle used for DMA. + * @param status DMA read status. + * @return Duty cycle output (0-1) from DMA. + */ double GetDutyCycleOutput(const DutyCycle* dutyCycle, int32_t* status) { return GetDutyCycleOutputRaw(dutyCycle, status) / static_cast(dutyCycle->GetOutputScaleFactor()); diff --git a/wpilibc/src/main/native/include/frc/DataLogManager.h b/wpilibc/src/main/native/include/frc/DataLogManager.h index 336af4a01ea..f171cd380a6 100644 --- a/wpilibc/src/main/native/include/frc/DataLogManager.h +++ b/wpilibc/src/main/native/include/frc/DataLogManager.h @@ -17,8 +17,8 @@ namespace frc { * Centralized data log that provides automatic data log file management. It * automatically cleans up old files when disk space is low and renames the file * based either on current date/time or (if available) competition match number. - * The deta file will be saved to a USB flash drive if one is attached, or to - * /home/lvuser otherwise. + * The data file will be saved to a USB flash drive in a folder named "logs" if + * one is attached, or to /home/lvuser/logs otherwise. * * Log files are initially named "FRC_TBD_{random}.wpilog" until the DS * connects. After the DS connects, the log file is renamed to diff --git a/wpilibc/src/main/native/include/frc/DoubleSolenoid.h b/wpilibc/src/main/native/include/frc/DoubleSolenoid.h index f02ba5a1949..57c2c11d82a 100644 --- a/wpilibc/src/main/native/include/frc/DoubleSolenoid.h +++ b/wpilibc/src/main/native/include/frc/DoubleSolenoid.h @@ -25,7 +25,17 @@ namespace frc { class DoubleSolenoid : public wpi::Sendable, public wpi::SendableHelper { public: - enum Value { kOff, kForward, kReverse }; + /** + * Possible values for a DoubleSolenoid. + */ + enum Value { + /// Off position. + kOff, + /// Forward position. + kForward, + /// Reverse position. + kReverse + }; /** * Constructs a double solenoid for a specified module of a specific module diff --git a/wpilibc/src/main/native/include/frc/DriverStation.h b/wpilibc/src/main/native/include/frc/DriverStation.h index ea568a722f7..b9b683f11b4 100644 --- a/wpilibc/src/main/native/include/frc/DriverStation.h +++ b/wpilibc/src/main/native/include/frc/DriverStation.h @@ -22,9 +22,31 @@ namespace frc { */ class DriverStation final { public: - enum Alliance { kRed, kBlue }; - enum MatchType { kNone, kPractice, kQualification, kElimination }; + /** + * The robot alliance that the robot is a part of. + */ + enum Alliance { + /// Red alliance. + kRed, + /// Blue alliance. + kBlue + }; + + /** + * The type of robot match that the robot is part of. + */ + enum MatchType { + /// None. + kNone, + /// Practice. + kPractice, + /// Qualification. + kQualification, + /// Elimination. + kElimination + }; + /// Number of Joystick ports. static constexpr int kJoystickPorts = 6; /** @@ -274,14 +296,13 @@ class DriverStation final { static int GetReplayNumber(); /** - * Return the alliance that the driver station says it is on from the FMS. + * Get the current alliance from the FMS. * * If the FMS is not connected, it is set from the team alliance setting on * the driver station. * - * This could return kRed or kBlue. - * - * @return The Alliance enum (kRed, kBlue or kInvalid) + * @return The alliance (red or blue) or an empty optional if the alliance is + * invalid */ static std::optional GetAlliance(); @@ -334,9 +355,25 @@ class DriverStation final { */ static double GetBatteryVoltage(); + /** + * Copy data from the DS task for the user. If no new data exists, it will + * just be returned, otherwise the data will be copied from the DS polling + * loop. + */ static void RefreshData(); + /** + * Registers the given handle for DS data refresh notifications. + * + * @param handle The event handle. + */ static void ProvideRefreshedDataEventHandle(WPI_EventHandle handle); + + /** + * Unregisters the given handle from DS data refresh notifications. + * + * @param handle The event handle. + */ static void RemoveRefreshedDataEventHandle(WPI_EventHandle handle); /** diff --git a/wpilibc/src/main/native/include/frc/Encoder.h b/wpilibc/src/main/native/include/frc/Encoder.h index 7315e1638af..8d6c10a4556 100644 --- a/wpilibc/src/main/native/include/frc/Encoder.h +++ b/wpilibc/src/main/native/include/frc/Encoder.h @@ -42,10 +42,17 @@ class Encoder : public CounterBase, friend class DMASample; public: + /** + * Encoder indexing types. + */ enum IndexingType { + /// Reset while the signal is high. kResetWhileHigh, + /// Reset while the signal is low. kResetWhileLow, + /// Reset on falling edge of the signal. kResetOnFallingEdge, + /// Reset on rising edge of the signal. kResetOnRisingEdge }; diff --git a/wpilibc/src/main/native/include/frc/GenericHID.h b/wpilibc/src/main/native/include/frc/GenericHID.h index f6db94c3743..aac4bec7026 100644 --- a/wpilibc/src/main/native/include/frc/GenericHID.h +++ b/wpilibc/src/main/native/include/frc/GenericHID.h @@ -23,25 +23,55 @@ class EventLoop; */ class GenericHID { public: - enum RumbleType { kLeftRumble, kRightRumble, kBothRumble }; + /** + * Represents a rumble output on the Joystick. + */ + enum RumbleType { + /// Left rumble motor. + kLeftRumble, + /// Right rumble motor. + kRightRumble, + /// Both left and right rumble motors. + kBothRumble + }; + /** + * USB HID interface type. + */ enum HIDType { + /// Unknown. kUnknown = -1, + /// XInputUnknown. kXInputUnknown = 0, + /// XInputGamepad. kXInputGamepad = 1, + /// XInputWheel. kXInputWheel = 2, + /// XInputArcadeStick. kXInputArcadeStick = 3, + /// XInputFlightStick. kXInputFlightStick = 4, + /// XInputDancePad. kXInputDancePad = 5, + /// XInputGuitar. kXInputGuitar = 6, + /// XInputGuitar2. kXInputGuitar2 = 7, + /// XInputDrumKit. kXInputDrumKit = 8, + /// XInputGuitar3. kXInputGuitar3 = 11, + /// XInputArcadePad. kXInputArcadePad = 19, + /// HIDJoystick. kHIDJoystick = 20, + /// HIDGamepad. kHIDGamepad = 21, + /// HIDDriving. kHIDDriving = 22, + /// HIDFlight. kHIDFlight = 23, + /// HID1stPerson. kHID1stPerson = 24 }; diff --git a/wpilibc/src/main/native/include/frc/I2C.h b/wpilibc/src/main/native/include/frc/I2C.h index 9489fcfb3ee..07f3d4a927c 100644 --- a/wpilibc/src/main/native/include/frc/I2C.h +++ b/wpilibc/src/main/native/include/frc/I2C.h @@ -22,7 +22,15 @@ namespace frc { */ class I2C { public: - enum Port { kOnboard = 0, kMXP }; + /** + * I2C connection ports. + */ + enum Port { + /// Onboard I2C port. + kOnboard = 0, + /// MXP (roboRIO MXP) I2C port. + kMXP + }; /** * Constructor. @@ -37,7 +45,18 @@ class I2C { I2C(I2C&&) = default; I2C& operator=(I2C&&) = default; + /** + * Returns I2C port. + * + * @return I2C port. + */ Port GetPort() const; + + /** + * Returns I2C device address. + * + * @return I2C device address. + */ int GetDeviceAddress() const; /** diff --git a/wpilibc/src/main/native/include/frc/IterativeRobotBase.h b/wpilibc/src/main/native/include/frc/IterativeRobotBase.h index 42b0c715df7..8329c0b10e7 100644 --- a/wpilibc/src/main/native/include/frc/IterativeRobotBase.h +++ b/wpilibc/src/main/native/include/frc/IterativeRobotBase.h @@ -215,7 +215,7 @@ class IterativeRobotBase : public RobotBase { /** * Sets whether LiveWindow operation is enabled during test mode. * - * @param testLW True to enable, false to disable. Defaults to true. + * @param testLW True to enable, false to disable. Defaults to false. * @throws if called in test mode. */ void EnableLiveWindowInTest(bool testLW); @@ -230,6 +230,11 @@ class IterativeRobotBase : public RobotBase { */ units::second_t GetPeriod() const; + /** + * Prints list of epochs added so far and their times. + */ + void PrintWatchdogEpochs(); + /** * Constructor for IterativeRobotBase. * @@ -243,6 +248,9 @@ class IterativeRobotBase : public RobotBase { IterativeRobotBase(IterativeRobotBase&&) = default; IterativeRobotBase& operator=(IterativeRobotBase&&) = default; + /** + * Loop function. + */ void LoopFunc(); private: @@ -252,7 +260,7 @@ class IterativeRobotBase : public RobotBase { units::second_t m_period; Watchdog m_watchdog; bool m_ntFlushEnabled = true; - bool m_lwEnabledInTest = true; + bool m_lwEnabledInTest = false; bool m_calledDsConnected = false; void PrintLoopOverrunMessage(); diff --git a/wpilibc/src/main/native/include/frc/Joystick.h b/wpilibc/src/main/native/include/frc/Joystick.h index a955718c3b0..0f8e1014914 100644 --- a/wpilibc/src/main/native/include/frc/Joystick.h +++ b/wpilibc/src/main/native/include/frc/Joystick.h @@ -22,14 +22,42 @@ namespace frc { */ class Joystick : public GenericHID { public: + /// Default X axis channel. static constexpr int kDefaultXChannel = 0; + /// Default Y axis channel. static constexpr int kDefaultYChannel = 1; + /// Default Z axis channel. static constexpr int kDefaultZChannel = 2; + /// Default twist axis channel. static constexpr int kDefaultTwistChannel = 2; + /// Default throttle axis channel. static constexpr int kDefaultThrottleChannel = 3; - enum AxisType { kXAxis, kYAxis, kZAxis, kTwistAxis, kThrottleAxis }; - enum ButtonType { kTriggerButton, kTopButton }; + /** + * Represents an analog axis on a joystick. + */ + enum AxisType { + /// X axis. + kXAxis, + /// Y axis. + kYAxis, + /// Z axis. + kZAxis, + /// Twist axis. + kTwistAxis, + /// Throttle axis. + kThrottleAxis + }; + + /** + * Represents a digital button on a joystick. + */ + enum ButtonType { + /// kTrigger. + kTriggerButton, + /// kTop. + kTopButton + }; /** * Construct an instance of a joystick. @@ -223,26 +251,6 @@ class Joystick : public GenericHID { */ double GetMagnitude() const; - /** - * Get the direction of the vector formed by the joystick and its origin - * in radians. - * - * @return The direction of the vector in radians - * @deprecated Use GetDirection() instead. - */ - [[deprecated("Use GetDirection() instead.")]] - double GetDirectionRadians() const; - - /** - * Get the direction of the vector formed by the joystick and its origin - * in degrees. - * - * @return The direction of the vector in degrees - * @deprecated Use GetDirection() instead. - */ - [[deprecated("Use GetDirection() instead.")]] - double GetDirectionDegrees() const; - /** * Get the direction of the vector formed by the joystick and its origin. * diff --git a/wpilibc/src/main/native/include/frc/MotorSafety.h b/wpilibc/src/main/native/include/frc/MotorSafety.h index a17cdc0cabd..efe7806a951 100644 --- a/wpilibc/src/main/native/include/frc/MotorSafety.h +++ b/wpilibc/src/main/native/include/frc/MotorSafety.h @@ -93,12 +93,15 @@ class MotorSafety { */ static void CheckMotors(); + /** + * Called to stop the motor when the timeout expires. + */ virtual void StopMotor() = 0; /** - * The return value from this method is printed out when an error occurs + * Returns a description to print when an error occurs. * - * This method must not throw! + * @return Description to print when an error occurs. */ virtual std::string GetDescription() const = 0; diff --git a/wpilibc/src/main/native/include/frc/Notifier.h b/wpilibc/src/main/native/include/frc/Notifier.h index 0bd54d46f77..53e980f4744 100644 --- a/wpilibc/src/main/native/include/frc/Notifier.h +++ b/wpilibc/src/main/native/include/frc/Notifier.h @@ -82,15 +82,6 @@ class Notifier { */ void SetName(std::string_view name); - /** - * Change the callback function. - * - * @param callback The callback function. - * @deprecated Use SetCallback() instead. - */ - [[deprecated("Use SetCallback() instead.")]] - void SetHandler(std::function callback); - /** * Change the callback function. * diff --git a/wpilibc/src/main/native/include/frc/PS4Controller.h b/wpilibc/src/main/native/include/frc/PS4Controller.h index 9487634e7cf..881f8564f25 100644 --- a/wpilibc/src/main/native/include/frc/PS4Controller.h +++ b/wpilibc/src/main/native/include/frc/PS4Controller.h @@ -11,10 +11,14 @@ namespace frc { /** * Handle input from PS4 controllers connected to the Driver Station. * - *

This class handles PS4 input that comes from the Driver Station. Each time + * This class handles PS4 input that comes from the Driver Station. Each time * a value is requested the most recent value is returned. There is a single * class instance for each controller and the mapping of ports to hardware * buttons depends on the code in the Driver Station. + * + * Only first party controllers from Sony are guaranteed to have the correct + * mapping, and only through the official NI DS. Sim is not guaranteed to have + * the same mapping, as well as any 3rd party controllers. */ class PS4Controller : public GenericHID { public: @@ -499,29 +503,55 @@ class PS4Controller : public GenericHID { */ BooleanEvent Touchpad(EventLoop* loop) const; + /** + * Represents a digital button on a PS4Controller. + */ struct Button { + /// Square button. static constexpr int kSquare = 1; + /// X button. static constexpr int kCross = 2; + /// Circle button. static constexpr int kCircle = 3; + /// Triangle button. static constexpr int kTriangle = 4; + /// Left Trigger 1 button. static constexpr int kL1 = 5; + /// Right Trigger 1 button. static constexpr int kR1 = 6; + /// Left Trigger 2 button. static constexpr int kL2 = 7; + /// Right Trigger 2 button. static constexpr int kR2 = 8; + /// Share button. static constexpr int kShare = 9; + /// Option button. static constexpr int kOptions = 10; + /// Left stick button. static constexpr int kL3 = 11; + /// Right stick button. static constexpr int kR3 = 12; + /// PlayStation button. static constexpr int kPS = 13; + /// Touchpad click button. static constexpr int kTouchpad = 14; }; + /** + * Represents an axis on a PS4Controller. + */ struct Axis { + /// Left X axis. static constexpr int kLeftX = 0; + /// Left Y axis. static constexpr int kLeftY = 1; + /// Right X axis. static constexpr int kRightX = 2; + /// Right Y axis. static constexpr int kRightY = 5; + /// Left Trigger 2. static constexpr int kL2 = 3; + /// Right Trigger 2. static constexpr int kR2 = 4; }; }; diff --git a/wpilibc/src/main/native/include/frc/PS5Controller.h b/wpilibc/src/main/native/include/frc/PS5Controller.h index 2a24f5e3612..e9d52352304 100644 --- a/wpilibc/src/main/native/include/frc/PS5Controller.h +++ b/wpilibc/src/main/native/include/frc/PS5Controller.h @@ -11,10 +11,14 @@ namespace frc { /** * Handle input from PS5 controllers connected to the Driver Station. * - *

This class handles PS5 input that comes from the Driver Station. Each time + * This class handles PS5 input that comes from the Driver Station. Each time * a value is requested the most recent value is returned. There is a single * class instance for each controller and the mapping of ports to hardware * buttons depends on the code in the Driver Station. + * + * Only first party controllers from Sony are guaranteed to have the correct + * mapping, and only through the official NI DS. Sim is not guaranteed to have + * the same mapping, as well as any 3rd party controllers. */ class PS5Controller : public GenericHID { public: @@ -499,30 +503,56 @@ class PS5Controller : public GenericHID { */ BooleanEvent Touchpad(EventLoop* loop) const; + /** + * Represents a digital button on a PS5Controller. + */ struct Button { - static constexpr int kSquare = 3; - static constexpr int kCross = 1; - static constexpr int kCircle = 2; + /// Square button. + static constexpr int kSquare = 1; + /// X button. + static constexpr int kCross = 2; + /// Circle button. + static constexpr int kCircle = 3; + /// Triangle button. static constexpr int kTriangle = 4; + /// Left trigger 1 button. static constexpr int kL1 = 5; + /// Right trigger 1 button. static constexpr int kR1 = 6; + /// Left trigger 2 button. static constexpr int kL2 = 7; + /// Right trigger 2 button. static constexpr int kR2 = 8; + /// Create button. static constexpr int kCreate = 9; + /// Options button. static constexpr int kOptions = 10; - static constexpr int kL3 = 12; - static constexpr int kR3 = 13; - static constexpr int kPS = 11; + /// Left stick button. + static constexpr int kL3 = 11; + /// Right stick button. + static constexpr int kR3 = 12; + /// PlayStation button. + static constexpr int kPS = 13; + /// Touchpad click button. static constexpr int kTouchpad = 14; }; + /** + * Represents an axis on a PS5Controller. + */ struct Axis { + /// Left X axis. static constexpr int kLeftX = 0; + /// Left Y axis. static constexpr int kLeftY = 1; - static constexpr int kRightX = 3; - static constexpr int kRightY = 4; - static constexpr int kL2 = 2; - static constexpr int kR2 = 5; + /// Right X axis. + static constexpr int kRightX = 2; + /// Right Y axis. + static constexpr int kRightY = 5; + /// Left Trigger 2. + static constexpr int kL2 = 3; + /// Right Trigger 2. + static constexpr int kR2 = 4; }; }; diff --git a/wpilibc/src/main/native/include/frc/PWM.h b/wpilibc/src/main/native/include/frc/PWM.h index 0871c9c527d..c1f162ee816 100644 --- a/wpilibc/src/main/native/include/frc/PWM.h +++ b/wpilibc/src/main/native/include/frc/PWM.h @@ -144,6 +144,9 @@ class PWM : public wpi::Sendable, public wpi::SendableHelper { */ void SetPeriodMultiplier(PeriodMultiplier mult); + /** + * Latches PWM to zero. + */ void SetZeroLatch(); /** diff --git a/wpilibc/src/main/native/include/frc/PneumaticHub.h b/wpilibc/src/main/native/include/frc/PneumaticHub.h index b69b3d5cd11..790a9d0a865 100644 --- a/wpilibc/src/main/native/include/frc/PneumaticHub.h +++ b/wpilibc/src/main/native/include/frc/PneumaticHub.h @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -157,6 +158,15 @@ class PneumaticHub : public PneumaticsBase { uint32_t Brownout : 1; uint32_t CanWarning : 1; uint32_t HardwareFault : 1; + + /** + * Gets whether there is a fault at the specified channel. + * @param channel Channel to check for faults. + * @return True if a a fault exists at the channel, otherwise false. + * @throws A ChannelIndexOutOfRange error if the provided channel is outside + * of the range supported by the hardware. + */ + bool GetChannelFault(int channel) const; }; /** diff --git a/wpilibc/src/main/native/include/frc/PneumaticsBase.h b/wpilibc/src/main/native/include/frc/PneumaticsBase.h index 59f899fabbd..52ae9b0bf03 100644 --- a/wpilibc/src/main/native/include/frc/PneumaticsBase.h +++ b/wpilibc/src/main/native/include/frc/PneumaticsBase.h @@ -18,6 +18,10 @@ namespace frc { class Solenoid; class DoubleSolenoid; class Compressor; + +/** + * Base class for pneumatics devices. + */ class PneumaticsBase { public: virtual ~PneumaticsBase() = default; diff --git a/wpilibc/src/main/native/include/frc/PneumaticsModuleType.h b/wpilibc/src/main/native/include/frc/PneumaticsModuleType.h index 7f706620b51..4fb225a217e 100644 --- a/wpilibc/src/main/native/include/frc/PneumaticsModuleType.h +++ b/wpilibc/src/main/native/include/frc/PneumaticsModuleType.h @@ -5,5 +5,13 @@ #pragma once namespace frc { -enum class PneumaticsModuleType { CTREPCM, REVPH }; +/** + * Pneumatics module type. + */ +enum class PneumaticsModuleType { + /// CTRE PCM. + CTREPCM, + /// REV PH. + REVPH +}; } // namespace frc diff --git a/wpilibc/src/main/native/include/frc/PowerDistribution.h b/wpilibc/src/main/native/include/frc/PowerDistribution.h index 763e6bfdc4b..9a219472ddd 100644 --- a/wpilibc/src/main/native/include/frc/PowerDistribution.h +++ b/wpilibc/src/main/native/include/frc/PowerDistribution.h @@ -17,8 +17,18 @@ namespace frc { class PowerDistribution : public wpi::Sendable, public wpi::SendableHelper { public: + /// Default module number. static constexpr int kDefaultModule = -1; - enum class ModuleType { kCTRE = 1, kRev = 2 }; + + /** + * Power distribution module type. + */ + enum class ModuleType { + /// CTRE (Cross The Road Electronics) CTRE Power Distribution Panel (PDP). + kCTRE = 1, + /// REV Power Distribution Hub (PDH). + kRev = 2 + }; /** * Constructs a PowerDistribution object. @@ -48,7 +58,10 @@ class PowerDistribution : public wpi::Sendable, double GetVoltage() const; /** - * Query the temperature of the PDP/PDH. + * Query the temperature of the PDP. + * + * Not supported on the Rev PDH and returns 0. + * * * @return The temperature in degrees Celsius */ @@ -70,21 +83,27 @@ class PowerDistribution : public wpi::Sendable, double GetTotalCurrent() const; /** - * Query the total power drawn from all monitored PDP/PDH channels. + * Query the total power drawn from all monitored PDP channels. + * + * Not supported on the Rev PDH and returns 0. * * @return The total power drawn in Watts */ double GetTotalPower() const; /** - * Query the total energy drawn from the monitored PDP/PDH channels. + * Query the total energy drawn from the monitored PDP channels. + * + * Not supported on the Rev PDH and returns 0. * * @return The total energy drawn in Joules */ double GetTotalEnergy() const; /** - * Reset the total energy drawn from the PDP/PDH. + * Reset the total energy drawn from the PDP. + * + * Not supported on the Rev PDH and does nothing. * * @see PowerDistribution#GetTotalEnergy */ @@ -159,8 +178,22 @@ class PowerDistribution : public wpi::Sendable, uint32_t Brownout : 1; uint32_t CanWarning : 1; uint32_t HardwareFault : 1; + + /** + * Gets whether there is a breaker fault at a specified channel. + * @param channel Channel to check for faults. + * @return If there is a breaker fault. + * @throws A ChannelIndexOutOfRange error if the given int is outside of the + * range supported by the hardware. + */ + bool GetBreakerFault(int channel) const; }; + /** + * Returns the power distribution faults. + * + * @return The power distribution faults. + */ Faults GetFaults() const; struct StickyFaults { @@ -192,8 +225,23 @@ class PowerDistribution : public wpi::Sendable, uint32_t CanWarning : 1; uint32_t CanBusOff : 1; uint32_t HasReset : 1; + + /** + * Gets whether there is a sticky breaker fault at the specified channel. + * @param channel Index to check for sticky faults. + * @return True if there is a sticky breaker fault at the channel, otherwise + * false. + * @throws A ChannelIndexOutOfRange error if the provided channel is outside + * of the range supported by the hardware. + */ + bool GetBreakerFault(int channel) const; }; + /** + * Returns the power distribution sticky faults. + * + * @return The power distribution sticky faults. + */ StickyFaults GetStickyFaults() const; void InitSendable(wpi::SendableBuilder& builder) override; diff --git a/wpilibc/src/main/native/include/frc/Relay.h b/wpilibc/src/main/native/include/frc/Relay.h index 4765c64a6a4..d08a0007daf 100644 --- a/wpilibc/src/main/native/include/frc/Relay.h +++ b/wpilibc/src/main/native/include/frc/Relay.h @@ -31,8 +31,31 @@ class Relay : public MotorSafety, public wpi::Sendable, public wpi::SendableHelper { public: - enum Value { kOff, kOn, kForward, kReverse }; - enum Direction { kBothDirections, kForwardOnly, kReverseOnly }; + /** + * The state to drive a Relay to. + */ + enum Value { + /// Off. + kOff, + /// On. + kOn, + /// Forward. + kForward, + /// Reverse. + kReverse + }; + + /** + * The Direction(s) that a relay is configured to operate in. + */ + enum Direction { + /// Both directions are valid. + kBothDirections, + /// Only forward is valid. + kForwardOnly, + /// Only reverse is valid. + kReverseOnly + }; /** * Relay constructor given a channel. diff --git a/wpilibc/src/main/native/include/frc/RobotBase.h b/wpilibc/src/main/native/include/frc/RobotBase.h index 504ac810f81..6dff3696cdd 100644 --- a/wpilibc/src/main/native/include/frc/RobotBase.h +++ b/wpilibc/src/main/native/include/frc/RobotBase.h @@ -189,7 +189,9 @@ class RobotBase { bool IsTestEnabled() const; /** - * Gets the ID of the main robot thread. + * Returns the main thread ID. + * + * @return The main thread ID. */ static std::thread::id GetThreadId(); diff --git a/wpilibc/src/main/native/include/frc/RobotController.h b/wpilibc/src/main/native/include/frc/RobotController.h index bf65a8cfaac..5d8ddfb4de2 100644 --- a/wpilibc/src/main/native/include/frc/RobotController.h +++ b/wpilibc/src/main/native/include/frc/RobotController.h @@ -21,6 +21,8 @@ struct CANStatus { int transmitErrorCount; }; +enum RadioLEDState { kOff = 0, kGreen = 1, kRed = 2, kOrange = 3 }; + class RobotController { public: RobotController() = delete; @@ -81,6 +83,10 @@ class RobotController { /** * Get the state of the "USER" button on the roboRIO. * + * @warning the User Button is used to stop user programs from automatically + * loading if it is held for more then 5 seconds. Because of this, it's not + * recommended to be used by teams for any other purpose. + * * @return True if the button is currently pressed down */ static bool GetUserButton(); @@ -274,6 +280,23 @@ class RobotController { */ static units::celsius_t GetCPUTemp(); + /** + * Set the state of the "Radio" LED. On the RoboRIO, this writes to sysfs, so + * this function should not be called multiple times per loop cycle to avoid + * overruns. + * @param state The state to set the LED to. + */ + static void SetRadioLEDState(RadioLEDState state); + + /** + * Get the state of the "Radio" LED. On the RoboRIO, this reads from sysfs, so + * this function should not be called multiple times per loop cycle to avoid + * overruns. + * + * @return The state of the LED. + */ + static RadioLEDState GetRadioLEDState(); + /** * Get the current status of the CAN bus. * diff --git a/wpilibc/src/main/native/include/frc/RobotState.h b/wpilibc/src/main/native/include/frc/RobotState.h index 0489b9bb742..ec8700e34ac 100644 --- a/wpilibc/src/main/native/include/frc/RobotState.h +++ b/wpilibc/src/main/native/include/frc/RobotState.h @@ -6,15 +6,53 @@ namespace frc { +/** + * Robot state utility functions. + */ class RobotState { public: RobotState() = delete; + /** + * Returns true if the robot is disabled. + * + * @return True if the robot is disabled. + */ static bool IsDisabled(); + + /** + * Returns true if the robot is enabled. + * + * @return True if the robot is enabled. + */ static bool IsEnabled(); + + /** + * Returns true if the robot is E-stopped. + * + * @return True if the robot is E-stopped. + */ static bool IsEStopped(); + + /** + * Returns true if the robot is in teleop mode. + * + * @return True if the robot is in teleop mode. + */ static bool IsTeleop(); + + /** + * Returns true if the robot is in autonomous mode. + * + * @return True if the robot is in autonomous mode. + */ static bool IsAutonomous(); + + /** + * Returns true if the robot is in test mode. + * + * @return True if the robot is in test mode. + */ static bool IsTest(); }; diff --git a/wpilibc/src/main/native/include/frc/RuntimeType.h b/wpilibc/src/main/native/include/frc/RuntimeType.h index c3a8a0bb71a..2be444a60f6 100644 --- a/wpilibc/src/main/native/include/frc/RuntimeType.h +++ b/wpilibc/src/main/native/include/frc/RuntimeType.h @@ -5,5 +5,15 @@ #pragma once namespace frc { -enum RuntimeType { kRoboRIO, kRoboRIO2, kSimulation }; +/** + * Runtime type. + */ +enum RuntimeType { + /// roboRIO 1.0. + kRoboRIO, + /// roboRIO 2.0. + kRoboRIO2, + /// Simulation runtime. + kSimulation +}; } // namespace frc diff --git a/wpilibc/src/main/native/include/frc/SPI.h b/wpilibc/src/main/native/include/frc/SPI.h index 1158cbdea2a..5b170bac230 100644 --- a/wpilibc/src/main/native/include/frc/SPI.h +++ b/wpilibc/src/main/native/include/frc/SPI.h @@ -25,14 +25,34 @@ class DigitalSource; */ class SPI { public: - enum Port { kOnboardCS0 = 0, kOnboardCS1, kOnboardCS2, kOnboardCS3, kMXP }; + /** + * SPI port. + */ + enum Port { + /// Onboard SPI bus port CS0. + kOnboardCS0 = 0, + /// Onboard SPI bus port CS1. + kOnboardCS1, + /// Onboard SPI bus port CS2. + kOnboardCS2, + /// Onboard SPI bus port CS3. + kOnboardCS3, + /// MXP (roboRIO MXP) SPI bus port. + kMXP + }; + + /** + * SPI mode. + */ enum Mode { - kMode0 = HAL_SPI_kMode0, /*!< Clock idle low, data sampled on rising edge */ - kMode1 = - HAL_SPI_kMode1, /*!< Clock idle low, data sampled on falling edge */ - kMode2 = - HAL_SPI_kMode2, /*!< Clock idle high, data sampled on falling edge */ - kMode3 = HAL_SPI_kMode3 /*!< Clock idle high, data sampled on rising edge */ + /// Clock idle low, data sampled on rising edge. + kMode0 = HAL_SPI_kMode0, + /// Clock idle low, data sampled on falling edge. + kMode1 = HAL_SPI_kMode1, + /// Clock idle high, data sampled on falling edge. + kMode2 = HAL_SPI_kMode2, + /// Clock idle high, data sampled on rising edge. + kMode3 = HAL_SPI_kMode3 }; /** @@ -47,6 +67,11 @@ class SPI { SPI(SPI&&) = default; SPI& operator=(SPI&&) = default; + /** + * Returns the SPI port. + * + * @return The SPI port. + */ Port GetPort() const; /** diff --git a/wpilibc/src/main/native/include/frc/SerialPort.h b/wpilibc/src/main/native/include/frc/SerialPort.h index dcc0a2e068a..b7784da794b 100644 --- a/wpilibc/src/main/native/include/frc/SerialPort.h +++ b/wpilibc/src/main/native/include/frc/SerialPort.h @@ -26,30 +26,73 @@ namespace frc { */ class SerialPort { public: + /** + * Serial port. + */ + enum Port { + /// Onboard serial port on the roboRIO. + kOnboard = 0, + /// MXP (roboRIO MXP) serial port. + kMXP = 1, + /// USB serial port (same as KUSB1). + kUSB = 2, + /// USB serial port 1. + kUSB1 = 2, + /// USB serial port 2. + kUSB2 = 3 + }; + + /** + * Represents the parity to use for serial communications. + */ enum Parity { + /// No parity. kParity_None = 0, + /// Odd parity. kParity_Odd = 1, + /// Even parity. kParity_Even = 2, + /// Parity bit always on. kParity_Mark = 3, + /// Parity bit always off. kParity_Space = 4 }; + /** + * Represents the number of stop bits to use for Serial Communication. + */ enum StopBits { + /// One stop bit. kStopBits_One = 10, + /// One and a half stop bits. kStopBits_OnePointFive = 15, + /// Two stop bits. kStopBits_Two = 20 }; + /** + * Represents what type of flow control to use for serial communication. + */ enum FlowControl { + /// No flow control. kFlowControl_None = 0, + /// XON/XOFF flow control. kFlowControl_XonXoff = 1, + /// RTS/CTS flow control. kFlowControl_RtsCts = 2, + /// DTS/DSR flow control. kFlowControl_DtrDsr = 4 }; - enum WriteBufferMode { kFlushOnAccess = 1, kFlushWhenFull = 2 }; - - enum Port { kOnboard = 0, kMXP = 1, kUSB = 2, kUSB1 = 2, kUSB2 = 3 }; + /** + * Represents which type of buffer mode to use when writing to a serial port. + */ + enum WriteBufferMode { + /// Flush the buffer on each access. + kFlushOnAccess = 1, + /// Flush the buffer when it is full. + kFlushWhenFull = 2 + }; /** * Create an instance of a Serial Port class. diff --git a/wpilibc/src/main/native/include/frc/Servo.h b/wpilibc/src/main/native/include/frc/Servo.h index 9383641a2cd..76b39a0d90e 100644 --- a/wpilibc/src/main/native/include/frc/Servo.h +++ b/wpilibc/src/main/native/include/frc/Servo.h @@ -19,6 +19,11 @@ namespace frc { class Servo : public PWM { public: /** + * Constructor. + * + * By default, 2.4 ms is used as the max PWM value and 0.6 ms is used as the + * min PWM value. + * * @param channel The PWM channel to which the servo is attached. 0-9 are * on-board, 10-19 are on the MXP port */ diff --git a/wpilibc/src/main/native/include/frc/StadiaController.h b/wpilibc/src/main/native/include/frc/StadiaController.h new file mode 100644 index 00000000000..cc9dbae981c --- /dev/null +++ b/wpilibc/src/main/native/include/frc/StadiaController.h @@ -0,0 +1,568 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include "frc/GenericHID.h" + +namespace frc { + +/** + * Handle input from Stadia controllers connected to the Driver + * Station. + * + * This class handles Stadia input that comes from the Driver Station. Each time + * a value is requested the most recent value is returned. There is a single + * class instance for each controller and the mapping of ports to hardware + * buttons depends on the code in the Driver Station. + */ +class StadiaController : public GenericHID { + public: + /** + * Construct an instance of a Stadia controller. + * + * The controller index is the USB port on the Driver Station. + * + * @param port The port on the Driver Station that the controller is plugged + * into (0-5). + */ + explicit StadiaController(int port); + + ~StadiaController() override = default; + + StadiaController(StadiaController&&) = default; + StadiaController& operator=(StadiaController&&) = default; + + /** + * Get the X axis value of left side of the controller. + * + * @return the axis value + */ + double GetLeftX() const; + + /** + * Get the X axis value of right side of the controller. + * + * @return the axis value + */ + double GetRightX() const; + + /** + * Get the Y axis value of left side of the controller. + * + * @return the axis value + */ + double GetLeftY() const; + + /** + * Get the Y axis value of right side of the controller. + * + * @return the axis value + */ + double GetRightY() const; + + /** + * Read the value of the left bumper (LB) button on the controller. + * + * @return the state of the button + */ + bool GetLeftBumper() const; + + /** + * Read the value of the right bumper (RB) button on the controller. + * + * @return the state of the button + */ + bool GetRightBumper() const; + + /** + * Whether the left bumper (LB) was pressed since the last check. + * + * @return Whether the button was pressed since the last check + */ + bool GetLeftBumperPressed(); + + /** + * Whether the right bumper (RB) was pressed since the last check. + * + * @return Whether the button was pressed since the last check + */ + bool GetRightBumperPressed(); + + /** + * Whether the left bumper (LB) was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetLeftBumperReleased(); + + /** + * Whether the right bumper (RB) was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetRightBumperReleased(); + + /** + * Constructs an event instance around the left bumper's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the left bumper's digital signal + * attached to the given loop. + */ + BooleanEvent LeftBumper(EventLoop* loop) const; + + /** + * Constructs an event instance around the right bumper's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the right bumper's digital signal + * attached to the given loop. + */ + BooleanEvent RightBumper(EventLoop* loop) const; + + /** + * Read the value of the left stick button (LSB) on the controller. + * + * @return the state of the button + */ + bool GetLeftStickButton() const; + + /** + * Read the value of the right stick button (RSB) on the controller. + * + * @return the state of the button + */ + bool GetRightStickButton() const; + + /** + * Whether the left stick button (LSB) was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + bool GetLeftStickButtonPressed(); + + /** + * Whether the right stick button (RSB) was pressed since the last check. + * + * @return Whether the button was pressed since the last check + */ + bool GetRightStickButtonPressed(); + + /** + * Whether the left stick button (LSB) was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetLeftStickButtonReleased(); + + /** + * Whether the right stick button (RSB) was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetRightStickButtonReleased(); + + /** + * Constructs an event instance around the left stick's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the left stick's digital signal + * attached to the given loop. + */ + BooleanEvent LeftStick(EventLoop* loop) const; + + /** + * Constructs an event instance around the right stick's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the right stick's digital signal + * attached to the given loop. + */ + BooleanEvent RightStick(EventLoop* loop) const; + + /** + * Read the value of the A button on the controller. + * + * @return The state of the button. + */ + bool GetAButton() const; + + /** + * Whether the A button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + bool GetAButtonPressed(); + + /** + * Whether the A button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetAButtonReleased(); + + /** + * Constructs an event instance around the A button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the A button's digital signal + * attached to the given loop. + */ + BooleanEvent A(EventLoop* loop) const; + + /** + * Read the value of the B button on the controller. + * + * @return The state of the button. + */ + bool GetBButton() const; + + /** + * Whether the B button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + bool GetBButtonPressed(); + + /** + * Whether the B button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetBButtonReleased(); + + /** + * Constructs an event instance around the B button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the B button's digital signal + * attached to the given loop. + */ + BooleanEvent B(EventLoop* loop) const; + + /** + * Read the value of the X button on the controller. + * + * @return The state of the button. + */ + bool GetXButton() const; + + /** + * Whether the X button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + bool GetXButtonPressed(); + + /** + * Whether the X button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetXButtonReleased(); + + /** + * Constructs an event instance around the X button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the X button's digital signal + * attached to the given loop. + */ + BooleanEvent X(EventLoop* loop) const; + + /** + * Read the value of the Y button on the controller. + * + * @return The state of the button. + */ + bool GetYButton() const; + + /** + * Whether the Y button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + bool GetYButtonPressed(); + + /** + * Whether the Y button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetYButtonReleased(); + + /** + * Constructs an event instance around the Y button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the Y button's digital signal + * attached to the given loop. + */ + BooleanEvent Y(EventLoop* loop) const; + + /** + * Read the value of the ellipses button on the controller. + * + * @return The state of the button. + */ + bool GetEllipsesButton() const; + + /** + * Whether the ellipses button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + bool GetEllipsesButtonPressed(); + + /** + * Whether the ellipses button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetEllipsesButtonReleased(); + + /** + * Constructs an event instance around the ellipses button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the ellipses button's digital signal + * attached to the given loop. + */ + BooleanEvent Ellipses(EventLoop* loop) const; + + /** + * Read the value of the hamburger button on the controller. + * + * @return The state of the button. + */ + bool GetHamburgerButton() const; + + /** + * Whether the hamburger button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + bool GetHamburgerButtonPressed(); + + /** + * Whether the hamburger button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetHamburgerButtonReleased(); + + /** + * Constructs an event instance around the hamburger button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the hamburger button's digital + * signal attached to the given loop. + */ + BooleanEvent Hamburger(EventLoop* loop) const; + + /** + * Read the value of the stadia button on the controller. + * + * @return The state of the button. + */ + bool GetStadiaButton() const; + + /** + * Whether the stadia button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + bool GetStadiaButtonPressed(); + + /** + * Whether the stadia button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetStadiaButtonReleased(); + + /** + * Constructs an event instance around the stadia button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the stadia button's digital signal + * attached to the given loop. + */ + BooleanEvent Stadia(EventLoop* loop) const; + + /** + * Read the value of the google button on the controller. + * + * @return The state of the button. + */ + bool GetGoogleButton() const; + + /** + * Whether the google button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + bool GetGoogleButtonPressed(); + + /** + * Whether the google button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetGoogleButtonReleased(); + + /** + * Constructs an event instance around the google button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the google button's digital signal + * attached to the given loop. + */ + BooleanEvent Google(EventLoop* loop) const; + + /** + * Read the value of the frame button on the controller. + * + * @return The state of the button. + */ + bool GetFrameButton() const; + + /** + * Whether the frame button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + bool GetFrameButtonPressed(); + + /** + * Whether the frame button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetFrameButtonReleased(); + + /** + * Constructs an event instance around the frame button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the frame button's digital signal + * attached to the given loop. + */ + BooleanEvent Frame(EventLoop* loop) const; + + /** + * Read the value of the left trigger button on the controller. + * + * @return The state of the button. + */ + bool GetLeftTriggerButton() const; + + /** + * Whether the left trigger button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + bool GetLeftTriggerButtonPressed(); + + /** + * Whether the left trigger button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetLeftTriggerButtonReleased(); + + /** + * Constructs an event instance around the left trigger button's digital + * signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the left trigger button's digital + * signal attached to the given loop. + */ + BooleanEvent LeftTrigger(EventLoop* loop) const; + + /** + * Read the value of the right trigger button on the controller. + * + * @return The state of the button. + */ + bool GetRightTriggerButton() const; + + /** + * Whether the right trigger button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + bool GetRightTriggerButtonPressed(); + + /** + * Whether the right trigger button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + bool GetRightTriggerButtonReleased(); + + /** + * Constructs an event instance around the right trigger button's digital + * signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the right trigger button's digital + * signal attached to the given loop. + */ + BooleanEvent RightTrigger(EventLoop* loop) const; + + /** + * Represents a digital button on a StadiaController. + */ + struct Button { + /// A button. + static constexpr int kA = 1; + /// B button. + static constexpr int kB = 2; + /// X button. + static constexpr int kX = 3; + /// Y button. + static constexpr int kY = 4; + /// Left bumper button. + static constexpr int kLeftBumper = 5; + /// Right bumper button. + static constexpr int kRightBumper = 6; + /// Left stick button. + static constexpr int kLeftStick = 7; + /// Right stick button. + static constexpr int kRightStick = 8; + /// Ellipses button. + static constexpr int kEllipses = 9; + /// Hamburger button. + static constexpr int kHamburger = 10; + /// Stadia button. + static constexpr int kStadia = 11; + /// Right trigger button. + static constexpr int kRightTrigger = 12; + /// Left trigger button. + static constexpr int kLeftTrigger = 13; + /// Google button. + static constexpr int kGoogle = 14; + /// Frame button. + static constexpr int kFrame = 15; + }; + + /** + * Represents an axis on a StadiaController. + */ + struct Axis { + /// Left X axis. + static constexpr int kLeftX = 0; + /// Right X axis. + static constexpr int kRightX = 4; + /// Left Y axis. + static constexpr int kLeftY = 1; + /// Right Y axis. + static constexpr int kRightY = 5; + }; +}; + +} // namespace frc diff --git a/wpilibc/src/main/native/include/frc/SynchronousInterrupt.h b/wpilibc/src/main/native/include/frc/SynchronousInterrupt.h index fbe0fca680e..3e396e85779 100644 --- a/wpilibc/src/main/native/include/frc/SynchronousInterrupt.h +++ b/wpilibc/src/main/native/include/frc/SynchronousInterrupt.h @@ -25,9 +25,13 @@ class SynchronousInterrupt { * Event trigger combinations for a synchronous interrupt. */ enum WaitResult { + /// Timeout event. kTimeout = 0x0, + /// Rising edge event. kRisingEdge = 0x1, + /// Falling edge event. kFallingEdge = 0x100, + /// Both rising and falling edge events. kBoth = 0x101, }; diff --git a/wpilibc/src/main/native/include/frc/TimedRobot.h b/wpilibc/src/main/native/include/frc/TimedRobot.h index f32e7483cf9..dcc510af2b8 100644 --- a/wpilibc/src/main/native/include/frc/TimedRobot.h +++ b/wpilibc/src/main/native/include/frc/TimedRobot.h @@ -29,6 +29,7 @@ namespace frc { */ class TimedRobot : public IterativeRobotBase { public: + /// Default loop period. static constexpr auto kDefaultPeriod = 20_ms; /** diff --git a/wpilibc/src/main/native/include/frc/Ultrasonic.h b/wpilibc/src/main/native/include/frc/Ultrasonic.h index 137a5b75aeb..f06392c9310 100644 --- a/wpilibc/src/main/native/include/frc/Ultrasonic.h +++ b/wpilibc/src/main/native/include/frc/Ultrasonic.h @@ -90,6 +90,11 @@ class Ultrasonic : public wpi::Sendable, Ultrasonic(Ultrasonic&&) = default; Ultrasonic& operator=(Ultrasonic&&) = default; + /** + * Returns the echo channel. + * + * @return The echo channel. + */ int GetEchoChannel() const; /** diff --git a/wpilibc/src/main/native/include/frc/XboxController.h b/wpilibc/src/main/native/include/frc/XboxController.h index 3caba1ae6df..4b720c1fc72 100644 --- a/wpilibc/src/main/native/include/frc/XboxController.h +++ b/wpilibc/src/main/native/include/frc/XboxController.h @@ -16,6 +16,10 @@ namespace frc { * value is requested the most recent value is returned. There is a single class * instance for each controller and the mapping of ports to hardware buttons * depends on the code in the Driver Station. + * + * Only first party controllers from Microsoft are guaranteed to have the + * correct mapping, and only through the official NI DS. Sim is not guaranteed + * to have the same mapping, as well as any 3rd party controllers. */ class XboxController : public GenericHID { public: @@ -422,25 +426,43 @@ class XboxController : public GenericHID { */ BooleanEvent RightTrigger(EventLoop* loop) const; + /** Represents a digital button on an XboxController. */ struct Button { + /// Left bumper. static constexpr int kLeftBumper = 5; + /// Right bumper. static constexpr int kRightBumper = 6; + /// Left stick. static constexpr int kLeftStick = 9; + /// Right stick. static constexpr int kRightStick = 10; + /// A. static constexpr int kA = 1; + /// B. static constexpr int kB = 2; + /// X. static constexpr int kX = 3; + /// Y. static constexpr int kY = 4; + /// Back. static constexpr int kBack = 7; + /// Start. static constexpr int kStart = 8; }; + /** Represents an axis on an XboxController. */ struct Axis { + /// Left X. static constexpr int kLeftX = 0; + /// Right X. static constexpr int kRightX = 4; + /// Left Y. static constexpr int kLeftY = 1; + /// Right Y. static constexpr int kRightY = 5; + /// Left trigger. static constexpr int kLeftTrigger = 2; + /// Right trigger. static constexpr int kRightTrigger = 3; }; }; diff --git a/wpilibc/src/main/native/include/frc/counter/EdgeConfiguration.h b/wpilibc/src/main/native/include/frc/counter/EdgeConfiguration.h index 508117d79ff..4f5a039de2a 100644 --- a/wpilibc/src/main/native/include/frc/counter/EdgeConfiguration.h +++ b/wpilibc/src/main/native/include/frc/counter/EdgeConfiguration.h @@ -5,10 +5,17 @@ #pragma once namespace frc { +/** + * Edge configuration. + */ enum class EdgeConfiguration { + /// No edge configuration (neither rising nor falling). kNone = 0, + /// Rising edge configuration. kRisingEdge = 0x1, + /// Falling edge configuration. kFallingEdge = 0x2, + /// Both rising and falling edges configuration. kBoth = 0x3 }; } // namespace frc diff --git a/wpilibc/src/main/native/include/frc/drive/DifferentialDrive.h b/wpilibc/src/main/native/include/frc/drive/DifferentialDrive.h index 2e701a38179..2baa49effa5 100644 --- a/wpilibc/src/main/native/include/frc/drive/DifferentialDrive.h +++ b/wpilibc/src/main/native/include/frc/drive/DifferentialDrive.h @@ -4,8 +4,10 @@ #pragma once +#include #include +#include #include #include @@ -20,43 +22,9 @@ class MotorController; * the Kit of Parts drive base, "tank drive", or West Coast Drive. * * These drive bases typically have drop-center / skid-steer with two or more - * wheels per side (e.g., 6WD or 8WD). This class takes a MotorController per - * side. For four and six motor drivetrains, construct and pass in - * MotorControllerGroup instances as follows. - * - * Four motor drivetrain: - * @code{.cpp} - * class Robot { - * public: - * frc::PWMVictorSPX m_frontLeft{1}; - * frc::PWMVictorSPX m_rearLeft{2}; - * frc::MotorControllerGroup m_left{m_frontLeft, m_rearLeft}; - * - * frc::PWMVictorSPX m_frontRight{3}; - * frc::PWMVictorSPX m_rearRight{4}; - * frc::MotorControllerGroup m_right{m_frontRight, m_rearRight}; - * - * frc::DifferentialDrive m_drive{m_left, m_right}; - * }; - * @endcode - * - * Six motor drivetrain: - * @code{.cpp} - * class Robot { - * public: - * frc::PWMVictorSPX m_frontLeft{1}; - * frc::PWMVictorSPX m_midLeft{2}; - * frc::PWMVictorSPX m_rearLeft{3}; - * frc::MotorControllerGroup m_left{m_frontLeft, m_midLeft, m_rearLeft}; - * - * frc::PWMVictorSPX m_frontRight{4}; - * frc::PWMVictorSPX m_midRight{5}; - * frc::PWMVictorSPX m_rearRight{6}; - * frc::MotorControllerGroup m_right{m_frontRight, m_midRight, m_rearRight}; - * - * frc::DifferentialDrive m_drive{m_left, m_right}; - * }; - * @endcode + * wheels per side (e.g., 6WD or 8WD). This class takes a setter per side. For + * four and six motor drivetrains, use CAN motor controller followers or + * PWMMotorController::AddFollower(). * * A differential drive robot has left and right wheels separated by an * arbitrary width. @@ -97,18 +65,41 @@ class DifferentialDrive : public RobotDriveBase, * Uses normalized voltage [-1.0..1.0]. */ struct WheelSpeeds { + /// Left wheel speed. double left = 0.0; + /// Right wheel speed. double right = 0.0; }; + WPI_IGNORE_DEPRECATED + /** * Construct a DifferentialDrive. * - * To pass multiple motors per side, use a MotorControllerGroup. If a motor - * needs to be inverted, do so before passing it in. + * To pass multiple motors per side, use CAN motor controller followers or + * PWMSpeedController::AddFollower(). If a motor needs to be inverted, do so + * before passing it in. + * + * @param leftMotor Left motor. + * @param rightMotor Right motor. */ DifferentialDrive(MotorController& leftMotor, MotorController& rightMotor); + WPI_UNIGNORE_DEPRECATED + + /** + * Construct a DifferentialDrive. + * + * To pass multiple motors per side, use CAN motor controller followers or + * PWMSpeedController::AddFollower(). If a motor needs to be inverted, do so + * before passing it in. + * + * @param leftMotor Left motor setter. + * @param rightMotor Right motor setter. + */ + DifferentialDrive(std::function leftMotor, + std::function rightMotor); + ~DifferentialDrive() override = default; DifferentialDrive(DifferentialDrive&&) = default; @@ -210,8 +201,12 @@ class DifferentialDrive : public RobotDriveBase, void InitSendable(wpi::SendableBuilder& builder) override; private: - MotorController* m_leftMotor; - MotorController* m_rightMotor; + std::function m_leftMotor; + std::function m_rightMotor; + + // Used for Sendable property getters + double m_leftOutput = 0.0; + double m_rightOutput = 0.0; }; } // namespace frc diff --git a/wpilibc/src/main/native/include/frc/drive/MecanumDrive.h b/wpilibc/src/main/native/include/frc/drive/MecanumDrive.h index f4c28f423d8..6d8ebac444f 100644 --- a/wpilibc/src/main/native/include/frc/drive/MecanumDrive.h +++ b/wpilibc/src/main/native/include/frc/drive/MecanumDrive.h @@ -4,10 +4,12 @@ #pragma once +#include #include #include #include +#include #include #include @@ -63,21 +65,49 @@ class MecanumDrive : public RobotDriveBase, * Uses normalized voltage [-1.0..1.0]. */ struct WheelSpeeds { + /// Front-left wheel speed. double frontLeft = 0.0; + /// Front-right wheel speed. double frontRight = 0.0; + /// Rear-left wheel speed. double rearLeft = 0.0; + /// Rear-right wheel speed. double rearRight = 0.0; }; + WPI_IGNORE_DEPRECATED + /** * Construct a MecanumDrive. * * If a motor needs to be inverted, do so before passing it in. + * + * @param frontLeftMotor Front-left motor. + * @param rearLeftMotor Rear-left motor. + * @param frontRightMotor Front-right motor. + * @param rearRightMotor Rear-right motor. */ MecanumDrive(MotorController& frontLeftMotor, MotorController& rearLeftMotor, MotorController& frontRightMotor, MotorController& rearRightMotor); + WPI_UNIGNORE_DEPRECATED + + /** + * Construct a MecanumDrive. + * + * If a motor needs to be inverted, do so before passing it in. + * + * @param frontLeftMotor Front-left motor setter. + * @param rearLeftMotor Rear-left motor setter. + * @param frontRightMotor Front-right motor setter. + * @param rearRightMotor Rear-right motor setter. + */ + MecanumDrive(std::function frontLeftMotor, + std::function rearLeftMotor, + std::function frontRightMotor, + std::function rearRightMotor); + ~MecanumDrive() override = default; MecanumDrive(MecanumDrive&&) = default; @@ -141,10 +171,16 @@ class MecanumDrive : public RobotDriveBase, void InitSendable(wpi::SendableBuilder& builder) override; private: - MotorController* m_frontLeftMotor; - MotorController* m_rearLeftMotor; - MotorController* m_frontRightMotor; - MotorController* m_rearRightMotor; + std::function m_frontLeftMotor; + std::function m_rearLeftMotor; + std::function m_frontRightMotor; + std::function m_rearRightMotor; + + // Used for Sendable property getters + double m_frontLeftOutput = 0.0; + double m_rearLeftOutput = 0.0; + double m_frontRightOutput = 0.0; + double m_rearRightOutput = 0.0; bool reported = false; }; diff --git a/wpilibc/src/main/native/include/frc/drive/RobotDriveBase.h b/wpilibc/src/main/native/include/frc/drive/RobotDriveBase.h index b3fb56be4ba..2a746434e4e 100644 --- a/wpilibc/src/main/native/include/frc/drive/RobotDriveBase.h +++ b/wpilibc/src/main/native/include/frc/drive/RobotDriveBase.h @@ -23,12 +23,19 @@ class RobotDriveBase : public MotorSafety { * The location of a motor on the robot for the purpose of driving. */ enum MotorType { + /// Front-left motor. kFrontLeft = 0, + /// Front-right motor. kFrontRight = 1, + /// Rear-left motor. kRearLeft = 2, + /// Rear-right motor. kRearRight = 3, + /// Left motor. kLeft = 0, + /// Right motor. kRight = 1, + /// Back motor. kBack = 2 }; @@ -70,14 +77,23 @@ class RobotDriveBase : public MotorSafety { std::string GetDescription() const override = 0; protected: + /// Default input deadband. + static constexpr double kDefaultDeadband = 0.02; + + /// Default maximum output. + static constexpr double kDefaultMaxOutput = 1.0; + /** * Renormalize all wheel speeds if the magnitude of any wheel is greater than * 1.0. */ static void Desaturate(std::span wheelSpeeds); - double m_deadband = 0.02; - double m_maxOutput = 1.0; + /// Input deadband. + double m_deadband = kDefaultDeadband; + + /// Maximum output. + double m_maxOutput = kDefaultMaxOutput; }; } // namespace frc diff --git a/wpilibc/src/main/native/include/frc/event/EventLoop.h b/wpilibc/src/main/native/include/frc/event/EventLoop.h index 224dd3b545e..dca61220a5b 100644 --- a/wpilibc/src/main/native/include/frc/event/EventLoop.h +++ b/wpilibc/src/main/native/include/frc/event/EventLoop.h @@ -38,5 +38,6 @@ class EventLoop { private: std::vector> m_bindings; + bool m_running{false}; }; } // namespace frc diff --git a/wpilibc/src/main/native/include/frc/interfaces/Accelerometer.h b/wpilibc/src/main/native/include/frc/interfaces/Accelerometer.h deleted file mode 100644 index 77f1d5bc3bd..00000000000 --- a/wpilibc/src/main/native/include/frc/interfaces/Accelerometer.h +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -namespace frc { - -/** - * Interface for 3-axis accelerometers. - * - * @deprecated This interface is being removed with no replacement. - */ -class [[deprecated( - "This interface is being removed with no replacement.")]] Accelerometer { - public: - Accelerometer() = default; - virtual ~Accelerometer() = default; - - Accelerometer(Accelerometer&&) = default; - Accelerometer& operator=(Accelerometer&&) = default; - - enum Range { kRange_2G = 0, kRange_4G = 1, kRange_8G = 2, kRange_16G = 3 }; - - /** - * Common interface for setting the measuring range of an accelerometer. - * - * @param range The maximum acceleration, positive or negative, that the - * accelerometer will measure. Not all accelerometers support all - * ranges. - */ - virtual void SetRange(Range range) = 0; - - /** - * Common interface for getting the x axis acceleration. - * - * @return The acceleration along the x axis in g-forces - */ - virtual double GetX() = 0; - - /** - * Common interface for getting the y axis acceleration. - * - * @return The acceleration along the y axis in g-forces - */ - virtual double GetY() = 0; - - /** - * Common interface for getting the z axis acceleration. - * - * @return The acceleration along the z axis in g-forces - */ - virtual double GetZ() = 0; -}; - -} // namespace frc diff --git a/wpilibc/src/main/native/include/frc/interfaces/Gyro.h b/wpilibc/src/main/native/include/frc/interfaces/Gyro.h deleted file mode 100644 index 51fea7dffcc..00000000000 --- a/wpilibc/src/main/native/include/frc/interfaces/Gyro.h +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include - -#include "frc/geometry/Rotation2d.h" - -namespace frc { - -/** - * Interface for yaw rate gyros. - * - * @deprecated This interface is being removed with no replacement. - */ -class [[deprecated( - "This interface is being removed with no replacement.")]] Gyro { - public: - Gyro() = default; - virtual ~Gyro() = default; - - Gyro(Gyro&&) = default; - Gyro& operator=(Gyro&&) = default; - - /** - * Calibrate the gyro. It's important to make sure that the robot is not - * moving while the calibration is in progress, this is typically - * done when the robot is first turned on while it's sitting at rest before - * the match starts. - */ - virtual void Calibrate() = 0; - - /** - * Reset the gyro. Resets the gyro to a heading of zero. This can be used if - * there is significant drift in the gyro and it needs to be recalibrated - * after it has been running. - */ - virtual void Reset() = 0; - - /** - * Return the heading of the robot in degrees. - * - * The angle is continuous, that is it will continue from 360 to 361 degrees. - * This allows algorithms that wouldn't want to see a discontinuity in the - * gyro output as it sweeps past from 360 to 0 on the second time around. - * - * The angle is expected to increase as the gyro turns clockwise when looked - * at from the top. It needs to follow the NED axis convention. - * - * @return the current heading of the robot in degrees. This heading is based - * on integration of the returned rate from the gyro. - */ - virtual double GetAngle() const = 0; - - /** - * Return the rate of rotation of the gyro. - * - * The rate is based on the most recent reading of the gyro analog value. - * - * The rate is expected to be positive as the gyro turns clockwise when looked - * at from the top. It needs to follow the NED axis convention. - * - * @return the current rate in degrees per second - */ - virtual double GetRate() const = 0; - - /** - * Return the heading of the robot as a Rotation2d. - * - * The angle is continuous, that is it will continue from 360 to 361 degrees. - * This allows algorithms that wouldn't want to see a discontinuity in the - * gyro output as it sweeps past from 360 to 0 on the second time around. - * - * The angle is expected to increase as the gyro turns counterclockwise when - * looked at from the top. It needs to follow the NWU axis convention. - * - * @return the current heading of the robot as a Rotation2d. This heading is - * based on integration of the returned rate from the gyro. - */ - virtual Rotation2d GetRotation2d() const { - return units::degree_t{-GetAngle()}; - } -}; - -} // namespace frc diff --git a/wpilibc/src/main/native/include/frc/internal/DriverStationModeThread.h b/wpilibc/src/main/native/include/frc/internal/DriverStationModeThread.h index f4fd11ca822..e646e15b665 100644 --- a/wpilibc/src/main/native/include/frc/internal/DriverStationModeThread.h +++ b/wpilibc/src/main/native/include/frc/internal/DriverStationModeThread.h @@ -8,9 +8,16 @@ #include namespace frc::internal { +/** + * For internal use only. + */ class DriverStationModeThread { public: + /** + * For internal use only. + */ DriverStationModeThread(); + ~DriverStationModeThread(); DriverStationModeThread(const DriverStationModeThread& other) = delete; @@ -19,9 +26,39 @@ class DriverStationModeThread { delete; DriverStationModeThread& operator=(DriverStationModeThread&& other) = delete; - void InAutonomous(bool entering); + /** + * Only to be used to tell the Driver Station what code you claim to be + * executing for diagnostic purposes only. + * + * @param entering If true, starting disabled code; if false, leaving disabled + * code + */ void InDisabled(bool entering); + + /** + * Only to be used to tell the Driver Station what code you claim to be + * executing for diagnostic purposes only. + * + * @param entering If true, starting autonomous code; if false, leaving + * autonomous code + */ + void InAutonomous(bool entering); + + /** + * Only to be used to tell the Driver Station what code you claim to be + * executing for diagnostic purposes only. + * + * @param entering If true, starting teleop code; if false, leaving teleop + * code + */ void InTeleop(bool entering); + + /** + * Only to be used to tell the Driver Station what code you claim to be + * executing for diagnostic purposes only. + * + * @param entering If true, starting test code; if false, leaving test code + */ void InTest(bool entering); private: diff --git a/wpilibc/src/main/native/include/frc/livewindow/LiveWindow.h b/wpilibc/src/main/native/include/frc/livewindow/LiveWindow.h index 3714146c433..2f0a34957ab 100644 --- a/wpilibc/src/main/native/include/frc/livewindow/LiveWindow.h +++ b/wpilibc/src/main/native/include/frc/livewindow/LiveWindow.h @@ -19,14 +19,14 @@ namespace frc { class LiveWindow final { public: /** - * Set function to be called when LiveWindow is enabled. + * Sets function to be called when LiveWindow is enabled. * * @param func function (or nullptr for none) */ static void SetEnabledCallback(std::function func); /** - * Set function to be called when LiveWindow is disabled. + * Sets function to be called when LiveWindow is disabled. * * @param func function (or nullptr for none) */ @@ -56,6 +56,11 @@ class LiveWindow final { */ static void EnableAllTelemetry(); + /** + * Returns true if LiveWindow is enabled. + * + * @return True if LiveWindow is enabled. + */ static bool IsEnabled(); /** diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.h b/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.h index 99a9e4e164c..6500fb3e2f0 100644 --- a/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.h +++ b/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.h @@ -7,23 +7,42 @@ #include #include +#include #include #include #include "frc/motorcontrol/MotorController.h" +WPI_IGNORE_DEPRECATED + namespace frc { /** * Allows multiple MotorController objects to be linked together. */ -class MotorControllerGroup : public wpi::Sendable, - public MotorController, - public wpi::SendableHelper { +class [[deprecated( + "Use PWMMotorController::AddFollower() or if using CAN motor controllers," + "use their method of following.")]] MotorControllerGroup + : public wpi::Sendable, + public MotorController, + public wpi::SendableHelper { public: + /** + * Create a new MotorControllerGroup with the provided MotorControllers. + * + * @tparam MotorControllers The MotorController types. + * @param motorController The first MotorController to add + * @param motorControllers The MotorControllers to add + */ template explicit MotorControllerGroup(MotorController& motorController, MotorControllers&... motorControllers); + + /** + * Create a new MotorControllerGroup with the provided MotorControllers. + * + * @param motorControllers The MotorControllers to add. + */ explicit MotorControllerGroup( std::vector>&& motorControllers); @@ -50,3 +69,5 @@ class MotorControllerGroup : public wpi::Sendable, } // namespace frc #include "frc/motorcontrol/MotorControllerGroup.inc" + +WPI_UNIGNORE_DEPRECATED diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/NidecBrushless.h b/wpilibc/src/main/native/include/frc/motorcontrol/NidecBrushless.h index cc95d7115d3..d50c836170f 100644 --- a/wpilibc/src/main/native/include/frc/motorcontrol/NidecBrushless.h +++ b/wpilibc/src/main/native/include/frc/motorcontrol/NidecBrushless.h @@ -6,6 +6,7 @@ #include +#include #include #include @@ -16,6 +17,8 @@ namespace frc { +WPI_IGNORE_DEPRECATED + /** * Nidec Brushless Motor. */ @@ -95,4 +98,6 @@ class NidecBrushless : public MotorController, double m_speed = 0.0; }; +WPI_UNIGNORE_DEPRECATED + } // namespace frc diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/PWMMotorController.h b/wpilibc/src/main/native/include/frc/motorcontrol/PWMMotorController.h index bca5d7f64e7..54a16bbd161 100644 --- a/wpilibc/src/main/native/include/frc/motorcontrol/PWMMotorController.h +++ b/wpilibc/src/main/native/include/frc/motorcontrol/PWMMotorController.h @@ -4,9 +4,16 @@ #pragma once +#include +#include #include #include +#include +#include +#include +#include +#include #include #include @@ -17,6 +24,8 @@ namespace frc { class DMA; +WPI_IGNORE_DEPRECATED + /** * Common base class for all PWM Motor Controllers. */ @@ -40,6 +49,20 @@ class PWMMotorController : public MotorController, */ void Set(double value) override; + /** + * Sets the voltage output of the PWMMotorController. Compensates for + * the current bus voltage to ensure that the desired voltage is output even + * if the battery voltage is below 12V - highly useful when the voltage + * outputs are "meaningful" (e.g. they come from a feedforward calculation). + * + *

NOTE: This function *must* be called regularly in order for voltage + * compensation to work properly - unlike the ordinary set function, it is not + * "set it and forget it." + * + * @param output The voltage to output. + */ + void SetVoltage(units::volt_t output) override; + /** * Get the recently set value of the PWM. This value is affected by the * inversion property. If you want the value that is sent directly to the @@ -71,6 +94,24 @@ class PWMMotorController : public MotorController, */ void EnableDeadbandElimination(bool eliminateDeadband); + /** + * Make the given PWM motor controller follow the output of this one. + * + * @param follower The motor controller follower. + */ + void AddFollower(PWMMotorController& follower); + + /** + * Make the given PWM motor controller follow the output of this one. + * + * @param follower The motor controller follower. + */ + template T> + void AddFollower(T&& follower) { + m_owningFollowers.emplace_back( + std::make_unique>(std::forward(follower))); + } + protected: /** * Constructor for a PWM Motor %Controller connected via PWM. @@ -83,12 +124,17 @@ class PWMMotorController : public MotorController, void InitSendable(wpi::SendableBuilder& builder) override; + /// PWM instances for motor controller. PWM m_pwm; private: bool m_isInverted = false; + std::vector m_nonowningFollowers; + std::vector> m_owningFollowers; PWM* GetPwm() { return &m_pwm; } }; +WPI_UNIGNORE_DEPRECATED + } // namespace frc diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/PWMSparkFlex.h b/wpilibc/src/main/native/include/frc/motorcontrol/PWMSparkFlex.h new file mode 100644 index 00000000000..3106921d130 --- /dev/null +++ b/wpilibc/src/main/native/include/frc/motorcontrol/PWMSparkFlex.h @@ -0,0 +1,41 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include "frc/motorcontrol/PWMMotorController.h" + +namespace frc { + +/** + * REV Robotics SPARK Flex Motor %Controller. + * + * Note that the SPARK Flex uses the following bounds for PWM values. These + * values should work reasonably well for most controllers, but if users + * experience issues such as asymmetric behavior around the deadband or + * inability to saturate the controller in either direction, calibration is + * recommended. The calibration procedure can be found in the SPARK Flex User + * Manual available from REV Robotics. + * + * \li 2.003ms = full "forward" + * \li 1.550ms = the "high end" of the deadband range + * \li 1.500ms = center of the deadband range (off) + * \li 1.460ms = the "low end" of the deadband range + * \li 0.999ms = full "reverse" + */ +class PWMSparkFlex : public PWMMotorController { + public: + /** + * Constructor for a SPARK Flex. + * + * @param channel The PWM channel that the SPARK Flex is attached to. 0-9 are + * on-board, 10-19 are on the MXP port + */ + explicit PWMSparkFlex(int channel); + + PWMSparkFlex(PWMSparkFlex&&) = default; + PWMSparkFlex& operator=(PWMSparkFlex&&) = default; +}; + +} // namespace frc diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.h index fc159482317..8cb867388bc 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.h @@ -26,6 +26,13 @@ class ShuffleboardContainer; template class ShuffleboardComponent : public ShuffleboardComponentBase { public: + /** + * Constructs a ShuffleboardComponent. + * + * @param parent The parent container. + * @param title The component title. + * @param type The component type. + */ ShuffleboardComponent(ShuffleboardContainer& parent, std::string_view title, std::string_view type = ""); diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardEventImportance.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardEventImportance.h index 1fa9c91f3d6..ea251ec9158 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardEventImportance.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardEventImportance.h @@ -14,6 +14,11 @@ namespace frc { enum ShuffleboardEventImportance { kTrivial, kLow, kNormal, kHigh, kCritical }; +/** + * Returns name of the given enum. + * + * @return Name of the given enum. + */ inline std::string_view ShuffleboardEventImportanceName( ShuffleboardEventImportance importance) { switch (importance) { diff --git a/wpilibc/src/main/native/include/frc/simulation/ADXL345Sim.h b/wpilibc/src/main/native/include/frc/simulation/ADXL345Sim.h index af96b39e748..3cf6162a0a3 100644 --- a/wpilibc/src/main/native/include/frc/simulation/ADXL345Sim.h +++ b/wpilibc/src/main/native/include/frc/simulation/ADXL345Sim.h @@ -14,7 +14,7 @@ class ADXL345_I2C; namespace sim { /** - * Class to control a simulated ADXRS450 gyroscope. + * Class to control a simulated ADXL345. */ class ADXL345Sim { public: diff --git a/wpilibc/src/main/native/include/frc/simulation/ADXL362Sim.h b/wpilibc/src/main/native/include/frc/simulation/ADXL362Sim.h index 269732b3bfc..cc63af27843 100644 --- a/wpilibc/src/main/native/include/frc/simulation/ADXL362Sim.h +++ b/wpilibc/src/main/native/include/frc/simulation/ADXL362Sim.h @@ -13,7 +13,7 @@ class ADXL362; namespace sim { /** - * Class to control a simulated ADXRS450 gyroscope. + * Class to control a simulated ADXL362. */ class ADXL362Sim { public: diff --git a/wpilibc/src/main/native/include/frc/simulation/DCMotorSim.h b/wpilibc/src/main/native/include/frc/simulation/DCMotorSim.h index be3a3259c50..c8019a36f9d 100644 --- a/wpilibc/src/main/native/include/frc/simulation/DCMotorSim.h +++ b/wpilibc/src/main/native/include/frc/simulation/DCMotorSim.h @@ -78,7 +78,7 @@ class DCMotorSim : public LinearSystemSim<2, 1, 2> { * * @return The DC motor current draw. */ - units::ampere_t GetCurrentDraw() const override; + units::ampere_t GetCurrentDraw() const; /** * Sets the input voltage for the DC motor. diff --git a/wpilibc/src/main/native/include/frc/simulation/DifferentialDrivetrainSim.h b/wpilibc/src/main/native/include/frc/simulation/DifferentialDrivetrainSim.h index 78310d78c74..644e348afd8 100644 --- a/wpilibc/src/main/native/include/frc/simulation/DifferentialDrivetrainSim.h +++ b/wpilibc/src/main/native/include/frc/simulation/DifferentialDrivetrainSim.h @@ -187,6 +187,13 @@ class DifferentialDrivetrainSim { */ void SetPose(const frc::Pose2d& pose); + /** + * The differential drive dynamics function. + * + * @param x The state. + * @param u The input. + * @return The state derivative with respect to time. + */ Vectord<7> Dynamics(const Vectord<7>& x, const Eigen::Vector2d& u); class State { @@ -210,32 +217,54 @@ class DifferentialDrivetrainSim { */ class KitbotGearing { public: + /// Gear ratio of 12.75:1. static constexpr double k12p75 = 12.75; + /// Gear ratio of 10.71:1. static constexpr double k10p71 = 10.71; + /// Gear ratio of 8.45:1. static constexpr double k8p45 = 8.45; + /// Gear ratio of 7.31:1. static constexpr double k7p31 = 7.31; + /// Gear ratio of 5.95:1. static constexpr double k5p95 = 5.95; }; + /** + * Represents common motor layouts of the kit drivetrain. + */ class KitbotMotor { public: + /// One CIM motor per drive side. static constexpr frc::DCMotor SingleCIMPerSide = frc::DCMotor::CIM(1); + /// Two CIM motors per drive side. static constexpr frc::DCMotor DualCIMPerSide = frc::DCMotor::CIM(2); + /// One Mini CIM motor per drive side. static constexpr frc::DCMotor SingleMiniCIMPerSide = frc::DCMotor::MiniCIM(1); + /// Two Mini CIM motors per drive side. static constexpr frc::DCMotor DualMiniCIMPerSide = frc::DCMotor::MiniCIM(2); + /// One Falcon 500 motor per drive side. static constexpr frc::DCMotor SingleFalcon500PerSide = frc::DCMotor::Falcon500(1); + /// Two Falcon 500 motors per drive side. static constexpr frc::DCMotor DualFalcon500PerSide = frc::DCMotor::Falcon500(2); + /// One NEO motor per drive side. static constexpr frc::DCMotor SingleNEOPerSide = frc::DCMotor::NEO(1); + /// Two NEO motors per drive side. static constexpr frc::DCMotor DualNEOPerSide = frc::DCMotor::NEO(2); }; + /** + * Represents common wheel sizes of the kit drivetrain. + */ class KitbotWheelSize { public: + /// Six inch diameter wheels. static constexpr units::meter_t kSixInch = 6_in; + /// Eight inch diameter wheels. static constexpr units::meter_t kEightInch = 8_in; + /// Ten inch diameter wheels. static constexpr units::meter_t kTenInch = 10_in; }; diff --git a/wpilibc/src/main/native/include/frc/simulation/ElevatorSim.h b/wpilibc/src/main/native/include/frc/simulation/ElevatorSim.h index 3d5c43398e5..03cc070ceeb 100644 --- a/wpilibc/src/main/native/include/frc/simulation/ElevatorSim.h +++ b/wpilibc/src/main/native/include/frc/simulation/ElevatorSim.h @@ -17,7 +17,7 @@ namespace frc::sim { /** * Represents a simulated elevator mechanism. */ -class ElevatorSim : public LinearSystemSim<2, 1, 1> { +class ElevatorSim : public LinearSystemSim<2, 1, 2> { public: template using Velocity_t = units::unit_t< @@ -42,10 +42,10 @@ class ElevatorSim : public LinearSystemSim<2, 1, 1> { * @param startingHeight The starting height of the elevator. * @param measurementStdDevs The standard deviation of the measurements. */ - ElevatorSim(const LinearSystem<2, 1, 1>& plant, const DCMotor& gearbox, + ElevatorSim(const LinearSystem<2, 1, 2>& plant, const DCMotor& gearbox, units::meter_t minHeight, units::meter_t maxHeight, bool simulateGravity, units::meter_t startingHeight, - const std::array& measurementStdDevs = {0.0}); + const std::array& measurementStdDevs = {0.0, 0.0}); /** * Constructs a simulated elevator mechanism. @@ -67,7 +67,7 @@ class ElevatorSim : public LinearSystemSim<2, 1, 1> { units::kilogram_t carriageMass, units::meter_t drumRadius, units::meter_t minHeight, units::meter_t maxHeight, bool simulateGravity, units::meter_t startingHeight, - const std::array& measurementStdDevs = {0.0}); + const std::array& measurementStdDevs = {0.0, 0.0}); /** * Constructs a simulated elevator mechanism. @@ -90,7 +90,7 @@ class ElevatorSim : public LinearSystemSim<2, 1, 1> { const DCMotor& gearbox, units::meter_t minHeight, units::meter_t maxHeight, bool simulateGravity, units::meter_t startingHeight, - const std::array& measurementStdDevs = {0.0}); + const std::array& measurementStdDevs = {0.0, 0.0}); using LinearSystemSim::SetState; /** @@ -150,7 +150,7 @@ class ElevatorSim : public LinearSystemSim<2, 1, 1> { * * @return The elevator current draw. */ - units::ampere_t GetCurrentDraw() const override; + units::ampere_t GetCurrentDraw() const; /** * Sets the input voltage for the elevator. diff --git a/wpilibc/src/main/native/include/frc/simulation/FlywheelSim.h b/wpilibc/src/main/native/include/frc/simulation/FlywheelSim.h index cc0eca9ae09..32c8aa3311e 100644 --- a/wpilibc/src/main/native/include/frc/simulation/FlywheelSim.h +++ b/wpilibc/src/main/native/include/frc/simulation/FlywheelSim.h @@ -68,7 +68,7 @@ class FlywheelSim : public LinearSystemSim<1, 1, 1> { * * @return The flywheel current draw. */ - units::ampere_t GetCurrentDraw() const override; + units::ampere_t GetCurrentDraw() const; /** * Sets the input voltage for the flywheel. diff --git a/wpilibc/src/main/native/include/frc/simulation/GenericHIDSim.h b/wpilibc/src/main/native/include/frc/simulation/GenericHIDSim.h index 399e0c16d16..ba56c4d106a 100644 --- a/wpilibc/src/main/native/include/frc/simulation/GenericHIDSim.h +++ b/wpilibc/src/main/native/include/frc/simulation/GenericHIDSim.h @@ -136,6 +136,7 @@ class GenericHIDSim { double GetRumble(GenericHID::RumbleType type); protected: + /// GenericHID port. int m_port; }; diff --git a/wpilibc/src/main/native/include/frc/simulation/LinearSystemSim.h b/wpilibc/src/main/native/include/frc/simulation/LinearSystemSim.h index cfc87b29499..86854353948 100644 --- a/wpilibc/src/main/native/include/frc/simulation/LinearSystemSim.h +++ b/wpilibc/src/main/native/include/frc/simulation/LinearSystemSim.h @@ -23,9 +23,9 @@ namespace frc::sim { * voltage). Call the Update() method to update the simulation. Set simulated * sensor readings with the simulated positions in the GetOutput() method. * - * @tparam States The number of states of the system. - * @tparam Inputs The number of inputs to the system. - * @tparam Outputs The number of outputs of the system. + * @tparam States Number of states of the system. + * @tparam Inputs Number of inputs to the system. + * @tparam Outputs Number of outputs of the system. */ template class LinearSystemSim { @@ -86,33 +86,37 @@ class LinearSystemSim { * * @param u The system inputs. */ - void SetInput(const Vectord& u) { m_u = ClampInput(u); } + void SetInput(const Vectord& u) { m_u = u; } - /* + /** * Sets the system inputs. * * @param row The row in the input matrix to set. * @param value The value to set the row to. */ - void SetInput(int row, double value) { - m_u(row, 0) = value; - ClampInput(m_u); - } + void SetInput(int row, double value) { m_u(row, 0) = value; } /** - * Sets the system state. + * Returns the current input of the plant. * - * @param state The new state. + * @return The current input of the plant. */ - void SetState(const Vectord& state) { m_x = state; } + const Vectord& GetInput() const { return m_u; } + + /** + * Returns an element of the current input of the plant. + * + * @param row The row to return. + * @return An element of the current input of the plant. + */ + double GetInput(int row) const { return m_u(row); } /** - * Returns the current drawn by this simulated system. Override this method to - * add a custom current calculation. + * Sets the system state. * - * @return The current drawn by this simulated mechanism. + * @param state The new state. */ - virtual units::ampere_t GetCurrentDraw() const { return 0_A; } + void SetState(const Vectord& state) { m_x = state; } protected: /** @@ -132,19 +136,26 @@ class LinearSystemSim { * Clamp the input vector such that no element exceeds the given voltage. If * any does, the relative magnitudes of the input will be maintained. * - * @param u The input vector. - * @return The normalized input. + * @param maxInput The maximum magnitude of the input vector after clamping. */ - Vectord ClampInput(Vectord u) { - return frc::DesaturateInputVector( - u, frc::RobotController::GetInputVoltage()); + void ClampInput(double maxInput) { + m_u = frc::DesaturateInputVector(m_u, maxInput); } + /// The plant that represents the linear system. LinearSystem m_plant; + /// State vector. Vectord m_x; - Vectord m_y; + + /// Input vector. Vectord m_u; + + /// Output vector. + Vectord m_y; + + /// The standard deviations of measurements, used for adding noise to the + /// measurements. std::array m_measurementStdDevs; }; } // namespace frc::sim diff --git a/wpilibc/src/main/native/include/frc/simulation/PneumaticsBaseSim.h b/wpilibc/src/main/native/include/frc/simulation/PneumaticsBaseSim.h index 510349f7695..f3000f4a3ed 100644 --- a/wpilibc/src/main/native/include/frc/simulation/PneumaticsBaseSim.h +++ b/wpilibc/src/main/native/include/frc/simulation/PneumaticsBaseSim.h @@ -177,9 +177,22 @@ class PneumaticsBaseSim { virtual void ResetData() = 0; protected: + /// PneumaticsBase index. const int m_index; - explicit PneumaticsBaseSim(const PneumaticsBase& module); + + /** + * Constructs a PneumaticsBaseSim with the given index. + * + * @param index The index. + */ explicit PneumaticsBaseSim(const int index); + + /** + * Constructs a PneumaticsBaseSim for the given module. + * + * @param module The module. + */ + explicit PneumaticsBaseSim(const PneumaticsBase& module); }; } // namespace frc::sim diff --git a/wpilibc/src/main/native/include/frc/simulation/RoboRioSim.h b/wpilibc/src/main/native/include/frc/simulation/RoboRioSim.h index 64e81e18397..64713473a9a 100644 --- a/wpilibc/src/main/native/include/frc/simulation/RoboRioSim.h +++ b/wpilibc/src/main/native/include/frc/simulation/RoboRioSim.h @@ -11,6 +11,7 @@ #include #include +#include "frc/RobotController.h" #include "frc/simulation/CallbackStore.h" namespace frc::sim { @@ -514,6 +515,32 @@ class RoboRioSim { */ static void SetComments(std::string_view comments); + /** + * Register a callback to be run whenever the Radio led state changes. + * + * @param callback the callback + * @param initialNotify whether the callback should be called with the + * initial value + * @return the CallbackStore object associated with this callback + */ + [[nodiscard]] + static std::unique_ptr RegisterRadioLEDStateCallback( + NotifyCallback callback, bool initialNotify); + + /** + * Get the state of the radio led. + * + * @return The state of the radio led. + */ + static RadioLEDState GetRadioLEDState(); + + /** + * Set the state of the radio led. + * + * @param state The state of the radio led. + */ + static void SetRadioLEDState(RadioLEDState state); + /** * Reset all simulation data. */ diff --git a/wpilibc/src/main/native/include/frc/simulation/SingleJointedArmSim.h b/wpilibc/src/main/native/include/frc/simulation/SingleJointedArmSim.h index 12a719b55ee..36924f8d0f1 100644 --- a/wpilibc/src/main/native/include/frc/simulation/SingleJointedArmSim.h +++ b/wpilibc/src/main/native/include/frc/simulation/SingleJointedArmSim.h @@ -18,7 +18,7 @@ namespace frc::sim { /** * Represents a simulated arm mechanism. */ -class SingleJointedArmSim : public LinearSystemSim<2, 1, 1> { +class SingleJointedArmSim : public LinearSystemSim<2, 1, 2> { public: /** * Creates a simulated arm mechanism. @@ -36,12 +36,13 @@ class SingleJointedArmSim : public LinearSystemSim<2, 1, 1> { * @param startingAngle The initial position of the arm. * @param measurementStdDevs The standard deviations of the measurements. */ - SingleJointedArmSim(const LinearSystem<2, 1, 1>& system, + SingleJointedArmSim(const LinearSystem<2, 1, 2>& system, const DCMotor& gearbox, double gearing, units::meter_t armLength, units::radian_t minAngle, units::radian_t maxAngle, bool simulateGravity, units::radian_t startingAngle, - const std::array& measurementStdDevs = {0.0}); + const std::array& measurementStdDevs = {0.0, + 0.0}); /** * Creates a simulated arm mechanism. * @@ -62,7 +63,8 @@ class SingleJointedArmSim : public LinearSystemSim<2, 1, 1> { units::meter_t armLength, units::radian_t minAngle, units::radian_t maxAngle, bool simulateGravity, units::radian_t startingAngle, - const std::array& measurementStdDevs = {0.0}); + const std::array& measurementStdDevs = {0.0, + 0.0}); using LinearSystemSim::SetState; @@ -124,7 +126,7 @@ class SingleJointedArmSim : public LinearSystemSim<2, 1, 1> { * * @return The arm current draw. */ - units::ampere_t GetCurrentDraw() const override; + units::ampere_t GetCurrentDraw() const; /** * Sets the input voltage for the arm. diff --git a/wpilibc/src/main/native/include/frc/simulation/UltrasonicSim.h b/wpilibc/src/main/native/include/frc/simulation/UltrasonicSim.h index 5db41f7f4d3..0d22d87df5b 100644 --- a/wpilibc/src/main/native/include/frc/simulation/UltrasonicSim.h +++ b/wpilibc/src/main/native/include/frc/simulation/UltrasonicSim.h @@ -36,14 +36,14 @@ class UltrasonicSim { /** * Sets if the range measurement is valid. * - * @param isValid True if valid + * @param valid True if valid */ - void SetRangeValid(bool isValid); + void SetRangeValid(bool valid); /** - * Sets the range measurement + * Sets the range measurement. * - * @param range The range + * @param range The range. */ void SetRange(units::inch_t range); diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/FieldObject2d.h b/wpilibc/src/main/native/include/frc/smartdashboard/FieldObject2d.h index f55938e8df0..cf5d7d4ccc2 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/FieldObject2d.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/FieldObject2d.h @@ -8,7 +8,6 @@ #include #include #include -#include #include #include diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h index baee6ffaa45..2051d1b5d59 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h @@ -21,6 +21,9 @@ namespace frc { +/** + * Implementation detail for SendableBuilder. + */ class SendableBuilderImpl : public nt::NTSendableBuilder { public: SendableBuilderImpl() = default; diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h index f06c2524db6..0c17fdefe96 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h @@ -36,13 +36,12 @@ class SendableChooser : public SendableChooserBase { template static U _unwrap_smart_ptr(const U& value); - template - static U* _unwrap_smart_ptr(const std::unique_ptr& value); - template static std::weak_ptr _unwrap_smart_ptr(const std::shared_ptr& value); public: + using CopyType = decltype(_unwrap_smart_ptr(m_choices.lookup(""))); + SendableChooser() = default; ~SendableChooser() override = default; SendableChooser(SendableChooser&& rhs) = default; @@ -71,8 +70,8 @@ class SendableChooser : public SendableChooserBase { void SetDefaultOption(std::string_view name, T object); /** - * Returns a copy of the selected option (a raw pointer U* if T = - * std::unique_ptr or a std::weak_ptr if T = std::shared_ptr). + * Returns a copy of the selected option (a std::weak_ptr if T = + * std::shared_ptr). * * If there is none selected, it will return the default. If there is none * selected and no default, then it will return a value-initialized instance. @@ -81,7 +80,7 @@ class SendableChooser : public SendableChooserBase { * * @return The option selected */ - auto GetSelected() -> decltype(_unwrap_smart_ptr(m_choices[""])); + CopyType GetSelected() const; /** * Bind a listener that's called when the selected value changes. diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc index e40befdb74b..2b93629959c 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc @@ -33,8 +33,7 @@ void SendableChooser::SetDefaultOption(std::string_view name, T object) { template requires std::copy_constructible && std::default_initializable -auto SendableChooser::GetSelected() - -> decltype(_unwrap_smart_ptr(m_choices[""])) { +typename SendableChooser::CopyType SendableChooser::GetSelected() const { std::string selected = m_defaultChoice; { std::scoped_lock lock(m_mutex); @@ -43,9 +42,9 @@ auto SendableChooser::GetSelected() } } if (selected.empty()) { - return decltype(_unwrap_smart_ptr(m_choices[""])){}; + return CopyType{}; } else { - return _unwrap_smart_ptr(m_choices[selected]); + return _unwrap_smart_ptr(m_choices.lookup(selected)); } } @@ -121,13 +120,6 @@ U SendableChooser::_unwrap_smart_ptr(const U& value) { return value; } -template - requires std::copy_constructible && std::default_initializable -template -U* SendableChooser::_unwrap_smart_ptr(const std::unique_ptr& value) { - return value.get(); -} - template requires std::copy_constructible && std::default_initializable template diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooserBase.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooserBase.h index f0b4fedcbb0..3263f92f6b8 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooserBase.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooserBase.h @@ -38,7 +38,7 @@ class SendableChooserBase : public wpi::Sendable, std::string m_defaultChoice; std::string m_selected; bool m_haveSelected = false; - wpi::mutex m_mutex; + mutable wpi::mutex m_mutex; int m_instance; std::string m_previousVal; static std::atomic_int s_instances; diff --git a/wpilibc/src/main/native/include/frc/sysid/SysIdRoutineLog.h b/wpilibc/src/main/native/include/frc/sysid/SysIdRoutineLog.h new file mode 100644 index 00000000000..5e727169068 --- /dev/null +++ b/wpilibc/src/main/native/include/frc/sysid/SysIdRoutineLog.h @@ -0,0 +1,200 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace frc::sysid { + +/** + * Possible state of a SysId routine. + */ +enum class State { + /// Quasistatic forward test. + kQuasistaticForward, + /// Quasistatic reverse test. + kQuasistaticReverse, + /// Dynamic forward test. + kDynamicForward, + /// Dynamic reverse test. + kDynamicReverse, + /// No test. + kNone +}; + +/** + * Utility for logging data from a SysId test routine. Each complete routine + * (quasistatic and dynamic, forward and reverse) should have its own + * SysIdRoutineLog instance, with a unique log name. + */ +class SysIdRoutineLog { + using MotorEntries = wpi::StringMap; + using LogEntries = wpi::StringMap; + + public: + /** Logs data from a single motor during a SysIdRoutine. */ + class MotorLog { + public: + /** + * Log a generic data value from the motor. + * + * @param name The name of the data field being recorded. + * @param value The numeric value of the data field. + * @param unit The unit string of the data field. + * @return The motor log (for call chaining). + */ + MotorLog& value(std::string_view name, double value, std::string_view unit); + + /** + * Log the voltage applied to the motor. + * + * @param voltage The voltage to record. + * @return The motor log (for call chaining). + */ + MotorLog& voltage(units::volt_t voltage) { + return value("voltage", voltage.value(), voltage.name()); + } + + /** + * Log the linear position of the motor. + * + * @param position The linear position to record. + * @return The motor log (for call chaining). + */ + MotorLog& position(units::meter_t position) { + return value("position", position.value(), position.name()); + } + + /** + * Log the angular position of the motor. + * + * @param position The angular position to record. + * @return The motor log (for call chaining). + */ + MotorLog& position(units::turn_t position) { + return value("position", position.value(), position.name()); + } + + /** + * Log the linear velocity of the motor. + * + * @param velocity The linear velocity to record. + * @return The motor log (for call chaining). + */ + MotorLog& velocity(units::meters_per_second_t velocity) { + return value("velocity", velocity.value(), velocity.name()); + } + + /** + * Log the angular velocity of the motor. + * + * @param velocity The angular velocity to record. + * @return The motor log (for call chaining). + */ + MotorLog& velocity(units::turns_per_second_t velocity) { + return value("velocity", velocity.value(), velocity.name()); + } + + /** + * Log the linear acceleration of the motor. + * + * This is optional; SysId can perform an accurate fit without it. + * + * @param acceleration The linear acceleration to record. + * @return The motor log (for call chaining). + */ + MotorLog& acceleration(units::meters_per_second_squared_t acceleration) { + return value("acceleration", acceleration.value(), acceleration.name()); + } + + /** + * Log the angular acceleration of the motor. + * + * This is optional; SysId can perform an accurate fit without it. + * + * @param acceleration The angular acceleration to record. + * @return The motor log (for call chaining). + */ + MotorLog& acceleration(units::turns_per_second_squared_t acceleration) { + return value("acceleration", acceleration.value(), acceleration.name()); + } + + /** + * Log the current applied to the motor. + * + * This is optional; SysId can perform an accurate fit without it. + * + * @param current The current to record. + * @return The motor log (for call chaining). + */ + MotorLog& current(units::ampere_t current) { + return value("current", current.value(), current.name()); + } + + private: + friend class SysIdRoutineLog; + /** + * Create a new SysId motor log handle. + * + * @param motorName The name of the motor whose data is being logged. + * @param logName The name of the SysIdRoutineLog that this motor belongs + * to. + * @param logEntries The DataLog entries of the SysIdRoutineLog that this + * motor belongs to. + */ + MotorLog(std::string_view motorName, std::string_view logName, + LogEntries* logEntries); + std::string m_motorName; + std::string m_logName; + LogEntries* m_logEntries; + }; + + /** + * Create a new logging utility for a SysId test routine. + * + * @param logName The name for the test routine in the log. Should be unique + * between complete test routines (quasistatic and dynamic, forward and + * reverse). The current state of this test (e.g. "quasistatic-forward") + * will appear in WPILog under the "sysid-test-state-logName" entry. + */ + explicit SysIdRoutineLog(std::string_view logName); + + /** + * Records the current state of the SysId test routine. Should be called once + * per iteration during tests with the type of the current test, and once upon + * test end with state `none`. + * + * @param state The current state of the SysId test routine. + */ + void RecordState(State state); + + /** + * Log data from a motor during a SysId routine. + * + * @param motorName The name of the motor. + * @return Handle with chainable callbacks to log individual data fields. + */ + MotorLog Motor(std::string_view motorName); + + static std::string StateEnumToString(State state); + + private: + LogEntries m_logEntries; + std::string m_logName; + bool m_stateInitialized = false; + wpi::log::StringLogEntry m_state; +}; +} // namespace frc::sysid diff --git a/wpilibc/src/main/native/include/frc/util/Color.h b/wpilibc/src/main/native/include/frc/util/Color.h index 87d8c12f497..f51d3b12b75 100644 --- a/wpilibc/src/main/native/include/frc/util/Color.h +++ b/wpilibc/src/main/native/include/frc/util/Color.h @@ -5,7 +5,14 @@ #pragma once #include +#include #include +#include + +#include +#include +#include +#include namespace frc { @@ -739,6 +746,9 @@ class Color { */ static const Color kYellowGreen; + /** + * Constructs a default color (black). + */ constexpr Color() = default; /** @@ -763,6 +773,33 @@ class Color { constexpr Color(int r, int g, int b) : Color(r / 255.0, g / 255.0, b / 255.0) {} + /** + * Constructs a Color from a hex string. + * + * @param hexString a string of the format \#RRGGBB + * @throws std::invalid_argument if the hex string is invalid. + */ + explicit constexpr Color(std::string_view hexString) { + if (hexString.length() != 7 || !hexString.starts_with("#") || + !wpi::isHexDigit(hexString[1]) || !wpi::isHexDigit(hexString[2]) || + !wpi::isHexDigit(hexString[3]) || !wpi::isHexDigit(hexString[4]) || + !wpi::isHexDigit(hexString[5]) || !wpi::isHexDigit(hexString[6])) { + throw std::invalid_argument( + fmt::format("Invalid hex string for Color \"{}\"", hexString)); + } + + int r = wpi::hexDigitValue(hexString[1]) * 16 + + wpi::hexDigitValue(hexString[2]); + int g = wpi::hexDigitValue(hexString[3]) * 16 + + wpi::hexDigitValue(hexString[4]); + int b = wpi::hexDigitValue(hexString[5]) * 16 + + wpi::hexDigitValue(hexString[6]); + + red = r / 255.0; + green = g / 255.0; + blue = b / 255.0; + } + constexpr bool operator==(const Color&) const = default; /** @@ -816,19 +853,29 @@ class Color { * * @return a string of the format \#RRGGBB */ - std::string HexString() const; + constexpr auto HexString() const { + const int r = 255.0 * red; + const int g = 255.0 * green; + const int b = 255.0 * blue; + + return wpi::ct_string, 7>{ + {'#', wpi::hexdigit(r / 16), wpi::hexdigit(r % 16), + wpi::hexdigit(g / 16), wpi::hexdigit(g % 16), wpi::hexdigit(b / 16), + wpi::hexdigit(b % 16)}}; + } + /// Red component (0-1). double red = 0.0; + + /// Green component (0-1). double green = 0.0; + + /// Blue component (0-1). double blue = 0.0; private: - static constexpr double kPrecision = 1.0 / (1 << 12); - static constexpr double roundAndClamp(double value) { - const auto rounded = - (static_cast(value / kPrecision) + 0.5) * kPrecision; - return std::clamp(rounded, 0.0, 1.0); + return std::clamp(gcem::ceil(value * (1 << 12)) / (1 << 12), 0.0, 1.0); } }; diff --git a/wpilibc/src/main/native/include/frc/util/Color8Bit.h b/wpilibc/src/main/native/include/frc/util/Color8Bit.h index 10afead93dc..f4bc10406e9 100644 --- a/wpilibc/src/main/native/include/frc/util/Color8Bit.h +++ b/wpilibc/src/main/native/include/frc/util/Color8Bit.h @@ -5,7 +5,13 @@ #pragma once #include +#include #include +#include + +#include +#include +#include #include "Color.h" @@ -16,6 +22,9 @@ namespace frc { */ class Color8Bit { public: + /** + * Constructs a default color (black). + */ constexpr Color8Bit() = default; /** @@ -40,21 +49,79 @@ class Color8Bit { green(color.green * 255), blue(color.blue * 255) {} + /** + * Constructs a Color8Bit from a hex string. + * + * @param hexString a string of the format \#RRGGBB + * @throws std::invalid_argument if the hex string is invalid. + */ + explicit constexpr Color8Bit(std::string_view hexString) { + if (hexString.length() != 7 || !hexString.starts_with("#") || + !wpi::isHexDigit(hexString[1]) || !wpi::isHexDigit(hexString[2]) || + !wpi::isHexDigit(hexString[3]) || !wpi::isHexDigit(hexString[4]) || + !wpi::isHexDigit(hexString[5]) || !wpi::isHexDigit(hexString[6])) { + throw std::invalid_argument( + fmt::format("Invalid hex string for Color \"{}\"", hexString)); + } + + red = wpi::hexDigitValue(hexString[1]) * 16 + + wpi::hexDigitValue(hexString[2]); + green = wpi::hexDigitValue(hexString[3]) * 16 + + wpi::hexDigitValue(hexString[4]); + blue = wpi::hexDigitValue(hexString[5]) * 16 + + wpi::hexDigitValue(hexString[6]); + } + + constexpr bool operator==(const Color8Bit&) const = default; + constexpr operator Color() const { // NOLINT return Color(red / 255.0, green / 255.0, blue / 255.0); } - constexpr bool operator==(const Color8Bit&) const = default; + /** + * Create a Color8Bit from a hex string. + * + * @param hexString a string of the format \#RRGGBB + * @return Color8Bit object from hex string. + * @throws std::invalid_argument if the hex string is invalid. + */ + static constexpr Color8Bit FromHexString(std::string_view hexString) { + if (hexString.length() != 7 || !hexString.starts_with("#") || + !wpi::isHexDigit(hexString[1]) || !wpi::isHexDigit(hexString[2]) || + !wpi::isHexDigit(hexString[3]) || !wpi::isHexDigit(hexString[4]) || + !wpi::isHexDigit(hexString[5]) || !wpi::isHexDigit(hexString[6])) { + throw std::invalid_argument( + fmt::format("Invalid hex string for Color \"{}\"", hexString)); + } + + int r = wpi::hexDigitValue(hexString[0]) * 16 + + wpi::hexDigitValue(hexString[1]); + int g = wpi::hexDigitValue(hexString[2]) * 16 + + wpi::hexDigitValue(hexString[3]); + int b = wpi::hexDigitValue(hexString[4]) * 16 + + wpi::hexDigitValue(hexString[5]); + return Color8Bit{r, g, b}; + } /** * Return this color represented as a hex string. * * @return a string of the format \#RRGGBB */ - std::string HexString() const; + constexpr auto HexString() const { + return wpi::ct_string, 7>{ + {'#', wpi::hexdigit(red / 16), wpi::hexdigit(red % 16), + wpi::hexdigit(green / 16), wpi::hexdigit(green % 16), + wpi::hexdigit(blue / 16), wpi::hexdigit(blue % 16)}}; + } + /// Red component (0-255). int red = 0; + + /// Green component (0-255). int green = 0; + + /// Blue component (0-255). int blue = 0; }; diff --git a/wpilibc/src/test/native/cpp/GenericHIDTest.cpp b/wpilibc/src/test/native/cpp/GenericHIDTest.cpp new file mode 100644 index 00000000000..0d5d6a6304d --- /dev/null +++ b/wpilibc/src/test/native/cpp/GenericHIDTest.cpp @@ -0,0 +1,50 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include +#include + +#include + +using namespace frc; +using RumbleType = GenericHID::RumbleType; +static constexpr double kEpsilon = 0.0001; +TEST(GenericHIDTest, RumbleRange) { + GenericHID hid{0}; + sim::GenericHIDSim sim{0}; + + for (int i = 0; i <= 100; i++) { + double rumbleValue = i / 100.0; + hid.SetRumble(RumbleType::kBothRumble, rumbleValue); + EXPECT_NEAR(rumbleValue, sim.GetRumble(RumbleType::kLeftRumble), kEpsilon); + EXPECT_NEAR(rumbleValue, sim.GetRumble(RumbleType::kRightRumble), kEpsilon); + } +} + +TEST(GenericHIDTest, RumbleTypes) { + GenericHID hid{0}; + sim::GenericHIDSim sim{0}; + + // Make sure both are off + hid.SetRumble(RumbleType::kBothRumble, 0); + EXPECT_NEAR(0, sim.GetRumble(RumbleType::kBothRumble), kEpsilon); + + // test both + hid.SetRumble(RumbleType::kBothRumble, 1); + EXPECT_NEAR(1, sim.GetRumble(RumbleType::kLeftRumble), kEpsilon); + EXPECT_NEAR(1, sim.GetRumble(RumbleType::kRightRumble), kEpsilon); + hid.SetRumble(RumbleType::kBothRumble, 0); + + // test left only + hid.SetRumble(RumbleType::kLeftRumble, 1); + EXPECT_NEAR(1, sim.GetRumble(RumbleType::kLeftRumble), kEpsilon); + EXPECT_NEAR(0, sim.GetRumble(RumbleType::kRightRumble), kEpsilon); + hid.SetRumble(RumbleType::kLeftRumble, 0); + + // test right only + hid.SetRumble(RumbleType::kRightRumble, 1); + EXPECT_NEAR(0, sim.GetRumble(RumbleType::kLeftRumble), kEpsilon); + EXPECT_NEAR(1, sim.GetRumble(RumbleType::kRightRumble), kEpsilon); + hid.SetRumble(RumbleType::kRightRumble, 0); +} diff --git a/wpilibc/src/test/native/cpp/drive/DifferentialDriveTest.cpp b/wpilibc/src/test/native/cpp/drive/DifferentialDriveTest.cpp index f21f268f25b..9a22987ee02 100644 --- a/wpilibc/src/test/native/cpp/drive/DifferentialDriveTest.cpp +++ b/wpilibc/src/test/native/cpp/drive/DifferentialDriveTest.cpp @@ -5,7 +5,7 @@ #include #include "frc/drive/DifferentialDrive.h" -#include "motorcontrol/MockMotorController.h" +#include "motorcontrol/MockPWMMotorController.h" TEST(DifferentialDriveTest, ArcadeDriveIK) { // Forward @@ -240,9 +240,10 @@ TEST(DifferentialDriveTest, TankDriveIKSquared) { } TEST(DifferentialDriveTest, ArcadeDrive) { - frc::MockMotorController left; - frc::MockMotorController right; - frc::DifferentialDrive drive{left, right}; + frc::MockPWMMotorController left; + frc::MockPWMMotorController right; + frc::DifferentialDrive drive{[&](double output) { left.Set(output); }, + [&](double output) { right.Set(output); }}; drive.SetDeadband(0.0); // Forward @@ -277,9 +278,10 @@ TEST(DifferentialDriveTest, ArcadeDrive) { } TEST(DifferentialDriveTest, ArcadeDriveSquared) { - frc::MockMotorController left; - frc::MockMotorController right; - frc::DifferentialDrive drive{left, right}; + frc::MockPWMMotorController left; + frc::MockPWMMotorController right; + frc::DifferentialDrive drive{[&](double output) { left.Set(output); }, + [&](double output) { right.Set(output); }}; drive.SetDeadband(0.0); // Forward @@ -314,9 +316,10 @@ TEST(DifferentialDriveTest, ArcadeDriveSquared) { } TEST(DifferentialDriveTest, CurvatureDrive) { - frc::MockMotorController left; - frc::MockMotorController right; - frc::DifferentialDrive drive{left, right}; + frc::MockPWMMotorController left; + frc::MockPWMMotorController right; + frc::DifferentialDrive drive{[&](double output) { left.Set(output); }, + [&](double output) { right.Set(output); }}; drive.SetDeadband(0.0); // Forward @@ -351,9 +354,10 @@ TEST(DifferentialDriveTest, CurvatureDrive) { } TEST(DifferentialDriveTest, CurvatureDriveTurnInPlace) { - frc::MockMotorController left; - frc::MockMotorController right; - frc::DifferentialDrive drive{left, right}; + frc::MockPWMMotorController left; + frc::MockPWMMotorController right; + frc::DifferentialDrive drive{[&](double output) { left.Set(output); }, + [&](double output) { right.Set(output); }}; drive.SetDeadband(0.0); // Forward @@ -388,9 +392,10 @@ TEST(DifferentialDriveTest, CurvatureDriveTurnInPlace) { } TEST(DifferentialDriveTest, TankDrive) { - frc::MockMotorController left; - frc::MockMotorController right; - frc::DifferentialDrive drive{left, right}; + frc::MockPWMMotorController left; + frc::MockPWMMotorController right; + frc::DifferentialDrive drive{[&](double output) { left.Set(output); }, + [&](double output) { right.Set(output); }}; drive.SetDeadband(0.0); // Forward @@ -425,9 +430,10 @@ TEST(DifferentialDriveTest, TankDrive) { } TEST(DifferentialDriveTest, TankDriveSquared) { - frc::MockMotorController left; - frc::MockMotorController right; - frc::DifferentialDrive drive{left, right}; + frc::MockPWMMotorController left; + frc::MockPWMMotorController right; + frc::DifferentialDrive drive{[&](double output) { left.Set(output); }, + [&](double output) { right.Set(output); }}; drive.SetDeadband(0.0); // Forward diff --git a/wpilibc/src/test/native/cpp/drive/MecanumDriveTest.cpp b/wpilibc/src/test/native/cpp/drive/MecanumDriveTest.cpp index 1bbf464106c..b32b03c8246 100644 --- a/wpilibc/src/test/native/cpp/drive/MecanumDriveTest.cpp +++ b/wpilibc/src/test/native/cpp/drive/MecanumDriveTest.cpp @@ -5,7 +5,7 @@ #include #include "frc/drive/MecanumDrive.h" -#include "motorcontrol/MockMotorController.h" +#include "motorcontrol/MockPWMMotorController.h" TEST(MecanumDriveTest, CartesianIK) { // Forward @@ -82,11 +82,14 @@ TEST(MecanumDriveTest, CartesianIKGyro90CW) { } TEST(MecanumDriveTest, Cartesian) { - frc::MockMotorController fl; - frc::MockMotorController rl; - frc::MockMotorController fr; - frc::MockMotorController rr; - frc::MecanumDrive drive{fl, rl, fr, rr}; + frc::MockPWMMotorController fl; + frc::MockPWMMotorController rl; + frc::MockPWMMotorController fr; + frc::MockPWMMotorController rr; + frc::MecanumDrive drive{[&](double output) { fl.Set(output); }, + [&](double output) { rl.Set(output); }, + [&](double output) { fr.Set(output); }, + [&](double output) { rr.Set(output); }}; drive.SetDeadband(0.0); // Forward @@ -126,11 +129,14 @@ TEST(MecanumDriveTest, Cartesian) { } TEST(MecanumDriveTest, CartesianGyro90CW) { - frc::MockMotorController fl; - frc::MockMotorController fr; - frc::MockMotorController rl; - frc::MockMotorController rr; - frc::MecanumDrive drive{fl, rl, fr, rr}; + frc::MockPWMMotorController fl; + frc::MockPWMMotorController rl; + frc::MockPWMMotorController fr; + frc::MockPWMMotorController rr; + frc::MecanumDrive drive{[&](double output) { fl.Set(output); }, + [&](double output) { rl.Set(output); }, + [&](double output) { fr.Set(output); }, + [&](double output) { rr.Set(output); }}; drive.SetDeadband(0.0); // Forward in global frame; left in robot frame @@ -170,11 +176,14 @@ TEST(MecanumDriveTest, CartesianGyro90CW) { } TEST(MecanumDriveTest, Polar) { - frc::MockMotorController fl; - frc::MockMotorController fr; - frc::MockMotorController rl; - frc::MockMotorController rr; - frc::MecanumDrive drive{fl, rl, fr, rr}; + frc::MockPWMMotorController fl; + frc::MockPWMMotorController rl; + frc::MockPWMMotorController fr; + frc::MockPWMMotorController rr; + frc::MecanumDrive drive{[&](double output) { fl.Set(output); }, + [&](double output) { rl.Set(output); }, + [&](double output) { fr.Set(output); }, + [&](double output) { rr.Set(output); }}; drive.SetDeadband(0.0); // Forward diff --git a/wpilibc/src/test/native/cpp/event/EventLoopTest.cpp b/wpilibc/src/test/native/cpp/event/EventLoopTest.cpp new file mode 100644 index 00000000000..c903e0f8cde --- /dev/null +++ b/wpilibc/src/test/native/cpp/event/EventLoopTest.cpp @@ -0,0 +1,24 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include + +#include "frc/Errors.h" +#include "frc/event/EventLoop.h" + +using namespace frc; + +TEST(EventLoopTest, ConcurrentModification) { + EventLoop loop; + + loop.Bind([&loop] { ASSERT_THROW(loop.Bind([] {}), frc::RuntimeError); }); + + loop.Poll(); + + loop.Clear(); + + loop.Bind([&loop] { ASSERT_THROW(loop.Clear(), frc::RuntimeError); }); + + loop.Poll(); +} diff --git a/wpilibc/src/test/native/cpp/motorcontrol/MockPWMMotorController.cpp b/wpilibc/src/test/native/cpp/motorcontrol/MockPWMMotorController.cpp new file mode 100644 index 00000000000..7a51f33b9a1 --- /dev/null +++ b/wpilibc/src/test/native/cpp/motorcontrol/MockPWMMotorController.cpp @@ -0,0 +1,31 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "motorcontrol/MockPWMMotorController.h" + +using namespace frc; + +void MockPWMMotorController::Set(double speed) { + m_speed = m_isInverted ? -speed : speed; +} + +double MockPWMMotorController::Get() const { + return m_speed; +} + +void MockPWMMotorController::SetInverted(bool isInverted) { + m_isInverted = isInverted; +} + +bool MockPWMMotorController::GetInverted() const { + return m_isInverted; +} + +void MockPWMMotorController::Disable() { + m_speed = 0; +} + +void MockPWMMotorController::StopMotor() { + Disable(); +} diff --git a/wpilibc/src/test/native/cpp/motorcontrol/MotorControllerGroupTest.cpp b/wpilibc/src/test/native/cpp/motorcontrol/MotorControllerGroupTest.cpp index 4ff889ad81e..740c46fe1a8 100644 --- a/wpilibc/src/test/native/cpp/motorcontrol/MotorControllerGroupTest.cpp +++ b/wpilibc/src/test/native/cpp/motorcontrol/MotorControllerGroupTest.cpp @@ -8,6 +8,7 @@ #include #include +#include #include "motorcontrol/MockMotorController.h" @@ -32,6 +33,8 @@ std::ostream& operator<<(std::ostream& os, return os; } +WPI_IGNORE_DEPRECATED + /** * A fixture used for MotorControllerGroup testing. */ @@ -124,3 +127,5 @@ TEST_P(MotorControllerGroupTest, StopMotor) { INSTANTIATE_TEST_SUITE_P(Tests, MotorControllerGroupTest, testing::Values(TEST_ONE, TEST_TWO, TEST_THREE)); + +WPI_UNIGNORE_DEPRECATED diff --git a/wpilibc/src/test/native/cpp/simulation/DifferentialDrivetrainSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/DifferentialDrivetrainSimTest.cpp index a942d16e3d5..9ed23624de3 100644 --- a/wpilibc/src/test/native/cpp/simulation/DifferentialDrivetrainSimTest.cpp +++ b/wpilibc/src/test/native/cpp/simulation/DifferentialDrivetrainSimTest.cpp @@ -7,8 +7,8 @@ #include #include +#include "frc/controller/LTVUnicycleController.h" #include "frc/controller/LinearPlantInversionFeedforward.h" -#include "frc/controller/RamseteController.h" #include "frc/kinematics/DifferentialDriveKinematics.h" #include "frc/simulation/DifferentialDrivetrainSim.h" #include "frc/system/NumericalIntegration.h" @@ -28,7 +28,7 @@ TEST(DifferentialDrivetrainSimTest, Convergence) { 1.0, 2_in, {0.001, 0.001, 0.0001, 0.1, 0.1, 0.005, 0.005}}; frc::LinearPlantInversionFeedforward feedforward{plant, 20_ms}; - frc::RamseteController ramsete; + frc::LTVUnicycleController feedback{20_ms}; feedforward.Reset(frc::Vectord<2>{0.0, 0.0}); @@ -44,9 +44,9 @@ TEST(DifferentialDrivetrainSimTest, Convergence) { for (auto t = 0_s; t < trajectory.TotalTime(); t += 20_ms) { auto state = trajectory.Sample(t); - auto ramseteOut = ramsete.Calculate(sim.GetPose(), state); + auto feedbackOut = feedback.Calculate(sim.GetPose(), state); - auto [l, r] = kinematics.ToWheelSpeeds(ramseteOut); + auto [l, r] = kinematics.ToWheelSpeeds(feedbackOut); auto voltages = feedforward.Calculate(frc::Vectord<2>{l.value(), r.value()}); diff --git a/wpilibc/src/test/native/cpp/simulation/DriverStationSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/DriverStationSimTest.cpp index 2513252893f..8a5941ad377 100644 --- a/wpilibc/src/test/native/cpp/simulation/DriverStationSimTest.cpp +++ b/wpilibc/src/test/native/cpp/simulation/DriverStationSimTest.cpp @@ -104,15 +104,19 @@ TEST(DriverStationTest, FmsAttached) { TEST(DriverStationTest, DsAttached) { HAL_Initialize(500, 0); DriverStationSim::ResetData(); + DriverStation::RefreshData(); + EXPECT_FALSE(DriverStationSim::GetDsAttached()); + EXPECT_FALSE(DriverStation::IsDSAttached()); DriverStationSim::NotifyNewData(); + EXPECT_TRUE(DriverStationSim::GetDsAttached()); EXPECT_TRUE(DriverStation::IsDSAttached()); BooleanCallback callback; auto cb = DriverStationSim::RegisterDsAttachedCallback(callback.GetCallback(), false); DriverStationSim::SetDsAttached(false); - DriverStationSim::NotifyNewData(); + DriverStation::RefreshData(); EXPECT_FALSE(DriverStationSim::GetDsAttached()); EXPECT_FALSE(DriverStation::IsDSAttached()); EXPECT_TRUE(callback.WasTriggered()); diff --git a/wpilibc/src/test/native/cpp/simulation/ElevatorSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/ElevatorSimTest.cpp index 28777bdbfff..dd835650cd6 100644 --- a/wpilibc/src/test/native/cpp/simulation/ElevatorSimTest.cpp +++ b/wpilibc/src/test/native/cpp/simulation/ElevatorSimTest.cpp @@ -74,8 +74,10 @@ TEST(ElevatorSimTest, Stability) { sim.Update(20_ms); } - frc::LinearSystem<2, 1, 1> system = frc::LinearSystemId::ElevatorSystem( - frc::DCMotor::Vex775Pro(4), 4_kg, 0.5_in, 100); + frc::LinearSystem<2, 1, 1> system = + frc::LinearSystemId::ElevatorSystem(frc::DCMotor::Vex775Pro(4), 4_kg, + 0.5_in, 100) + .Slice(0); EXPECT_NEAR_UNITS( units::meter_t{system.CalculateX(frc::Vectord<2>{0.0, 0.0}, frc::Vectord<1>{12.0}, 20_ms * 50)(0)}, diff --git a/wpilibc/src/test/native/cpp/simulation/RoboRioSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/RoboRioSimTest.cpp index e42f38fd137..3b74a9157a8 100644 --- a/wpilibc/src/test/native/cpp/simulation/RoboRioSimTest.cpp +++ b/wpilibc/src/test/native/cpp/simulation/RoboRioSimTest.cpp @@ -274,4 +274,26 @@ TEST(RoboRioSimTest, SetComments) { EXPECT_EQ(kCommentsTruncated, RobotController::GetComments()); } +TEST(RoboRioSimTest, SetRadioLEDState) { + RoboRioSim::ResetData(); + + EnumCallback callback; + auto cbHandle = + RoboRioSim::RegisterRadioLEDStateCallback(callback.GetCallback(), false); + + RobotController::SetRadioLEDState(RadioLEDState::kGreen); + EXPECT_TRUE(callback.WasTriggered()); + EXPECT_EQ(RadioLEDState::kGreen, callback.GetLastValue()); + EXPECT_EQ(RadioLEDState::kGreen, RoboRioSim::GetRadioLEDState()); + EXPECT_EQ(RadioLEDState::kGreen, RobotController::GetRadioLEDState()); + + callback.Reset(); + + RoboRioSim::SetRadioLEDState(RadioLEDState::kOrange); + EXPECT_TRUE(callback.WasTriggered()); + EXPECT_EQ(RadioLEDState::kOrange, callback.GetLastValue()); + EXPECT_EQ(RadioLEDState::kOrange, RoboRioSim::GetRadioLEDState()); + EXPECT_EQ(RadioLEDState::kOrange, RobotController::GetRadioLEDState()); +} + } // namespace frc::sim diff --git a/wpilibc/src/test/native/cpp/util/Color8BitTest.cpp b/wpilibc/src/test/native/cpp/util/Color8BitTest.cpp new file mode 100644 index 00000000000..775b0a695a8 --- /dev/null +++ b/wpilibc/src/test/native/cpp/util/Color8BitTest.cpp @@ -0,0 +1,70 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include + +#include + +#include "frc/util/Color8Bit.h" + +TEST(Color8BitTest, ConstructDefault) { + constexpr frc::Color8Bit color; + + EXPECT_EQ(0, color.red); + EXPECT_EQ(0, color.green); + EXPECT_EQ(0, color.blue); +} + +TEST(Color8BitTest, ConstructFromInts) { + constexpr frc::Color8Bit color{255, 128, 64}; + + EXPECT_EQ(255, color.red); + EXPECT_EQ(128, color.green); + EXPECT_EQ(64, color.blue); +} + +TEST(Color8BitTest, ConstructFromColor) { + constexpr frc::Color8Bit color{frc::Color{255, 128, 64}}; + + EXPECT_EQ(255, color.red); + EXPECT_EQ(128, color.green); + EXPECT_EQ(64, color.blue); +} + +TEST(Color8BitTest, ConstructFromHexString) { + constexpr frc::Color8Bit color{"#FF8040"}; + + EXPECT_EQ(255, color.red); + EXPECT_EQ(128, color.green); + EXPECT_EQ(64, color.blue); + + // No leading # + EXPECT_THROW(frc::Color8Bit{"112233"}, std::invalid_argument); + + // Too long + EXPECT_THROW(frc::Color8Bit{"#11223344"}, std::invalid_argument); + + // Invalid hex characters + EXPECT_THROW(frc::Color8Bit{"#$$$$$$"}, std::invalid_argument); +} + +TEST(Color8BitTest, ImplicitConversionToColor) { + frc::Color color = frc::Color8Bit{255, 128, 64}; + + EXPECT_NEAR(1.0, color.red, 1e-2); + EXPECT_NEAR(0.5, color.green, 1e-2); + EXPECT_NEAR(0.25, color.blue, 1e-2); +} + +TEST(Color8BitTest, ToHexString) { + constexpr frc::Color8Bit color1{255, 128, 64}; + EXPECT_EQ("#FF8040", color1.HexString()); + + // Ensure conversion to std::string works + [[maybe_unused]] + std::string str = color1.HexString(); + + frc::Color8Bit color2{255, 128, 64}; + EXPECT_EQ("#FF8040", color2.HexString()); +} diff --git a/wpilibc/src/test/native/cpp/util/ColorTest.cpp b/wpilibc/src/test/native/cpp/util/ColorTest.cpp new file mode 100644 index 00000000000..a62c0157f1d --- /dev/null +++ b/wpilibc/src/test/native/cpp/util/ColorTest.cpp @@ -0,0 +1,81 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include + +#include + +#include "frc/util/Color.h" + +TEST(ColorTest, ConstructDefault) { + constexpr frc::Color color; + + EXPECT_DOUBLE_EQ(0.0, color.red); + EXPECT_DOUBLE_EQ(0.0, color.green); + EXPECT_DOUBLE_EQ(0.0, color.blue); +} + +TEST(ColorTest, ConstructFromDoubles) { + { + constexpr frc::Color color{1.0, 0.5, 0.25}; + + EXPECT_NEAR(1.0, color.red, 1e-2); + EXPECT_NEAR(0.5, color.green, 1e-2); + EXPECT_NEAR(0.25, color.blue, 1e-2); + } + + { + constexpr frc::Color color{1.0, 0.0, 0.0}; + + // Check for exact match to ensure round-and-clamp is correct + EXPECT_EQ(1.0, color.red); + EXPECT_EQ(0.0, color.green); + EXPECT_EQ(0.0, color.blue); + } +} + +TEST(ColorTest, ConstructFromInts) { + constexpr frc::Color color{255, 128, 64}; + + EXPECT_NEAR(1.0, color.red, 1e-2); + EXPECT_NEAR(0.5, color.green, 1e-2); + EXPECT_NEAR(0.25, color.blue, 1e-2); +} + +TEST(ColorTest, ConstructFromHexString) { + constexpr frc::Color color{"#FF8040"}; + + EXPECT_NEAR(1.0, color.red, 1e-2); + EXPECT_NEAR(0.5, color.green, 1e-2); + EXPECT_NEAR(0.25, color.blue, 1e-2); + + // No leading # + EXPECT_THROW(frc::Color{"112233"}, std::invalid_argument); + + // Too long + EXPECT_THROW(frc::Color{"#11223344"}, std::invalid_argument); + + // Invalid hex characters + EXPECT_THROW(frc::Color{"#$$$$$$"}, std::invalid_argument); +} + +TEST(ColorTest, FromHSV) { + constexpr frc::Color color = frc::Color::FromHSV(90, 128, 64); + + EXPECT_DOUBLE_EQ(0.125732421875, color.red); + EXPECT_DOUBLE_EQ(0.251220703125, color.green); + EXPECT_DOUBLE_EQ(0.251220703125, color.blue); +} + +TEST(ColorTest, ToHexString) { + constexpr frc::Color color1{255, 128, 64}; + EXPECT_EQ("#FF8040", color1.HexString()); + + // Ensure conversion to std::string works + [[maybe_unused]] + std::string str = color1.HexString(); + + frc::Color color2{255, 128, 64}; + EXPECT_EQ("#FF8040", color2.HexString()); +} diff --git a/wpilibc/src/test/native/include/motorcontrol/MockMotorController.h b/wpilibc/src/test/native/include/motorcontrol/MockMotorController.h index e17931fbb69..aab6ce47492 100644 --- a/wpilibc/src/test/native/include/motorcontrol/MockMotorController.h +++ b/wpilibc/src/test/native/include/motorcontrol/MockMotorController.h @@ -4,10 +4,14 @@ #pragma once +#include + #include "frc/motorcontrol/MotorController.h" namespace frc { +WPI_IGNORE_DEPRECATED + class MockMotorController : public MotorController { public: void Set(double speed) override; @@ -22,4 +26,6 @@ class MockMotorController : public MotorController { bool m_isInverted = false; }; +WPI_UNIGNORE_DEPRECATED + } // namespace frc diff --git a/wpilibc/src/test/native/include/motorcontrol/MockPWMMotorController.h b/wpilibc/src/test/native/include/motorcontrol/MockPWMMotorController.h new file mode 100644 index 00000000000..18bd1f56159 --- /dev/null +++ b/wpilibc/src/test/native/include/motorcontrol/MockPWMMotorController.h @@ -0,0 +1,23 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +namespace frc { + +class MockPWMMotorController { + public: + void Set(double speed); + double Get() const; + void SetInverted(bool isInverted); + bool GetInverted() const; + void Disable(); + void StopMotor(); + + private: + double m_speed = 0.0; + bool m_isInverted = false; +}; + +} // namespace frc diff --git a/wpilibcExamples/CMakeLists.txt b/wpilibcExamples/CMakeLists.txt index f46d1c246d3..4554b94dcfd 100644 --- a/wpilibcExamples/CMakeLists.txt +++ b/wpilibcExamples/CMakeLists.txt @@ -7,29 +7,53 @@ subdir_list(TEMPLATES ${CMAKE_SOURCE_DIR}/wpilibcExamples/src/main/cpp/templates subdir_list(EXAMPLES ${CMAKE_SOURCE_DIR}/wpilibcExamples/src/main/cpp/examples) foreach(example ${EXAMPLES}) - file(GLOB_RECURSE sources src/main/cpp/examples/${example}/cpp/*.cpp - src/main/cpp/examples/${example}/c/*.c) - add_executable(${example} ${sources}) - wpilib_target_warnings(${example}) - target_include_directories(${example} PUBLIC src/main/cpp/examples/${example}/include) - target_link_libraries(${example} apriltag wpilibc wpilibNewCommands romiVendordep xrpVendordep) + file( + GLOB_RECURSE sources + src/main/cpp/examples/${example}/cpp/*.cpp + src/main/cpp/examples/${example}/c/*.c + ) + add_executable(${example} ${sources}) + wpilib_target_warnings(${example}) + target_include_directories(${example} PUBLIC src/main/cpp/examples/${example}/include) + target_link_libraries( + ${example} + apriltag + wpilibc + wpilibNewCommands + romiVendordep + xrpVendordep + ) - if (WITH_TESTS AND EXISTS ${CMAKE_SOURCE_DIR}/wpilibcExamples/src/test/cpp/examples/${example}) - wpilib_add_test(${example} src/test/cpp/examples/${example}/cpp) - target_sources(${example}_test PRIVATE ${sources}) - target_include_directories(${example}_test PRIVATE - src/main/cpp/examples/${example}/include - src/test/cpp/examples/${example}/include) - target_compile_definitions(${example}_test PUBLIC RUNNING_FRC_TESTS) - target_link_libraries(${example}_test apriltag wpilibc wpilibNewCommands romiVendordep xrpVendordep gmock_main) - endif() + if(WITH_TESTS AND EXISTS ${CMAKE_SOURCE_DIR}/wpilibcExamples/src/test/cpp/examples/${example}) + wpilib_add_test(${example} src/test/cpp/examples/${example}/cpp) + target_sources(${example}_test PRIVATE ${sources}) + target_include_directories( + ${example}_test + PRIVATE + src/main/cpp/examples/${example}/include + src/test/cpp/examples/${example}/include + ) + target_compile_definitions(${example}_test PUBLIC RUNNING_FRC_TESTS) + target_link_libraries( + ${example}_test + apriltag + wpilibc + wpilibNewCommands + romiVendordep + xrpVendordep + gmock_main + ) + endif() endforeach() foreach(template ${TEMPLATES}) - file(GLOB_RECURSE sources src/main/cpp/templates/${template}/cpp/*.cpp - src/main/cpp/templates/${template}/c/*.c) - add_executable(${template} ${sources}) - wpilib_target_warnings(${template}) - target_include_directories(${template} PUBLIC src/main/cpp/templates/${template}/include) - target_link_libraries(${template} wpilibc wpilibNewCommands romiVendordep xrpVendordep) + file( + GLOB_RECURSE sources + src/main/cpp/templates/${template}/cpp/*.cpp + src/main/cpp/templates/${template}/c/*.c + ) + add_executable(${template} ${sources}) + wpilib_target_warnings(${template}) + target_include_directories(${template} PUBLIC src/main/cpp/templates/${template}/include) + target_link_libraries(${template} wpilibc wpilibNewCommands romiVendordep xrpVendordep) endforeach() diff --git a/wpilibcExamples/src/main/cpp/examples/AprilTagsVision/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/AprilTagsVision/cpp/Robot.cpp index 0ed53fd8536..9f23be34075 100644 --- a/wpilibcExamples/src/main/cpp/examples/AprilTagsVision/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/AprilTagsVision/cpp/Robot.cpp @@ -37,13 +37,16 @@ class Robot : public frc::TimedRobot { private: static void VisionThread() { frc::AprilTagDetector detector; - // look for tag16h5, don't correct any error bits - detector.AddFamily("tag16h5", 0); + // look for tag36h11, correct 1 error bit + // hamming 1 allocates 781KB, 2 allocates 27.4 MB, 3 allocates 932 MB + // max of 1 recommended for RoboRIO 1, while hamming 2 is feasible on the + // RoboRIO 2 + detector.AddFamily("tag36h11", 1); // Set up Pose Estimator - parameters are for a Microsoft Lifecam HD-3000 // (https://www.chiefdelphi.com/t/wpilib-apriltagdetector-sample-code/421411/21) frc::AprilTagPoseEstimator::Config poseEstConfig = { - .tagSize = units::length::inch_t(6.0), + .tagSize = units::length::inch_t(6.5), .fx = 699.3778103158814, .fy = 677.7161226393544, .cx = 345.6059345433618, diff --git a/wpilibcExamples/src/main/cpp/examples/ArcadeDrive/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ArcadeDrive/cpp/Robot.cpp index b636b44b47f..9c8d64064fa 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArcadeDrive/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArcadeDrive/cpp/Robot.cpp @@ -14,10 +14,17 @@ class Robot : public frc::TimedRobot { frc::PWMSparkMax m_leftMotor{0}; frc::PWMSparkMax m_rightMotor{1}; - frc::DifferentialDrive m_robotDrive{m_leftMotor, m_rightMotor}; + frc::DifferentialDrive m_robotDrive{ + [&](double output) { m_leftMotor.Set(output); }, + [&](double output) { m_rightMotor.Set(output); }}; frc::Joystick m_stick{0}; public: + Robot() { + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_leftMotor); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_rightMotor); + } + void RobotInit() override { // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's diff --git a/wpilibcExamples/src/main/cpp/examples/ArcadeDriveXboxController/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ArcadeDriveXboxController/cpp/Robot.cpp index 23c9a569dd1..38ff862ab96 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArcadeDriveXboxController/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArcadeDriveXboxController/cpp/Robot.cpp @@ -14,10 +14,17 @@ class Robot : public frc::TimedRobot { frc::PWMSparkMax m_leftMotor{0}; frc::PWMSparkMax m_rightMotor{1}; - frc::DifferentialDrive m_robotDrive{m_leftMotor, m_rightMotor}; + frc::DifferentialDrive m_robotDrive{ + [&](double output) { m_leftMotor.Set(output); }, + [&](double output) { m_rightMotor.Set(output); }}; frc::XboxController m_driverController{0}; public: + Robot() { + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_leftMotor); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_rightMotor); + } + void RobotInit() override { // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/Robot.cpp index d3a106b3935..13eb9f9ac46 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/Robot.cpp @@ -39,7 +39,7 @@ void Robot::DisabledPeriodic() {} void Robot::AutonomousInit() { m_autonomousCommand = m_container.GetAutonomousCommand(); - if (m_autonomousCommand != nullptr) { + if (m_autonomousCommand) { m_autonomousCommand->Schedule(); } } @@ -51,9 +51,9 @@ void Robot::TeleopInit() { // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. - if (m_autonomousCommand != nullptr) { + if (m_autonomousCommand) { m_autonomousCommand->Cancel(); - m_autonomousCommand = nullptr; + m_autonomousCommand.reset(); } } diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/RobotContainer.cpp b/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/RobotContainer.cpp index 90aa789ab4c..1bf4dcf6df8 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/RobotContainer.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/RobotContainer.cpp @@ -60,6 +60,6 @@ void RobotContainer::DisablePIDSubsystems() { m_arm.Disable(); } -frc2::Command* RobotContainer::GetAutonomousCommand() { - return nullptr; +frc2::CommandPtr RobotContainer::GetAutonomousCommand() { + return frc2::cmd::None(); } diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/subsystems/DriveSubsystem.cpp index aeeac3ddf90..13522950d80 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArmBot/cpp/subsystems/DriveSubsystem.cpp @@ -13,13 +13,20 @@ DriveSubsystem::DriveSubsystem() m_right2{kRightMotor2Port}, m_leftEncoder{kLeftEncoderPorts[0], kLeftEncoderPorts[1]}, m_rightEncoder{kRightEncoderPorts[0], kRightEncoderPorts[1]} { + wpi::SendableRegistry::AddChild(&m_drive, &m_left1); + wpi::SendableRegistry::AddChild(&m_drive, &m_right1); + + m_left1.AddFollower(m_left2); + m_right1.AddFollower(m_right2); + // Set the distance per pulse for the encoders m_leftEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); m_rightEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.SetInverted(true); + m_right1.SetInverted(true); } void DriveSubsystem::Periodic() { diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBot/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/ArmBot/include/Constants.h index cff39322b27..556ee4c54b4 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBot/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/ArmBot/include/Constants.h @@ -21,54 +21,54 @@ */ namespace DriveConstants { -constexpr int kLeftMotor1Port = 0; -constexpr int kLeftMotor2Port = 1; -constexpr int kRightMotor1Port = 2; -constexpr int kRightMotor2Port = 3; +inline constexpr int kLeftMotor1Port = 0; +inline constexpr int kLeftMotor2Port = 1; +inline constexpr int kRightMotor1Port = 2; +inline constexpr int kRightMotor2Port = 3; -constexpr int kLeftEncoderPorts[]{0, 1}; -constexpr int kRightEncoderPorts[]{2, 3}; -constexpr bool kLeftEncoderReversed = false; -constexpr bool kRightEncoderReversed = true; +inline constexpr int kLeftEncoderPorts[]{0, 1}; +inline constexpr int kRightEncoderPorts[]{2, 3}; +inline constexpr bool kLeftEncoderReversed = false; +inline constexpr bool kRightEncoderReversed = true; -constexpr int kEncoderCPR = 1024; -constexpr double kWheelDiameterInches = 6; -constexpr double kEncoderDistancePerPulse = +inline constexpr int kEncoderCPR = 1024; +inline constexpr double kWheelDiameterInches = 6; +inline constexpr double kEncoderDistancePerPulse = // Assumes the encoders are directly mounted on the wheel shafts (kWheelDiameterInches * std::numbers::pi) / static_cast(kEncoderCPR); } // namespace DriveConstants namespace ArmConstants { -constexpr int kMotorPort = 4; +inline constexpr int kMotorPort = 4; -constexpr double kP = 1; +inline constexpr double kP = 1; // These are fake gains; in actuality these must be determined individually for // each robot -constexpr auto kS = 1_V; -constexpr auto kG = 1_V; -constexpr auto kV = 0.5_V * 1_s / 1_rad; -constexpr auto kA = 0.1_V * 1_s * 1_s / 1_rad; +inline constexpr auto kS = 1_V; +inline constexpr auto kG = 1_V; +inline constexpr auto kV = 0.5_V * 1_s / 1_rad; +inline constexpr auto kA = 0.1_V * 1_s * 1_s / 1_rad; -constexpr auto kMaxVelocity = 3_rad_per_s; -constexpr auto kMaxAcceleration = 10_rad / (1_s * 1_s); +inline constexpr auto kMaxVelocity = 3_rad_per_s; +inline constexpr auto kMaxAcceleration = 10_rad / (1_s * 1_s); -constexpr int kEncoderPorts[]{4, 5}; -constexpr int kEncoderPPR = 256; -constexpr auto kEncoderDistancePerPulse = +inline constexpr int kEncoderPorts[]{4, 5}; +inline constexpr int kEncoderPPR = 256; +inline constexpr auto kEncoderDistancePerPulse = 2.0_rad * std::numbers::pi / kEncoderPPR; // The offset of the arm from the horizontal in its neutral position, // measured from the horizontal -constexpr auto kArmOffset = 0.5_rad; +inline constexpr auto kArmOffset = 0.5_rad; } // namespace ArmConstants namespace AutoConstants { -constexpr auto kAutoTimeoutSeconds = 12_s; -constexpr auto kAutoShootTimeSeconds = 7_s; +inline constexpr auto kAutoTimeoutSeconds = 12_s; +inline constexpr auto kAutoShootTimeSeconds = 7_s; } // namespace AutoConstants namespace OIConstants { -constexpr int kDriverControllerPort = 0; +inline constexpr int kDriverControllerPort = 0; } // namespace OIConstants diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBot/include/Robot.h b/wpilibcExamples/src/main/cpp/examples/ArmBot/include/Robot.h index a82f2ac63b0..de9c814e752 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBot/include/Robot.h +++ b/wpilibcExamples/src/main/cpp/examples/ArmBot/include/Robot.h @@ -4,6 +4,8 @@ #pragma once +#include + #include #include @@ -24,7 +26,7 @@ class Robot : public frc::TimedRobot { private: // Have it null by default so that if testing teleop it // doesn't have undefined behavior and potentially crash. - frc2::Command* m_autonomousCommand = nullptr; + std::optional m_autonomousCommand; RobotContainer m_container; }; diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBot/include/RobotContainer.h b/wpilibcExamples/src/main/cpp/examples/ArmBot/include/RobotContainer.h index 67d194c6941..ab77985e541 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBot/include/RobotContainer.h +++ b/wpilibcExamples/src/main/cpp/examples/ArmBot/include/RobotContainer.h @@ -5,6 +5,7 @@ #pragma once #include +#include #include #include "Constants.h" @@ -28,7 +29,7 @@ class RobotContainer { */ void DisablePIDSubsystems(); - frc2::Command* GetAutonomousCommand(); + frc2::CommandPtr GetAutonomousCommand(); private: // The driver's controller diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBot/include/subsystems/DriveSubsystem.h b/wpilibcExamples/src/main/cpp/examples/ArmBot/include/subsystems/DriveSubsystem.h index 47bf28e4d91..47d3f3d49b2 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBot/include/subsystems/DriveSubsystem.h +++ b/wpilibcExamples/src/main/cpp/examples/ArmBot/include/subsystems/DriveSubsystem.h @@ -6,7 +6,6 @@ #include #include -#include #include #include @@ -75,14 +74,9 @@ class DriveSubsystem : public frc2::SubsystemBase { frc::PWMSparkMax m_right1; frc::PWMSparkMax m_right2; - // The motors on the left side of the drive - frc::MotorControllerGroup m_leftMotors{m_left1, m_left2}; - - // The motors on the right side of the drive - frc::MotorControllerGroup m_rightMotors{m_right1, m_right2}; - // The robot's drive - frc::DifferentialDrive m_drive{m_leftMotors, m_rightMotors}; + frc::DifferentialDrive m_drive{[&](double output) { m_left1.Set(output); }, + [&](double output) { m_right1.Set(output); }}; // The left-side drive encoder frc::Encoder m_leftEncoder; diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/Robot.cpp index c7eab485a5d..c4c1661d699 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/Robot.cpp @@ -37,7 +37,7 @@ void Robot::DisabledPeriodic() {} void Robot::AutonomousInit() { m_autonomousCommand = m_container.GetAutonomousCommand(); - if (m_autonomousCommand != nullptr) { + if (m_autonomousCommand) { m_autonomousCommand->Schedule(); } } @@ -49,9 +49,9 @@ void Robot::TeleopInit() { // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. - if (m_autonomousCommand != nullptr) { + if (m_autonomousCommand) { m_autonomousCommand->Cancel(); - m_autonomousCommand = nullptr; + m_autonomousCommand.reset(); } } diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/RobotContainer.cpp b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/RobotContainer.cpp index dce4b95c18f..a8704165a5b 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/RobotContainer.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/RobotContainer.cpp @@ -4,6 +4,7 @@ #include "RobotContainer.h" +#include #include RobotContainer::RobotContainer() { @@ -34,6 +35,6 @@ void RobotContainer::ConfigureButtonBindings() { .OnFalse(m_drive.SetMaxOutputCommand(1.0)); } -frc2::Command* RobotContainer::GetAutonomousCommand() { - return nullptr; +frc2::CommandPtr RobotContainer::GetAutonomousCommand() { + return frc2::cmd::None(); } diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/subsystems/DriveSubsystem.cpp index 16409ad7a77..236d4682357 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/cpp/subsystems/DriveSubsystem.cpp @@ -13,13 +13,20 @@ DriveSubsystem::DriveSubsystem() m_right2{kRightMotor2Port}, m_leftEncoder{kLeftEncoderPorts[0], kLeftEncoderPorts[1]}, m_rightEncoder{kRightEncoderPorts[0], kRightEncoderPorts[1]} { + wpi::SendableRegistry::AddChild(&m_drive, &m_left1); + wpi::SendableRegistry::AddChild(&m_drive, &m_right1); + + m_left1.AddFollower(m_left2); + m_right1.AddFollower(m_right2); + // Set the distance per pulse for the encoders m_leftEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); m_rightEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.SetInverted(true); + m_right1.SetInverted(true); } void DriveSubsystem::Periodic() { diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/Constants.h index cff39322b27..b91fe195c46 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/Constants.h @@ -21,52 +21,52 @@ */ namespace DriveConstants { -constexpr int kLeftMotor1Port = 0; -constexpr int kLeftMotor2Port = 1; -constexpr int kRightMotor1Port = 2; -constexpr int kRightMotor2Port = 3; +inline constexpr int kLeftMotor1Port = 0; +inline constexpr int kLeftMotor2Port = 1; +inline constexpr int kRightMotor1Port = 2; +inline constexpr int kRightMotor2Port = 3; -constexpr int kLeftEncoderPorts[]{0, 1}; -constexpr int kRightEncoderPorts[]{2, 3}; -constexpr bool kLeftEncoderReversed = false; -constexpr bool kRightEncoderReversed = true; +inline constexpr int kLeftEncoderPorts[]{0, 1}; +inline constexpr int kRightEncoderPorts[]{2, 3}; +inline constexpr bool kLeftEncoderReversed = false; +inline constexpr bool kRightEncoderReversed = true; -constexpr int kEncoderCPR = 1024; -constexpr double kWheelDiameterInches = 6; -constexpr double kEncoderDistancePerPulse = +inline constexpr int kEncoderCPR = 1024; +inline constexpr double kWheelDiameterInches = 6; +inline constexpr double kEncoderDistancePerPulse = // Assumes the encoders are directly mounted on the wheel shafts (kWheelDiameterInches * std::numbers::pi) / static_cast(kEncoderCPR); } // namespace DriveConstants namespace ArmConstants { -constexpr int kMotorPort = 4; +inline constexpr int kMotorPort = 4; -constexpr double kP = 1; +inline constexpr double kP = 1; // These are fake gains; in actuality these must be determined individually for // each robot -constexpr auto kS = 1_V; -constexpr auto kG = 1_V; -constexpr auto kV = 0.5_V * 1_s / 1_rad; -constexpr auto kA = 0.1_V * 1_s * 1_s / 1_rad; +inline constexpr auto kS = 1_V; +inline constexpr auto kG = 1_V; +inline constexpr auto kV = 0.5_V * 1_s / 1_rad; +inline constexpr auto kA = 0.1_V * 1_s * 1_s / 1_rad; -constexpr auto kMaxVelocity = 3_rad_per_s; -constexpr auto kMaxAcceleration = 10_rad / (1_s * 1_s); +inline constexpr auto kMaxVelocity = 3_rad_per_s; +inline constexpr auto kMaxAcceleration = 10_rad / (1_s * 1_s); -constexpr int kEncoderPorts[]{4, 5}; -constexpr int kEncoderPPR = 256; -constexpr auto kEncoderDistancePerPulse = +inline constexpr int kEncoderPorts[]{4, 5}; +inline constexpr int kEncoderPPR = 256; +inline constexpr auto kEncoderDistancePerPulse = 2.0_rad * std::numbers::pi / kEncoderPPR; // The offset of the arm from the horizontal in its neutral position, // measured from the horizontal -constexpr auto kArmOffset = 0.5_rad; +inline constexpr auto kArmOffset = 0.5_rad; } // namespace ArmConstants namespace AutoConstants { -constexpr auto kAutoTimeoutSeconds = 12_s; -constexpr auto kAutoShootTimeSeconds = 7_s; +inline constexpr auto kAutoTimeoutSeconds = 12_s; +inline constexpr auto kAutoShootTimeSeconds = 7_s; } // namespace AutoConstants namespace OIConstants { diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/ExampleSmartMotorController.h b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/ExampleSmartMotorController.h index 5d55839892f..bd48d88e0bc 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/ExampleSmartMotorController.h +++ b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/ExampleSmartMotorController.h @@ -4,15 +4,13 @@ #pragma once -#include - /** * A simplified stub class that simulates the API of a common "smart" motor * controller. * *

Has no actual functionality. */ -class ExampleSmartMotorController : public frc::MotorController { +class ExampleSmartMotorController { public: enum PIDMode { kPosition, kVelocity, kMovementWitchcraft }; @@ -68,15 +66,15 @@ class ExampleSmartMotorController : public frc::MotorController { */ void ResetEncoder() {} - void Set(double speed) override {} + void Set(double speed) {} - double Get() const override { return 0; } + double Get() const { return 0; } - void SetInverted(bool isInverted) override {} + void SetInverted(bool isInverted) {} - bool GetInverted() const override { return false; } + bool GetInverted() const { return false; } - void Disable() override {} + void Disable() {} - void StopMotor() override {} + void StopMotor() {} }; diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/Robot.h b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/Robot.h index a82f2ac63b0..de9c814e752 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/Robot.h +++ b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/Robot.h @@ -4,6 +4,8 @@ #pragma once +#include + #include #include @@ -24,7 +26,7 @@ class Robot : public frc::TimedRobot { private: // Have it null by default so that if testing teleop it // doesn't have undefined behavior and potentially crash. - frc2::Command* m_autonomousCommand = nullptr; + std::optional m_autonomousCommand; RobotContainer m_container; }; diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/RobotContainer.h b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/RobotContainer.h index 08a4dbea307..7668c03e9a9 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/RobotContainer.h +++ b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/RobotContainer.h @@ -5,6 +5,7 @@ #pragma once #include +#include #include #include "Constants.h" @@ -24,7 +25,7 @@ class RobotContainer { public: RobotContainer(); - frc2::Command* GetAutonomousCommand(); + frc2::CommandPtr GetAutonomousCommand(); private: // The driver's controller diff --git a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/subsystems/DriveSubsystem.h b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/subsystems/DriveSubsystem.h index 6830b960d09..ca7e28e8293 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/subsystems/DriveSubsystem.h +++ b/wpilibcExamples/src/main/cpp/examples/ArmBotOffboard/include/subsystems/DriveSubsystem.h @@ -8,7 +8,6 @@ #include #include -#include #include #include #include @@ -73,14 +72,9 @@ class DriveSubsystem : public frc2::SubsystemBase { frc::PWMSparkMax m_right1; frc::PWMSparkMax m_right2; - // The motors on the left side of the drive - frc::MotorControllerGroup m_leftMotors{m_left1, m_left2}; - - // The motors on the right side of the drive - frc::MotorControllerGroup m_rightMotors{m_right1, m_right2}; - // The robot's drive - frc::DifferentialDrive m_drive{m_leftMotors, m_rightMotors}; + frc::DifferentialDrive m_drive{[&](double output) { m_left1.Set(output); }, + [&](double output) { m_right1.Set(output); }}; // The left-side drive encoder frc::Encoder m_leftEncoder; diff --git a/wpilibcExamples/src/main/cpp/examples/ArmSimulation/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/ArmSimulation/include/Constants.h index 0018a8aa586..c5883dbd4d0 100644 --- a/wpilibcExamples/src/main/cpp/examples/ArmSimulation/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/ArmSimulation/include/Constants.h @@ -22,25 +22,25 @@ * they are needed. */ -static constexpr int kMotorPort = 0; -static constexpr int kEncoderAChannel = 0; -static constexpr int kEncoderBChannel = 1; -static constexpr int kJoystickPort = 0; +inline constexpr int kMotorPort = 0; +inline constexpr int kEncoderAChannel = 0; +inline constexpr int kEncoderBChannel = 1; +inline constexpr int kJoystickPort = 0; -static constexpr std::string_view kArmPositionKey = "ArmPosition"; -static constexpr std::string_view kArmPKey = "ArmP"; +inline constexpr std::string_view kArmPositionKey = "ArmPosition"; +inline constexpr std::string_view kArmPKey = "ArmP"; -static constexpr double kDefaultArmKp = 50.0; -static constexpr units::degree_t kDefaultArmSetpoint = 75.0_deg; +inline constexpr double kDefaultArmKp = 50.0; +inline constexpr units::degree_t kDefaultArmSetpoint = 75.0_deg; -static constexpr units::radian_t kMinAngle = -75.0_deg; -static constexpr units::radian_t kMaxAngle = 255.0_deg; +inline constexpr units::radian_t kMinAngle = -75.0_deg; +inline constexpr units::radian_t kMaxAngle = 255.0_deg; -static constexpr double kArmReduction = 200.0; -static constexpr units::kilogram_t kArmMass = 8.0_kg; -static constexpr units::meter_t kArmLength = 30.0_in; +inline constexpr double kArmReduction = 200.0; +inline constexpr units::kilogram_t kArmMass = 8.0_kg; +inline constexpr units::meter_t kArmLength = 30.0_in; // distance per pulse = (angle per revolution) / (pulses per revolution) // = (2 * PI rads) / (4096 pulses) -static constexpr double kArmEncoderDistPerPulse = +inline constexpr double kArmEncoderDistPerPulse = 2.0 * std::numbers::pi / 4096.0; diff --git a/wpilibcExamples/src/main/cpp/examples/DifferentialDriveBot/cpp/Drivetrain.cpp b/wpilibcExamples/src/main/cpp/examples/DifferentialDriveBot/cpp/Drivetrain.cpp index cc7db7b3bab..9470a7ad3aa 100644 --- a/wpilibcExamples/src/main/cpp/examples/DifferentialDriveBot/cpp/Drivetrain.cpp +++ b/wpilibcExamples/src/main/cpp/examples/DifferentialDriveBot/cpp/Drivetrain.cpp @@ -12,8 +12,8 @@ void Drivetrain::SetSpeeds(const frc::DifferentialDriveWheelSpeeds& speeds) { const double rightOutput = m_rightPIDController.Calculate( m_rightEncoder.GetRate(), speeds.right.value()); - m_leftGroup.SetVoltage(units::volt_t{leftOutput} + leftFeedforward); - m_rightGroup.SetVoltage(units::volt_t{rightOutput} + rightFeedforward); + m_leftLeader.SetVoltage(units::volt_t{leftOutput} + leftFeedforward); + m_rightLeader.SetVoltage(units::volt_t{rightOutput} + rightFeedforward); } void Drivetrain::Drive(units::meters_per_second_t xSpeed, diff --git a/wpilibcExamples/src/main/cpp/examples/DifferentialDriveBot/include/Drivetrain.h b/wpilibcExamples/src/main/cpp/examples/DifferentialDriveBot/include/Drivetrain.h index 54b2e26290f..85bccc7f521 100644 --- a/wpilibcExamples/src/main/cpp/examples/DifferentialDriveBot/include/Drivetrain.h +++ b/wpilibcExamples/src/main/cpp/examples/DifferentialDriveBot/include/Drivetrain.h @@ -12,7 +12,6 @@ #include #include #include -#include #include #include #include @@ -25,10 +24,13 @@ class Drivetrain { public: Drivetrain() { + m_leftLeader.AddFollower(m_leftFollower); + m_rightLeader.AddFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightGroup.SetInverted(true); + m_rightLeader.SetInverted(true); m_gyro.Reset(); // Set the distance per pulse for the drive encoders. We can simply use the @@ -63,9 +65,6 @@ class Drivetrain { frc::PWMSparkMax m_rightLeader{3}; frc::PWMSparkMax m_rightFollower{4}; - frc::MotorControllerGroup m_leftGroup{m_leftLeader, m_leftFollower}; - frc::MotorControllerGroup m_rightGroup{m_rightLeader, m_rightFollower}; - frc::Encoder m_leftEncoder{0, 1}; frc::Encoder m_rightEncoder{2, 3}; diff --git a/wpilibcExamples/src/main/cpp/examples/DifferentialDrivePoseEstimator/cpp/Drivetrain.cpp b/wpilibcExamples/src/main/cpp/examples/DifferentialDrivePoseEstimator/cpp/Drivetrain.cpp index 725074a71a7..caba17d9e93 100644 --- a/wpilibcExamples/src/main/cpp/examples/DifferentialDrivePoseEstimator/cpp/Drivetrain.cpp +++ b/wpilibcExamples/src/main/cpp/examples/DifferentialDrivePoseEstimator/cpp/Drivetrain.cpp @@ -7,10 +7,13 @@ #include "ExampleGlobalMeasurementSensor.h" Drivetrain::Drivetrain() { + m_leftLeader.AddFollower(m_leftFollower); + m_rightLeader.AddFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightGroup.SetInverted(true); + m_rightLeader.SetInverted(true); m_gyro.Reset(); @@ -37,8 +40,8 @@ void Drivetrain::SetSpeeds(const frc::DifferentialDriveWheelSpeeds& speeds) { const double rightOutput = m_rightPIDController.Calculate( m_rightEncoder.GetRate(), speeds.right.value()); - m_leftGroup.SetVoltage(units::volt_t{leftOutput} + leftFeedforward); - m_rightGroup.SetVoltage(units::volt_t{rightOutput} + rightFeedforward); + m_leftLeader.SetVoltage(units::volt_t{leftOutput} + leftFeedforward); + m_rightLeader.SetVoltage(units::volt_t{rightOutput} + rightFeedforward); } void Drivetrain::Drive(units::meters_per_second_t xSpeed, @@ -110,9 +113,9 @@ void Drivetrain::SimulationPeriodic() { // To update our simulation, we set motor voltage inputs, update the // simulation, and write the simulated positions and velocities to our // simulated encoder and gyro. - m_drivetrainSimulator.SetInputs(units::volt_t{m_leftGroup.Get()} * + m_drivetrainSimulator.SetInputs(units::volt_t{m_leftLeader.Get()} * frc::RobotController::GetInputVoltage(), - units::volt_t{m_rightGroup.Get()} * + units::volt_t{m_rightLeader.Get()} * frc::RobotController::GetInputVoltage()); m_drivetrainSimulator.Update(20_ms); diff --git a/wpilibcExamples/src/main/cpp/examples/DifferentialDrivePoseEstimator/include/Drivetrain.h b/wpilibcExamples/src/main/cpp/examples/DifferentialDrivePoseEstimator/include/Drivetrain.h index ac4de4c566f..633571ef173 100644 --- a/wpilibcExamples/src/main/cpp/examples/DifferentialDrivePoseEstimator/include/Drivetrain.h +++ b/wpilibcExamples/src/main/cpp/examples/DifferentialDrivePoseEstimator/include/Drivetrain.h @@ -21,7 +21,6 @@ #include #include #include -#include #include #include #include @@ -132,7 +131,7 @@ class Drivetrain { nt::DoubleArrayEntry& m_cameraToObjectEntryRef = m_cameraToObjectEntry; frc::AprilTagFieldLayout m_aprilTagFieldLayout{ - frc::LoadAprilTagLayoutField(frc::AprilTagField::k2022RapidReact)}; + frc::AprilTagFieldLayout::LoadField(frc::AprilTagField::k2024Crescendo)}; frc::Pose3d m_objectInField{m_aprilTagFieldLayout.GetTagPose(0).value()}; frc::PWMSparkMax m_leftLeader{1}; @@ -140,9 +139,6 @@ class Drivetrain { frc::PWMSparkMax m_rightLeader{3}; frc::PWMSparkMax m_rightFollower{4}; - frc::MotorControllerGroup m_leftGroup{m_leftLeader, m_leftFollower}; - frc::MotorControllerGroup m_rightGroup{m_rightLeader, m_rightFollower}; - frc::Encoder m_leftEncoder{0, 1}; frc::Encoder m_rightEncoder{2, 3}; diff --git a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/Robot.cpp index c7eab485a5d..c4c1661d699 100644 --- a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/Robot.cpp @@ -37,7 +37,7 @@ void Robot::DisabledPeriodic() {} void Robot::AutonomousInit() { m_autonomousCommand = m_container.GetAutonomousCommand(); - if (m_autonomousCommand != nullptr) { + if (m_autonomousCommand) { m_autonomousCommand->Schedule(); } } @@ -49,9 +49,9 @@ void Robot::TeleopInit() { // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. - if (m_autonomousCommand != nullptr) { + if (m_autonomousCommand) { m_autonomousCommand->Cancel(); - m_autonomousCommand = nullptr; + m_autonomousCommand.reset(); } } diff --git a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/RobotContainer.cpp b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/RobotContainer.cpp index bcb7e7367b6..37ae1aac11a 100644 --- a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/RobotContainer.cpp +++ b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/RobotContainer.cpp @@ -4,6 +4,8 @@ #include "RobotContainer.h" +#include + #include "commands/DriveDistanceProfiled.h" RobotContainer::RobotContainer() { @@ -60,7 +62,7 @@ void RobotContainer::ConfigureButtonBindings() { .WithTimeout(10_s)); } -frc2::Command* RobotContainer::GetAutonomousCommand() { +frc2::CommandPtr RobotContainer::GetAutonomousCommand() { // Runs the chosen command in autonomous - return nullptr; + return frc2::cmd::None(); } diff --git a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/subsystems/DriveSubsystem.cpp index db8ba707551..84fae4f2f0e 100644 --- a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/cpp/subsystems/DriveSubsystem.cpp @@ -12,16 +12,14 @@ DriveSubsystem::DriveSubsystem() m_rightLeader{kRightMotor1Port}, m_rightFollower{kRightMotor2Port}, m_feedforward{ks, kv, ka} { + wpi::SendableRegistry::AddChild(&m_drive, &m_leftLeader); + wpi::SendableRegistry::AddChild(&m_drive, &m_rightLeader); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. m_rightLeader.SetInverted(true); - // You might need to not do this depending on the specific motor controller - // that you are using -- contact the respective vendor's documentation for - // more details. - m_rightFollower.SetInverted(true); - m_leftFollower.Follow(m_leftLeader); m_rightFollower.Follow(m_rightLeader); diff --git a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/Constants.h index 7b7de4080ee..c9ec7e710f0 100644 --- a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/Constants.h @@ -22,26 +22,26 @@ */ namespace DriveConstants { -constexpr int kLeftMotor1Port = 0; -constexpr int kLeftMotor2Port = 1; -constexpr int kRightMotor1Port = 2; -constexpr int kRightMotor2Port = 3; +inline constexpr int kLeftMotor1Port = 0; +inline constexpr int kLeftMotor2Port = 1; +inline constexpr int kRightMotor1Port = 2; +inline constexpr int kRightMotor2Port = 3; // These are example values only - DO NOT USE THESE FOR YOUR OWN ROBOT! // These characterization values MUST be determined either experimentally or // theoretically for *your* robot's drive. The SysId tool provides a convenient // method for obtaining these values for your robot. -constexpr auto ks = 1_V; -constexpr auto kv = 0.8_V * 1_s / 1_m; -constexpr auto ka = 0.15_V * 1_s * 1_s / 1_m; +inline constexpr auto ks = 1_V; +inline constexpr auto kv = 0.8_V * 1_s / 1_m; +inline constexpr auto ka = 0.15_V * 1_s * 1_s / 1_m; -constexpr double kp = 1; +inline constexpr double kp = 1; -constexpr auto kMaxSpeed = 3_mps; -constexpr auto kMaxAcceleration = 3_mps_sq; +inline constexpr auto kMaxSpeed = 3_mps; +inline constexpr auto kMaxAcceleration = 3_mps_sq; } // namespace DriveConstants namespace OIConstants { -constexpr int kDriverControllerPort = 0; +inline constexpr int kDriverControllerPort = 0; } // namespace OIConstants diff --git a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/ExampleSmartMotorController.h b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/ExampleSmartMotorController.h index 71dc4d4864a..fe09a15f226 100644 --- a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/ExampleSmartMotorController.h +++ b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/ExampleSmartMotorController.h @@ -4,15 +4,13 @@ #pragma once -#include - /** * A simplified stub class that simulates the API of a common "smart" motor * controller. * *

Has no actual functionality. */ -class ExampleSmartMotorController : public frc::MotorController { +class ExampleSmartMotorController { public: enum PIDMode { kPosition, kVelocity, kMovementWitchcraft }; @@ -68,17 +66,17 @@ class ExampleSmartMotorController : public frc::MotorController { */ void ResetEncoder() {} - void Set(double speed) override { m_value = speed; } + void Set(double speed) { m_value = speed; } - double Get() const override { return m_value; } + double Get() const { return m_value; } - void SetInverted(bool isInverted) override {} + void SetInverted(bool isInverted) {} - bool GetInverted() const override { return false; } + bool GetInverted() const { return false; } - void Disable() override {} + void Disable() {} - void StopMotor() override {} + void StopMotor() {} private: double m_value = 0.0; diff --git a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/Robot.h b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/Robot.h index a82f2ac63b0..de9c814e752 100644 --- a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/Robot.h +++ b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/Robot.h @@ -4,6 +4,8 @@ #pragma once +#include + #include #include @@ -24,7 +26,7 @@ class Robot : public frc::TimedRobot { private: // Have it null by default so that if testing teleop it // doesn't have undefined behavior and potentially crash. - frc2::Command* m_autonomousCommand = nullptr; + std::optional m_autonomousCommand; RobotContainer m_container; }; diff --git a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/RobotContainer.h b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/RobotContainer.h index 4700a70564c..6bfda5828b4 100644 --- a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/RobotContainer.h +++ b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/RobotContainer.h @@ -23,7 +23,7 @@ class RobotContainer { public: RobotContainer(); - frc2::Command* GetAutonomousCommand(); + frc2::CommandPtr GetAutonomousCommand(); private: // The driver's controller diff --git a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/subsystems/DriveSubsystem.h b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/subsystems/DriveSubsystem.h index 9086353bf94..3dd5f03f10a 100644 --- a/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/subsystems/DriveSubsystem.h +++ b/wpilibcExamples/src/main/cpp/examples/DriveDistanceOffboard/include/subsystems/DriveSubsystem.h @@ -83,5 +83,7 @@ class DriveSubsystem : public frc2::SubsystemBase { frc::SimpleMotorFeedforward m_feedforward; // The robot's drive - frc::DifferentialDrive m_drive{m_leftLeader, m_rightLeader}; + frc::DifferentialDrive m_drive{ + [&](double output) { m_leftLeader.Set(output); }, + [&](double output) { m_rightLeader.Set(output); }}; }; diff --git a/wpilibcExamples/src/main/cpp/examples/ElevatorExponentialProfile/include/ExampleSmartMotorController.h b/wpilibcExamples/src/main/cpp/examples/ElevatorExponentialProfile/include/ExampleSmartMotorController.h index 5d55839892f..bd48d88e0bc 100644 --- a/wpilibcExamples/src/main/cpp/examples/ElevatorExponentialProfile/include/ExampleSmartMotorController.h +++ b/wpilibcExamples/src/main/cpp/examples/ElevatorExponentialProfile/include/ExampleSmartMotorController.h @@ -4,15 +4,13 @@ #pragma once -#include - /** * A simplified stub class that simulates the API of a common "smart" motor * controller. * *

Has no actual functionality. */ -class ExampleSmartMotorController : public frc::MotorController { +class ExampleSmartMotorController { public: enum PIDMode { kPosition, kVelocity, kMovementWitchcraft }; @@ -68,15 +66,15 @@ class ExampleSmartMotorController : public frc::MotorController { */ void ResetEncoder() {} - void Set(double speed) override {} + void Set(double speed) {} - double Get() const override { return 0; } + double Get() const { return 0; } - void SetInverted(bool isInverted) override {} + void SetInverted(bool isInverted) {} - bool GetInverted() const override { return false; } + bool GetInverted() const { return false; } - void Disable() override {} + void Disable() {} - void StopMotor() override {} + void StopMotor() {} }; diff --git a/wpilibcExamples/src/main/cpp/examples/ElevatorExponentialSimulation/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/ElevatorExponentialSimulation/include/Constants.h index 7c53018fe9b..65d9815757e 100644 --- a/wpilibcExamples/src/main/cpp/examples/ElevatorExponentialSimulation/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/ElevatorExponentialSimulation/include/Constants.h @@ -25,33 +25,33 @@ namespace Constants { -static constexpr int kMotorPort = 0; -static constexpr int kEncoderAChannel = 0; -static constexpr int kEncoderBChannel = 1; -static constexpr int kJoystickPort = 0; - -static constexpr double kElevatorKp = 0.75; -static constexpr double kElevatorKi = 0.0; -static constexpr double kElevatorKd = 0.0; - -static constexpr units::volt_t kElevatorMaxV = 10_V; -static constexpr units::volt_t kElevatorkS = 0.0_V; -static constexpr units::volt_t kElevatorkG = 0.62_V; -static constexpr auto kElevatorkV = 3.9_V / 1_mps; -static constexpr auto kElevatorkA = 0.06_V / 1_mps_sq; - -static constexpr double kElevatorGearing = 5.0; -static constexpr units::meter_t kElevatorDrumRadius = 1_in; -static constexpr units::kilogram_t kCarriageMass = 12_lb; - -static constexpr units::meter_t kSetpoint = 42.875_in; -static constexpr units::meter_t kLowerSetpoint = 15_in; -static constexpr units::meter_t kMinElevatorHeight = 0_cm; -static constexpr units::meter_t kMaxElevatorHeight = 50_in; +inline constexpr int kMotorPort = 0; +inline constexpr int kEncoderAChannel = 0; +inline constexpr int kEncoderBChannel = 1; +inline constexpr int kJoystickPort = 0; + +inline constexpr double kElevatorKp = 0.75; +inline constexpr double kElevatorKi = 0.0; +inline constexpr double kElevatorKd = 0.0; + +inline constexpr units::volt_t kElevatorMaxV = 10_V; +inline constexpr units::volt_t kElevatorkS = 0.0_V; +inline constexpr units::volt_t kElevatorkG = 0.62_V; +inline constexpr auto kElevatorkV = 3.9_V / 1_mps; +inline constexpr auto kElevatorkA = 0.06_V / 1_mps_sq; + +inline constexpr double kElevatorGearing = 5.0; +inline constexpr units::meter_t kElevatorDrumRadius = 1_in; +inline constexpr units::kilogram_t kCarriageMass = 12_lb; + +inline constexpr units::meter_t kSetpoint = 42.875_in; +inline constexpr units::meter_t kLowerSetpoint = 15_in; +inline constexpr units::meter_t kMinElevatorHeight = 0_cm; +inline constexpr units::meter_t kMaxElevatorHeight = 50_in; // distance per pulse = (distance per revolution) / (pulses per revolution) // = (Pi * D) / ppr -static constexpr double kArmEncoderDistPerPulse = +inline constexpr double kArmEncoderDistPerPulse = 2.0 * std::numbers::pi * kElevatorDrumRadius.value() / 4096.0; } // namespace Constants diff --git a/wpilibcExamples/src/main/cpp/examples/ElevatorSimulation/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/ElevatorSimulation/include/Constants.h index 7be706f9f5c..1123dc0cd4e 100644 --- a/wpilibcExamples/src/main/cpp/examples/ElevatorSimulation/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/ElevatorSimulation/include/Constants.h @@ -25,31 +25,31 @@ namespace Constants { -static constexpr int kMotorPort = 0; -static constexpr int kEncoderAChannel = 0; -static constexpr int kEncoderBChannel = 1; -static constexpr int kJoystickPort = 0; +inline constexpr int kMotorPort = 0; +inline constexpr int kEncoderAChannel = 0; +inline constexpr int kEncoderBChannel = 1; +inline constexpr int kJoystickPort = 0; -static constexpr double kElevatorKp = 5.0; -static constexpr double kElevatorKi = 0.0; -static constexpr double kElevatorKd = 0.0; +inline constexpr double kElevatorKp = 5.0; +inline constexpr double kElevatorKi = 0.0; +inline constexpr double kElevatorKd = 0.0; -static constexpr units::volt_t kElevatorkS = 0.0_V; -static constexpr units::volt_t kElevatorkG = 0.762_V; -static constexpr auto kElevatorkV = 0.762_V / 1_mps; -static constexpr auto kElevatorkA = 0.0_V / 1_mps_sq; +inline constexpr units::volt_t kElevatorkS = 0.0_V; +inline constexpr units::volt_t kElevatorkG = 0.762_V; +inline constexpr auto kElevatorkV = 0.762_V / 1_mps; +inline constexpr auto kElevatorkA = 0.0_V / 1_mps_sq; -static constexpr double kElevatorGearing = 10.0; -static constexpr units::meter_t kElevatorDrumRadius = 2_in; -static constexpr units::kilogram_t kCarriageMass = 4.0_kg; +inline constexpr double kElevatorGearing = 10.0; +inline constexpr units::meter_t kElevatorDrumRadius = 2_in; +inline constexpr units::kilogram_t kCarriageMass = 4.0_kg; -static constexpr units::meter_t kSetpoint = 75_cm; -static constexpr units::meter_t kMinElevatorHeight = 0_cm; -static constexpr units::meter_t kMaxElevatorHeight = 1.25_m; +inline constexpr units::meter_t kSetpoint = 75_cm; +inline constexpr units::meter_t kMinElevatorHeight = 0_cm; +inline constexpr units::meter_t kMaxElevatorHeight = 1.25_m; // distance per pulse = (distance per revolution) / (pulses per revolution) // = (Pi * D) / ppr -static constexpr double kArmEncoderDistPerPulse = +inline constexpr double kArmEncoderDistPerPulse = 2.0 * std::numbers::pi * kElevatorDrumRadius.value() / 4096.0; } // namespace Constants diff --git a/wpilibcExamples/src/main/cpp/examples/ElevatorTrapezoidProfile/include/ExampleSmartMotorController.h b/wpilibcExamples/src/main/cpp/examples/ElevatorTrapezoidProfile/include/ExampleSmartMotorController.h index 5d55839892f..bd48d88e0bc 100644 --- a/wpilibcExamples/src/main/cpp/examples/ElevatorTrapezoidProfile/include/ExampleSmartMotorController.h +++ b/wpilibcExamples/src/main/cpp/examples/ElevatorTrapezoidProfile/include/ExampleSmartMotorController.h @@ -4,15 +4,13 @@ #pragma once -#include - /** * A simplified stub class that simulates the API of a common "smart" motor * controller. * *

Has no actual functionality. */ -class ExampleSmartMotorController : public frc::MotorController { +class ExampleSmartMotorController { public: enum PIDMode { kPosition, kVelocity, kMovementWitchcraft }; @@ -68,15 +66,15 @@ class ExampleSmartMotorController : public frc::MotorController { */ void ResetEncoder() {} - void Set(double speed) override {} + void Set(double speed) {} - double Get() const override { return 0; } + double Get() const { return 0; } - void SetInverted(bool isInverted) override {} + void SetInverted(bool isInverted) {} - bool GetInverted() const override { return false; } + bool GetInverted() const { return false; } - void Disable() override {} + void Disable() {} - void StopMotor() override {} + void StopMotor() {} }; diff --git a/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/subsystems/DriveSubsystem.cpp index f40a649ec84..0e4068f22eb 100644 --- a/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/Frisbeebot/cpp/subsystems/DriveSubsystem.cpp @@ -13,10 +13,16 @@ DriveSubsystem::DriveSubsystem() m_right2{kRightMotor2Port}, m_leftEncoder{kLeftEncoderPorts[0], kLeftEncoderPorts[1]}, m_rightEncoder{kRightEncoderPorts[0], kRightEncoderPorts[1]} { + wpi::SendableRegistry::AddChild(&m_drive, &m_left1); + wpi::SendableRegistry::AddChild(&m_drive, &m_right1); + + m_left1.AddFollower(m_left2); + m_right1.AddFollower(m_right2); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_leftMotors.SetInverted(true); + m_left1.SetInverted(true); // Set the distance per pulse for the encoders m_leftEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); diff --git a/wpilibcExamples/src/main/cpp/examples/Frisbeebot/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/Frisbeebot/include/Constants.h index 855603ac194..d3aab419d63 100644 --- a/wpilibcExamples/src/main/cpp/examples/Frisbeebot/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/Frisbeebot/include/Constants.h @@ -20,56 +20,56 @@ */ namespace DriveConstants { -constexpr int kLeftMotor1Port = 0; -constexpr int kLeftMotor2Port = 1; -constexpr int kRightMotor1Port = 2; -constexpr int kRightMotor2Port = 3; +inline constexpr int kLeftMotor1Port = 0; +inline constexpr int kLeftMotor2Port = 1; +inline constexpr int kRightMotor1Port = 2; +inline constexpr int kRightMotor2Port = 3; -constexpr int kLeftEncoderPorts[]{0, 1}; -constexpr int kRightEncoderPorts[]{2, 3}; -constexpr bool kLeftEncoderReversed = false; -constexpr bool kRightEncoderReversed = true; +inline constexpr int kLeftEncoderPorts[]{0, 1}; +inline constexpr int kRightEncoderPorts[]{2, 3}; +inline constexpr bool kLeftEncoderReversed = false; +inline constexpr bool kRightEncoderReversed = true; -constexpr int kEncoderCPR = 1024; -constexpr double kWheelDiameterInches = 6; -constexpr double kEncoderDistancePerPulse = +inline constexpr int kEncoderCPR = 1024; +inline constexpr double kWheelDiameterInches = 6; +inline constexpr double kEncoderDistancePerPulse = // Assumes the encoders are directly mounted on the wheel shafts (kWheelDiameterInches * std::numbers::pi) / static_cast(kEncoderCPR); } // namespace DriveConstants namespace ShooterConstants { -constexpr int kEncoderPorts[]{4, 5}; -constexpr bool kEncoderReversed = false; -constexpr int kEncoderCPR = 1024; -constexpr double kEncoderDistancePerPulse = +inline constexpr int kEncoderPorts[]{4, 5}; +inline constexpr bool kEncoderReversed = false; +inline constexpr int kEncoderCPR = 1024; +inline constexpr double kEncoderDistancePerPulse = // Distance units will be rotations 1.0 / static_cast(kEncoderCPR); -constexpr int kShooterMotorPort = 4; -constexpr int kFeederMotorPort = 5; +inline constexpr int kShooterMotorPort = 4; +inline constexpr int kFeederMotorPort = 5; -constexpr auto kShooterFreeRPS = 5300_tr / 1_s; -constexpr auto kShooterTargetRPS = 4000_tr / 1_s; -constexpr auto kShooterToleranceRPS = 50_tr / 1_s; +inline constexpr auto kShooterFreeRPS = 5300_tr / 1_s; +inline constexpr auto kShooterTargetRPS = 4000_tr / 1_s; +inline constexpr auto kShooterToleranceRPS = 50_tr / 1_s; -constexpr double kP = 1; -constexpr double kI = 0; -constexpr double kD = 0; +inline constexpr double kP = 1; +inline constexpr double kI = 0; +inline constexpr double kD = 0; // On a real robot the feedforward constants should be empirically determined; // these are reasonable guesses. -constexpr auto kS = 0.05_V; -constexpr auto kV = +inline constexpr auto kS = 0.05_V; +inline constexpr auto kV = // Should have value 12V at free speed... 12_V / kShooterFreeRPS; -constexpr double kFeederSpeed = 0.5; +inline constexpr double kFeederSpeed = 0.5; } // namespace ShooterConstants namespace AutoConstants { -constexpr auto kAutoTimeoutSeconds = 12_s; -constexpr auto kAutoShootTimeSeconds = 7_s; +inline constexpr auto kAutoTimeoutSeconds = 12_s; +inline constexpr auto kAutoShootTimeSeconds = 7_s; } // namespace AutoConstants namespace OIConstants { diff --git a/wpilibcExamples/src/main/cpp/examples/Frisbeebot/include/subsystems/DriveSubsystem.h b/wpilibcExamples/src/main/cpp/examples/Frisbeebot/include/subsystems/DriveSubsystem.h index 47bf28e4d91..47d3f3d49b2 100644 --- a/wpilibcExamples/src/main/cpp/examples/Frisbeebot/include/subsystems/DriveSubsystem.h +++ b/wpilibcExamples/src/main/cpp/examples/Frisbeebot/include/subsystems/DriveSubsystem.h @@ -6,7 +6,6 @@ #include #include -#include #include #include @@ -75,14 +74,9 @@ class DriveSubsystem : public frc2::SubsystemBase { frc::PWMSparkMax m_right1; frc::PWMSparkMax m_right2; - // The motors on the left side of the drive - frc::MotorControllerGroup m_leftMotors{m_left1, m_left2}; - - // The motors on the right side of the drive - frc::MotorControllerGroup m_rightMotors{m_right1, m_right2}; - // The robot's drive - frc::DifferentialDrive m_drive{m_leftMotors, m_rightMotors}; + frc::DifferentialDrive m_drive{[&](double output) { m_left1.Set(output); }, + [&](double output) { m_right1.Set(output); }}; // The left-side drive encoder frc::Encoder m_leftEncoder; diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Drivetrain.cpp b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Drivetrain.cpp index 2bfd391d6aa..2928036afc9 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Drivetrain.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/cpp/subsystems/Drivetrain.cpp @@ -11,10 +11,16 @@ #include Drivetrain::Drivetrain() { + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_frontLeft); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_frontRight); + + m_frontLeft.AddFollower(m_rearLeft); + m_frontRight.AddFollower(m_rearRight); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_right.SetInverted(true); + m_frontRight.SetInverted(true); // Encoders may measure differently in the real world and in // simulation. In this example the robot moves 0.042 barleycorns diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Drivetrain.h b/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Drivetrain.h index 9e739c4dbc3..cc3c95f9b3a 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Drivetrain.h +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Drivetrain.h @@ -8,7 +8,6 @@ #include #include #include -#include #include #include @@ -66,13 +65,13 @@ class Drivetrain : public frc2::SubsystemBase { private: frc::PWMSparkMax m_frontLeft{1}; frc::PWMSparkMax m_rearLeft{2}; - frc::MotorControllerGroup m_left{m_frontLeft, m_rearLeft}; frc::PWMSparkMax m_frontRight{3}; frc::PWMSparkMax m_rearRight{4}; - frc::MotorControllerGroup m_right{m_frontRight, m_rearRight}; - frc::DifferentialDrive m_robotDrive{m_left, m_right}; + frc::DifferentialDrive m_robotDrive{ + [&](double output) { m_frontLeft.Set(output); }, + [&](double output) { m_frontRight.Set(output); }}; frc::Encoder m_leftEncoder{1, 2}; frc::Encoder m_rightEncoder{3, 4}; diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Elevator.h b/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Elevator.h index 80008c5d0ed..055680d9dcc 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Elevator.h +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Elevator.h @@ -44,7 +44,6 @@ class Elevator : public frc2::PIDSubsystem { private: frc::PWMSparkMax m_motor{5}; - double m_setpoint = 0; // Conversion value of potentiometer varies between the real world and // simulation diff --git a/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Wrist.h b/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Wrist.h index 7df08b95ef5..7b99f175d0a 100644 --- a/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Wrist.h +++ b/wpilibcExamples/src/main/cpp/examples/GearsBot/include/subsystems/Wrist.h @@ -41,7 +41,6 @@ class Wrist : public frc2::PIDSubsystem { private: frc::PWMSparkMax m_motor{6}; - double m_setpoint = 0; // Conversion value of potentiometer varies between the real world and // simulation diff --git a/wpilibcExamples/src/main/cpp/examples/GettingStarted/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/GettingStarted/cpp/Robot.cpp index 01b72108759..0a73f1402f8 100644 --- a/wpilibcExamples/src/main/cpp/examples/GettingStarted/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GettingStarted/cpp/Robot.cpp @@ -11,6 +11,9 @@ class Robot : public frc::TimedRobot { public: Robot() { + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_left); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_right); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. @@ -48,7 +51,9 @@ class Robot : public frc::TimedRobot { // Robot drive system frc::PWMSparkMax m_left{0}; frc::PWMSparkMax m_right{1}; - frc::DifferentialDrive m_robotDrive{m_left, m_right}; + frc::DifferentialDrive m_robotDrive{ + [&](double output) { m_left.Set(output); }, + [&](double output) { m_right.Set(output); }}; frc::XboxController m_controller{0}; frc::Timer m_timer; diff --git a/wpilibcExamples/src/main/cpp/examples/Gyro/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/Gyro/cpp/Robot.cpp index 5230c7c3973..d8af4100acb 100644 --- a/wpilibcExamples/src/main/cpp/examples/Gyro/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/Gyro/cpp/Robot.cpp @@ -17,6 +17,11 @@ */ class Robot : public frc::TimedRobot { public: + Robot() { + wpi::SendableRegistry::AddChild(&m_drive, &m_left); + wpi::SendableRegistry::AddChild(&m_drive, &m_right); + } + void RobotInit() override { m_gyro.SetSensitivity(kVoltsPerDegreePerSecond); // We need to invert one side of the drivetrain so that positive voltages @@ -50,7 +55,8 @@ class Robot : public frc::TimedRobot { frc::PWMSparkMax m_left{kLeftMotorPort}; frc::PWMSparkMax m_right{kRightMotorPort}; - frc::DifferentialDrive m_drive{m_left, m_right}; + frc::DifferentialDrive m_drive{[&](double output) { m_left.Set(output); }, + [&](double output) { m_right.Set(output); }}; frc::AnalogGyro m_gyro{kGyroPort}; frc::Joystick m_joystick{kJoystickPort}; diff --git a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/Robot.cpp index c7eab485a5d..c4c1661d699 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/Robot.cpp @@ -37,7 +37,7 @@ void Robot::DisabledPeriodic() {} void Robot::AutonomousInit() { m_autonomousCommand = m_container.GetAutonomousCommand(); - if (m_autonomousCommand != nullptr) { + if (m_autonomousCommand) { m_autonomousCommand->Schedule(); } } @@ -49,9 +49,9 @@ void Robot::TeleopInit() { // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. - if (m_autonomousCommand != nullptr) { + if (m_autonomousCommand) { m_autonomousCommand->Cancel(); - m_autonomousCommand = nullptr; + m_autonomousCommand.reset(); } } diff --git a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/RobotContainer.cpp b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/RobotContainer.cpp index 50b9900c225..7b076840b9b 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/RobotContainer.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/RobotContainer.cpp @@ -64,7 +64,7 @@ void RobotContainer::ConfigureButtonBindings() { .OnFalse(frc2::cmd::RunOnce([this] { m_drive.SetMaxOutput(1); }, {})); } -frc2::Command* RobotContainer::GetAutonomousCommand() { +frc2::CommandPtr RobotContainer::GetAutonomousCommand() { // no auto - return nullptr; + return frc2::cmd::None(); } diff --git a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/subsystems/DriveSubsystem.cpp index 0cbd0e548d1..a97a5c071f6 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/cpp/subsystems/DriveSubsystem.cpp @@ -13,10 +13,16 @@ DriveSubsystem::DriveSubsystem() m_right2{kRightMotor2Port}, m_leftEncoder{kLeftEncoderPorts[0], kLeftEncoderPorts[1]}, m_rightEncoder{kRightEncoderPorts[0], kRightEncoderPorts[1]} { + wpi::SendableRegistry::AddChild(&m_drive, &m_left1); + wpi::SendableRegistry::AddChild(&m_drive, &m_right1); + + m_left1.AddFollower(m_left2); + m_right1.AddFollower(m_right2); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.SetInverted(true); + m_right1.SetInverted(true); // Set the distance per pulse for the encoders m_leftEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); diff --git a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/Constants.h index 77673c96a17..4d25b0bfb90 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/Constants.h @@ -19,46 +19,46 @@ */ namespace DriveConstants { -constexpr int kLeftMotor1Port = 0; -constexpr int kLeftMotor2Port = 1; -constexpr int kRightMotor1Port = 2; -constexpr int kRightMotor2Port = 3; +inline constexpr int kLeftMotor1Port = 0; +inline constexpr int kLeftMotor2Port = 1; +inline constexpr int kRightMotor1Port = 2; +inline constexpr int kRightMotor2Port = 3; -constexpr int kLeftEncoderPorts[]{0, 1}; -constexpr int kRightEncoderPorts[]{2, 3}; -constexpr bool kLeftEncoderReversed = false; -constexpr bool kRightEncoderReversed = true; +inline constexpr int kLeftEncoderPorts[]{0, 1}; +inline constexpr int kRightEncoderPorts[]{2, 3}; +inline constexpr bool kLeftEncoderReversed = false; +inline constexpr bool kRightEncoderReversed = true; -constexpr int kEncoderCPR = 1024; -constexpr double kWheelDiameterInches = 6; -constexpr double kEncoderDistancePerPulse = +inline constexpr int kEncoderCPR = 1024; +inline constexpr double kWheelDiameterInches = 6; +inline constexpr double kEncoderDistancePerPulse = // Assumes the encoders are directly mounted on the wheel shafts (kWheelDiameterInches * std::numbers::pi) / static_cast(kEncoderCPR); -constexpr bool kGyroReversed = true; +inline constexpr bool kGyroReversed = true; -constexpr double kStabilizationP = 1; -constexpr double kStabilizationI = 0.5; -constexpr double kStabilizationD = 0; +inline constexpr double kStabilizationP = 1; +inline constexpr double kStabilizationI = 0.5; +inline constexpr double kStabilizationD = 0; -constexpr double kTurnP = 1; -constexpr double kTurnI = 0; -constexpr double kTurnD = 0; +inline constexpr double kTurnP = 1; +inline constexpr double kTurnI = 0; +inline constexpr double kTurnD = 0; -constexpr auto kTurnTolerance = 5_deg; -constexpr auto kTurnRateTolerance = 10_deg_per_s; +inline constexpr auto kTurnTolerance = 5_deg; +inline constexpr auto kTurnRateTolerance = 10_deg_per_s; -constexpr auto kMaxTurnRate = 100_deg_per_s; -constexpr auto kMaxTurnAcceleration = 300_deg_per_s / 1_s; +inline constexpr auto kMaxTurnRate = 100_deg_per_s; +inline constexpr auto kMaxTurnAcceleration = 300_deg_per_s / 1_s; } // namespace DriveConstants namespace AutoConstants { -constexpr double kAutoDriveDistanceInches = 60; -constexpr double kAutoBackupDistanceInches = 20; -constexpr double kAutoDriveSpeed = 0.5; +inline constexpr double kAutoDriveDistanceInches = 60; +inline constexpr double kAutoBackupDistanceInches = 20; +inline constexpr double kAutoDriveSpeed = 0.5; } // namespace AutoConstants namespace OIConstants { -constexpr int kDriverControllerPort = 0; +inline constexpr int kDriverControllerPort = 0; } // namespace OIConstants diff --git a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/Robot.h b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/Robot.h index a82f2ac63b0..de9c814e752 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/Robot.h +++ b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/Robot.h @@ -4,6 +4,8 @@ #pragma once +#include + #include #include @@ -24,7 +26,7 @@ class Robot : public frc::TimedRobot { private: // Have it null by default so that if testing teleop it // doesn't have undefined behavior and potentially crash. - frc2::Command* m_autonomousCommand = nullptr; + std::optional m_autonomousCommand; RobotContainer m_container; }; diff --git a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/RobotContainer.h b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/RobotContainer.h index 041812e8e45..0ecb7286d9f 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/RobotContainer.h +++ b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/RobotContainer.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include "Constants.h" @@ -28,7 +29,7 @@ class RobotContainer { public: RobotContainer(); - frc2::Command* GetAutonomousCommand(); + frc2::CommandPtr GetAutonomousCommand(); private: // The driver's controller @@ -39,8 +40,5 @@ class RobotContainer { // The robot's subsystems DriveSubsystem m_drive; - // The chooser for the autonomous routines - frc::SendableChooser m_chooser; - void ConfigureButtonBindings(); }; diff --git a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/subsystems/DriveSubsystem.h b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/subsystems/DriveSubsystem.h index 96174dd4f7a..d7cce6c05c2 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/subsystems/DriveSubsystem.h +++ b/wpilibcExamples/src/main/cpp/examples/GyroDriveCommands/include/subsystems/DriveSubsystem.h @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -91,14 +90,9 @@ class DriveSubsystem : public frc2::SubsystemBase { frc::PWMSparkMax m_right1; frc::PWMSparkMax m_right2; - // The motors on the left side of the drive - frc::MotorControllerGroup m_leftMotors{m_left1, m_left2}; - - // The motors on the right side of the drive - frc::MotorControllerGroup m_rightMotors{m_right1, m_right2}; - // The robot's drive - frc::DifferentialDrive m_drive{m_leftMotors, m_rightMotors}; + frc::DifferentialDrive m_drive{[&](double output) { m_left1.Set(output); }, + [&](double output) { m_right1.Set(output); }}; // The left-side drive encoder frc::Encoder m_leftEncoder; diff --git a/wpilibcExamples/src/main/cpp/examples/GyroMecanum/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/GyroMecanum/cpp/Robot.cpp index 2207f79de51..7c589fd268e 100644 --- a/wpilibcExamples/src/main/cpp/examples/GyroMecanum/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/GyroMecanum/cpp/Robot.cpp @@ -16,6 +16,11 @@ class Robot : public frc::TimedRobot { public: void RobotInit() override { + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_frontLeft); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_rearLeft); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_frontRight); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_rearRight); + // Invert the right side motors. You may need to change or remove this to // match your robot. m_frontRight.SetInverted(true); @@ -48,8 +53,11 @@ class Robot : public frc::TimedRobot { frc::PWMSparkMax m_rearLeft{kRearLeftMotorPort}; frc::PWMSparkMax m_frontRight{kFrontRightMotorPort}; frc::PWMSparkMax m_rearRight{kRearRightMotorPort}; - frc::MecanumDrive m_robotDrive{m_frontLeft, m_rearLeft, m_frontRight, - m_rearRight}; + frc::MecanumDrive m_robotDrive{ + [&](double output) { m_frontLeft.Set(output); }, + [&](double output) { m_rearLeft.Set(output); }, + [&](double output) { m_frontRight.Set(output); }, + [&](double output) { m_rearRight.Set(output); }}; frc::AnalogGyro m_gyro{kGyroPort}; frc::Joystick m_joystick{kJoystickPort}; diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/cpp/subsystems/DriveSubsystem.cpp index 3372a4dca9d..d7b33eac79d 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/cpp/subsystems/DriveSubsystem.cpp @@ -15,10 +15,16 @@ DriveSubsystem::DriveSubsystem() m_right2{kRightMotor2Port}, m_leftEncoder{kLeftEncoderPorts[0], kLeftEncoderPorts[1]}, m_rightEncoder{kRightEncoderPorts[0], kRightEncoderPorts[1]} { + wpi::SendableRegistry::AddChild(&m_drive, &m_left1); + wpi::SendableRegistry::AddChild(&m_drive, &m_right1); + + m_left1.AddFollower(m_left2); + m_right1.AddFollower(m_right2); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.SetInverted(true); + m_right1.SetInverted(true); // Set the distance per pulse for the encoders m_leftEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/include/Constants.h index 7a2bdae72e8..f82b8dba619 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/include/Constants.h @@ -16,35 +16,35 @@ */ namespace DriveConstants { -constexpr int kLeftMotor1Port = 0; -constexpr int kLeftMotor2Port = 1; -constexpr int kRightMotor1Port = 2; -constexpr int kRightMotor2Port = 3; - -constexpr int kLeftEncoderPorts[]{0, 1}; -constexpr int kRightEncoderPorts[]{2, 3}; -constexpr bool kLeftEncoderReversed = false; -constexpr bool kRightEncoderReversed = true; - -constexpr int kEncoderCPR = 1024; -constexpr double kWheelDiameterInches = 6; -constexpr double kEncoderDistancePerPulse = +inline constexpr int kLeftMotor1Port = 0; +inline constexpr int kLeftMotor2Port = 1; +inline constexpr int kRightMotor1Port = 2; +inline constexpr int kRightMotor2Port = 3; + +inline constexpr int kLeftEncoderPorts[]{0, 1}; +inline constexpr int kRightEncoderPorts[]{2, 3}; +inline constexpr bool kLeftEncoderReversed = false; +inline constexpr bool kRightEncoderReversed = true; + +inline constexpr int kEncoderCPR = 1024; +inline constexpr double kWheelDiameterInches = 6; +inline constexpr double kEncoderDistancePerPulse = // Assumes the encoders are directly mounted on the wheel shafts (kWheelDiameterInches * std::numbers::pi) / static_cast(kEncoderCPR); } // namespace DriveConstants namespace HatchConstants { -constexpr int kHatchSolenoidModule = 0; -constexpr int kHatchSolenoidPorts[]{0, 1}; +inline constexpr int kHatchSolenoidModule = 0; +inline constexpr int kHatchSolenoidPorts[]{0, 1}; } // namespace HatchConstants namespace AutoConstants { -constexpr double kAutoDriveDistanceInches = 60; -constexpr double kAutoBackupDistanceInches = 20; -constexpr double kAutoDriveSpeed = 0.5; +inline constexpr double kAutoDriveDistanceInches = 60; +inline constexpr double kAutoBackupDistanceInches = 20; +inline constexpr double kAutoDriveSpeed = 0.5; } // namespace AutoConstants namespace OIConstants { -constexpr int kDriverControllerPort = 0; +inline constexpr int kDriverControllerPort = 0; } // namespace OIConstants diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/include/subsystems/DriveSubsystem.h b/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/include/subsystems/DriveSubsystem.h index 5984a1a4f38..6cab5803884 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/include/subsystems/DriveSubsystem.h +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotInlined/include/subsystems/DriveSubsystem.h @@ -6,7 +6,6 @@ #include #include -#include #include #include @@ -63,14 +62,9 @@ class DriveSubsystem : public frc2::SubsystemBase { frc::PWMSparkMax m_right1; frc::PWMSparkMax m_right2; - // The motors on the left side of the drive - frc::MotorControllerGroup m_leftMotors{m_left1, m_left2}; - - // The motors on the right side of the drive - frc::MotorControllerGroup m_rightMotors{m_right1, m_right2}; - // The robot's drive - frc::DifferentialDrive m_drive{m_leftMotors, m_rightMotors}; + frc::DifferentialDrive m_drive{[&](double output) { m_left1.Set(output); }, + [&](double output) { m_right1.Set(output); }}; // The left-side drive encoder frc::Encoder m_leftEncoder; diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/subsystems/DriveSubsystem.cpp index 3372a4dca9d..d7b33eac79d 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/cpp/subsystems/DriveSubsystem.cpp @@ -15,10 +15,16 @@ DriveSubsystem::DriveSubsystem() m_right2{kRightMotor2Port}, m_leftEncoder{kLeftEncoderPorts[0], kLeftEncoderPorts[1]}, m_rightEncoder{kRightEncoderPorts[0], kRightEncoderPorts[1]} { + wpi::SendableRegistry::AddChild(&m_drive, &m_left1); + wpi::SendableRegistry::AddChild(&m_drive, &m_right1); + + m_left1.AddFollower(m_left2); + m_right1.AddFollower(m_right2); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.SetInverted(true); + m_right1.SetInverted(true); // Set the distance per pulse for the encoders m_leftEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/include/Constants.h index 7a2bdae72e8..534d8f18078 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/include/Constants.h @@ -16,27 +16,27 @@ */ namespace DriveConstants { -constexpr int kLeftMotor1Port = 0; -constexpr int kLeftMotor2Port = 1; -constexpr int kRightMotor1Port = 2; -constexpr int kRightMotor2Port = 3; - -constexpr int kLeftEncoderPorts[]{0, 1}; -constexpr int kRightEncoderPorts[]{2, 3}; -constexpr bool kLeftEncoderReversed = false; -constexpr bool kRightEncoderReversed = true; - -constexpr int kEncoderCPR = 1024; -constexpr double kWheelDiameterInches = 6; -constexpr double kEncoderDistancePerPulse = +inline constexpr int kLeftMotor1Port = 0; +inline constexpr int kLeftMotor2Port = 1; +inline constexpr int kRightMotor1Port = 2; +inline constexpr int kRightMotor2Port = 3; + +inline constexpr int kLeftEncoderPorts[]{0, 1}; +inline constexpr int kRightEncoderPorts[]{2, 3}; +inline constexpr bool kLeftEncoderReversed = false; +inline constexpr bool kRightEncoderReversed = true; + +inline constexpr int kEncoderCPR = 1024; +inline constexpr double kWheelDiameterInches = 6; +inline constexpr double kEncoderDistancePerPulse = // Assumes the encoders are directly mounted on the wheel shafts (kWheelDiameterInches * std::numbers::pi) / static_cast(kEncoderCPR); } // namespace DriveConstants namespace HatchConstants { -constexpr int kHatchSolenoidModule = 0; -constexpr int kHatchSolenoidPorts[]{0, 1}; +inline constexpr int kHatchSolenoidModule = 0; +inline constexpr int kHatchSolenoidPorts[]{0, 1}; } // namespace HatchConstants namespace AutoConstants { diff --git a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/include/subsystems/DriveSubsystem.h b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/include/subsystems/DriveSubsystem.h index 5984a1a4f38..6cab5803884 100644 --- a/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/include/subsystems/DriveSubsystem.h +++ b/wpilibcExamples/src/main/cpp/examples/HatchbotTraditional/include/subsystems/DriveSubsystem.h @@ -6,7 +6,6 @@ #include #include -#include #include #include @@ -63,14 +62,9 @@ class DriveSubsystem : public frc2::SubsystemBase { frc::PWMSparkMax m_right1; frc::PWMSparkMax m_right2; - // The motors on the left side of the drive - frc::MotorControllerGroup m_leftMotors{m_left1, m_left2}; - - // The motors on the right side of the drive - frc::MotorControllerGroup m_rightMotors{m_right1, m_right2}; - // The robot's drive - frc::DifferentialDrive m_drive{m_leftMotors, m_rightMotors}; + frc::DifferentialDrive m_drive{[&](double output) { m_left1.Set(output); }, + [&](double output) { m_right1.Set(output); }}; // The left-side drive encoder frc::Encoder m_leftEncoder; diff --git a/wpilibcExamples/src/main/cpp/examples/AxisCameraSample/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/HttpCamera/cpp/Robot.cpp similarity index 83% rename from wpilibcExamples/src/main/cpp/examples/AxisCameraSample/cpp/Robot.cpp rename to wpilibcExamples/src/main/cpp/examples/HttpCamera/cpp/Robot.cpp index 7f4f7615d20..e8b5fe0aa24 100644 --- a/wpilibcExamples/src/main/cpp/examples/AxisCameraSample/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/HttpCamera/cpp/Robot.cpp @@ -10,16 +10,18 @@ /** * This is a demo program showing the use of OpenCV to do vision processing. The - * image is acquired from the Axis camera, then a rectangle is put on the image + * image is acquired from an HTTP camera, then a rectangle is put on the image * and sent to the dashboard. OpenCV has many methods for different types of * processing. */ class Robot : public frc::TimedRobot { private: static void VisionThread() { - // Get the Axis camera from CameraServer - cs::AxisCamera camera = - frc::CameraServer::AddAxisCamera("axis-camera.local"); + // Create an HTTP camera. The address will need to be modified to have the + // correct team number. The exact path will depend on the source. + cs::HttpCamera camera{"My Camera", "http://10.x.y.11/video/stream.mjpg"}; + // Start capturing images + frc::CameraServer::StartAutomaticCapture(camera); // Set the resolution camera.SetResolution(640, 480); diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/Robot.cpp index c7eab485a5d..c4c1661d699 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/Robot.cpp @@ -37,7 +37,7 @@ void Robot::DisabledPeriodic() {} void Robot::AutonomousInit() { m_autonomousCommand = m_container.GetAutonomousCommand(); - if (m_autonomousCommand != nullptr) { + if (m_autonomousCommand) { m_autonomousCommand->Schedule(); } } @@ -49,9 +49,9 @@ void Robot::TeleopInit() { // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. - if (m_autonomousCommand != nullptr) { + if (m_autonomousCommand) { m_autonomousCommand->Cancel(); - m_autonomousCommand = nullptr; + m_autonomousCommand.reset(); } } diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/RobotContainer.cpp b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/RobotContainer.cpp index 0f691e00389..0d3db36cb04 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/RobotContainer.cpp +++ b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/RobotContainer.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -47,7 +48,7 @@ void RobotContainer::ConfigureButtonBindings() { .OnFalse(&m_driveFullSpeed); } -frc2::Command* RobotContainer::GetAutonomousCommand() { +frc2::CommandPtr RobotContainer::GetAutonomousCommand() { // Set up config for trajectory frc::TrajectoryConfig config(AutoConstants::kMaxSpeed, AutoConstants::kMaxAcceleration); @@ -65,48 +66,57 @@ frc2::Command* RobotContainer::GetAutonomousCommand() { // Pass the config config); - frc2::MecanumControllerCommand mecanumControllerCommand( - exampleTrajectory, [this]() { return m_drive.GetPose(); }, - - frc::SimpleMotorFeedforward(ks, kv, ka), - DriveConstants::kDriveKinematics, - - frc::PIDController{AutoConstants::kPXController, 0, 0}, - frc::PIDController{AutoConstants::kPYController, 0, 0}, - frc::ProfiledPIDController( - AutoConstants::kPThetaController, 0, 0, - AutoConstants::kThetaControllerConstraints), - - AutoConstants::kMaxSpeed, - - [this]() { - return frc::MecanumDriveWheelSpeeds{ - units::meters_per_second_t{m_drive.GetFrontLeftEncoder().GetRate()}, - units::meters_per_second_t{ - m_drive.GetFrontRightEncoder().GetRate()}, - units::meters_per_second_t{m_drive.GetRearLeftEncoder().GetRate()}, - units::meters_per_second_t{ - m_drive.GetRearRightEncoder().GetRate()}}; - }, - - frc::PIDController{DriveConstants::kPFrontLeftVel, 0, 0}, - frc::PIDController{DriveConstants::kPRearLeftVel, 0, 0}, - frc::PIDController{DriveConstants::kPFrontRightVel, 0, 0}, - frc::PIDController{DriveConstants::kPRearRightVel, 0, 0}, - - [this](units::volt_t frontLeft, units::volt_t rearLeft, - units::volt_t frontRight, units::volt_t rearRight) { - m_drive.SetMotorControllersVolts(frontLeft, rearLeft, frontRight, - rearRight); - }, - - {&m_drive}); - - // Reset odometry to the starting pose of the trajectory. - m_drive.ResetOdometry(exampleTrajectory.InitialPose()); - - // no auto - return new frc2::SequentialCommandGroup( + frc2::CommandPtr mecanumControllerCommand = + frc2::MecanumControllerCommand( + exampleTrajectory, [this]() { return m_drive.GetPose(); }, + + frc::SimpleMotorFeedforward(ks, kv, ka), + DriveConstants::kDriveKinematics, + + frc::PIDController{AutoConstants::kPXController, 0, 0}, + frc::PIDController{AutoConstants::kPYController, 0, 0}, + frc::ProfiledPIDController( + AutoConstants::kPThetaController, 0, 0, + AutoConstants::kThetaControllerConstraints), + + AutoConstants::kMaxSpeed, + + [this]() { + return frc::MecanumDriveWheelSpeeds{ + units::meters_per_second_t{ + m_drive.GetFrontLeftEncoder().GetRate()}, + units::meters_per_second_t{ + m_drive.GetFrontRightEncoder().GetRate()}, + units::meters_per_second_t{ + m_drive.GetRearLeftEncoder().GetRate()}, + units::meters_per_second_t{ + m_drive.GetRearRightEncoder().GetRate()}}; + }, + + frc::PIDController{DriveConstants::kPFrontLeftVel, 0, 0}, + frc::PIDController{DriveConstants::kPRearLeftVel, 0, 0}, + frc::PIDController{DriveConstants::kPFrontRightVel, 0, 0}, + frc::PIDController{DriveConstants::kPRearRightVel, 0, 0}, + + [this](units::volt_t frontLeft, units::volt_t rearLeft, + units::volt_t frontRight, units::volt_t rearRight) { + m_drive.SetMotorControllersVolts(frontLeft, rearLeft, frontRight, + rearRight); + }, + + {&m_drive}) + .ToPtr(); + + // Reset odometry to the initial pose of the trajectory, run path following + // command, then stop at the end. + return frc2::cmd::Sequence( + frc2::InstantCommand( + [this, initialPose = exampleTrajectory.InitialPose()]() { + m_drive.ResetOdometry(initialPose); + }, + {}) + .ToPtr(), std::move(mecanumControllerCommand), - frc2::InstantCommand([this]() { m_drive.Drive(0, 0, 0, false); }, {})); + frc2::InstantCommand([this]() { m_drive.Drive(0, 0, 0, false); }, {}) + .ToPtr()); } diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/subsystems/DriveSubsystem.cpp index 292ad1f52c9..8a55821e71b 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/subsystems/DriveSubsystem.cpp +++ b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/cpp/subsystems/DriveSubsystem.cpp @@ -30,6 +30,11 @@ DriveSubsystem::DriveSubsystem() m_odometry{kDriveKinematics, m_gyro.GetRotation2d(), getCurrentWheelDistances(), frc::Pose2d{}} { + wpi::SendableRegistry::AddChild(&m_drive, &m_frontLeft); + wpi::SendableRegistry::AddChild(&m_drive, &m_rearLeft); + wpi::SendableRegistry::AddChild(&m_drive, &m_frontRight); + wpi::SendableRegistry::AddChild(&m_drive, &m_rearRight); + // Set the distance per pulse for the encoders m_frontLeftEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); m_rearLeftEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/Constants.h index 527504ac3c0..7dde79c308a 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/Constants.h @@ -28,30 +28,30 @@ */ namespace DriveConstants { -constexpr int kFrontLeftMotorPort = 0; -constexpr int kRearLeftMotorPort = 1; -constexpr int kFrontRightMotorPort = 2; -constexpr int kRearRightMotorPort = 3; - -constexpr int kFrontLeftEncoderPorts[]{0, 1}; -constexpr int kRearLeftEncoderPorts[]{2, 3}; -constexpr int kFrontRightEncoderPorts[]{4, 5}; -constexpr int kRearRightEncoderPorts[]{6, 7}; - -constexpr bool kFrontLeftEncoderReversed = false; -constexpr bool kRearLeftEncoderReversed = true; -constexpr bool kFrontRightEncoderReversed = false; -constexpr bool kRearRightEncoderReversed = true; - -constexpr auto kTrackWidth = +inline constexpr int kFrontLeftMotorPort = 0; +inline constexpr int kRearLeftMotorPort = 1; +inline constexpr int kFrontRightMotorPort = 2; +inline constexpr int kRearRightMotorPort = 3; + +inline constexpr int kFrontLeftEncoderPorts[]{0, 1}; +inline constexpr int kRearLeftEncoderPorts[]{2, 3}; +inline constexpr int kFrontRightEncoderPorts[]{4, 5}; +inline constexpr int kRearRightEncoderPorts[]{6, 7}; + +inline constexpr bool kFrontLeftEncoderReversed = false; +inline constexpr bool kRearLeftEncoderReversed = true; +inline constexpr bool kFrontRightEncoderReversed = false; +inline constexpr bool kRearRightEncoderReversed = true; + +inline constexpr auto kTrackWidth = 0.5_m; // Distance between centers of right and left wheels on robot -constexpr auto kWheelBase = +inline constexpr auto kWheelBase = 0.7_m; // Distance between centers of front and back wheels on robot extern const frc::MecanumDriveKinematics kDriveKinematics; -constexpr int kEncoderCPR = 1024; -constexpr double kWheelDiameterMeters = 0.15; -constexpr double kEncoderDistancePerPulse = +inline constexpr int kEncoderCPR = 1024; +inline constexpr double kWheelDiameterMeters = 0.15; +inline constexpr double kEncoderDistancePerPulse = // Assumes the encoders are directly mounted on the wheel shafts (kWheelDiameterMeters * std::numbers::pi) / static_cast(kEncoderCPR); @@ -60,26 +60,26 @@ constexpr double kEncoderDistancePerPulse = // These characterization values MUST be determined either experimentally or // theoretically for *your* robot's drive. The SysId tool provides a convenient // method for obtaining these values for your robot. -constexpr auto ks = 1_V; -constexpr auto kv = 0.8 * 1_V * 1_s / 1_m; -constexpr auto ka = 0.15 * 1_V * 1_s * 1_s / 1_m; +inline constexpr auto ks = 1_V; +inline constexpr auto kv = 0.8 * 1_V * 1_s / 1_m; +inline constexpr auto ka = 0.15 * 1_V * 1_s * 1_s / 1_m; // Example value only - as above, this must be tuned for your drive! -constexpr double kPFrontLeftVel = 0.5; -constexpr double kPRearLeftVel = 0.5; -constexpr double kPFrontRightVel = 0.5; -constexpr double kPRearRightVel = 0.5; +inline constexpr double kPFrontLeftVel = 0.5; +inline constexpr double kPRearLeftVel = 0.5; +inline constexpr double kPFrontRightVel = 0.5; +inline constexpr double kPRearRightVel = 0.5; } // namespace DriveConstants namespace AutoConstants { -constexpr auto kMaxSpeed = 3_mps; -constexpr auto kMaxAcceleration = 3_mps_sq; -constexpr auto kMaxAngularSpeed = 3_rad_per_s; -constexpr auto kMaxAngularAcceleration = 3_rad_per_s_sq; +inline constexpr auto kMaxSpeed = 3_mps; +inline constexpr auto kMaxAcceleration = 3_mps_sq; +inline constexpr auto kMaxAngularSpeed = 3_rad_per_s; +inline constexpr auto kMaxAngularAcceleration = 3_rad_per_s_sq; -constexpr double kPXController = 0.5; -constexpr double kPYController = 0.5; -constexpr double kPThetaController = 0.5; +inline constexpr double kPXController = 0.5; +inline constexpr double kPYController = 0.5; +inline constexpr double kPThetaController = 0.5; extern const frc::TrapezoidProfile::Constraints kThetaControllerConstraints; @@ -87,5 +87,5 @@ extern const frc::TrapezoidProfile::Constraints } // namespace AutoConstants namespace OIConstants { -constexpr int kDriverControllerPort = 0; +inline constexpr int kDriverControllerPort = 0; } // namespace OIConstants diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/Robot.h b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/Robot.h index a82f2ac63b0..de9c814e752 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/Robot.h +++ b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/Robot.h @@ -4,6 +4,8 @@ #pragma once +#include + #include #include @@ -24,7 +26,7 @@ class Robot : public frc::TimedRobot { private: // Have it null by default so that if testing teleop it // doesn't have undefined behavior and potentially crash. - frc2::Command* m_autonomousCommand = nullptr; + std::optional m_autonomousCommand; RobotContainer m_container; }; diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/RobotContainer.h b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/RobotContainer.h index 93485e3bb0f..c6f8afc703c 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/RobotContainer.h +++ b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/RobotContainer.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -28,7 +29,7 @@ class RobotContainer { public: RobotContainer(); - frc2::Command* GetAutonomousCommand(); + frc2::CommandPtr GetAutonomousCommand(); private: // The driver's controller @@ -44,8 +45,5 @@ class RobotContainer { frc2::InstantCommand m_driveFullSpeed{[this] { m_drive.SetMaxOutput(1); }, {}}; - // The chooser for the autonomous routines - frc::SendableChooser m_chooser; - void ConfigureButtonBindings(); }; diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/subsystems/DriveSubsystem.h b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/subsystems/DriveSubsystem.h index 579a3950eaa..df50dcda092 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/subsystems/DriveSubsystem.h +++ b/wpilibcExamples/src/main/cpp/examples/MecanumControllerCommand/include/subsystems/DriveSubsystem.h @@ -9,7 +9,6 @@ #include #include #include -#include #include #include #include @@ -148,7 +147,10 @@ class DriveSubsystem : public frc2::SubsystemBase { frc::PWMSparkMax m_rearRight; // The robot's drive - frc::MecanumDrive m_drive{m_frontLeft, m_rearLeft, m_frontRight, m_rearRight}; + frc::MecanumDrive m_drive{[&](double output) { m_frontLeft.Set(output); }, + [&](double output) { m_rearLeft.Set(output); }, + [&](double output) { m_frontRight.Set(output); }, + [&](double output) { m_rearRight.Set(output); }}; // The front-left-side drive encoder frc::Encoder m_frontLeftEncoder; diff --git a/wpilibcExamples/src/main/cpp/examples/MecanumDrive/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/MecanumDrive/cpp/Robot.cpp index 8d9d7aebf75..eeb9ce13233 100644 --- a/wpilibcExamples/src/main/cpp/examples/MecanumDrive/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/MecanumDrive/cpp/Robot.cpp @@ -14,6 +14,11 @@ class Robot : public frc::TimedRobot { public: void RobotInit() override { + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_frontLeft); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_rearLeft); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_frontRight); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_rearRight); + // Invert the right side motors. You may need to change or remove this to // match your robot. m_frontRight.SetInverted(true); @@ -40,8 +45,11 @@ class Robot : public frc::TimedRobot { frc::PWMSparkMax m_rearLeft{kRearLeftChannel}; frc::PWMSparkMax m_frontRight{kFrontRightChannel}; frc::PWMSparkMax m_rearRight{kRearRightChannel}; - frc::MecanumDrive m_robotDrive{m_frontLeft, m_rearLeft, m_frontRight, - m_rearRight}; + frc::MecanumDrive m_robotDrive{ + [&](double output) { m_frontLeft.Set(output); }, + [&](double output) { m_rearLeft.Set(output); }, + [&](double output) { m_frontRight.Set(output); }, + [&](double output) { m_rearRight.Set(output); }}; frc::Joystick m_stick{kJoystickChannel}; }; diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/Robot.cpp deleted file mode 100644 index c4c1661d699..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/Robot.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "Robot.h" - -#include -#include - -void Robot::RobotInit() {} - -/** - * This function is called every 20 ms, no matter the mode. Use - * this for items like diagnostics that you want to run during disabled, - * autonomous, teleoperated and test. - * - *

This runs after the mode specific periodic functions, but before - * LiveWindow and SmartDashboard integrated updating. - */ -void Robot::RobotPeriodic() { - frc2::CommandScheduler::GetInstance().Run(); -} - -/** - * This function is called once each time the robot enters Disabled mode. You - * can use it to reset any subsystem information you want to clear when the - * robot is disabled. - */ -void Robot::DisabledInit() {} - -void Robot::DisabledPeriodic() {} - -/** - * This autonomous runs the autonomous command selected by your {@link - * RobotContainer} class. - */ -void Robot::AutonomousInit() { - m_autonomousCommand = m_container.GetAutonomousCommand(); - - if (m_autonomousCommand) { - m_autonomousCommand->Schedule(); - } -} - -void Robot::AutonomousPeriodic() {} - -void Robot::TeleopInit() { - // This makes sure that the autonomous stops running when - // teleop starts running. If you want the autonomous to - // continue until interrupted by another command, remove - // this line or comment it out. - if (m_autonomousCommand) { - m_autonomousCommand->Cancel(); - m_autonomousCommand.reset(); - } -} - -/** - * This function is called periodically during operator control. - */ -void Robot::TeleopPeriodic() {} - -/** - * This function is called periodically during test mode. - */ -void Robot::TestPeriodic() {} - -#ifndef RUNNING_FRC_TESTS -int main() { - return frc::StartRobot(); -} -#endif diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/RobotContainer.cpp b/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/RobotContainer.cpp deleted file mode 100644 index e880af2d5e3..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/RobotContainer.cpp +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "RobotContainer.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Constants.h" - -RobotContainer::RobotContainer() { - // Initialize all of your commands and subsystems here - - // Configure the button bindings - ConfigureButtonBindings(); - - // Set up default drive command - m_drive.SetDefaultCommand(frc2::cmd::Run( - [this] { - m_drive.ArcadeDrive(-m_driverController.GetLeftY(), - -m_driverController.GetRightX()); - }, - {&m_drive})); -} - -void RobotContainer::ConfigureButtonBindings() { - // Configure your button bindings here - - // While holding the shoulder button, drive at half speed - frc2::JoystickButton{&m_driverController, 6} - .OnTrue(&m_driveHalfSpeed) - .OnFalse(&m_driveFullSpeed); -} - -frc2::CommandPtr RobotContainer::GetAutonomousCommand() { - // Create a voltage constraint to ensure we don't accelerate too fast - frc::DifferentialDriveVoltageConstraint autoVoltageConstraint{ - frc::SimpleMotorFeedforward{ - DriveConstants::ks, DriveConstants::kv, DriveConstants::ka}, - DriveConstants::kDriveKinematics, 10_V}; - - // Set up config for trajectory - frc::TrajectoryConfig config{AutoConstants::kMaxSpeed, - AutoConstants::kMaxAcceleration}; - // Add kinematics to ensure max speed is actually obeyed - config.SetKinematics(DriveConstants::kDriveKinematics); - // Apply the voltage constraint - config.AddConstraint(autoVoltageConstraint); - - // An example trajectory to follow. All units in meters. - auto exampleTrajectory = frc::TrajectoryGenerator::GenerateTrajectory( - // Start at the origin facing the +X direction - frc::Pose2d{0_m, 0_m, 0_deg}, - // Pass through these two interior waypoints, making an 's' curve path - {frc::Translation2d{1_m, 1_m}, frc::Translation2d{2_m, -1_m}}, - // End 3 meters straight ahead of where we started, facing forward - frc::Pose2d{3_m, 0_m, 0_deg}, - // Pass the config - config); - - frc2::CommandPtr ramseteCommand{frc2::RamseteCommand( - exampleTrajectory, [this] { return m_drive.GetPose(); }, - frc::RamseteController{AutoConstants::kRamseteB, - AutoConstants::kRamseteZeta}, - frc::SimpleMotorFeedforward{ - DriveConstants::ks, DriveConstants::kv, DriveConstants::ka}, - DriveConstants::kDriveKinematics, - [this] { return m_drive.GetWheelSpeeds(); }, - frc::PIDController{DriveConstants::kPDriveVel, 0, 0}, - frc::PIDController{DriveConstants::kPDriveVel, 0, 0}, - [this](auto left, auto right) { m_drive.TankDriveVolts(left, right); }, - {&m_drive})}; - - // Reset odometry to the starting pose of the trajectory. - m_drive.ResetOdometry(exampleTrajectory.InitialPose()); - - return std::move(ramseteCommand) - .BeforeStarting( - frc2::cmd::RunOnce([this] { m_drive.TankDriveVolts(0_V, 0_V); }, {})); -} diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/subsystems/DriveSubsystem.cpp deleted file mode 100644 index 0bc598e4e9d..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/cpp/subsystems/DriveSubsystem.cpp +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "subsystems/DriveSubsystem.h" - -#include -#include - -using namespace DriveConstants; - -DriveSubsystem::DriveSubsystem() - : m_left1{kLeftMotor1Port}, - m_left2{kLeftMotor2Port}, - m_right1{kRightMotor1Port}, - m_right2{kRightMotor2Port}, - m_leftEncoder{kLeftEncoderPorts[0], kLeftEncoderPorts[1]}, - m_rightEncoder{kRightEncoderPorts[0], kRightEncoderPorts[1]}, - m_odometry{m_gyro.GetRotation2d(), units::meter_t{0}, units::meter_t{0}} { - // We need to invert one side of the drivetrain so that positive voltages - // result in both sides moving forward. Depending on how your robot's - // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.SetInverted(true); - - // Set the distance per pulse for the encoders - m_leftEncoder.SetDistancePerPulse(kEncoderDistancePerPulse.value()); - m_rightEncoder.SetDistancePerPulse(kEncoderDistancePerPulse.value()); - - ResetEncoders(); -} - -void DriveSubsystem::Periodic() { - // Implementation of subsystem periodic method goes here. - m_odometry.Update(m_gyro.GetRotation2d(), - units::meter_t{m_leftEncoder.GetDistance()}, - units::meter_t{m_rightEncoder.GetDistance()}); -} - -void DriveSubsystem::ArcadeDrive(double fwd, double rot) { - m_drive.ArcadeDrive(fwd, rot); -} - -void DriveSubsystem::TankDriveVolts(units::volt_t left, units::volt_t right) { - m_leftMotors.SetVoltage(left); - m_rightMotors.SetVoltage(right); - m_drive.Feed(); -} - -void DriveSubsystem::ResetEncoders() { - m_leftEncoder.Reset(); - m_rightEncoder.Reset(); -} - -double DriveSubsystem::GetAverageEncoderDistance() { - return (m_leftEncoder.GetDistance() + m_rightEncoder.GetDistance()) / 2.0; -} - -frc::Encoder& DriveSubsystem::GetLeftEncoder() { - return m_leftEncoder; -} - -frc::Encoder& DriveSubsystem::GetRightEncoder() { - return m_rightEncoder; -} - -void DriveSubsystem::SetMaxOutput(double maxOutput) { - m_drive.SetMaxOutput(maxOutput); -} - -units::degree_t DriveSubsystem::GetHeading() const { - return m_gyro.GetRotation2d().Degrees(); -} - -double DriveSubsystem::GetTurnRate() { - return -m_gyro.GetRate(); -} - -frc::Pose2d DriveSubsystem::GetPose() { - return m_odometry.GetPose(); -} - -frc::DifferentialDriveWheelSpeeds DriveSubsystem::GetWheelSpeeds() { - return {units::meters_per_second_t{m_leftEncoder.GetRate()}, - units::meters_per_second_t{m_rightEncoder.GetRate()}}; -} - -void DriveSubsystem::ResetOdometry(frc::Pose2d pose) { - ResetEncoders(); - m_odometry.ResetPosition(m_gyro.GetRotation2d(), - units::meter_t{m_leftEncoder.GetDistance()}, - units::meter_t{m_rightEncoder.GetDistance()}, pose); -} diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/RamseteCommand/include/Constants.h deleted file mode 100644 index f7a061a4ab6..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/include/Constants.h +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#pragma once - -/** - * The Constants header provides a convenient place for teams to hold robot-wide - * numerical or bool constants. This should not be used for any other purpose. - * - * It is generally a good idea to place constants into subsystem- or - * command-specific namespaces within this header, which can then be used where - * they are needed. - */ - -namespace DriveConstants { -constexpr int kLeftMotor1Port = 0; -constexpr int kLeftMotor2Port = 1; -constexpr int kRightMotor1Port = 2; -constexpr int kRightMotor2Port = 3; - -constexpr int kLeftEncoderPorts[]{0, 1}; -constexpr int kRightEncoderPorts[]{2, 3}; -constexpr bool kLeftEncoderReversed = false; -constexpr bool kRightEncoderReversed = true; - -constexpr auto kTrackwidth = 0.69_m; -extern const frc::DifferentialDriveKinematics kDriveKinematics; - -constexpr int kEncoderCPR = 1024; -constexpr units::meter_t kWheelDiameter = 6_in; -constexpr auto kEncoderDistancePerPulse = - // Assumes the encoders are directly mounted on the wheel shafts - (kWheelDiameter * std::numbers::pi) / static_cast(kEncoderCPR); - -// These are example values only - DO NOT USE THESE FOR YOUR OWN ROBOT! -// These characterization values MUST be determined either experimentally or -// theoretically for *your* robot's drive. The Robot Characterization -// Toolsuite provides a convenient tool for obtaining these values for your -// robot. -constexpr auto ks = 0.22_V; -constexpr auto kv = 1.98 * 1_V * 1_s / 1_m; -constexpr auto ka = 0.2 * 1_V * 1_s * 1_s / 1_m; - -// Example value only - as above, this must be tuned for your drive! -constexpr double kPDriveVel = 8.5; -} // namespace DriveConstants - -namespace AutoConstants { -constexpr auto kMaxSpeed = 3_mps; -constexpr auto kMaxAcceleration = 1_mps_sq; - -// Reasonable baseline values for a RAMSETE follower in units of meters and -// seconds -constexpr auto kRamseteB = 2.0 * 1_rad * 1_rad / (1_m * 1_m); -constexpr auto kRamseteZeta = 0.7 / 1_rad; -} // namespace AutoConstants - -namespace OIConstants { -constexpr int kDriverControllerPort = 0; -} // namespace OIConstants diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/include/RobotContainer.h b/wpilibcExamples/src/main/cpp/examples/RamseteCommand/include/RobotContainer.h deleted file mode 100644 index b01e6e242ad..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/include/RobotContainer.h +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include -#include -#include -#include - -#include "Constants.h" -#include "subsystems/DriveSubsystem.h" - -/** - * This class is where the bulk of the robot should be declared. Since - * Command-based is a "declarative" paradigm, very little robot logic should - * actually be handled in the {@link Robot} periodic methods (other than the - * scheduler calls). Instead, the structure of the robot (including subsystems, - * commands, and button mappings) should be declared here. - */ -class RobotContainer { - public: - RobotContainer(); - - frc2::CommandPtr GetAutonomousCommand(); - - private: - // The driver's controller - frc::XboxController m_driverController{OIConstants::kDriverControllerPort}; - - // The robot's subsystems and commands are defined here... - - // The robot's subsystems - DriveSubsystem m_drive; - - // RobotContainer-owned commands - frc2::InstantCommand m_driveHalfSpeed{[this] { m_drive.SetMaxOutput(0.5); }, - {}}; - frc2::InstantCommand m_driveFullSpeed{[this] { m_drive.SetMaxOutput(1); }, - {}}; - - void ConfigureButtonBindings(); -}; diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/include/subsystems/DriveSubsystem.h b/wpilibcExamples/src/main/cpp/examples/RamseteCommand/include/subsystems/DriveSubsystem.h deleted file mode 100644 index 8ea14dad398..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/include/subsystems/DriveSubsystem.h +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Constants.h" - -class DriveSubsystem : public frc2::SubsystemBase { - public: - DriveSubsystem(); - - /** - * Will be called periodically whenever the CommandScheduler runs. - */ - void Periodic() override; - - // Subsystem methods go here. - - /** - * Drives the robot using arcade controls. - * - * @param fwd the commanded forward movement - * @param rot the commanded rotation - */ - void ArcadeDrive(double fwd, double rot); - - /** - * Controls each side of the drive directly with a voltage. - * - * @param left the commanded left output - * @param right the commanded right output - */ - void TankDriveVolts(units::volt_t left, units::volt_t right); - - /** - * Resets the drive encoders to currently read a position of 0. - */ - void ResetEncoders(); - - /** - * Gets the average distance of the TWO encoders. - * - * @return the average of the TWO encoder readings - */ - double GetAverageEncoderDistance(); - - /** - * Gets the left drive encoder. - * - * @return the left drive encoder - */ - frc::Encoder& GetLeftEncoder(); - - /** - * Gets the right drive encoder. - * - * @return the right drive encoder - */ - frc::Encoder& GetRightEncoder(); - - /** - * Sets the max output of the drive. Useful for scaling the drive to drive - * more slowly. - * - * @param maxOutput the maximum output to which the drive will be constrained - */ - void SetMaxOutput(double maxOutput); - - /** - * Returns the heading of the robot. - * - * @return the robot's heading in degrees, from -180 to 180 - */ - units::degree_t GetHeading() const; - - /** - * Returns the turn rate of the robot. - * - * @return The turn rate of the robot, in degrees per second - */ - double GetTurnRate(); - - /** - * Returns the currently-estimated pose of the robot. - * - * @return The pose. - */ - frc::Pose2d GetPose(); - - /** - * Returns the current wheel speeds of the robot. - * - * @return The current wheel speeds. - */ - frc::DifferentialDriveWheelSpeeds GetWheelSpeeds(); - - /** - * Resets the odometry to the specified pose. - * - * @param pose The pose to which to set the odometry. - */ - void ResetOdometry(frc::Pose2d pose); - - private: - // Components (e.g. motor controllers and sensors) should generally be - // declared private and exposed only through public methods. - - // The motor controllers - frc::PWMSparkMax m_left1; - frc::PWMSparkMax m_left2; - frc::PWMSparkMax m_right1; - frc::PWMSparkMax m_right2; - - // The motors on the left side of the drive - frc::MotorControllerGroup m_leftMotors{m_left1, m_left2}; - - // The motors on the right side of the drive - frc::MotorControllerGroup m_rightMotors{m_right1, m_right2}; - - // The robot's drive - frc::DifferentialDrive m_drive{m_leftMotors, m_rightMotors}; - - // The left-side drive encoder - frc::Encoder m_leftEncoder; - - // The right-side drive encoder - frc::Encoder m_rightEncoder; - - // The gyro sensor - frc::ADXRS450_Gyro m_gyro; - - // Odometry class for tracking robot pose - frc::DifferentialDriveOdometry m_odometry; -}; diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Drivetrain.cpp b/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Drivetrain.cpp deleted file mode 100644 index 8c1e6323bed..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Drivetrain.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "Drivetrain.h" - -void Drivetrain::SetSpeeds(const frc::DifferentialDriveWheelSpeeds& speeds) { - const auto leftFeedforward = m_feedforward.Calculate(speeds.left); - const auto rightFeedforward = m_feedforward.Calculate(speeds.right); - const double leftOutput = m_leftPIDController.Calculate( - m_leftEncoder.GetRate(), speeds.left.value()); - const double rightOutput = m_rightPIDController.Calculate( - m_rightEncoder.GetRate(), speeds.right.value()); - - m_leftGroup.SetVoltage(units::volt_t{leftOutput} + leftFeedforward); - m_rightGroup.SetVoltage(units::volt_t{rightOutput} + rightFeedforward); -} - -void Drivetrain::Drive(units::meters_per_second_t xSpeed, - units::radians_per_second_t rot) { - SetSpeeds(m_kinematics.ToWheelSpeeds({xSpeed, 0_mps, rot})); -} - -void Drivetrain::UpdateOdometry() { - m_odometry.Update(m_gyro.GetRotation2d(), - units::meter_t{m_leftEncoder.GetDistance()}, - units::meter_t{m_rightEncoder.GetDistance()}); -} - -void Drivetrain::ResetOdometry(const frc::Pose2d& pose) { - m_odometry.ResetPosition(m_gyro.GetRotation2d(), - units::meter_t{m_leftEncoder.GetDistance()}, - units::meter_t{m_rightEncoder.GetDistance()}, pose); -} - -frc::Pose2d Drivetrain::GetPose() const { - return m_odometry.GetPose(); -} diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Robot.cpp deleted file mode 100644 index d7902f17d5e..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/RamseteController/cpp/Robot.cpp +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Drivetrain.h" - -class Robot : public frc::TimedRobot { - public: - void AutonomousInit() override { - // Start the timer. - m_timer.Start(); - - // Send Field2d to SmartDashboard. - frc::SmartDashboard::PutData(&m_field); - - // Reset the drivetrain's odometry to the starting pose of the trajectory. - m_drive.ResetOdometry(m_trajectory.InitialPose()); - - // Send our generated trajectory to Field2d. - m_field.GetObject("traj")->SetTrajectory(m_trajectory); - } - - void AutonomousPeriodic() override { - // Update odometry. - m_drive.UpdateOdometry(); - - // Update robot position on Field2d. - m_field.SetRobotPose(m_drive.GetPose()); - - if (m_timer.Get() < m_trajectory.TotalTime()) { - // Get the desired pose from the trajectory. - auto desiredPose = m_trajectory.Sample(m_timer.Get()); - - // Get the reference chassis speeds from the Ramsete Controller. - auto refChassisSpeeds = - m_ramseteController.Calculate(m_drive.GetPose(), desiredPose); - - // Set the linear and angular speeds. - m_drive.Drive(refChassisSpeeds.vx, refChassisSpeeds.omega); - } else { - m_drive.Drive(0_mps, 0_rad_per_s); - } - } - - void TeleopPeriodic() override { - // Get the x speed. We are inverting this because Xbox controllers return - // negative values when we push forward. - const auto xSpeed = -m_speedLimiter.Calculate(m_controller.GetLeftY()) * - Drivetrain::kMaxSpeed; - - // Get the rate of angular rotation. We are inverting this because we want a - // positive value when we pull to the left (remember, CCW is positive in - // mathematics). Xbox controllers return positive values when you pull to - // the right by default. - const auto rot = -m_rotLimiter.Calculate(m_controller.GetRightX()) * - Drivetrain::kMaxAngularSpeed; - - m_drive.Drive(xSpeed, rot); - } - - private: - frc::XboxController m_controller{0}; - - // Slew rate limiters to make joystick inputs more gentle; 1/3 sec from 0 - // to 1. - frc::SlewRateLimiter m_speedLimiter{3 / 1_s}; - frc::SlewRateLimiter m_rotLimiter{3 / 1_s}; - - Drivetrain m_drive; - - // An example trajectory to follow. - frc::Trajectory m_trajectory = frc::TrajectoryGenerator::GenerateTrajectory( - frc::Pose2d{0_m, 0_m, 0_rad}, - {frc::Translation2d{1_m, 1_m}, frc::Translation2d{2_m, -1_m}}, - frc::Pose2d{3_m, 0_m, 0_rad}, frc::TrajectoryConfig(3_fps, 3_fps_sq)); - - // The Ramsete Controller to follow the trajectory. - frc::RamseteController m_ramseteController; - - // The timer to use during the autonomous period. - frc::Timer m_timer; - - // Create Field2d for robot and trajectory visualizations. - frc::Field2d m_field; -}; - -#ifndef RUNNING_FRC_TESTS -int main() { - return frc::StartRobot(); -} -#endif diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteController/include/Drivetrain.h b/wpilibcExamples/src/main/cpp/examples/RamseteController/include/Drivetrain.h deleted file mode 100644 index 341cd38c1cd..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/RamseteController/include/Drivetrain.h +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/** - * Represents a differential drive style drivetrain. - */ -class Drivetrain { - public: - Drivetrain() { - m_gyro.Reset(); - - // We need to invert one side of the drivetrain so that positive voltages - // result in both sides moving forward. Depending on how your robot's - // gearbox is constructed, you might have to invert the left side instead. - m_rightGroup.SetInverted(true); - - // Set the distance per pulse for the drive encoders. We can simply use the - // distance traveled for one rotation of the wheel divided by the encoder - // resolution. - m_leftEncoder.SetDistancePerPulse(2 * std::numbers::pi * kWheelRadius / - kEncoderResolution); - m_rightEncoder.SetDistancePerPulse(2 * std::numbers::pi * kWheelRadius / - kEncoderResolution); - - m_leftEncoder.Reset(); - m_rightEncoder.Reset(); - } - - static constexpr units::meters_per_second_t kMaxSpeed = - 3.0_mps; // 3 meters per second - static constexpr units::radians_per_second_t kMaxAngularSpeed{ - std::numbers::pi}; // 1/2 rotation per second - - void SetSpeeds(const frc::DifferentialDriveWheelSpeeds& speeds); - void Drive(units::meters_per_second_t xSpeed, - units::radians_per_second_t rot); - void UpdateOdometry(); - void ResetOdometry(const frc::Pose2d& pose); - frc::Pose2d GetPose() const; - - private: - static constexpr units::meter_t kTrackWidth = 0.381_m * 2; - static constexpr double kWheelRadius = 0.0508; // meters - static constexpr int kEncoderResolution = 4096; - - frc::PWMSparkMax m_leftLeader{1}; - frc::PWMSparkMax m_leftFollower{2}; - frc::PWMSparkMax m_rightLeader{3}; - frc::PWMSparkMax m_rightFollower{4}; - - frc::MotorControllerGroup m_leftGroup{m_leftLeader, m_leftFollower}; - frc::MotorControllerGroup m_rightGroup{m_rightLeader, m_rightFollower}; - - frc::Encoder m_leftEncoder{0, 1}; - frc::Encoder m_rightEncoder{2, 3}; - - frc::PIDController m_leftPIDController{1.0, 0.0, 0.0}; - frc::PIDController m_rightPIDController{1.0, 0.0, 0.0}; - - frc::AnalogGyro m_gyro{0}; - - frc::DifferentialDriveKinematics m_kinematics{kTrackWidth}; - frc::DifferentialDriveOdometry m_odometry{ - m_gyro.GetRotation2d(), units::meter_t{m_leftEncoder.GetDistance()}, - units::meter_t{m_rightEncoder.GetDistance()}}; - - // Gains are for example purposes only - must be determined for your own - // robot! - frc::SimpleMotorFeedforward m_feedforward{1_V, 3_V / 1_mps}; -}; diff --git a/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/cpp/RapidReactCommandBot.cpp b/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/cpp/RapidReactCommandBot.cpp index 1b46affa21a..653aad3ce52 100644 --- a/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/cpp/RapidReactCommandBot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/cpp/RapidReactCommandBot.cpp @@ -12,16 +12,13 @@ void RapidReactCommandBot::ConfigureBindings() { // Automatically run the storage motor whenever the ball storage is not full, - // and turn it off whenever it fills. - frc2::Trigger([this] { - return m_storage.IsFull(); - }).WhileFalse(m_storage.RunCommand()); + // and turn it off whenever it fills. Uses subsystem-hosted trigger to + // improve readability and make inter-subsystem communication easier. + m_storage.HasCargo.WhileFalse(m_storage.RunCommand()); // Automatically disable and retract the intake whenever the ball storage is // full. - frc2::Trigger([this] { - return m_storage.IsFull(); - }).OnTrue(m_intake.RetractCommand()); + m_storage.HasCargo.OnTrue(m_intake.RetractCommand()); // Control the drive with split-stick arcade controls m_drive.SetDefaultCommand(m_drive.ArcadeDriveCommand( diff --git a/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/cpp/subsystems/Drive.cpp b/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/cpp/subsystems/Drive.cpp index 98ff0cac75f..e03ce432124 100644 --- a/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/cpp/subsystems/Drive.cpp +++ b/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/cpp/subsystems/Drive.cpp @@ -9,10 +9,16 @@ #include Drive::Drive() { + wpi::SendableRegistry::AddChild(&m_drive, &m_leftLeader); + wpi::SendableRegistry::AddChild(&m_drive, &m_rightLeader); + + m_leftLeader.AddFollower(m_leftFollower); + m_rightLeader.AddFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.SetInverted(true); + m_rightLeader.SetInverted(true); // Sets the distance per pulse for the encoders m_leftEncoder.SetDistancePerPulse(DriveConstants::kEncoderDistancePerPulse); diff --git a/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/cpp/subsystems/Storage.cpp b/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/cpp/subsystems/Storage.cpp index 3e9dc6203be..59c2a023516 100644 --- a/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/cpp/subsystems/Storage.cpp +++ b/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/cpp/subsystems/Storage.cpp @@ -12,7 +12,3 @@ Storage::Storage() { frc2::CommandPtr Storage::RunCommand() { return Run([this] { m_motor.Set(1.0); }).WithName("Run"); } - -bool Storage::IsFull() const { - return m_ballSensor.Get(); -} diff --git a/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/include/Constants.h index 330eebacc95..a552c448560 100644 --- a/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/include/Constants.h @@ -13,63 +13,63 @@ #include namespace DriveConstants { -constexpr int kLeftMotor1Port = 0; -constexpr int kLeftMotor2Port = 1; -constexpr int kRightMotor1Port = 2; -constexpr int kRightMotor2Port = 3; - -constexpr int kLeftEncoderPorts[]{0, 1}; -constexpr int kRightEncoderPorts[]{2, 3}; -constexpr bool kLeftEncoderReversed = false; -constexpr bool kRightEncoderReversed = true; - -constexpr double kEncoderCPR = 1024; -constexpr units::meter_t kWheelDiameter = 6.0_in; -constexpr double kEncoderDistancePerPulse = +inline constexpr int kLeftMotor1Port = 0; +inline constexpr int kLeftMotor2Port = 1; +inline constexpr int kRightMotor1Port = 2; +inline constexpr int kRightMotor2Port = 3; + +inline constexpr int kLeftEncoderPorts[]{0, 1}; +inline constexpr int kRightEncoderPorts[]{2, 3}; +inline constexpr bool kLeftEncoderReversed = false; +inline constexpr bool kRightEncoderReversed = true; + +inline constexpr double kEncoderCPR = 1024; +inline constexpr units::meter_t kWheelDiameter = 6.0_in; +inline constexpr double kEncoderDistancePerPulse = // Assumes the encoders are directly mounted on the wheel shafts ((kWheelDiameter * std::numbers::pi) / kEncoderCPR).value(); } // namespace DriveConstants namespace IntakeConstants { -constexpr int kMotorPort = 6; -constexpr int kSolenoidPorts[]{0, 1}; +inline constexpr int kMotorPort = 6; +inline constexpr int kSolenoidPorts[]{0, 1}; } // namespace IntakeConstants namespace StorageConstants { -constexpr int kMotorPort = 7; -constexpr int kBallSensorPort = 6; +inline constexpr int kMotorPort = 7; +inline constexpr int kBallSensorPort = 6; } // namespace StorageConstants namespace ShooterConstants { -constexpr int kEncoderPorts[]{4, 5}; -constexpr bool kEncoderReversed = false; -constexpr double kEncoderCPR = 1024; -constexpr double kEncoderDistancePerPulse = +inline constexpr int kEncoderPorts[]{4, 5}; +inline constexpr bool kEncoderReversed = false; +inline constexpr double kEncoderCPR = 1024; +inline constexpr double kEncoderDistancePerPulse = // Distance units will be rotations 1.0 / kEncoderCPR; -constexpr int kShooterMotorPort = 4; -constexpr int kFeederMotorPort = 5; +inline constexpr int kShooterMotorPort = 4; +inline constexpr int kFeederMotorPort = 5; -constexpr auto kShooterFree = 5300_tps; -constexpr auto kShooterTarget = 4000_tps; -constexpr auto kShooterTolerance = 50_tps; +inline constexpr auto kShooterFree = 5300_tps; +inline constexpr auto kShooterTarget = 4000_tps; +inline constexpr auto kShooterTolerance = 50_tps; // These are not real PID gains, and will have to be tuned for your specific // robot. -constexpr double kP = 1; +inline constexpr double kP = 1; -constexpr units::volt_t kS = 0.05_V; -constexpr auto kV = +inline constexpr units::volt_t kS = 0.05_V; +inline constexpr auto kV = // Should have value 12V at free speed... 12.0_V / kShooterFree; -constexpr double kFeederSpeed = 0.5; +inline constexpr double kFeederSpeed = 0.5; } // namespace ShooterConstants namespace OIConstants { -constexpr int kDriverControllerPort = 0; +inline constexpr int kDriverControllerPort = 0; } // namespace OIConstants namespace AutoConstants { diff --git a/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/include/subsystems/Drive.h b/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/include/subsystems/Drive.h index ac96c52839c..8432e57b6b0 100644 --- a/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/include/subsystems/Drive.h +++ b/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/include/subsystems/Drive.h @@ -8,7 +8,6 @@ #include #include -#include #include #include #include @@ -45,10 +44,9 @@ class Drive : public frc2::SubsystemBase { frc::PWMSparkMax m_rightLeader{DriveConstants::kRightMotor1Port}; frc::PWMSparkMax m_rightFollower{DriveConstants::kRightMotor2Port}; - frc::MotorControllerGroup m_leftMotors{m_leftLeader, m_leftFollower}; - frc::MotorControllerGroup m_rightMotors{m_rightLeader, m_rightFollower}; - - frc::DifferentialDrive m_drive{m_leftMotors, m_rightMotors}; + frc::DifferentialDrive m_drive{ + [&](double output) { m_leftLeader.Set(output); }, + [&](double output) { m_rightLeader.Set(output); }}; frc::Encoder m_leftEncoder{DriveConstants::kLeftEncoderPorts[0], DriveConstants::kLeftEncoderPorts[1], diff --git a/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/include/subsystems/Storage.h b/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/include/subsystems/Storage.h index 58694b3035d..ec99118d600 100644 --- a/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/include/subsystems/Storage.h +++ b/wpilibcExamples/src/main/cpp/examples/RapidReactCommandBot/include/subsystems/Storage.h @@ -8,6 +8,7 @@ #include #include #include +#include #include "Constants.h" @@ -19,7 +20,7 @@ class Storage : frc2::SubsystemBase { frc2::CommandPtr RunCommand(); /** Whether the ball storage is full. */ - bool IsFull() const; + frc2::Trigger HasCargo{[this] { return m_ballSensor.Get(); }}; private: frc::PWMSparkMax m_motor{StorageConstants::kMotorPort}; diff --git a/wpilibcExamples/src/main/cpp/examples/RomiReference/cpp/subsystems/Drivetrain.cpp b/wpilibcExamples/src/main/cpp/examples/RomiReference/cpp/subsystems/Drivetrain.cpp index 979f8a0e5d4..1d212d5c5d8 100644 --- a/wpilibcExamples/src/main/cpp/examples/RomiReference/cpp/subsystems/Drivetrain.cpp +++ b/wpilibcExamples/src/main/cpp/examples/RomiReference/cpp/subsystems/Drivetrain.cpp @@ -15,6 +15,9 @@ using namespace DriveConstants; // The Romi has onboard encoders that are hardcoded // to use DIO pins 4/5 and 6/7 for the left and right Drivetrain::Drivetrain() { + wpi::SendableRegistry::AddChild(&m_drive, &m_leftMotor); + wpi::SendableRegistry::AddChild(&m_drive, &m_rightMotor); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. diff --git a/wpilibcExamples/src/main/cpp/examples/RomiReference/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/RomiReference/include/Constants.h index e5cee33afd1..dddb741e72e 100644 --- a/wpilibcExamples/src/main/cpp/examples/RomiReference/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/RomiReference/include/Constants.h @@ -14,6 +14,6 @@ */ namespace DriveConstants { -constexpr double kCountsPerRevolution = 1440.0; -constexpr double kWheelDiameterInch = 2.75; +inline constexpr double kCountsPerRevolution = 1440.0; +inline constexpr double kWheelDiameterInch = 2.75; } // namespace DriveConstants diff --git a/wpilibcExamples/src/main/cpp/examples/RomiReference/include/subsystems/Drivetrain.h b/wpilibcExamples/src/main/cpp/examples/RomiReference/include/subsystems/Drivetrain.h index ace7d33bc77..d679178fd04 100644 --- a/wpilibcExamples/src/main/cpp/examples/RomiReference/include/subsystems/Drivetrain.h +++ b/wpilibcExamples/src/main/cpp/examples/RomiReference/include/subsystems/Drivetrain.h @@ -114,7 +114,9 @@ class Drivetrain : public frc2::SubsystemBase { frc::Encoder m_leftEncoder{4, 5}; frc::Encoder m_rightEncoder{6, 7}; - frc::DifferentialDrive m_drive{m_leftMotor, m_rightMotor}; + frc::DifferentialDrive m_drive{ + [&](double output) { m_leftMotor.Set(output); }, + [&](double output) { m_rightMotor.Set(output); }}; frc::RomiGyro m_gyro; frc::BuiltInAccelerometer m_accelerometer; diff --git a/wpilibcExamples/src/main/cpp/examples/SelectCommand/cpp/RobotContainer.cpp b/wpilibcExamples/src/main/cpp/examples/SelectCommand/cpp/RobotContainer.cpp index 69895cb1cae..df5ba8ce95e 100644 --- a/wpilibcExamples/src/main/cpp/examples/SelectCommand/cpp/RobotContainer.cpp +++ b/wpilibcExamples/src/main/cpp/examples/SelectCommand/cpp/RobotContainer.cpp @@ -4,9 +4,17 @@ #include "RobotContainer.h" +#include + RobotContainer::RobotContainer() { // Initialize all of your commands and subsystems here + m_chooser.SetDefaultOption("ONE", CommandSelector::ONE); + m_chooser.AddOption("TWO", CommandSelector::TWO); + m_chooser.AddOption("THREE", CommandSelector::THREE); + + frc::SmartDashboard::PutData("Auto Chooser", &m_chooser); + // Configure the button bindings ConfigureButtonBindings(); } diff --git a/wpilibcExamples/src/main/cpp/examples/SelectCommand/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/SelectCommand/include/Constants.h index ae5d02dffcb..e07663a4fb8 100644 --- a/wpilibcExamples/src/main/cpp/examples/SelectCommand/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/SelectCommand/include/Constants.h @@ -15,5 +15,5 @@ */ namespace OIConstants { -constexpr int kDriverControllerPort = 0; +inline constexpr int kDriverControllerPort = 0; } // namespace OIConstants diff --git a/wpilibcExamples/src/main/cpp/examples/SelectCommand/include/RobotContainer.h b/wpilibcExamples/src/main/cpp/examples/SelectCommand/include/RobotContainer.h index a1a2c86fac7..ce5e26d679e 100644 --- a/wpilibcExamples/src/main/cpp/examples/SelectCommand/include/RobotContainer.h +++ b/wpilibcExamples/src/main/cpp/examples/SelectCommand/include/RobotContainer.h @@ -4,7 +4,9 @@ #pragma once +#include #include +#include #include /** @@ -24,10 +26,8 @@ class RobotContainer { // The enum used as keys for selecting the command to run. enum CommandSelector { ONE, TWO, THREE }; - // An example selector method for the selectcommand. Returns the selector - // that will select which command to run. Can base this choice on logical - // conditions evaluated at runtime. - CommandSelector Select() { return ONE; } + // An example of how command selector may be used with SendableChooser + frc::SendableChooser m_chooser; // The robot's subsystems and commands are defined here... @@ -36,7 +36,7 @@ class RobotContainer { // takes a generic type, so the selector does not have to be an enum; it could // be any desired type (string, integer, boolean, double...) frc2::CommandPtr m_exampleSelectCommand = frc2::cmd::Select( - [this] { return Select(); }, + [this] { return m_chooser.GetSelected(); }, // Maps selector values to commands std::pair{ONE, frc2::cmd::Print("Command one was selected!")}, std::pair{TWO, frc2::cmd::Print("Command two was selected!")}, diff --git a/wpilibcExamples/src/main/cpp/examples/ShuffleBoard/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/ShuffleBoard/cpp/Robot.cpp index b951f18bbe9..b532bcbf75b 100644 --- a/wpilibcExamples/src/main/cpp/examples/ShuffleBoard/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/ShuffleBoard/cpp/Robot.cpp @@ -30,6 +30,9 @@ class Robot : public frc::TimedRobot { public: void RobotInit() override { + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_left); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_right); + // Add a widget titled 'Max Speed' with a number slider. m_maxSpeed = frc::Shuffleboard::GetTab("Configuration") .Add("Max Speed", 1) @@ -65,7 +68,9 @@ class Robot : public frc::TimedRobot { frc::PWMSparkMax m_right{1}; frc::PWMSparkMax m_elevatorMotor{2}; - frc::DifferentialDrive m_robotDrive{m_left, m_right}; + frc::DifferentialDrive m_robotDrive{ + [&](double output) { m_left.Set(output); }, + [&](double output) { m_right.Set(output); }}; frc::Joystick m_stick{0}; diff --git a/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/cpp/Drivetrain.cpp b/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/cpp/Drivetrain.cpp index 93d0889df50..603facaa2f0 100644 --- a/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/cpp/Drivetrain.cpp +++ b/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/cpp/Drivetrain.cpp @@ -14,8 +14,8 @@ void Drivetrain::SetSpeeds(const frc::DifferentialDriveWheelSpeeds& speeds) { double rightOutput = m_rightPIDController.Calculate(m_rightEncoder.GetRate(), speeds.right.value()); - m_leftGroup.SetVoltage(units::volt_t{leftOutput} + leftFeedforward); - m_rightGroup.SetVoltage(units::volt_t{rightOutput} + rightFeedforward); + m_leftLeader.SetVoltage(units::volt_t{leftOutput} + leftFeedforward); + m_rightLeader.SetVoltage(units::volt_t{rightOutput} + rightFeedforward); } void Drivetrain::Drive(units::meters_per_second_t xSpeed, @@ -30,8 +30,6 @@ void Drivetrain::UpdateOdometry() { } void Drivetrain::ResetOdometry(const frc::Pose2d& pose) { - m_leftEncoder.Reset(); - m_rightEncoder.Reset(); m_drivetrainSimulator.SetPose(pose); m_odometry.ResetPosition(m_gyro.GetRotation2d(), units::meter_t{m_leftEncoder.GetDistance()}, @@ -43,9 +41,9 @@ void Drivetrain::SimulationPeriodic() { // simulation, and write the simulated positions and velocities to our // simulated encoder and gyro. We negate the right side so that positive // voltages make the right side move forward. - m_drivetrainSimulator.SetInputs(units::volt_t{m_leftGroup.Get()} * + m_drivetrainSimulator.SetInputs(units::volt_t{m_leftLeader.Get()} * frc::RobotController::GetInputVoltage(), - units::volt_t{m_rightGroup.Get()} * + units::volt_t{m_rightLeader.Get()} * frc::RobotController::GetInputVoltage()); m_drivetrainSimulator.Update(20_ms); diff --git a/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/cpp/Robot.cpp index 523bb7b343c..fa1cfe1bdb9 100644 --- a/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/cpp/Robot.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #include @@ -29,7 +29,7 @@ class Robot : public frc::TimedRobot { void AutonomousPeriodic() override { auto elapsed = m_timer.Get(); auto reference = m_trajectory.Sample(elapsed); - auto speeds = m_ramsete.Calculate(m_drive.GetPose(), reference); + auto speeds = m_feedback.Calculate(m_drive.GetPose(), reference); m_drive.Drive(speeds.vx, speeds.omega); } @@ -61,7 +61,7 @@ class Robot : public frc::TimedRobot { Drivetrain m_drive; frc::Trajectory m_trajectory; - frc::RamseteController m_ramsete; + frc::LTVUnicycleController m_feedback{20_ms}; frc::Timer m_timer; }; diff --git a/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/include/Drivetrain.h b/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/include/Drivetrain.h index 4c274fe476d..ca82547f7cb 100644 --- a/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/include/Drivetrain.h +++ b/wpilibcExamples/src/main/cpp/examples/SimpleDifferentialDriveSimulation/include/Drivetrain.h @@ -12,7 +12,6 @@ #include #include #include -#include #include #include #include @@ -33,10 +32,13 @@ class Drivetrain { Drivetrain() { m_gyro.Reset(); + m_leftLeader.AddFollower(m_leftFollower); + m_rightLeader.AddFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightGroup.SetInverted(true); + m_rightLeader.SetInverted(true); // Set the distance per pulse for the drive encoders. We can simply use the // distance traveled for one rotation of the wheel divided by the encoder @@ -49,7 +51,7 @@ class Drivetrain { m_leftEncoder.Reset(); m_rightEncoder.Reset(); - m_rightGroup.SetInverted(true); + m_rightLeader.SetInverted(true); frc::SmartDashboard::PutData("Field", &m_fieldSim); } @@ -80,9 +82,6 @@ class Drivetrain { frc::PWMSparkMax m_rightLeader{3}; frc::PWMSparkMax m_rightFollower{4}; - frc::MotorControllerGroup m_leftGroup{m_leftLeader, m_leftFollower}; - frc::MotorControllerGroup m_rightGroup{m_rightLeader, m_rightFollower}; - frc::Encoder m_leftEncoder{0, 1}; frc::Encoder m_rightEncoder{2, 3}; diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceArm/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceArm/cpp/Robot.cpp index 38e9262613f..9b91e205c66 100644 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceArm/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/StateSpaceArm/cpp/Robot.cpp @@ -47,7 +47,8 @@ class Robot : public frc::TimedRobot { // Outputs (what we can measure): [position], in radians. frc::LinearSystem<2, 1, 1> m_armPlant = frc::LinearSystemId::SingleJointedArmSystem(frc::DCMotor::NEO(2), kArmMOI, - kArmGearing); + kArmGearing) + .Slice(0); // The observer fuses our encoder data and voltage inputs to reject noise. frc::KalmanFilter<2, 1, 1> m_observer{ diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/Constants.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/Constants.cpp deleted file mode 100644 index be6bfe03511..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/Constants.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "Constants.h" - -using namespace DriveConstants; - -const frc::DifferentialDriveKinematics DriveConstants::kDriveKinematics( - kTrackwidth); - -const frc::LinearSystem<2, 2, 2> DriveConstants::kDrivetrainPlant = - frc::LinearSystemId::IdentifyDrivetrainSystem(kv, ka, kvAngular, kaAngular); diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/Robot.cpp deleted file mode 100644 index fce5aececc9..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/Robot.cpp +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "Robot.h" - -#include -#include -#include -#include - -void Robot::RobotInit() {} - -/** - * This function is called every 20 ms, no matter the mode. Use - * this for items like diagnostics that you want to run during disabled, - * autonomous, teleoperated and test. - * - *

This runs after the mode specific periodic functions, but before - * LiveWindow and SmartDashboard integrated updating. - */ -void Robot::RobotPeriodic() { - frc2::CommandScheduler::GetInstance().Run(); -} - -/** - * This function is called once each time the robot enters Disabled mode. You - * can use it to reset any subsystem information you want to clear when the - * robot is disabled. - */ -void Robot::DisabledInit() { - frc2::CommandScheduler::GetInstance().CancelAll(); - m_container.ZeroAllOutputs(); -} - -void Robot::DisabledPeriodic() {} - -/** - * This autonomous runs the autonomous command selected by your {@link - * RobotContainer} class. - */ -void Robot::AutonomousInit() { - m_autonomousCommand = m_container.GetAutonomousCommand(); - - if (m_autonomousCommand != nullptr) { - m_autonomousCommand->Schedule(); - } -} - -void Robot::AutonomousPeriodic() {} - -void Robot::TeleopInit() { - // This makes sure that the autonomous stops running when - // teleop starts running. If you want the autonomous to - // continue until interrupted by another command, remove - // this line or comment it out. - if (m_autonomousCommand != nullptr) { - m_autonomousCommand->Cancel(); - m_autonomousCommand = nullptr; - } -} - -/** - * This function is called periodically during operator control. - */ -void Robot::TeleopPeriodic() {} - -/** - * This function is called periodically during test mode. - */ -void Robot::TestPeriodic() {} - -void Robot::SimulationPeriodic() { - // Here we calculate the battery voltage based on drawn current. - // As our robot draws more power from the battery its voltage drops. - // The estimated voltage is highly dependent on the battery's internal - // resistance. - auto current = m_container.GetRobotDrive().GetCurrentDraw(); - auto loadedVoltage = frc::sim::BatterySim::Calculate({current}); - frc::sim::RoboRioSim::SetVInVoltage(loadedVoltage); -} - -#ifndef RUNNING_FRC_TESTS -int main() { - return frc::StartRobot(); -} -#endif diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/RobotContainer.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/RobotContainer.cpp deleted file mode 100644 index 8c73dc879b6..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/RobotContainer.cpp +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "RobotContainer.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Constants.h" - -RobotContainer::RobotContainer() { - // Initialize all of your commands and subsystems here - - // Configure the button bindings - ConfigureButtonBindings(); - - // Set up default drive command - // A split-stick arcade command, with forward/backward controlled by the left - // hand, and turning controlled by the right. - // If you are using the keyboard as a joystick, it is recommended that you go - // to the following link to read about editing the keyboard settings. - // https://docs.wpilib.org/en/stable/docs/software/wpilib-tools/robot-simulation/simulation-gui.html#using-the-keyboard-as-a-joystick - m_drive.SetDefaultCommand(frc2::RunCommand( - [this] { - m_drive.ArcadeDrive(-m_driverController.GetLeftY(), - -m_driverController.GetLeftX()); - }, - {&m_drive})); -} - -void RobotContainer::ZeroAllOutputs() { - m_drive.TankDriveVolts(0_V, 0_V); -} - -const DriveSubsystem& RobotContainer::GetRobotDrive() const { - return m_drive; -} - -void RobotContainer::ConfigureButtonBindings() { - // Configure your button bindings here - - // While holding the shoulder button, drive at half speed - frc2::JoystickButton(&m_driverController, - frc::XboxController::Button::kRightBumper) - .OnTrue(&m_driveHalfSpeed) - .OnFalse(&m_driveFullSpeed); -} - -frc2::Command* RobotContainer::GetAutonomousCommand() { - // Create a voltage constraint to ensure we don't accelerate too fast - frc::DifferentialDriveVoltageConstraint autoVoltageConstraint( - frc::SimpleMotorFeedforward( - DriveConstants::ks, DriveConstants::kv, DriveConstants::ka), - DriveConstants::kDriveKinematics, 10_V); - - // Set up config for trajectory - frc::TrajectoryConfig config(AutoConstants::kMaxSpeed, - AutoConstants::kMaxAcceleration); - // Add kinematics to ensure max speed is actually obeyed - config.SetKinematics(DriveConstants::kDriveKinematics); - // Apply the voltage constraint - config.AddConstraint(autoVoltageConstraint); - - // An example trajectory to follow. All units in meters. - auto exampleTrajectory = frc::TrajectoryGenerator::GenerateTrajectory( - // Start at (1, 2) facing the +X direction - frc::Pose2d{1_m, 2_m, 0_deg}, - // Pass through these two interior waypoints, making an 's' curve path - {frc::Translation2d{2_m, 3_m}, frc::Translation2d{3_m, 1_m}}, - // End 3 meters straight ahead of where we started, facing forward - frc::Pose2d{4_m, 2_m, 0_deg}, - // Pass the config - config); - - frc2::RamseteCommand ramseteCommand( - exampleTrajectory, [this] { return m_drive.GetPose(); }, - frc::RamseteController{AutoConstants::kRamseteB, - AutoConstants::kRamseteZeta}, - frc::SimpleMotorFeedforward( - DriveConstants::ks, DriveConstants::kv, DriveConstants::ka), - DriveConstants::kDriveKinematics, - [this] { return m_drive.GetWheelSpeeds(); }, - frc::PIDController{DriveConstants::kPDriveVel, 0, 0}, - frc::PIDController{DriveConstants::kPDriveVel, 0, 0}, - [this](auto left, auto right) { m_drive.TankDriveVolts(left, right); }, - {&m_drive}); - - // Reset odometry to starting pose of trajectory. - m_drive.ResetOdometry(exampleTrajectory.InitialPose()); - - // no auto - return new frc2::SequentialCommandGroup( - std::move(ramseteCommand), - frc2::InstantCommand([this] { m_drive.TankDriveVolts(0_V, 0_V); }, {})); -} diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/subsystems/DriveSubsystem.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/subsystems/DriveSubsystem.cpp deleted file mode 100644 index 15d85964359..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/cpp/subsystems/DriveSubsystem.cpp +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include "subsystems/DriveSubsystem.h" - -#include -#include -#include -#include -#include -#include - -using namespace DriveConstants; - -DriveSubsystem::DriveSubsystem() { - // We need to invert one side of the drivetrain so that positive voltages - // result in both sides moving forward. Depending on how your robot's - // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.SetInverted(true); - - // Set the distance per pulse for the encoders - m_leftEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); - m_rightEncoder.SetDistancePerPulse(kEncoderDistancePerPulse); - - ResetEncoders(); - frc::SmartDashboard::PutData("Field", &m_fieldSim); -} - -void DriveSubsystem::Periodic() { - // Implementation of subsystem periodic method goes here. - m_odometry.Update(m_gyro.GetRotation2d(), - units::meter_t{m_leftEncoder.GetDistance()}, - units::meter_t{m_rightEncoder.GetDistance()}); - m_fieldSim.SetRobotPose(m_odometry.GetPose()); -} - -void DriveSubsystem::SimulationPeriodic() { - // To update our simulation, we set motor voltage inputs, update the - // simulation, and write the simulated positions and velocities to our - // simulated encoder and gyro. We negate the right side so that positive - // voltages make the right side move forward. - m_drivetrainSimulator.SetInputs(units::volt_t{m_leftMotors.Get()} * - frc::RobotController::GetInputVoltage(), - units::volt_t{m_rightMotors.Get()} * - frc::RobotController::GetInputVoltage()); - m_drivetrainSimulator.Update(20_ms); - - m_leftEncoderSim.SetDistance(m_drivetrainSimulator.GetLeftPosition().value()); - m_leftEncoderSim.SetRate(m_drivetrainSimulator.GetLeftVelocity().value()); - m_rightEncoderSim.SetDistance( - m_drivetrainSimulator.GetRightPosition().value()); - m_rightEncoderSim.SetRate(m_drivetrainSimulator.GetRightVelocity().value()); - m_gyroSim.SetAngle(-m_drivetrainSimulator.GetHeading().Degrees()); -} - -units::ampere_t DriveSubsystem::GetCurrentDraw() const { - return m_drivetrainSimulator.GetCurrentDraw(); -} - -void DriveSubsystem::ArcadeDrive(double fwd, double rot) { - m_drive.ArcadeDrive(fwd, rot); -} - -void DriveSubsystem::TankDriveVolts(units::volt_t left, units::volt_t right) { - m_leftMotors.SetVoltage(left); - m_rightMotors.SetVoltage(right); - m_drive.Feed(); -} - -void DriveSubsystem::ResetEncoders() { - m_leftEncoder.Reset(); - m_rightEncoder.Reset(); -} - -double DriveSubsystem::GetAverageEncoderDistance() { - return (m_leftEncoder.GetDistance() + m_rightEncoder.GetDistance()) / 2.0; -} - -frc::Encoder& DriveSubsystem::GetLeftEncoder() { - return m_leftEncoder; -} - -frc::Encoder& DriveSubsystem::GetRightEncoder() { - return m_rightEncoder; -} - -void DriveSubsystem::SetMaxOutput(double maxOutput) { - m_drive.SetMaxOutput(maxOutput); -} - -units::degree_t DriveSubsystem::GetHeading() const { - return m_gyro.GetRotation2d().Degrees(); -} - -double DriveSubsystem::GetTurnRate() { - return -m_gyro.GetRate(); -} - -frc::Pose2d DriveSubsystem::GetPose() { - return m_odometry.GetPose(); -} - -frc::DifferentialDriveWheelSpeeds DriveSubsystem::GetWheelSpeeds() { - return {units::meters_per_second_t{m_leftEncoder.GetRate()}, - units::meters_per_second_t{m_rightEncoder.GetRate()}}; -} - -void DriveSubsystem::ResetOdometry(frc::Pose2d pose) { - ResetEncoders(); - m_drivetrainSimulator.SetPose(pose); - m_odometry.ResetPosition(m_gyro.GetRotation2d(), - units::meter_t{m_leftEncoder.GetDistance()}, - units::meter_t{m_rightEncoder.GetDistance()}, pose); -} diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/include/Constants.h deleted file mode 100644 index d8080cafd18..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/include/Constants.h +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#pragma once - -/** - * The Constants header provides a convenient place for teams to hold robot-wide - * numerical or bool constants. This should not be used for any other purpose. - * - * It is generally a good idea to place constants into subsystem- or - * command-specific namespaces within this header, which can then be used where - * they are needed. - */ - -namespace DriveConstants { -constexpr int kLeftMotor1Port = 0; -constexpr int kLeftMotor2Port = 1; -constexpr int kRightMotor1Port = 2; -constexpr int kRightMotor2Port = 3; - -constexpr int kLeftEncoderPorts[]{0, 1}; -constexpr int kRightEncoderPorts[]{2, 3}; -constexpr bool kLeftEncoderReversed = false; -constexpr bool kRightEncoderReversed = true; - -constexpr auto kTrackwidth = 0.69_m; -extern const frc::DifferentialDriveKinematics kDriveKinematics; - -constexpr int kEncoderCPR = 1024; -constexpr auto kWheelDiameter = 6_in; -constexpr double kEncoderDistancePerPulse = - // Assumes the encoders are directly mounted on the wheel shafts - (kWheelDiameter.value() * std::numbers::pi) / - static_cast(kEncoderCPR); - -// These are example values only - DO NOT USE THESE FOR YOUR OWN ROBOT! -// These characterization values MUST be determined either experimentally or -// theoretically for *your* robot's drive. The Robot Characterization -// Toolsuite provides a convenient tool for obtaining these values for your -// robot. -constexpr auto ks = 0.22_V; -constexpr auto kv = 1.98 * 1_V / 1_mps; -constexpr auto ka = 0.2 * 1_V / 1_mps_sq; - -constexpr auto kvAngular = 1.5 * 1_V / 1_mps; -constexpr auto kaAngular = 0.3 * 1_V / 1_mps_sq; - -extern const frc::LinearSystem<2, 2, 2> kDrivetrainPlant; - -// Example values only -- use what's on your physical robot! -constexpr auto kDrivetrainGearbox = frc::DCMotor::CIM(2); -constexpr auto kDrivetrainGearing = 8.0; - -// Example value only - as above, this must be tuned for your drive! -constexpr double kPDriveVel = 8.5; -} // namespace DriveConstants - -namespace AutoConstants { -constexpr auto kMaxSpeed = 3_mps; -constexpr auto kMaxAcceleration = 3_mps_sq; - -// Reasonable baseline values for a RAMSETE follower in units of meters and -// seconds -constexpr auto kRamseteB = 2 * 1_rad * 1_rad / (1_m * 1_m); -constexpr auto kRamseteZeta = 0.7 / 1_rad; -} // namespace AutoConstants - -namespace OIConstants { -constexpr int kDriverControllerPort = 0; -} // namespace OIConstants diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/include/Robot.h b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/include/Robot.h deleted file mode 100644 index 00271e6e21c..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/include/Robot.h +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include - -#include "RobotContainer.h" - -class Robot : public frc::TimedRobot { - public: - void RobotInit() override; - void RobotPeriodic() override; - void DisabledInit() override; - void DisabledPeriodic() override; - void AutonomousInit() override; - void AutonomousPeriodic() override; - void TeleopInit() override; - void TeleopPeriodic() override; - void TestPeriodic() override; - void SimulationPeriodic() override; - - private: - // Have it null by default so that if testing teleop it - // doesn't have undefined behavior and potentially crash. - frc2::Command* m_autonomousCommand = nullptr; - - RobotContainer m_container; -}; diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/include/RobotContainer.h b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/include/RobotContainer.h deleted file mode 100644 index 012e3c6b351..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/include/RobotContainer.h +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Constants.h" -#include "subsystems/DriveSubsystem.h" - -/** - * This class is where the bulk of the robot should be declared. Since - * Command-based is a "declarative" paradigm, very little robot logic should - * actually be handled in the {@link Robot} periodic methods (other than the - * scheduler calls). Instead, the structure of the robot (including subsystems, - * commands, and button mappings) should be declared here. - */ -class RobotContainer { - public: - RobotContainer(); - - void ZeroAllOutputs(); - frc2::Command* GetAutonomousCommand(); - const DriveSubsystem& GetRobotDrive() const; - - private: - // The driver's controller - frc::XboxController m_driverController{OIConstants::kDriverControllerPort}; - - // The robot's subsystems and commands are defined here... - - // The robot's subsystems - DriveSubsystem m_drive; - - frc2::InstantCommand m_driveHalfSpeed{[this] { m_drive.SetMaxOutput(0.5); }, - {}}; - frc2::InstantCommand m_driveFullSpeed{[this] { m_drive.SetMaxOutput(1); }, - {}}; - - // The chooser for the autonomous routines - frc::SendableChooser m_chooser; - - void ConfigureButtonBindings(); -}; diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/include/subsystems/DriveSubsystem.h b/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/include/subsystems/DriveSubsystem.h deleted file mode 100644 index 57392c723ba..00000000000 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceDifferentialDriveSimulation/include/subsystems/DriveSubsystem.h +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Constants.h" - -class DriveSubsystem : public frc2::SubsystemBase { - public: - DriveSubsystem(); - - /** - * Will be called periodically whenever the CommandScheduler runs. - */ - void Periodic() override; - - /** - * Will be called periodically during simulation. - */ - void SimulationPeriodic() override; - - // Subsystem methods go here. - - units::ampere_t GetCurrentDraw() const; - - /** - * Drives the robot using arcade controls. - * - * @param fwd the commanded forward movement - * @param rot the commanded rotation - */ - void ArcadeDrive(double fwd, double rot); - - /** - * Controls each side of the drive directly with a voltage. - * - * @param left the commanded left output - * @param right the commanded right output - */ - void TankDriveVolts(units::volt_t left, units::volt_t right); - - /** - * Resets the drive encoders to currently read a position of 0. - */ - void ResetEncoders(); - - /** - * Gets the average distance of the TWO encoders. - * - * @return the average of the TWO encoder readings - */ - double GetAverageEncoderDistance(); - - /** - * Gets the left drive encoder. - * - * @return the left drive encoder - */ - frc::Encoder& GetLeftEncoder(); - - /** - * Gets the right drive encoder. - * - * @return the right drive encoder - */ - frc::Encoder& GetRightEncoder(); - - /** - * Sets the max output of the drive. Useful for scaling the drive to drive - * more slowly. - * - * @param maxOutput the maximum output to which the drive will be constrained - */ - void SetMaxOutput(double maxOutput); - - /** - * Returns the heading of the robot. - * - * @return the robot's heading in degrees, from -180 to 180 - */ - units::degree_t GetHeading() const; - - /** - * Returns the turn rate of the robot. - * - * @return The turn rate of the robot, in degrees per second - */ - double GetTurnRate(); - - /** - * Returns the currently-estimated pose of the robot. - * - * @return The pose. - */ - frc::Pose2d GetPose(); - - /** - * Returns the current wheel speeds of the robot. - * - * @return The current wheel speeds. - */ - frc::DifferentialDriveWheelSpeeds GetWheelSpeeds(); - - /** - * Resets the odometry to the specified pose. - * - * @param pose The pose to which to set the odometry. - */ - void ResetOdometry(frc::Pose2d pose); - - private: - // Components (e.g. motor controllers and sensors) should generally be - // declared private and exposed only through public methods. - - // The motor controllers - frc::PWMSparkMax m_left1{DriveConstants::kLeftMotor1Port}; - frc::PWMSparkMax m_left2{DriveConstants::kLeftMotor2Port}; - frc::PWMSparkMax m_right1{DriveConstants::kRightMotor1Port}; - frc::PWMSparkMax m_right2{DriveConstants::kRightMotor2Port}; - - // The motors on the left side of the drive - frc::MotorControllerGroup m_leftMotors{m_left1, m_left2}; - - // The motors on the right side of the drive - frc::MotorControllerGroup m_rightMotors{m_right1, m_right2}; - - // The robot's drive - frc::DifferentialDrive m_drive{m_leftMotors, m_rightMotors}; - - // The left-side drive encoder - frc::Encoder m_leftEncoder{DriveConstants::kLeftEncoderPorts[0], - DriveConstants::kLeftEncoderPorts[1], - DriveConstants::kLeftEncoderReversed}; - - // The right-side drive encoder - frc::Encoder m_rightEncoder{DriveConstants::kRightEncoderPorts[0], - DriveConstants::kRightEncoderPorts[1], - DriveConstants::kRightEncoderReversed}; - - // The gyro sensor - frc::ADXRS450_Gyro m_gyro; - - // Odometry class for tracking robot pose - frc::DifferentialDriveOdometry m_odometry{ - m_gyro.GetRotation2d(), units::meter_t{m_leftEncoder.GetDistance()}, - units::meter_t{m_rightEncoder.GetDistance()}}; - - // These classes help simulate our drivetrain. - frc::sim::DifferentialDrivetrainSim m_drivetrainSimulator{ - DriveConstants::kDrivetrainPlant, - DriveConstants::kTrackwidth, - DriveConstants::kDrivetrainGearbox, - DriveConstants::kDrivetrainGearing, - DriveConstants::kWheelDiameter / 2, - {0.001, 0.001, 0.0001, 0.1, 0.1, 0.005, 0.005}}; - - frc::sim::EncoderSim m_leftEncoderSim{m_leftEncoder}; - frc::sim::EncoderSim m_rightEncoderSim{m_rightEncoder}; - frc::sim::ADXRS450_GyroSim m_gyroSim{m_gyro}; - - // The Field2d class shows the field in the sim GUI. - frc::Field2d m_fieldSim; -}; diff --git a/wpilibcExamples/src/main/cpp/examples/StateSpaceElevator/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/StateSpaceElevator/cpp/Robot.cpp index ceadd8392bf..7b982b581bb 100644 --- a/wpilibcExamples/src/main/cpp/examples/StateSpaceElevator/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/StateSpaceElevator/cpp/Robot.cpp @@ -45,7 +45,8 @@ class Robot : public frc::TimedRobot { // Outputs (what we can measure): [position], in meters. frc::LinearSystem<2, 1, 1> m_elevatorPlant = frc::LinearSystemId::ElevatorSystem(frc::DCMotor::NEO(2), kCarriageMass, - kDrumRadius, kGearRatio); + kDrumRadius, kGearRatio) + .Slice(0); // The observer fuses our encoder data and voltage inputs to reject noise. frc::KalmanFilter<2, 1, 1> m_observer{ diff --git a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/Robot.cpp index c7eab485a5d..c4c1661d699 100644 --- a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/Robot.cpp @@ -37,7 +37,7 @@ void Robot::DisabledPeriodic() {} void Robot::AutonomousInit() { m_autonomousCommand = m_container.GetAutonomousCommand(); - if (m_autonomousCommand != nullptr) { + if (m_autonomousCommand) { m_autonomousCommand->Schedule(); } } @@ -49,9 +49,9 @@ void Robot::TeleopInit() { // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. - if (m_autonomousCommand != nullptr) { + if (m_autonomousCommand) { m_autonomousCommand->Cancel(); - m_autonomousCommand = nullptr; + m_autonomousCommand.reset(); } } diff --git a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/RobotContainer.cpp b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/RobotContainer.cpp index 4bbbe0c4c94..6c8de057532 100644 --- a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/RobotContainer.cpp +++ b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/cpp/RobotContainer.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -48,7 +49,7 @@ RobotContainer::RobotContainer() { void RobotContainer::ConfigureButtonBindings() {} -frc2::Command* RobotContainer::GetAutonomousCommand() { +frc2::CommandPtr RobotContainer::GetAutonomousCommand() { // Set up config for trajectory frc::TrajectoryConfig config(AutoConstants::kMaxSpeed, AutoConstants::kMaxAcceleration); @@ -73,24 +74,32 @@ frc2::Command* RobotContainer::GetAutonomousCommand() { thetaController.EnableContinuousInput(units::radian_t{-std::numbers::pi}, units::radian_t{std::numbers::pi}); - frc2::SwerveControllerCommand<4> swerveControllerCommand( - exampleTrajectory, [this]() { return m_drive.GetPose(); }, + frc2::CommandPtr swerveControllerCommand = + frc2::SwerveControllerCommand<4>( + exampleTrajectory, [this]() { return m_drive.GetPose(); }, - m_drive.kDriveKinematics, + m_drive.kDriveKinematics, - frc::PIDController{AutoConstants::kPXController, 0, 0}, - frc::PIDController{AutoConstants::kPYController, 0, 0}, thetaController, + frc::PIDController{AutoConstants::kPXController, 0, 0}, + frc::PIDController{AutoConstants::kPYController, 0, 0}, + thetaController, - [this](auto moduleStates) { m_drive.SetModuleStates(moduleStates); }, + [this](auto moduleStates) { m_drive.SetModuleStates(moduleStates); }, - {&m_drive}); + {&m_drive}) + .ToPtr(); - // Reset odometry to the starting pose of the trajectory. - m_drive.ResetOdometry(exampleTrajectory.InitialPose()); - - // no auto - return new frc2::SequentialCommandGroup( + // Reset odometry to the initial pose of the trajectory, run path following + // command, then stop at the end. + return frc2::cmd::Sequence( + frc2::InstantCommand( + [this, initialPose = exampleTrajectory.InitialPose()]() { + m_drive.ResetOdometry(initialPose); + }, + {}) + .ToPtr(), std::move(swerveControllerCommand), frc2::InstantCommand( - [this]() { m_drive.Drive(0_mps, 0_mps, 0_rad_per_s, false); }, {})); + [this] { m_drive.Drive(0_mps, 0_mps, 0_rad_per_s, false); }, {}) + .ToPtr()); } diff --git a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/Constants.h index 779927d7cd5..5e95629f184 100644 --- a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/Constants.h @@ -29,80 +29,80 @@ */ namespace DriveConstants { -constexpr int kFrontLeftDriveMotorPort = 0; -constexpr int kRearLeftDriveMotorPort = 2; -constexpr int kFrontRightDriveMotorPort = 4; -constexpr int kRearRightDriveMotorPort = 6; - -constexpr int kFrontLeftTurningMotorPort = 1; -constexpr int kRearLeftTurningMotorPort = 3; -constexpr int kFrontRightTurningMotorPort = 5; -constexpr int kRearRightTurningMotorPort = 7; - -constexpr int kFrontLeftTurningEncoderPorts[2]{0, 1}; -constexpr int kRearLeftTurningEncoderPorts[2]{2, 3}; -constexpr int kFrontRightTurningEncoderPorts[2]{4, 5}; -constexpr int kRearRightTurningEncoderPorts[2]{6, 7}; - -constexpr bool kFrontLeftTurningEncoderReversed = false; -constexpr bool kRearLeftTurningEncoderReversed = true; -constexpr bool kFrontRightTurningEncoderReversed = false; -constexpr bool kRearRightTurningEncoderReversed = true; - -constexpr int kFrontLeftDriveEncoderPorts[2]{8, 9}; -constexpr int kRearLeftDriveEncoderPorts[2]{10, 11}; -constexpr int kFrontRightDriveEncoderPorts[2]{12, 13}; -constexpr int kRearRightDriveEncoderPorts[2]{14, 15}; - -constexpr bool kFrontLeftDriveEncoderReversed = false; -constexpr bool kRearLeftDriveEncoderReversed = true; -constexpr bool kFrontRightDriveEncoderReversed = false; -constexpr bool kRearRightDriveEncoderReversed = true; +inline constexpr int kFrontLeftDriveMotorPort = 0; +inline constexpr int kRearLeftDriveMotorPort = 2; +inline constexpr int kFrontRightDriveMotorPort = 4; +inline constexpr int kRearRightDriveMotorPort = 6; + +inline constexpr int kFrontLeftTurningMotorPort = 1; +inline constexpr int kRearLeftTurningMotorPort = 3; +inline constexpr int kFrontRightTurningMotorPort = 5; +inline constexpr int kRearRightTurningMotorPort = 7; + +inline constexpr int kFrontLeftTurningEncoderPorts[2]{0, 1}; +inline constexpr int kRearLeftTurningEncoderPorts[2]{2, 3}; +inline constexpr int kFrontRightTurningEncoderPorts[2]{4, 5}; +inline constexpr int kRearRightTurningEncoderPorts[2]{6, 7}; + +inline constexpr bool kFrontLeftTurningEncoderReversed = false; +inline constexpr bool kRearLeftTurningEncoderReversed = true; +inline constexpr bool kFrontRightTurningEncoderReversed = false; +inline constexpr bool kRearRightTurningEncoderReversed = true; + +inline constexpr int kFrontLeftDriveEncoderPorts[2]{8, 9}; +inline constexpr int kRearLeftDriveEncoderPorts[2]{10, 11}; +inline constexpr int kFrontRightDriveEncoderPorts[2]{12, 13}; +inline constexpr int kRearRightDriveEncoderPorts[2]{14, 15}; + +inline constexpr bool kFrontLeftDriveEncoderReversed = false; +inline constexpr bool kRearLeftDriveEncoderReversed = true; +inline constexpr bool kFrontRightDriveEncoderReversed = false; +inline constexpr bool kRearRightDriveEncoderReversed = true; // If you call DriveSubsystem::Drive with a different period make sure to update // this. -constexpr units::second_t kDrivePeriod = frc::TimedRobot::kDefaultPeriod; +inline constexpr units::second_t kDrivePeriod = frc::TimedRobot::kDefaultPeriod; // These are example values only - DO NOT USE THESE FOR YOUR OWN ROBOT! // These characterization values MUST be determined either experimentally or // theoretically for *your* robot's drive. The SysId tool provides a convenient // method for obtaining these values for your robot. -constexpr auto ks = 1_V; -constexpr auto kv = 0.8 * 1_V * 1_s / 1_m; -constexpr auto ka = 0.15 * 1_V * 1_s * 1_s / 1_m; +inline constexpr auto ks = 1_V; +inline constexpr auto kv = 0.8 * 1_V * 1_s / 1_m; +inline constexpr auto ka = 0.15 * 1_V * 1_s * 1_s / 1_m; // Example value only - as above, this must be tuned for your drive! -constexpr double kPFrontLeftVel = 0.5; -constexpr double kPRearLeftVel = 0.5; -constexpr double kPFrontRightVel = 0.5; -constexpr double kPRearRightVel = 0.5; +inline constexpr double kPFrontLeftVel = 0.5; +inline constexpr double kPRearLeftVel = 0.5; +inline constexpr double kPFrontRightVel = 0.5; +inline constexpr double kPRearRightVel = 0.5; } // namespace DriveConstants namespace ModuleConstants { -constexpr int kEncoderCPR = 1024; -constexpr double kWheelDiameterMeters = 0.15; -constexpr double kDriveEncoderDistancePerPulse = +inline constexpr int kEncoderCPR = 1024; +inline constexpr double kWheelDiameterMeters = 0.15; +inline constexpr double kDriveEncoderDistancePerPulse = // Assumes the encoders are directly mounted on the wheel shafts (kWheelDiameterMeters * std::numbers::pi) / static_cast(kEncoderCPR); -constexpr double kTurningEncoderDistancePerPulse = +inline constexpr double kTurningEncoderDistancePerPulse = // Assumes the encoders are directly mounted on the wheel shafts (std::numbers::pi * 2) / static_cast(kEncoderCPR); -constexpr double kPModuleTurningController = 1; -constexpr double kPModuleDriveController = 1; +inline constexpr double kPModuleTurningController = 1; +inline constexpr double kPModuleDriveController = 1; } // namespace ModuleConstants namespace AutoConstants { -constexpr auto kMaxSpeed = 3_mps; -constexpr auto kMaxAcceleration = 3_mps_sq; -constexpr auto kMaxAngularSpeed = 3.142_rad_per_s; -constexpr auto kMaxAngularAcceleration = 3.142_rad_per_s_sq; +inline constexpr auto kMaxSpeed = 3_mps; +inline constexpr auto kMaxAcceleration = 3_mps_sq; +inline constexpr auto kMaxAngularSpeed = 3.142_rad_per_s; +inline constexpr auto kMaxAngularAcceleration = 3.142_rad_per_s_sq; -constexpr double kPXController = 0.5; -constexpr double kPYController = 0.5; -constexpr double kPThetaController = 0.5; +inline constexpr double kPXController = 0.5; +inline constexpr double kPYController = 0.5; +inline constexpr double kPThetaController = 0.5; // @@ -112,5 +112,5 @@ extern const frc::TrapezoidProfile::Constraints } // namespace AutoConstants namespace OIConstants { -constexpr int kDriverControllerPort = 0; +inline constexpr int kDriverControllerPort = 0; } // namespace OIConstants diff --git a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/Robot.h b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/Robot.h index a82f2ac63b0..de9c814e752 100644 --- a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/Robot.h +++ b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/Robot.h @@ -4,6 +4,8 @@ #pragma once +#include + #include #include @@ -24,7 +26,7 @@ class Robot : public frc::TimedRobot { private: // Have it null by default so that if testing teleop it // doesn't have undefined behavior and potentially crash. - frc2::Command* m_autonomousCommand = nullptr; + std::optional m_autonomousCommand; RobotContainer m_container; }; diff --git a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/RobotContainer.h b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/RobotContainer.h index 3466121ab6a..4c7916456ab 100644 --- a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/RobotContainer.h +++ b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/RobotContainer.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -28,7 +29,7 @@ class RobotContainer { public: RobotContainer(); - frc2::Command* GetAutonomousCommand(); + frc2::CommandPtr GetAutonomousCommand(); private: // The driver's controller @@ -39,8 +40,5 @@ class RobotContainer { // The robot's subsystems DriveSubsystem m_drive; - // The chooser for the autonomous routines - frc::SendableChooser m_chooser; - void ConfigureButtonBindings(); }; diff --git a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/subsystems/DriveSubsystem.h b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/subsystems/DriveSubsystem.h index b7b47fc128f..c428fd7f347 100644 --- a/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/subsystems/DriveSubsystem.h +++ b/wpilibcExamples/src/main/cpp/examples/SwerveControllerCommand/include/subsystems/DriveSubsystem.h @@ -9,7 +9,6 @@ #include #include #include -#include #include #include #include diff --git a/wpilibcExamples/src/main/cpp/examples/SysId/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/SysId/cpp/Robot.cpp new file mode 100644 index 00000000000..32782b29ae2 --- /dev/null +++ b/wpilibcExamples/src/main/cpp/examples/SysId/cpp/Robot.cpp @@ -0,0 +1,55 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "Robot.h" + +#include + +void Robot::RobotInit() {} + +void Robot::RobotPeriodic() { + frc2::CommandScheduler::GetInstance().Run(); +} + +void Robot::DisabledInit() {} + +void Robot::DisabledPeriodic() {} + +void Robot::DisabledExit() {} + +void Robot::AutonomousInit() { + m_autonomousCommand = m_container.GetAutonomousCommand(); + + if (m_autonomousCommand) { + m_autonomousCommand->Schedule(); + } +} + +void Robot::AutonomousPeriodic() {} + +void Robot::AutonomousExit() {} + +void Robot::TeleopInit() { + if (m_autonomousCommand) { + m_autonomousCommand->Cancel(); + } +} + +void Robot::TeleopPeriodic() {} + +void Robot::TeleopExit() {} + +void Robot::TestInit() { + frc2::CommandScheduler::GetInstance().CancelAll(); +} + +void Robot::TestPeriodic() {} + +void Robot::TestExit() {} + +#ifndef RUNNING_FRC_TESTS +int main() { + return frc::StartRobot(); +} +#endif diff --git a/wpilibcExamples/src/main/cpp/examples/SysId/cpp/SysIdRoutineBot.cpp b/wpilibcExamples/src/main/cpp/examples/SysId/cpp/SysIdRoutineBot.cpp new file mode 100644 index 00000000000..4e38374bff8 --- /dev/null +++ b/wpilibcExamples/src/main/cpp/examples/SysId/cpp/SysIdRoutineBot.cpp @@ -0,0 +1,44 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "SysIdRoutineBot.h" + +#include + +SysIdRoutineBot::SysIdRoutineBot() { + ConfigureBindings(); +} + +void SysIdRoutineBot::ConfigureBindings() { + m_drive.SetDefaultCommand(m_drive.ArcadeDriveCommand( + [this] { return -m_driverController.GetLeftY(); }, + [this] { return -m_driverController.GetRightX(); })); + + // Using bumpers as a modifier and combining it with the buttons so that we + // can have both sets of bindings at once + (m_driverController.A() && m_driverController.RightBumper()) + .WhileTrue(m_drive.SysIdQuasistatic(frc2::sysid::Direction::kForward)); + (m_driverController.B() && m_driverController.RightBumper()) + .WhileTrue(m_drive.SysIdQuasistatic(frc2::sysid::Direction::kReverse)); + (m_driverController.X() && m_driverController.RightBumper()) + .WhileTrue(m_drive.SysIdDynamic(frc2::sysid::Direction::kForward)); + (m_driverController.Y() && m_driverController.RightBumper()) + .WhileTrue(m_drive.SysIdDynamic(frc2::sysid::Direction::kReverse)); + + m_shooter.SetDefaultCommand(m_shooter.RunShooterCommand( + [this] { return m_driverController.GetLeftTriggerAxis(); })); + + (m_driverController.A() && m_driverController.LeftBumper()) + .WhileTrue(m_shooter.SysIdQuasistatic(frc2::sysid::Direction::kForward)); + (m_driverController.B() && m_driverController.LeftBumper()) + .WhileTrue(m_shooter.SysIdQuasistatic(frc2::sysid::Direction::kReverse)); + (m_driverController.X() && m_driverController.LeftBumper()) + .WhileTrue(m_shooter.SysIdDynamic(frc2::sysid::Direction::kForward)); + (m_driverController.Y() && m_driverController.LeftBumper()) + .WhileTrue(m_shooter.SysIdDynamic(frc2::sysid::Direction::kReverse)); +} + +frc2::CommandPtr SysIdRoutineBot::GetAutonomousCommand() { + return m_drive.Run([] {}); +} diff --git a/wpilibcExamples/src/main/cpp/examples/SysId/cpp/subsystems/Drive.cpp b/wpilibcExamples/src/main/cpp/examples/SysId/cpp/subsystems/Drive.cpp new file mode 100644 index 00000000000..331c17afc40 --- /dev/null +++ b/wpilibcExamples/src/main/cpp/examples/SysId/cpp/subsystems/Drive.cpp @@ -0,0 +1,37 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "subsystems/Drive.h" + +#include + +Drive::Drive() { + m_leftMotor.AddFollower(frc::PWMSparkMax{constants::drive::kLeftMotor2Port}); + m_rightMotor.AddFollower( + frc::PWMSparkMax{constants::drive::kRightMotor2Port}); + + m_rightMotor.SetInverted(true); + + m_leftEncoder.SetDistancePerPulse( + constants::drive::kEncoderDistancePerPulse.value()); + m_rightEncoder.SetDistancePerPulse( + constants::drive::kEncoderDistancePerPulse.value()); + + m_drive.SetSafetyEnabled(false); +} + +frc2::CommandPtr Drive::ArcadeDriveCommand(std::function fwd, + std::function rot) { + return frc2::cmd::Run([this, fwd, rot] { m_drive.ArcadeDrive(fwd(), rot()); }, + {this}) + .WithName("Arcade Drive"); +} + +frc2::CommandPtr Drive::SysIdQuasistatic(frc2::sysid::Direction direction) { + return m_sysIdRoutine.Quasistatic(direction); +} + +frc2::CommandPtr Drive::SysIdDynamic(frc2::sysid::Direction direction) { + return m_sysIdRoutine.Dynamic(direction); +} diff --git a/wpilibcExamples/src/main/cpp/examples/SysId/cpp/subsystems/Shooter.cpp b/wpilibcExamples/src/main/cpp/examples/SysId/cpp/subsystems/Shooter.cpp new file mode 100644 index 00000000000..8146cdd133b --- /dev/null +++ b/wpilibcExamples/src/main/cpp/examples/SysId/cpp/subsystems/Shooter.cpp @@ -0,0 +1,37 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "subsystems/Shooter.h" + +#include +#include +#include + +Shooter::Shooter() { + m_shooterEncoder.SetDistancePerPulse( + constants::shooter::kEncoderDistancePerPulse.value()); +} + +frc2::CommandPtr Shooter::RunShooterCommand( + std::function shooterSpeed) { + return frc2::cmd::Run( + [this, shooterSpeed] { + m_shooterMotor.SetVoltage( + units::volt_t{m_shooterFeedback.Calculate( + m_shooterEncoder.GetRate(), shooterSpeed())} + + m_shooterFeedforward.Calculate( + units::turns_per_second_t{shooterSpeed()})); + m_feederMotor.Set(constants::shooter::kFeederSpeed); + }, + {this}) + .WithName("Set Shooter Speed"); +} + +frc2::CommandPtr Shooter::SysIdQuasistatic(frc2::sysid::Direction direction) { + return m_sysIdRoutine.Quasistatic(direction); +} + +frc2::CommandPtr Shooter::SysIdDynamic(frc2::sysid::Direction direction) { + return m_sysIdRoutine.Dynamic(direction); +} diff --git a/wpilibcExamples/src/main/cpp/examples/SysId/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/SysId/include/Constants.h new file mode 100644 index 00000000000..79f6d44b364 --- /dev/null +++ b/wpilibcExamples/src/main/cpp/examples/SysId/include/Constants.h @@ -0,0 +1,88 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace constants { +namespace drive { +inline constexpr int kLeftMotor1Port = 0; +inline constexpr int kLeftMotor2Port = 1; +inline constexpr int kRightMotor1Port = 2; +inline constexpr int kRightMotor2Port = 3; + +inline constexpr std::array kLeftEncoderPorts = {0, 1}; +inline constexpr std::array kRightEncoderPorts = {2, 3}; +inline constexpr bool kLeftEncoderReversed = false; +inline constexpr bool kRightEncoderReversed = true; + +inline constexpr int kEncoderCpr = 1024; +inline constexpr units::meter_t kWheelDiameter = 6_in; +inline constexpr units::meter_t kEncoderDistancePerPulse = + (kWheelDiameter * std::numbers::pi) / static_cast(kEncoderCpr); +} // namespace drive + +namespace shooter { + +using kv_unit = + units::compound_unit, + units::inverse>; +using kv_unit_t = units::unit_t; + +using ka_unit = + units::compound_unit>; +using ka_unit_t = units::unit_t; + +inline constexpr std::array kEncoderPorts = {4, 5}; +inline constexpr bool kEncoderReversed = false; +inline constexpr int kEncoderCpr = 1024; +inline constexpr units::turn_t kEncoderDistancePerPulse = + 1_tr / static_cast(kEncoderCpr); + +inline constexpr int kShooterMotorPort = 4; +inline constexpr int kFeederMotorPort = 5; + +inline constexpr units::turns_per_second_t kShooterFreeSpeed = 5300_tps; +inline constexpr units::turns_per_second_t kShooterTargetSpeed = 4000_tps; +inline constexpr units::turns_per_second_t kShooterTolerance = 50_tps; + +inline constexpr double kP = 1.0; + +inline constexpr units::volt_t kS = 0.05_V; +inline constexpr kv_unit_t kV = (12_V) / kShooterFreeSpeed; +inline constexpr ka_unit_t kA = 0_V * 1_s * 1_s / 1_tr; + +inline constexpr double kFeederSpeed = 0.5; +} // namespace shooter + +namespace intake { +inline constexpr int kMotorPort = 6; +inline constexpr std::array kSolenoidPorts = {2, 3}; +} // namespace intake + +namespace storage { +inline constexpr int kMotorPort = 7; +inline constexpr int kBallSensorPort = 6; +} // namespace storage + +namespace autonomous { +inline constexpr units::second_t kTimeout = 3_s; +inline constexpr units::meter_t kDriveDistance = 2_m; +inline constexpr double kDriveSpeed = 0.5; +} // namespace autonomous + +namespace oi { +inline constexpr int kDriverControllerPort = 0; +} // namespace oi +} // namespace constants diff --git a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/include/Robot.h b/wpilibcExamples/src/main/cpp/examples/SysId/include/Robot.h similarity index 77% rename from wpilibcExamples/src/main/cpp/examples/RamseteCommand/include/Robot.h rename to wpilibcExamples/src/main/cpp/examples/SysId/include/Robot.h index 889bfdf3fa5..b6142c2405b 100644 --- a/wpilibcExamples/src/main/cpp/examples/RamseteCommand/include/Robot.h +++ b/wpilibcExamples/src/main/cpp/examples/SysId/include/Robot.h @@ -9,7 +9,7 @@ #include #include -#include "RobotContainer.h" +#include "SysIdRoutineBot.h" class Robot : public frc::TimedRobot { public: @@ -17,15 +17,19 @@ class Robot : public frc::TimedRobot { void RobotPeriodic() override; void DisabledInit() override; void DisabledPeriodic() override; + void DisabledExit() override; void AutonomousInit() override; void AutonomousPeriodic() override; + void AutonomousExit() override; void TeleopInit() override; void TeleopPeriodic() override; + void TeleopExit() override; + void TestInit() override; void TestPeriodic() override; + void TestExit() override; private: - // Have it empty by default std::optional m_autonomousCommand; - RobotContainer m_container; + SysIdRoutineBot m_container; }; diff --git a/wpilibcExamples/src/main/cpp/examples/SysId/include/SysIdRoutineBot.h b/wpilibcExamples/src/main/cpp/examples/SysId/include/SysIdRoutineBot.h new file mode 100644 index 00000000000..4363bb30ffc --- /dev/null +++ b/wpilibcExamples/src/main/cpp/examples/SysId/include/SysIdRoutineBot.h @@ -0,0 +1,26 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "Constants.h" +#include "subsystems/Drive.h" +#include "subsystems/Shooter.h" + +class SysIdRoutineBot { + public: + SysIdRoutineBot(); + + frc2::CommandPtr GetAutonomousCommand(); + + private: + void ConfigureBindings(); + frc2::CommandXboxController m_driverController{ + constants::oi::kDriverControllerPort}; + Drive m_drive; + Shooter m_shooter; +}; diff --git a/wpilibcExamples/src/main/cpp/examples/SysId/include/subsystems/Drive.h b/wpilibcExamples/src/main/cpp/examples/SysId/include/subsystems/Drive.h new file mode 100644 index 00000000000..45d4fa3aab0 --- /dev/null +++ b/wpilibcExamples/src/main/cpp/examples/SysId/include/subsystems/Drive.h @@ -0,0 +1,61 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +#include "Constants.h" + +class Drive : public frc2::SubsystemBase { + public: + Drive(); + + frc2::CommandPtr ArcadeDriveCommand(std::function fwd, + std::function rot); + frc2::CommandPtr SysIdQuasistatic(frc2::sysid::Direction direction); + frc2::CommandPtr SysIdDynamic(frc2::sysid::Direction direction); + + private: + frc::PWMSparkMax m_leftMotor{constants::drive::kLeftMotor1Port}; + frc::PWMSparkMax m_rightMotor{constants::drive::kRightMotor1Port}; + frc::DifferentialDrive m_drive{[this](auto val) { m_leftMotor.Set(val); }, + [this](auto val) { m_rightMotor.Set(val); }}; + + frc::Encoder m_leftEncoder{constants::drive::kLeftEncoderPorts[0], + constants::drive::kLeftEncoderPorts[1], + constants::drive::kLeftEncoderReversed}; + + frc::Encoder m_rightEncoder{constants::drive::kRightEncoderPorts[0], + constants::drive::kRightEncoderPorts[1], + constants::drive::kRightEncoderReversed}; + + frc2::sysid::SysIdRoutine m_sysIdRoutine{ + frc2::sysid::Config{std::nullopt, std::nullopt, std::nullopt, nullptr}, + frc2::sysid::Mechanism{ + [this](units::volt_t driveVoltage) { + m_leftMotor.SetVoltage(driveVoltage); + m_rightMotor.SetVoltage(driveVoltage); + }, + [this](frc::sysid::SysIdRoutineLog* log) { + log->Motor("drive-left") + .voltage(m_leftMotor.Get() * + frc::RobotController::GetBatteryVoltage()) + .position(units::meter_t{m_leftEncoder.GetDistance()}) + .velocity(units::meters_per_second_t{m_leftEncoder.GetRate()}); + log->Motor("drive-right") + .voltage(m_rightMotor.Get() * + frc::RobotController::GetBatteryVoltage()) + .position(units::meter_t{m_rightEncoder.GetDistance()}) + .velocity(units::meters_per_second_t{m_rightEncoder.GetRate()}); + }, + this}}; +}; diff --git a/wpilibcExamples/src/main/cpp/examples/SysId/include/subsystems/Shooter.h b/wpilibcExamples/src/main/cpp/examples/SysId/include/subsystems/Shooter.h new file mode 100644 index 00000000000..4f10c18277d --- /dev/null +++ b/wpilibcExamples/src/main/cpp/examples/SysId/include/subsystems/Shooter.h @@ -0,0 +1,53 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "Constants.h" + +class Shooter : public frc2::SubsystemBase { + public: + Shooter(); + + frc2::CommandPtr RunShooterCommand(std::function shooterSpeed); + frc2::CommandPtr SysIdQuasistatic(frc2::sysid::Direction direction); + frc2::CommandPtr SysIdDynamic(frc2::sysid::Direction direction); + + private: + frc::PWMSparkMax m_shooterMotor{constants::shooter::kShooterMotorPort}; + frc::PWMSparkMax m_feederMotor{constants::shooter::kFeederMotorPort}; + + frc::Encoder m_shooterEncoder{constants::shooter::kEncoderPorts[0], + constants::shooter::kEncoderPorts[1], + constants::shooter::kEncoderReversed}; + + frc2::sysid::SysIdRoutine m_sysIdRoutine{ + frc2::sysid::Config{std::nullopt, std::nullopt, std::nullopt, nullptr}, + frc2::sysid::Mechanism{ + [this](units::volt_t driveVoltage) { + m_shooterMotor.SetVoltage(driveVoltage); + }, + [this](frc::sysid::SysIdRoutineLog* log) { + log->Motor("shooter-wheel") + .voltage(m_shooterMotor.Get() * + frc::RobotController::GetBatteryVoltage()) + .position(units::turn_t{m_shooterEncoder.GetDistance()}) + .velocity( + units::turns_per_second_t{m_shooterEncoder.GetRate()}); + }, + this}}; + frc::PIDController m_shooterFeedback{constants::shooter::kP, 0, 0}; + frc::SimpleMotorFeedforward m_shooterFeedforward{ + constants::shooter::kS, constants::shooter::kV, constants::shooter::kA}; +}; diff --git a/wpilibcExamples/src/main/cpp/examples/TankDrive/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/TankDrive/cpp/Robot.cpp index 4e48d475842..f7b3e9c6900 100644 --- a/wpilibcExamples/src/main/cpp/examples/TankDrive/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/TankDrive/cpp/Robot.cpp @@ -14,12 +14,17 @@ class Robot : public frc::TimedRobot { frc::PWMSparkMax m_leftMotor{0}; frc::PWMSparkMax m_rightMotor{1}; - frc::DifferentialDrive m_robotDrive{m_leftMotor, m_rightMotor}; + frc::DifferentialDrive m_robotDrive{ + [&](double output) { m_leftMotor.Set(output); }, + [&](double output) { m_rightMotor.Set(output); }}; frc::Joystick m_leftStick{0}; frc::Joystick m_rightStick{1}; public: void RobotInit() override { + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_leftMotor); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_rightMotor); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. diff --git a/wpilibcExamples/src/main/cpp/examples/TankDriveXboxController/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/TankDriveXboxController/cpp/Robot.cpp index b8cff3271e7..7c0706ef791 100644 --- a/wpilibcExamples/src/main/cpp/examples/TankDriveXboxController/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/TankDriveXboxController/cpp/Robot.cpp @@ -14,11 +14,16 @@ class Robot : public frc::TimedRobot { frc::PWMSparkMax m_leftMotor{0}; frc::PWMSparkMax m_rightMotor{1}; - frc::DifferentialDrive m_robotDrive{m_leftMotor, m_rightMotor}; + frc::DifferentialDrive m_robotDrive{ + [&](double output) { m_leftMotor.Set(output); }, + [&](double output) { m_rightMotor.Set(output); }}; frc::XboxController m_driverController{0}; public: void RobotInit() override { + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_leftMotor); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_rightMotor); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. diff --git a/wpilibcExamples/src/main/cpp/examples/UltrasonicPID/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/UltrasonicPID/cpp/Robot.cpp index 9d2b5c2003c..fecaf97fb9d 100644 --- a/wpilibcExamples/src/main/cpp/examples/UltrasonicPID/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/UltrasonicPID/cpp/Robot.cpp @@ -4,6 +4,11 @@ #include "Robot.h" +Robot::Robot() { + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_left); + wpi::SendableRegistry::AddChild(&m_robotDrive, &m_right); +} + void Robot::AutonomousInit() { // Set setpoint of the pid controller m_pidController.SetSetpoint(kHoldDistance.value()); diff --git a/wpilibcExamples/src/main/cpp/examples/UltrasonicPID/include/Robot.h b/wpilibcExamples/src/main/cpp/examples/UltrasonicPID/include/Robot.h index 4ff2700d6a0..696f0668fc9 100644 --- a/wpilibcExamples/src/main/cpp/examples/UltrasonicPID/include/Robot.h +++ b/wpilibcExamples/src/main/cpp/examples/UltrasonicPID/include/Robot.h @@ -18,6 +18,7 @@ */ class Robot : public frc::TimedRobot { public: + Robot(); void AutonomousInit() override; void AutonomousPeriodic() override; @@ -31,9 +32,7 @@ class Robot : public frc::TimedRobot { private: // proportional speed constant - // negative because applying positive voltage will bring us closer to the - // target - static constexpr double kP = -0.001; + static constexpr double kP = 0.001; // integral speed constant static constexpr double kI = 0.0; // derivative speed constant @@ -46,6 +45,8 @@ class Robot : public frc::TimedRobot { frc::Ultrasonic m_ultrasonic{kUltrasonicPingPort, kUltrasonicEchoPort}; frc::PWMSparkMax m_left{kLeftMotorPort}; frc::PWMSparkMax m_right{kRightMotorPort}; - frc::DifferentialDrive m_robotDrive{m_left, m_right}; + frc::DifferentialDrive m_robotDrive{ + [&](double output) { m_left.Set(output); }, + [&](double output) { m_right.Set(output); }}; frc::PIDController m_pidController{kP, kI, kD}; }; diff --git a/wpilibcExamples/src/main/cpp/examples/UnitTest/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/UnitTest/include/Constants.h index 2ad9b079a4a..f736bd354d8 100644 --- a/wpilibcExamples/src/main/cpp/examples/UnitTest/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/UnitTest/include/Constants.h @@ -14,13 +14,13 @@ */ namespace IntakeConstants { -constexpr int kMotorPort = 1; +inline constexpr int kMotorPort = 1; -constexpr int kPistonFwdChannel = 0; -constexpr int kPistonRevChannel = 1; -constexpr double kIntakeSpeed = 0.5; +inline constexpr int kPistonFwdChannel = 0; +inline constexpr int kPistonRevChannel = 1; +inline constexpr double kIntakeSpeed = 0.5; } // namespace IntakeConstants namespace OperatorConstants { -constexpr int kJoystickIndex = 0; +inline constexpr int kJoystickIndex = 0; } // namespace OperatorConstants diff --git a/wpilibcExamples/src/main/cpp/examples/XRPReference/cpp/subsystems/Drivetrain.cpp b/wpilibcExamples/src/main/cpp/examples/XRPReference/cpp/subsystems/Drivetrain.cpp index bcec018bcda..25c520cef25 100644 --- a/wpilibcExamples/src/main/cpp/examples/XRPReference/cpp/subsystems/Drivetrain.cpp +++ b/wpilibcExamples/src/main/cpp/examples/XRPReference/cpp/subsystems/Drivetrain.cpp @@ -15,6 +15,9 @@ using namespace DriveConstants; // The XRP has onboard encoders that are hardcoded // to use DIO pins 4/5 and 6/7 for the left and right Drivetrain::Drivetrain() { + wpi::SendableRegistry::AddChild(&m_drive, &m_leftMotor); + wpi::SendableRegistry::AddChild(&m_drive, &m_rightMotor); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. diff --git a/wpilibcExamples/src/main/cpp/examples/XRPReference/include/Constants.h b/wpilibcExamples/src/main/cpp/examples/XRPReference/include/Constants.h index e5cee33afd1..dddb741e72e 100644 --- a/wpilibcExamples/src/main/cpp/examples/XRPReference/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/examples/XRPReference/include/Constants.h @@ -14,6 +14,6 @@ */ namespace DriveConstants { -constexpr double kCountsPerRevolution = 1440.0; -constexpr double kWheelDiameterInch = 2.75; +inline constexpr double kCountsPerRevolution = 1440.0; +inline constexpr double kWheelDiameterInch = 2.75; } // namespace DriveConstants diff --git a/wpilibcExamples/src/main/cpp/examples/XRPReference/include/subsystems/Drivetrain.h b/wpilibcExamples/src/main/cpp/examples/XRPReference/include/subsystems/Drivetrain.h index e665601228e..c2a2ef319f1 100644 --- a/wpilibcExamples/src/main/cpp/examples/XRPReference/include/subsystems/Drivetrain.h +++ b/wpilibcExamples/src/main/cpp/examples/XRPReference/include/subsystems/Drivetrain.h @@ -118,7 +118,9 @@ class Drivetrain : public frc2::SubsystemBase { frc::Encoder m_leftEncoder{4, 5}; frc::Encoder m_rightEncoder{6, 7}; - frc::DifferentialDrive m_drive{m_leftMotor, m_rightMotor}; + frc::DifferentialDrive m_drive{ + [&](double output) { m_leftMotor.Set(output); }, + [&](double output) { m_rightMotor.Set(output); }}; frc::XRPGyro m_gyro; frc::BuiltInAccelerometer m_accelerometer; diff --git a/wpilibcExamples/src/main/cpp/examples/examples.json b/wpilibcExamples/src/main/cpp/examples/examples.json index 803290918cc..2aed3990203 100644 --- a/wpilibcExamples/src/main/cpp/examples/examples.json +++ b/wpilibcExamples/src/main/cpp/examples/examples.json @@ -310,12 +310,12 @@ "commandversion": 2 }, { - "name": "Axis Camera Sample", - "description": "Acquire images from an Axis network camera and adds some annotation to the image (as you might do for showing operators the result of some image recognition), and sends it to the dashboard for display.", + "name": "HTTP Camera", + "description": "Acquire images from an HTTP network camera and adds some annotation to the image (as you might do for showing operators the result of some image recognition), and sends it to the dashboard for display.", "tags": [ "Vision" ], - "foldername": "AxisCameraSample", + "foldername": "HttpCamera", "gradlebase": "cpp", "commandversion": 2 }, @@ -502,24 +502,6 @@ "gradlebase": "cpp", "commandversion": 2 }, - { - "name": "RamseteCommand", - "description": "Follow a pre-generated trajectory with a differential drive using RamseteCommand.", - "tags": [ - "Differential Drive", - "Command-based", - "Ramsete", - "Trajectory", - "Path Following", - "Odometry", - "Encoder", - "Gyro", - "XboxController" - ], - "foldername": "RamseteCommand", - "gradlebase": "cpp", - "commandversion": 2 - }, { "name": "Arcade Drive Xbox Controller", "description": "Control a differential drive with split-stick arcade drive in teleop.", @@ -671,23 +653,6 @@ "gradlebase": "cpp", "commandversion": 2 }, - { - "name": "RamseteController", - "description": "Follow a pre-generated trajectory with a differential drive using RamseteController.", - "tags": [ - "Basic Robot", - "Differential Drive", - "Ramsete", - "PID", - "Odometry", - "Path Following", - "Trajectory", - "XboxController" - ], - "foldername": "RamseteController", - "gradlebase": "cpp", - "commandversion": 2 - }, { "name": "RomiReference", "description": "An example command-based robot program that can be used with the Romi reference robot design.", @@ -887,20 +852,6 @@ "gradlebase": "cpp", "commandversion": 2 }, - { - "name": "StateSpaceDriveSimulation", - "description": "Simulate a differential drivetrain and follow trajectories with RamseteCommand (command-based).", - "tags": [ - "Command-based", - "Differential Drive", - "State-Space", - "XboxController", - "Simulation" - ], - "foldername": "StateSpaceDifferentialDriveSimulation", - "gradlebase": "cpp", - "commandversion": 2 - }, { "name": "SwerveDrivePoseEstimator", "description": "Combine swerve-drive odometry with vision data using SwerveDrivePoseEstimator.", @@ -927,5 +878,17 @@ "foldername": "FlywheelBangBangController", "gradlebase": "cpp", "commandversion": 2 + }, + { + "name": "SysIdRoutine", + "description": "A sample command-based robot demonstrating use of the SysIdRoutine command factory", + "tags": [ + "SysId", + "Command-based", + "DataLog" + ], + "foldername": "SysId", + "gradlebase": "cpp", + "commandversion": 2 } ] diff --git a/wpilibcExamples/src/main/cpp/templates/commandbased/include/Constants.h b/wpilibcExamples/src/main/cpp/templates/commandbased/include/Constants.h index 963b31c6b55..87dd5b91b9d 100644 --- a/wpilibcExamples/src/main/cpp/templates/commandbased/include/Constants.h +++ b/wpilibcExamples/src/main/cpp/templates/commandbased/include/Constants.h @@ -16,6 +16,6 @@ namespace OperatorConstants { -constexpr int kDriverControllerPort = 0; +inline constexpr int kDriverControllerPort = 0; } // namespace OperatorConstants diff --git a/wpilibcExamples/src/main/cpp/templates/timed/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/templates/timed/cpp/Robot.cpp index f74262bef9e..c248d043593 100644 --- a/wpilibcExamples/src/main/cpp/templates/timed/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/templates/timed/cpp/Robot.cpp @@ -4,8 +4,8 @@ #include "Robot.h" -#include #include +#include void Robot::RobotInit() { m_chooser.SetDefaultOption(kAutoNameDefault, kAutoNameDefault); @@ -38,7 +38,7 @@ void Robot::AutonomousInit() { m_autoSelected = m_chooser.GetSelected(); // m_autoSelected = SmartDashboard::GetString("Auto Selector", // kAutoNameDefault); - fmt::print("Auto selected: {}\n", m_autoSelected); + wpi::print("Auto selected: {}\n", m_autoSelected); if (m_autoSelected == kAutoNameCustom) { // Custom Auto goes here diff --git a/wpilibcExamples/src/main/cpp/templates/timeslice/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/templates/timeslice/cpp/Robot.cpp index 548457b5428..3dec6eb3657 100644 --- a/wpilibcExamples/src/main/cpp/templates/timeslice/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/templates/timeslice/cpp/Robot.cpp @@ -4,9 +4,9 @@ #include "Robot.h" -#include #include #include +#include // Run robot periodic() functions for 5 ms, and run controllers every 10 ms Robot::Robot() : frc::TimesliceRobot{5_ms, 10_ms} { @@ -56,7 +56,7 @@ void Robot::AutonomousInit() { m_autoSelected = m_chooser.GetSelected(); // m_autoSelected = SmartDashboard::GetString("Auto Selector", // kAutoNameDefault); - fmt::print("Auto selected: {}\n", m_autoSelected); + wpi::print("Auto selected: {}\n", m_autoSelected); if (m_autoSelected == kAutoNameCustom) { // Custom Auto goes here diff --git a/wpilibcExamples/src/test/cpp/examples/MecanumControllerCommand/cpp/MecanumControllerCommandTest.cpp b/wpilibcExamples/src/test/cpp/examples/MecanumControllerCommand/cpp/MecanumControllerCommandTest.cpp new file mode 100644 index 00000000000..74d84f167fa --- /dev/null +++ b/wpilibcExamples/src/test/cpp/examples/MecanumControllerCommand/cpp/MecanumControllerCommandTest.cpp @@ -0,0 +1,64 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include + +#include +#include +#include +#include + +#include "Robot.h" + +class MecanumControllerCommandTest : public testing::Test { + Robot m_robot; + std::optional m_thread; + bool joystickWarning; + + public: + void SetUp() override { + frc::sim::PauseTiming(); + joystickWarning = frc::DriverStation::IsJoystickConnectionWarningSilenced(); + frc::DriverStation::SilenceJoystickConnectionWarning(true); + + m_thread = std::thread([&] { m_robot.StartCompetition(); }); + frc::sim::StepTiming(0.0_ms); // Wait for Notifiers + } + + void TearDown() override { + m_robot.EndCompetition(); + m_thread->join(); + + frc::sim::DriverStationSim::ResetData(); + frc::DriverStation::SilenceJoystickConnectionWarning(joystickWarning); + } +}; + +TEST_F(MecanumControllerCommandTest, Match) { + // auto + frc::sim::DriverStationSim::SetAutonomous(true); + frc::sim::DriverStationSim::SetEnabled(true); + frc::sim::DriverStationSim::NotifyNewData(); + + frc::sim::StepTiming(15_s); + + // brief disabled period- exact duration shouldn't matter + frc::sim::DriverStationSim::SetAutonomous(false); + frc::sim::DriverStationSim::SetEnabled(false); + frc::sim::DriverStationSim::NotifyNewData(); + + frc::sim::StepTiming(3_s); + + // teleop + frc::sim::DriverStationSim::SetAutonomous(false); + frc::sim::DriverStationSim::SetEnabled(true); + frc::sim::DriverStationSim::NotifyNewData(); + + frc::sim::StepTiming(135_s); + + // end of match + frc::sim::DriverStationSim::SetAutonomous(false); + frc::sim::DriverStationSim::SetEnabled(false); + frc::sim::DriverStationSim::NotifyNewData(); +} diff --git a/wpilibcExamples/src/test/cpp/examples/MecanumControllerCommand/cpp/main.cpp b/wpilibcExamples/src/test/cpp/examples/MecanumControllerCommand/cpp/main.cpp new file mode 100644 index 00000000000..38d5cfa2fed --- /dev/null +++ b/wpilibcExamples/src/test/cpp/examples/MecanumControllerCommand/cpp/main.cpp @@ -0,0 +1,16 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include +#include + +/** + * Runs all unit tests. + */ +int main(int argc, char** argv) { + HAL_Initialize(500, 0); + ::testing::InitGoogleTest(&argc, argv); + int ret = RUN_ALL_TESTS(); + return ret; +} diff --git a/wpilibcExamples/src/test/cpp/examples/RamseteCommand/cpp/RamseteCommandTest.cpp b/wpilibcExamples/src/test/cpp/examples/RamseteCommand/cpp/RamseteCommandTest.cpp new file mode 100644 index 00000000000..74d84f167fa --- /dev/null +++ b/wpilibcExamples/src/test/cpp/examples/RamseteCommand/cpp/RamseteCommandTest.cpp @@ -0,0 +1,64 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include + +#include +#include +#include +#include + +#include "Robot.h" + +class MecanumControllerCommandTest : public testing::Test { + Robot m_robot; + std::optional m_thread; + bool joystickWarning; + + public: + void SetUp() override { + frc::sim::PauseTiming(); + joystickWarning = frc::DriverStation::IsJoystickConnectionWarningSilenced(); + frc::DriverStation::SilenceJoystickConnectionWarning(true); + + m_thread = std::thread([&] { m_robot.StartCompetition(); }); + frc::sim::StepTiming(0.0_ms); // Wait for Notifiers + } + + void TearDown() override { + m_robot.EndCompetition(); + m_thread->join(); + + frc::sim::DriverStationSim::ResetData(); + frc::DriverStation::SilenceJoystickConnectionWarning(joystickWarning); + } +}; + +TEST_F(MecanumControllerCommandTest, Match) { + // auto + frc::sim::DriverStationSim::SetAutonomous(true); + frc::sim::DriverStationSim::SetEnabled(true); + frc::sim::DriverStationSim::NotifyNewData(); + + frc::sim::StepTiming(15_s); + + // brief disabled period- exact duration shouldn't matter + frc::sim::DriverStationSim::SetAutonomous(false); + frc::sim::DriverStationSim::SetEnabled(false); + frc::sim::DriverStationSim::NotifyNewData(); + + frc::sim::StepTiming(3_s); + + // teleop + frc::sim::DriverStationSim::SetAutonomous(false); + frc::sim::DriverStationSim::SetEnabled(true); + frc::sim::DriverStationSim::NotifyNewData(); + + frc::sim::StepTiming(135_s); + + // end of match + frc::sim::DriverStationSim::SetAutonomous(false); + frc::sim::DriverStationSim::SetEnabled(false); + frc::sim::DriverStationSim::NotifyNewData(); +} diff --git a/wpilibcExamples/src/test/cpp/examples/RamseteCommand/cpp/main.cpp b/wpilibcExamples/src/test/cpp/examples/RamseteCommand/cpp/main.cpp new file mode 100644 index 00000000000..38d5cfa2fed --- /dev/null +++ b/wpilibcExamples/src/test/cpp/examples/RamseteCommand/cpp/main.cpp @@ -0,0 +1,16 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include +#include + +/** + * Runs all unit tests. + */ +int main(int argc, char** argv) { + HAL_Initialize(500, 0); + ::testing::InitGoogleTest(&argc, argv); + int ret = RUN_ALL_TESTS(); + return ret; +} diff --git a/wpilibcExamples/src/test/cpp/examples/SwerveControllerCommand/cpp/SwerveControllerCommandTest.cpp b/wpilibcExamples/src/test/cpp/examples/SwerveControllerCommand/cpp/SwerveControllerCommandTest.cpp new file mode 100644 index 00000000000..eb20804de01 --- /dev/null +++ b/wpilibcExamples/src/test/cpp/examples/SwerveControllerCommand/cpp/SwerveControllerCommandTest.cpp @@ -0,0 +1,69 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include +#include + +#include +#include +#include +#include + +#include "Robot.h" + +class SwerveControllerCommandTest : public testing::Test { + Robot m_robot; + std::optional m_thread; + bool joystickWarning; + + public: + void SetUp() override { + frc::sim::PauseTiming(); + joystickWarning = frc::DriverStation::IsJoystickConnectionWarningSilenced(); + frc::DriverStation::SilenceJoystickConnectionWarning(true); + + m_thread = std::thread([&] { m_robot.StartCompetition(); }); + frc::sim::StepTiming(0.0_ms); // Wait for Notifiers + } + + void TearDown() override { + m_robot.EndCompetition(); + m_thread->join(); + + frc::sim::DriverStationSim::ResetData(); + frc::DriverStation::SilenceJoystickConnectionWarning(joystickWarning); + } +}; + +TEST_F(SwerveControllerCommandTest, Match) { + std::cerr << "autonomous" << std::endl; + // auto + frc::sim::DriverStationSim::SetAutonomous(true); + frc::sim::DriverStationSim::SetEnabled(true); + frc::sim::DriverStationSim::NotifyNewData(); + + frc::sim::StepTiming(15_s); + + // brief disabled period- exact duration shouldn't matter + std::cerr << "mid disabled" << std::endl; + frc::sim::DriverStationSim::SetAutonomous(false); + frc::sim::DriverStationSim::SetEnabled(false); + frc::sim::DriverStationSim::NotifyNewData(); + + frc::sim::StepTiming(3_s); + + // teleop + std::cerr << "teleop" << std::endl; + frc::sim::DriverStationSim::SetAutonomous(false); + frc::sim::DriverStationSim::SetEnabled(true); + frc::sim::DriverStationSim::NotifyNewData(); + + frc::sim::StepTiming(135_s); + + // end of match + std::cerr << "end of match" << std::endl; + frc::sim::DriverStationSim::SetAutonomous(false); + frc::sim::DriverStationSim::SetEnabled(false); + frc::sim::DriverStationSim::NotifyNewData(); +} diff --git a/wpilibcExamples/src/test/cpp/examples/SwerveControllerCommand/cpp/main.cpp b/wpilibcExamples/src/test/cpp/examples/SwerveControllerCommand/cpp/main.cpp new file mode 100644 index 00000000000..38d5cfa2fed --- /dev/null +++ b/wpilibcExamples/src/test/cpp/examples/SwerveControllerCommand/cpp/main.cpp @@ -0,0 +1,16 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include +#include + +/** + * Runs all unit tests. + */ +int main(int argc, char** argv) { + HAL_Initialize(500, 0); + ::testing::InitGoogleTest(&argc, argv); + int ret = RUN_ALL_TESTS(); + return ret; +} diff --git a/wpilibcExamples/src/test/cpp/examples/UltrasonicPID/cpp/UltrasonicPIDTest.cpp b/wpilibcExamples/src/test/cpp/examples/UltrasonicPID/cpp/UltrasonicPIDTest.cpp index a970a3a1bc6..5cfcbe8dbc7 100644 --- a/wpilibcExamples/src/test/cpp/examples/UltrasonicPID/cpp/UltrasonicPIDTest.cpp +++ b/wpilibcExamples/src/test/cpp/examples/UltrasonicPID/cpp/UltrasonicPIDTest.cpp @@ -57,7 +57,7 @@ class UltrasonicPIDTest : public testing::TestWithParam { m_driveSim.Update(20_ms); auto startingDistance = units::meter_t{GetParam()}; - m_distance = startingDistance - m_driveSim.GetLeftPosition(); + m_distance = m_driveSim.GetLeftPosition() - startingDistance; m_ultrasonicSim.SetRange(m_distance); } @@ -99,8 +99,7 @@ TEST_P(UltrasonicPIDTest, Auto) { } { - // advance 100 timesteps - frc::sim::StepTiming(2_s); + frc::sim::StepTiming(5_s); EXPECT_NEAR(Robot::kHoldDistance.value(), m_distance.value(), 10.0); } diff --git a/wpilibcIntegrationTests/src/main/native/cpp/MotorEncoderTest.cpp b/wpilibcIntegrationTests/src/main/native/cpp/MotorEncoderTest.cpp index be7efb8e68e..949950472ca 100644 --- a/wpilibcIntegrationTests/src/main/native/cpp/MotorEncoderTest.cpp +++ b/wpilibcIntegrationTests/src/main/native/cpp/MotorEncoderTest.cpp @@ -6,6 +6,7 @@ #include #include +#include #include "TestBench.h" #include "frc/Encoder.h" @@ -37,6 +38,8 @@ std::ostream& operator<<(std::ostream& os, MotorEncoderTestType const& type) { static constexpr auto kMotorTime = 0.5_s; +WPI_IGNORE_DEPRECATED + /** * A fixture that includes a PWM motor controller and an encoder connected to * the same motor. @@ -197,3 +200,5 @@ TEST_P(MotorEncoderTest, Reset) { INSTANTIATE_TEST_SUITE_P(Tests, MotorEncoderTest, testing::Values(TEST_VICTOR, TEST_JAGUAR, TEST_TALON)); + +WPI_UNIGNORE_DEPRECATED diff --git a/wpilibcIntegrationTests/src/main/native/cpp/MotorInvertingTest.cpp b/wpilibcIntegrationTests/src/main/native/cpp/MotorInvertingTest.cpp index 870f029f9d7..49a419c10dc 100644 --- a/wpilibcIntegrationTests/src/main/native/cpp/MotorInvertingTest.cpp +++ b/wpilibcIntegrationTests/src/main/native/cpp/MotorInvertingTest.cpp @@ -4,6 +4,7 @@ #include #include +#include #include "TestBench.h" #include "frc/Encoder.h" @@ -32,6 +33,9 @@ std::ostream& operator<<(std::ostream& os, MotorInvertingTestType const& type) { return os; } + +WPI_IGNORE_DEPRECATED + class MotorInvertingTest : public testing::TestWithParam { protected: @@ -153,3 +157,5 @@ TEST_P(MotorInvertingTest, InvertingSwitchingNegToPos) { INSTANTIATE_TEST_SUITE_P(Tests, MotorInvertingTest, testing::Values(TEST_VICTOR, TEST_JAGUAR, TEST_TALON)); + +WPI_UNIGNORE_DEPRECATED diff --git a/wpilibcIntegrationTests/src/main/native/cpp/NotifierTest.cpp b/wpilibcIntegrationTests/src/main/native/cpp/NotifierTest.cpp index ca7fb8499fd..08c8e39e960 100644 --- a/wpilibcIntegrationTests/src/main/native/cpp/NotifierTest.cpp +++ b/wpilibcIntegrationTests/src/main/native/cpp/NotifierTest.cpp @@ -4,8 +4,8 @@ #include "frc/Notifier.h" // NOLINT(build/include_order) -#include #include +#include #include "frc/Timer.h" @@ -20,13 +20,13 @@ TEST(NotifierTest, StartPeriodicAndStop) { notifier.Stop(); EXPECT_EQ(10u, counter) << "Received " << counter << " notifications in 10.5 seconds\n"; - fmt::print("Received {} notifications in 10.5 seconds\n", counter); + wpi::print("Received {} notifications in 10.5 seconds\n", counter); frc::Wait(3_s); EXPECT_EQ(10u, counter) << "Received " << counter - 10 << " notifications in 3 seconds\n"; - fmt::print("Received {} notifications in 3 seconds\n", counter - 10); + wpi::print("Received {} notifications in 3 seconds\n", counter - 10); } TEST(NotifierTest, StartSingle) { @@ -39,5 +39,5 @@ TEST(NotifierTest, StartSingle) { EXPECT_EQ(1u, counter) << "Received " << counter << " notifications in 10.5 seconds\n"; - fmt::print("Received {} notifications in 10.5 seconds\n", counter); + wpi::print("Received {} notifications in 10.5 seconds\n", counter); } diff --git a/wpilibcIntegrationTests/src/main/native/cpp/PreferencesTest.cpp b/wpilibcIntegrationTests/src/main/native/cpp/PreferencesTest.cpp index ef58bb4bed1..cdc8ecbd42a 100644 --- a/wpilibcIntegrationTests/src/main/native/cpp/PreferencesTest.cpp +++ b/wpilibcIntegrationTests/src/main/native/cpp/PreferencesTest.cpp @@ -35,8 +35,8 @@ TEST(PreferencesTest, ReadPreferencesFromFile) { << "\"properties\":{\"persistent\":true}}," << std::endl; preferencesFile << "{\"type\":\"int\"," << "\"name\":\"/Preferences/testFileGetInt\"," - << "\"value\":1," - << "\"properties\":{\"persistent\":true}}," << std::endl; + << "\"value\":1," << "\"properties\":{\"persistent\":true}}," + << std::endl; preferencesFile << "{\"type\":\"double\"," << "\"name\":\"/Preferences/testFileGetDouble\"," << "\"value\":0.5," diff --git a/wpilibcIntegrationTests/src/main/native/cpp/TestEnvironment.cpp b/wpilibcIntegrationTests/src/main/native/cpp/TestEnvironment.cpp index 91f27b91a8f..1628b7e8208 100644 --- a/wpilibcIntegrationTests/src/main/native/cpp/TestEnvironment.cpp +++ b/wpilibcIntegrationTests/src/main/native/cpp/TestEnvironment.cpp @@ -5,9 +5,9 @@ #include #include -#include #include #include +#include #include "frc/DriverStation.h" #include "frc/livewindow/LiveWindow.h" @@ -29,7 +29,7 @@ class TestEnvironment : public testing::Environment { m_alreadySetUp = true; if (!HAL_Initialize(500, 0)) { - fmt::print(stderr, "FATAL ERROR: HAL could not be initialized\n"); + wpi::print(stderr, "FATAL ERROR: HAL could not be initialized\n"); std::exit(-1); } @@ -42,7 +42,7 @@ class TestEnvironment : public testing::Environment { HAL_ObserveUserProgramStarting(); frc::LiveWindow::SetEnabled(false); - fmt::print("Started coms\n"); + wpi::print("Started coms\n"); int enableCounter = 0; frc::DriverStation::RefreshData(); @@ -50,13 +50,13 @@ class TestEnvironment : public testing::Environment { if (enableCounter > 50) { // Robot did not enable properly after 5 seconds. // Force exit - fmt::print(stderr, " Failed to enable. Aborting\n"); + wpi::print(stderr, " Failed to enable. Aborting\n"); std::terminate(); } std::this_thread::sleep_for(100ms); - fmt::print("Waiting for enable: {}\n", enableCounter++); + wpi::print("Waiting for enable: {}\n", enableCounter++); frc::DriverStation::RefreshData(); } } diff --git a/wpilibcIntegrationTests/src/main/native/cpp/mockds/MockDS.cpp b/wpilibcIntegrationTests/src/main/native/cpp/mockds/MockDS.cpp index 2e53a9ab5e0..317e4db8186 100644 --- a/wpilibcIntegrationTests/src/main/native/cpp/mockds/MockDS.cpp +++ b/wpilibcIntegrationTests/src/main/native/cpp/mockds/MockDS.cpp @@ -8,16 +8,16 @@ #include -#include #include #include #include +#include #include static void LoggerFunc(unsigned int level, const char* file, unsigned int line, const char* msg) { if (level == 20) { - fmt::print(stderr, "DS: {}\n", msg); + wpi::print(stderr, "DS: {}\n", msg); return; } @@ -31,7 +31,7 @@ static void LoggerFunc(unsigned int level, const char* file, unsigned int line, } else { return; } - fmt::print(stderr, "DS: {}: {} ({}:{})\n", levelmsg, msg, file, line); + wpi::print(stderr, "DS: {}: {} ({}:{})\n", levelmsg, msg, file, line); } static void generateEnabledDsPacket(wpi::SmallVectorImpl& data, diff --git a/wpilibj/CMakeLists.txt b/wpilibj/CMakeLists.txt index c2cea44d9a7..624e87a39a4 100644 --- a/wpilibj/CMakeLists.txt +++ b/wpilibj/CMakeLists.txt @@ -1,15 +1,20 @@ -project (wpilibj) +project(wpilibj) # Java bindings -if (WITH_JAVA) - find_package( OpenCV REQUIRED ) +if(WITH_JAVA) + find_package(OpenCV REQUIRED) find_package(Java REQUIRED) include(UseJava) set(CMAKE_JAVA_COMPILE_FLAGS "-encoding" "UTF8" "-Xlint:unchecked") set(OPENCV_JAVA_INSTALL_DIR ${OpenCV_INSTALL_PATH}/share/OpenCV/java/) - find_file(OPENCV_JAR_FILE NAMES opencv-${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.jar PATHS ${OPENCV_JAVA_INSTALL_DIR} ${OpenCV_INSTALL_PATH}/bin NO_DEFAULT_PATH) + find_file( + OPENCV_JAR_FILE + NAMES opencv-${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.jar + PATHS ${OPENCV_JAVA_INSTALL_DIR} ${OpenCV_INSTALL_PATH}/bin + NO_DEFAULT_PATH + ) configure_file(src/generate/WPILibVersion.java.in WPILibVersion.java) @@ -17,23 +22,31 @@ if (WITH_JAVA) file(GLOB EJML_JARS "${WPILIB_BINARY_DIR}/wpimath/thirdparty/ejml/*.jar") file(GLOB JACKSON_JARS "${WPILIB_BINARY_DIR}/wpiutil/thirdparty/jackson/*.jar") - add_jar(wpilibj_jar ${JAVA_SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/WPILibVersion.java INCLUDE_JARS hal_jar ntcore_jar ${EJML_JARS} ${JACKSON_JARS} ${OPENCV_JAR_FILE} cscore_jar cameraserver_jar wpimath_jar wpiunits_jar wpiutil_jar OUTPUT_NAME wpilibj) + add_jar( + wpilibj_jar + ${JAVA_SOURCES} + ${CMAKE_CURRENT_BINARY_DIR}/WPILibVersion.java + INCLUDE_JARS + hal_jar + ntcore_jar + ${EJML_JARS} + ${JACKSON_JARS} + ${OPENCV_JAR_FILE} + cscore_jar + cameraserver_jar + wpimath_jar + wpiunits_jar + wpiutil_jar + OUTPUT_NAME wpilibj + ) - get_property(WPILIBJ_JAR_FILE TARGET wpilibj_jar PROPERTY JAR_FILE) - install(FILES ${WPILIBJ_JAR_FILE} DESTINATION "${java_lib_dest}") + install_jar(wpilibj_jar DESTINATION ${java_lib_dest}) + install_jar_exports(TARGETS wpilibj_jar FILE wpilibj.cmake DESTINATION share/wpilibj) - set_property(TARGET wpilibj_jar PROPERTY FOLDER "java") - - if (WITH_FLAT_INSTALL) - set (wpilibj_config_dir ${wpilib_dest}) - else() - set (wpilibj_config_dir share/wpilibj) - endif() - - install(FILES wpilibj-config.cmake DESTINATION ${wpilibj_config_dir}) + install(FILES wpilibj-config.cmake DESTINATION share/wpilibj) endif() -if (WITH_JAVA_SOURCE) +if(WITH_JAVA_SOURCE) find_package(Java REQUIRED) include(UseJava) file(GLOB WPILIBJ_SOURCES src/main/java/edu/wpi/first/wpilibj/*.java) @@ -45,21 +58,32 @@ if (WITH_JAVA_SOURCE) file(GLOB WPILIBJ_SHUFFLEBOARD_SOURCES src/main/java/edu/wpi/first/wpilibj/shuffleboard*.java) file(GLOB WPILIBJ_SIMULATION_SOURCES src/main/java/edu/wpi/first/wpilibj/simulation*.java) file(GLOB WPILIBJ_SMARTDASHBOARD_SOURCES src/main/java/edu/wpi/first/wpilibj/*.java) - file(GLOB WPILIBJ_UTIL_SOURCES src/main/java/edu/wpi/first/wpilibj/*.java ${CMAKE_CURRENT_BINARY_DIR}/WPILibVersion.java) - add_jar(wpilibj_src_jar - RESOURCES NAMESPACE "edu/wpi/first/wpilibj" ${WPILIBJ_SOURCES} - NAMESPACE "edu/wpi/first/wpilibj/counter" ${WPILIBJ_COUNTER_SOURCES} - NAMESPACE "edu/wpi/first/wpilibj/drive" ${WPILIBJ_DRIVE_SOURCES} - NAMESPACE "edu/wpi/first/wpilibj/event" ${WPILIBJ_EVENT_SOURCES} - NAMESPACE "edu/wpi/first/wpilibj/interfaces" ${WPILIBJ_INTERFACES_SOURCES} - NAMESPACE "edu/wpi/first/wpilibj/internal" src/main/java/edu/wpi/first/wpilibj/internal/DriverStationModeThread.java - NAMESPACE "edu/wpi/first/wpilibj/livewindow" src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java - NAMESPACE "edu/wpi/first/wpilibj/motorcontrol" ${WPILIBJ_MOTORCONTROL_SOURCES} - NAMESPACE "edu/wpi/first/wpilibj/shuffleboard" ${WPILIBJ_SHUFFLEBOARD_SOURCES} - NAMESPACE "edu/wpi/first/wpilibj/simulation" ${WPILIBJ_SIMULATION_SOURCES} - NAMESPACE "edu/wpi/first/wpilibj/smartdashboard" ${WPILIBJ_SMARTDASHBOARD_SOURCES} - NAMESPACE "edu/wpi/first/wpilibj/util" ${WPILIBJ_UTIL_SOURCES} - OUTPUT_NAME wpilibj-sources) + file( + GLOB WPILIBJ_UTIL_SOURCES + src/main/java/edu/wpi/first/wpilibj/*.java + ${CMAKE_CURRENT_BINARY_DIR}/WPILibVersion.java + ) + add_jar( + wpilibj_src_jar + RESOURCES + NAMESPACE "edu/wpi/first/wpilibj" ${WPILIBJ_SOURCES} + NAMESPACE "edu/wpi/first/wpilibj/counter" ${WPILIBJ_COUNTER_SOURCES} + NAMESPACE "edu/wpi/first/wpilibj/drive" ${WPILIBJ_DRIVE_SOURCES} + NAMESPACE "edu/wpi/first/wpilibj/event" ${WPILIBJ_EVENT_SOURCES} + NAMESPACE "edu/wpi/first/wpilibj/interfaces" ${WPILIBJ_INTERFACES_SOURCES} + NAMESPACE + "edu/wpi/first/wpilibj/internal" + src/main/java/edu/wpi/first/wpilibj/internal/DriverStationModeThread.java + NAMESPACE + "edu/wpi/first/wpilibj/livewindow" + src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java + NAMESPACE "edu/wpi/first/wpilibj/motorcontrol" ${WPILIBJ_MOTORCONTROL_SOURCES} + NAMESPACE "edu/wpi/first/wpilibj/shuffleboard" ${WPILIBJ_SHUFFLEBOARD_SOURCES} + NAMESPACE "edu/wpi/first/wpilibj/simulation" ${WPILIBJ_SIMULATION_SOURCES} + NAMESPACE "edu/wpi/first/wpilibj/smartdashboard" ${WPILIBJ_SMARTDASHBOARD_SOURCES} + NAMESPACE "edu/wpi/first/wpilibj/util" ${WPILIBJ_UTIL_SOURCES} + OUTPUT_NAME wpilibj-sources + ) get_property(WPILIBJ_SRC_JAR_FILE TARGET wpilibj_src_jar PROPERTY JAR_FILE) install(FILES ${WPILIBJ_SRC_JAR_FILE} DESTINATION "${java_lib_dest}") diff --git a/wpilibj/src/generate/WPILibVersion.java.in b/wpilibj/src/generate/WPILibVersion.java.in index cc5e6b084d3..f38d1b0b721 100644 --- a/wpilibj/src/generate/WPILibVersion.java.in +++ b/wpilibj/src/generate/WPILibVersion.java.in @@ -1,10 +1,13 @@ package edu.wpi.first.wpilibj.util; -/* +/** * Autogenerated file! Do not manually edit this file. This version is regenerated * any time the publish task is run, or when this file is deleted. */ - public final class WPILibVersion { + /** The version number. */ public static final String Version = "${wpilib_version}"; + + /** Utility class. */ + private WPILibVersion() {} } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16448_IMU.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16448_IMU.java index 2eddf64ee6e..6117b8816a7 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16448_IMU.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16448_IMU.java @@ -94,30 +94,47 @@ public class ADIS16448_IMU implements AutoCloseable, Sendable { private static final int PROD_ID = 0x56; // Product identifier private static final int SERIAL_NUM = 0x58; // Lot-specific serial number + /** ADIS16448 calibration times. */ public enum CalibrationTime { + /** 32 ms calibration time */ _32ms(0), + /** 64 ms calibration time */ _64ms(1), + /** 128 ms calibration time */ _128ms(2), + /** 256 ms calibration time */ _256ms(3), + /** 512 ms calibration time */ _512ms(4), + /** 1 s calibration time */ _1s(5), + /** 2 s calibration time */ _2s(6), + /** 4 s calibration time */ _4s(7), + /** 8 s calibration time */ _8s(8), + /** 16 s calibration time */ _16s(9), + /** 32 s calibration time */ _32s(10), + /** 64 s calibration time */ _64s(11); - private int value; + private final int value; - private CalibrationTime(int value) { + CalibrationTime(int value) { this.value = value; } } + /** IMU axes. */ public enum IMUAxis { + /** The IMU's X axis. */ kX, + /** The IMU's Y axis. */ kY, + /** The IMU's Z axis. */ kZ } @@ -130,9 +147,9 @@ public enum IMUAxis { private IMUAxis m_yaw_axis; /* Offset data storage */ - private double m_offset_data_gyro_rate_x[]; - private double m_offset_data_gyro_rate_y[]; - private double m_offset_data_gyro_rate_z[]; + private double[] m_offset_data_gyro_rate_x; + private double[] m_offset_data_gyro_rate_y; + private double[] m_offset_data_gyro_rate_z; /* Instant raw output variables */ private double m_gyro_rate_x = 0.0; @@ -175,6 +192,7 @@ public enum IMUAxis { private volatile boolean m_thread_idle = false; private boolean m_auto_configured = false; private boolean m_start_up_mode = true; + private boolean m_needs_flash = false; /* Resources */ private SPI m_spi; @@ -199,7 +217,7 @@ public enum IMUAxis { private SimDouble m_simAccelZ; /* CRC-16 Look-Up Table */ - int adiscrc[] = + int[] adiscrc = new int[] { 0x0000, 0x17CE, 0x0FDF, 0x1811, 0x1FBE, 0x0870, 0x1061, 0x07AF, 0x1F3F, 0x08F1, 0x10E0, 0x072E, 0x0081, 0x174F, 0x0F5E, 0x1890, @@ -248,15 +266,19 @@ public void run() { } } + /** Creates a new ADIS16448_IMU object. */ public ADIS16448_IMU() { this(IMUAxis.kZ, SPI.Port.kMXP, CalibrationTime._512ms); } /** + * Creates a new ADIS16448_IMU object. + * * @param yaw_axis The axis that measures the yaw * @param port The SPI Port the gyro is plugged into * @param cal_time Calibration time */ + @SuppressWarnings("this-escape") public ADIS16448_IMU(final IMUAxis yaw_axis, SPI.Port port, CalibrationTime cal_time) { m_yaw_axis = yaw_axis; m_spi_port = port; @@ -291,24 +313,77 @@ public ADIS16448_IMU(final IMUAxis yaw_axis, SPI.Port port, CalibrationTime cal_ return; } - // Set IMU internal decimation to 819.2 SPS - writeRegister(SMPL_PRD, 0x0001); - // Enable Data Ready (LOW = Good Data) on DIO1 (PWM0 on MXP) - writeRegister(MSC_CTRL, 0x0016); - // Disable IMU internal Bartlett filter - writeRegister(SENS_AVG, 0x0400); + // Set IMU internal decimation to 1 (ODR = 819.2 SPS / (1 + 1) = 409.6Hz), BW = 204.8Hz + if (readRegister(SMPL_PRD) != 0x0001) { + writeRegister(SMPL_PRD, 0x0001); + m_needs_flash = true; + DriverStation.reportWarning( + "ADIS16448: SMPL_PRD register configuration inconsistent! Scheduling flash update.", + false); + } + + // Set data ready polarity (LOW = Good Data) on DIO1 (PWM0 on MXP) + if (readRegister(MSC_CTRL) != 0x0016) { + writeRegister(MSC_CTRL, 0x0016); + m_needs_flash = true; + DriverStation.reportWarning( + "ADIS16448: MSC_CTRL register configuration inconsistent! Scheduling flash update.", + false); + } + + // Disable IMU internal Bartlett filter (204Hz BW is sufficient) and set IMU scale factor + if (readRegister(SENS_AVG) != 0x0400) { + writeRegister(SENS_AVG, 0x0400); + m_needs_flash = true; + DriverStation.reportWarning( + "ADIS16448: SENS_AVG register configuration inconsistent! Scheduling flash update.", + false); + } // Clear offset registers - writeRegister(XGYRO_OFF, 0x0000); - writeRegister(YGYRO_OFF, 0x0000); - writeRegister(ZGYRO_OFF, 0x0000); + if (readRegister(XGYRO_OFF) != 0x0000) { + writeRegister(XGYRO_OFF, 0x0000); + m_needs_flash = true; + DriverStation.reportWarning( + "ADIS16448: XGYRO_OFF register configuration inconsistent! Scheduling flash update.", + false); + } + + if (readRegister(YGYRO_OFF) != 0x0000) { + writeRegister(YGYRO_OFF, 0x0000); + m_needs_flash = true; + DriverStation.reportWarning( + "ADIS16448: YGYRO_OFF register configuration inconsistent! Scheduling flash update.", + false); + } + + if (readRegister(ZGYRO_OFF) != 0x0000) { + writeRegister(ZGYRO_OFF, 0x0000); + m_needs_flash = true; + DriverStation.reportWarning( + "ADIS16448: ZGYRO_OFF register configuration inconsistent! Scheduling flash update.", + false); + } + + // If any registers on the IMU don't match the config, trigger a flash update + if (m_needs_flash) { + DriverStation.reportWarning( + "ADIS16448: Register configuration changed! Starting IMU flash update.", false); + writeRegister(GLOB_CMD, 0x0008); + // Wait long enough for the flash update to finish (75ms minimum as per the datasheet) + Timer.delay(0.5); + DriverStation.reportWarning("ADIS16448: Flash update finished!", false); + m_needs_flash = false; + } else { + DriverStation.reportWarning( + "ADIS16448: and RAM configuration consistent. No flash update required!", false); + } // Configure standard SPI if (!switchToAutoSPI()) { return; } // Notify DS that IMU calibration delay is active - DriverStation.reportWarning( - "ADIS16448 IMU Detected. Starting initial calibration delay.", false); + DriverStation.reportWarning("ADIS16448: Starting initial calibration delay.", false); // Wait for whatever time the user set as the start-up delay try { Thread.sleep((long) (m_calibration_time.value * 1.2 * 1000)); @@ -331,6 +406,11 @@ public ADIS16448_IMU(final IMUAxis yaw_axis, SPI.Port port, CalibrationTime cal_ m_connected = true; } + /** + * Checks the connection status of the IMU. + * + * @return True if the IMU is connected, false otherwise. + */ public boolean isConnected() { if (m_simConnected != null) { return m_simConnected.get(); @@ -338,7 +418,6 @@ public boolean isConnected() { return m_connected; } - /** */ private static int toUShort(byte[] buf) { return (((buf[0] & 0xFF) << 8) + ((buf[1] & 0xFF) << 0)); } @@ -347,7 +426,7 @@ private static int toUByte(int... buf) { return (buf[0] & 0xFF); } - public static int toUShort(int... buf) { + private static int toUShort(int... buf) { return (((buf[0] & 0xFF) << 8) + (buf[1] & 0xFF)); } @@ -358,7 +437,7 @@ private static long toULong(int sint) { /** */ private static int toShort(int... buf) { - return (short) (((buf[0] & 0xFF) << 8) + ((buf[1] & 0xFF) << 0)); + return (short) (((buf[0] & 0xFF) << 8) + (buf[1] & 0xFF)); } /** */ @@ -480,8 +559,19 @@ boolean switchToAutoSPI() { return true; } - public int configDecRate(int m_decRate) { - int writeValue = m_decRate; + /** + * Configures the decimation rate of the IMU. + * + * @param decimationRate The new decimation value. + * @return 0 if success, 1 if no change, 2 if error. + */ + public int configDecRate(int decimationRate) { + // Switches the active SPI port to standard SPI mode, writes a new value to + // the DECIMATE register in the IMU, and re-enables auto SPI. + // + // This function enters standard SPI mode, writes a new DECIMATE setting to + // the IMU, adjusts the sample scale factor, and re-enters auto SPI mode. + int writeValue; int readbackValue; if (!switchToStandardSPI()) { DriverStation.reportError("Failed to configure/reconfigure standard SPI.", false); @@ -489,19 +579,19 @@ public int configDecRate(int m_decRate) { } /* Check max */ - if (m_decRate > 9) { + if (decimationRate > 9) { DriverStation.reportError( "Attempted to write an invalid decimation value. Capping at 9", false); - m_decRate = 9; + decimationRate = 9; } - if (m_decRate < 0) { + if (decimationRate < 0) { DriverStation.reportError( "Attempted to write an invalid decimation value. Capping at 0", false); - m_decRate = 0; + decimationRate = 0; } /* Shift decimation setting to correct position and select internal sync */ - writeValue = (m_decRate << 8) | 0x1; + writeValue = (decimationRate << 8) | 0x1; /* Apply to IMU */ writeRegister(SMPL_PRD, writeValue); @@ -527,7 +617,7 @@ public int configDecRate(int m_decRate) { * @param new_cal_time New calibration time * @return 1 if the new calibration time is the same as the current one else 0 */ - public int configCalTime(CalibrationTime new_cal_time) { + public final int configCalTime(CalibrationTime new_cal_time) { if (m_calibration_time == new_cal_time) { return 1; } else { @@ -623,6 +713,12 @@ private void writeRegister(final int reg, final int val) { m_spi.write(buf, 2); } + /** + * Reset the gyro. + * + *

Resets the gyro accumulations to a heading of zero. This can be used if there is significant + * drift in the gyro and it needs to be recalibrated after running. + */ public void reset() { synchronized (this) { m_integ_gyro_angle_x = 0.0; @@ -956,7 +1052,9 @@ private double compFilterProcess(double compAngle, double accelAngle, double ome } /** - * @return Yaw axis angle in degrees (CCW positive) + * Returns the yaw axis angle in degrees (CCW positive). + * + * @return Yaw axis angle in degrees (CCW positive). */ public synchronized double getAngle() { switch (m_yaw_axis) { @@ -972,7 +1070,9 @@ public synchronized double getAngle() { } /** - * @return Yaw axis angular rate in degrees per second (CCW positive) + * Returns the yaw axis angular rate in degrees per second (CCW positive). + * + * @return Yaw axis angular rate in degrees per second (CCW positive). */ public synchronized double getRate() { switch (m_yaw_axis) { @@ -988,14 +1088,18 @@ public synchronized double getRate() { } /** - * @return Yaw Axis + * Returns which axis, kX, kY, or kZ, is set to the yaw axis. + * + * @return IMUAxis Yaw Axis */ public IMUAxis getYawAxis() { return m_yaw_axis; } /** - * @return accumulated gyro angle in the X axis in degrees + * Returns the accumulated gyro angle in the X axis in degrees. + * + * @return The accumulated gyro angle in the X axis in degrees. */ public synchronized double getGyroAngleX() { if (m_simGyroAngleX != null) { @@ -1005,7 +1109,9 @@ public synchronized double getGyroAngleX() { } /** - * @return accumulated gyro angle in the Y axis in degrees + * Returns the accumulated gyro angle in the Y axis in degrees. + * + * @return The accumulated gyro angle in the Y axis in degrees. */ public synchronized double getGyroAngleY() { if (m_simGyroAngleY != null) { @@ -1015,7 +1121,9 @@ public synchronized double getGyroAngleY() { } /** - * @return accumulated gyro angle in the Z axis in degrees + * Returns the accumulated gyro angle in the Z axis in degrees. + * + * @return The accumulated gyro angle in the Z axis in degrees. */ public synchronized double getGyroAngleZ() { if (m_simGyroAngleZ != null) { @@ -1025,7 +1133,9 @@ public synchronized double getGyroAngleZ() { } /** - * @return gyro angular rate in the X axis in degrees per second + * Returns the gyro angular rate in the X axis in degrees per second. + * + * @return The gyro angular rate in the X axis in degrees per second. */ public synchronized double getGyroRateX() { if (m_simGyroRateX != null) { @@ -1035,7 +1145,9 @@ public synchronized double getGyroRateX() { } /** - * @return gyro angular rate in the Y axis in degrees per second + * Returns the gyro angular rate in the Y axis in degrees per second. + * + * @return The gyro angular rate in the Y axis in degrees per second. */ public synchronized double getGyroRateY() { if (m_simGyroRateY != null) { @@ -1045,7 +1157,9 @@ public synchronized double getGyroRateY() { } /** - * @return gyro angular rate in the Z axis in degrees per second + * Returns the gyro angular rate in the Z axis in degrees per second. + * + * @return The gyro angular rate in the Z axis in degrees per second. */ public synchronized double getGyroRateZ() { if (m_simGyroRateZ != null) { @@ -1055,7 +1169,9 @@ public synchronized double getGyroRateZ() { } /** - * @return urrent acceleration in the X axis in meters per second squared + * Returns the acceleration in the X axis in meters per second squared. + * + * @return The acceleration in the X axis in meters per second squared. */ public synchronized double getAccelX() { if (m_simAccelX != null) { @@ -1065,7 +1181,9 @@ public synchronized double getAccelX() { } /** - * @return current acceleration in the Y axis in meters per second squared + * Returns the acceleration in the Y axis in meters per second squared. + * + * @return The acceleration in the Y axis in meters per second squared. */ public synchronized double getAccelY() { if (m_simAccelY != null) { @@ -1075,7 +1193,9 @@ public synchronized double getAccelY() { } /** - * @return current acceleration in the Z axis in meters per second squared + * Returns the acceleration in the Z axis in meters per second squared. + * + * @return The acceleration in the Z axis in meters per second squared. */ public synchronized double getAccelZ() { if (m_simAccelZ != null) { @@ -1085,7 +1205,9 @@ public synchronized double getAccelZ() { } /** - * @return Magnetic field strength in the X axis in Tesla + * Returns the magnetic field strength in the X axis in Tesla. + * + * @return The magnetic field strength in the X axis in Tesla. */ public synchronized double getMagneticFieldX() { // mG to T @@ -1093,7 +1215,9 @@ public synchronized double getMagneticFieldX() { } /** - * @return Magnetic field strength in the Y axis in Tesla + * Returns the magnetic field strength in the Y axis in Tesla. + * + * @return The magnetic field strength in the Y axis in Tesla. */ public synchronized double getMagneticFieldY() { // mG to T @@ -1101,7 +1225,9 @@ public synchronized double getMagneticFieldY() { } /** - * @return Magnetic field strength in the Z axis in Tesla + * Returns the magnetic field strength in the Z axis in Tesla. + * + * @return The magnetic field strength in the Z axis in Tesla. */ public synchronized double getMagneticFieldZ() { // mG to T @@ -1109,35 +1235,47 @@ public synchronized double getMagneticFieldZ() { } /** - * @return X-axis complementary angle in degrees + * Returns the complementary angle around the X axis computed from accelerometer and gyro rate + * measurements. + * + * @return The X-axis complementary angle in degrees. */ public synchronized double getXComplementaryAngle() { return m_compAngleX; } /** - * @return Y-axis complementary angle in degrees + * Returns the complementary angle around the Y axis computed from accelerometer and gyro rate + * measurements. + * + * @return The Y-axis complementary angle in degrees. */ public synchronized double getYComplementaryAngle() { return m_compAngleY; } /** - * @return X-axis filtered acceleration angle in degrees + * Returns the X-axis filtered acceleration angle in degrees. + * + * @return The X-axis filtered acceleration angle in degrees. */ public synchronized double getXFilteredAccelAngle() { return m_accelAngleX; } /** - * @return Y-axis filtered acceleration angle in degrees + * Returns the Y-axis filtered acceleration angle in degrees. + * + * @return The Y-axis filtered acceleration angle in degrees. */ public synchronized double getYFilteredAccelAngle() { return m_accelAngleY; } /** - * @return Barometric Pressure in PSI + * Returns the barometric pressure in PSI. + * + * @return The barometric pressure in PSI. */ public synchronized double getBarometricPressure() { // mbar to PSI conversion @@ -1145,7 +1283,9 @@ public synchronized double getBarometricPressure() { } /** - * @return Temperature in degrees Celsius + * Returns the temperature in degrees Celsius. + * + * @return The temperature in degrees Celsius. */ public synchronized double getTemperature() { return m_temp; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16470_IMU.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16470_IMU.java index 2fad3f34dac..c51d209cea7 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16470_IMU.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADIS16470_IMU.java @@ -122,45 +122,21 @@ public class ADIS16470_IMU implements AutoCloseable, Sendable { private static final int FLSHCNT_LOW = 0x7C; // Flash update count, lower word private static final int FLSHCNT_HIGH = 0x7E; // Flash update count, upper word - private static final byte[] m_autospi_x_packet = { + // Weight between the previous and current gyro angles represents 1 second for the timestamp, + // this is the point at which we ignore the previous angle because it is too old to be of use. + // The IMU timestamp conversion is 1 = 49.02us, the value 1_000_000 is the number of microseconds + // we average over. + private static final double AVERAGE_RATE_SCALING_FACTOR = 49.02 / 1_000_000; + + private static final byte[] m_autospi_allAngle_packet = { X_DELTANG_OUT, FLASH_CNT, X_DELTANG_LOW, FLASH_CNT, - X_GYRO_OUT, - FLASH_CNT, - Y_GYRO_OUT, - FLASH_CNT, - Z_GYRO_OUT, - FLASH_CNT, - X_ACCL_OUT, - FLASH_CNT, - Y_ACCL_OUT, - FLASH_CNT, - Z_ACCL_OUT, - FLASH_CNT - }; - - private static final byte[] m_autospi_y_packet = { Y_DELTANG_OUT, FLASH_CNT, Y_DELTANG_LOW, FLASH_CNT, - X_GYRO_OUT, - FLASH_CNT, - Y_GYRO_OUT, - FLASH_CNT, - Z_GYRO_OUT, - FLASH_CNT, - X_ACCL_OUT, - FLASH_CNT, - Y_ACCL_OUT, - FLASH_CNT, - Z_ACCL_OUT, - FLASH_CNT - }; - - private static final byte[] m_autospi_z_packet = { Z_DELTANG_OUT, FLASH_CNT, Z_DELTANG_LOW, @@ -179,31 +155,59 @@ public class ADIS16470_IMU implements AutoCloseable, Sendable { FLASH_CNT }; + /** ADIS16470 calibration times. */ public enum CalibrationTime { + /** 32 ms calibration time */ _32ms(0), + /** 64 ms calibration time */ _64ms(1), + /** 128 ms calibration time */ _128ms(2), + /** 256 ms calibration time */ _256ms(3), + /** 512 ms calibration time */ _512ms(4), + /** 1 s calibration time */ _1s(5), + /** 2 s calibration time */ _2s(6), + /** 4 s calibration time */ _4s(7), + /** 8 s calibration time */ _8s(8), + /** 16 s calibration time */ _16s(9), + /** 32 s calibration time */ _32s(10), + /** 64 s calibration time */ _64s(11); - private int value; + private final int value; - private CalibrationTime(int value) { + CalibrationTime(int value) { this.value = value; } } + /** + * IMU axes. + * + *

kX, kY, and kZ refer to the IMU's X, Y, and Z axes respectively. kYaw, kPitch, and kRoll are + * configured by the user to refer to an X, Y, or Z axis. + */ public enum IMUAxis { + /** The IMU's X axis */ kX, + /** The IMU's Y axis */ kY, - kZ + /** The IMU's Z axis */ + kZ, + /** The user-configured yaw axis */ + kYaw, + /** The user-configured pitch axis */ + kPitch, + /** The user-configured roll axis */ + kRoll, } // Static Constants @@ -212,19 +216,26 @@ public enum IMUAxis { private static final double deg_to_rad = 0.0174532; private static final double grav = 9.81; - // User-specified yaw axis + // User-specified axes private IMUAxis m_yaw_axis; + private IMUAxis m_pitch_axis; + private IMUAxis m_roll_axis; // Instant raw outputs private double m_gyro_rate_x = 0.0; private double m_gyro_rate_y = 0.0; private double m_gyro_rate_z = 0.0; + private double m_average_gyro_rate_x = 0.0; + private double m_average_gyro_rate_y = 0.0; + private double m_average_gyro_rate_z = 0.0; private double m_accel_x = 0.0; private double m_accel_y = 0.0; private double m_accel_z = 0.0; // Integrated gyro angle - private double m_integ_angle = 0.0; + private double m_integ_angle_x = 0.0; + private double m_integ_angle_y = 0.0; + private double m_integ_angle_z = 0.0; // Complementary filter variables private double m_dt = 0.0; @@ -242,6 +253,7 @@ public enum IMUAxis { private volatile boolean m_thread_idle = false; private boolean m_auto_configured = false; private double m_scaled_sample_rate = 2500.0; + private boolean m_needs_flash = false; // Resources private SPI m_spi; @@ -278,17 +290,74 @@ public void run() { } } + /** + * Creates a new ADIS16740 IMU object. + * + *

The default setup is the onboard SPI port with a calibration time of 1 second. Yaw, pitch, + * and roll are kZ, kX, and kY respectively. + */ public ADIS16470_IMU() { - this(IMUAxis.kZ, SPI.Port.kOnboardCS0, CalibrationTime._4s); + this(IMUAxis.kZ, IMUAxis.kX, IMUAxis.kY, SPI.Port.kOnboardCS0, CalibrationTime._1s); + } + + /** + * Creates a new ADIS16740 IMU object. + * + *

The default setup is the onboard SPI port with a calibration time of 1 second. + * + *

Input axes limited to kX, kY and kZ. Specifying kYaw, kPitch,or kRoll will result in + * an error. + * + * @param yaw_axis The axis that measures the yaw + * @param pitch_axis The axis that measures the pitch + * @param roll_axis The axis that measures the roll + */ + public ADIS16470_IMU(IMUAxis yaw_axis, IMUAxis pitch_axis, IMUAxis roll_axis) { + this(yaw_axis, pitch_axis, roll_axis, SPI.Port.kOnboardCS0, CalibrationTime._1s); } /** + * Creates a new ADIS16740 IMU object. + * + *

Input axes limited to kX, kY and kZ. Specifying kYaw, kPitch,or kRoll will result in + * an error. + * * @param yaw_axis The axis that measures the yaw + * @param pitch_axis The axis that measures the pitch + * @param roll_axis The axis that measures the roll * @param port The SPI Port the gyro is plugged into * @param cal_time Calibration time */ - public ADIS16470_IMU(IMUAxis yaw_axis, SPI.Port port, CalibrationTime cal_time) { + @SuppressWarnings("this-escape") + public ADIS16470_IMU( + IMUAxis yaw_axis, + IMUAxis pitch_axis, + IMUAxis roll_axis, + SPI.Port port, + CalibrationTime cal_time) { + if (yaw_axis == IMUAxis.kYaw + || yaw_axis == IMUAxis.kPitch + || yaw_axis == IMUAxis.kRoll + || pitch_axis == IMUAxis.kYaw + || pitch_axis == IMUAxis.kPitch + || pitch_axis == IMUAxis.kRoll + || roll_axis == IMUAxis.kYaw + || roll_axis == IMUAxis.kPitch + || roll_axis == IMUAxis.kRoll) { + DriverStation.reportError( + "ADIS16470 constructor only allows IMUAxis.kX, IMUAxis.kY or IMUAxis.kZ as arguments.", + false); + DriverStation.reportError( + "Constructing ADIS with default axes. (IMUAxis.kZ is defined as Yaw)", false); + yaw_axis = IMUAxis.kZ; + pitch_axis = IMUAxis.kY; + roll_axis = IMUAxis.kX; + } + m_yaw_axis = yaw_axis; + m_pitch_axis = pitch_axis; + m_roll_axis = roll_axis; + m_calibration_time = cal_time.value; m_spi_port = port; @@ -323,23 +392,52 @@ public ADIS16470_IMU(IMUAxis yaw_axis, SPI.Port port, CalibrationTime cal_time) return; } - // Set IMU internal decimation to 4 (output data rate of 2000 SPS / (4 + 1) = - // 400Hz) - writeRegister(DEC_RATE, 4); + // Set IMU internal decimation to 4 (ODR = 2000 SPS / (4 + 1) = 400Hz), BW = 200Hz + if (readRegister(DEC_RATE) != 0x0004) { + writeRegister(DEC_RATE, 0x0004); + m_needs_flash = true; + DriverStation.reportWarning( + "ADIS16470: DEC_RATE register configuration inconsistent! Scheduling flash update.", + false); + } + + // Set data ready polarity (HIGH = Good Data), Disable gSense Compensation and PoP + if (readRegister(MSC_CTRL) != 0x0001) { + writeRegister(MSC_CTRL, 0x0001); + m_needs_flash = true; + DriverStation.reportWarning( + "ADIS16470: MSC_CTRL register configuration inconsistent! Scheduling flash update.", + false); + } - // Set data ready polarity (HIGH = Good Data), Disable gSense Compensation and - // PoP - writeRegister(MSC_CTRL, 1); + // Disable IMU internal Bartlett filter (200Hz bandwidth is sufficient) + if (readRegister(FILT_CTRL) != 0x0000) { + writeRegister(FILT_CTRL, 0x0000); + m_needs_flash = true; + DriverStation.reportWarning( + "ADIS16470: FILT_CTRL register configuration inconsistent! Scheduling flash update.", + false); + } - // Configure IMU internal Bartlett filter - writeRegister(FILT_CTRL, 0); + // If any registers on the IMU don't match the config, trigger a flash update + if (m_needs_flash) { + DriverStation.reportWarning( + "ADIS16470: Register configuration changed! Starting IMU flash update.", false); + writeRegister(GLOB_CMD, 0x0008); + // Wait long enough for the flash update to finish (72ms minimum as per the datasheet) + Timer.delay(0.3); + DriverStation.reportWarning("ADIS16470: Flash update finished!", false); + m_needs_flash = false; + } else { + DriverStation.reportWarning( + "ADIS16470: Flash and RAM configuration consistent. No flash update required!", false); + } // Configure continuous bias calibration time based on user setting writeRegister(NULL_CNFG, (m_calibration_time | 0x0700)); // Notify DS that IMU calibration delay is active - DriverStation.reportWarning( - "ADIS16470 IMU Detected. Starting initial calibration delay.", false); + DriverStation.reportWarning("ADIS16470: Starting initial calibration delay.", false); // Wait for samples to accumulate internal to the IMU (110% of user-defined // time) @@ -368,6 +466,11 @@ public ADIS16470_IMU(IMUAxis yaw_axis, SPI.Port port, CalibrationTime cal_time) m_connected = true; } + /** + * Checks the connection status of the IMU. + * + * @return True if the IMU is connected, false otherwise. + */ public boolean isConnected() { if (m_simConnected != null) { return m_simConnected.get(); @@ -380,7 +483,7 @@ public boolean isConnected() { * @return */ private static int toUShort(ByteBuffer buf) { - return (buf.getShort(0)) & 0xFFFF; + return buf.getShort(0) & 0xFFFF; } /** @@ -396,7 +499,7 @@ private static long toULong(int sint) { * @return */ private static int toShort(int... buf) { - return (short) (((buf[0] & 0xFF) << 8) + ((buf[1] & 0xFF) << 0)); + return (short) (((buf[0] & 0xFF) << 8) + (buf[1] & 0xFF)); } /** @@ -410,7 +513,7 @@ private static int toInt(int... buf) { /** * Switch to standard SPI mode. * - * @return + * @return True if successful, false otherwise. */ private boolean switchToStandardSPI() { // Check to see whether the acquire thread is active. If so, wait for it to stop @@ -476,7 +579,9 @@ private boolean switchToStandardSPI() { } /** - * @return + * Switch to auto SPI mode. + * + * @return True if successful, false otherwise. */ boolean switchToAutoSPI() { // No SPI port has been set up. Go set one up first. @@ -498,17 +603,7 @@ boolean switchToAutoSPI() { m_auto_configured = true; } // Do we need to change auto SPI settings? - switch (m_yaw_axis) { - case kX: - m_spi.setAutoTransmitData(m_autospi_x_packet, 2); - break; - case kY: - m_spi.setAutoTransmitData(m_autospi_y_packet, 2); - break; - default: - m_spi.setAutoTransmitData(m_autospi_z_packet, 2); - break; - } + m_spi.setAutoTransmitData(m_autospi_allAngle_packet, 2); // Configure auto stall time m_spi.configureAutoStall(5, 1000, 1); // Kick off auto SPI (Note: Device configuration impossible after auto SPI is @@ -560,18 +655,28 @@ public int configCalTime(CalibrationTime new_cal_time) { return 0; } - public int configDecRate(int reg) { - int m_reg = reg; + /** + * Configures the decimation rate of the IMU. + * + * @param decimationRate The new decimation value. + * @return 0 if success, 1 if no change, 2 if error. + */ + public int configDecRate(int decimationRate) { + // Switches the active SPI port to standard SPI mode, writes a new value to + // the DECIMATE register in the IMU, and re-enables auto SPI. + // + // This function enters standard SPI mode, writes a new DECIMATE setting to + // the IMU, adjusts the sample scale factor, and re-enters auto SPI mode. if (!switchToStandardSPI()) { DriverStation.reportError("Failed to configure/reconfigure standard SPI.", false); return 2; } - if (m_reg > 1999) { - DriverStation.reportError("Attempted to write an invalid deimation value.", false); - m_reg = 1999; + if (decimationRate > 1999) { + DriverStation.reportError("Attempted to write an invalid decimation value.", false); + decimationRate = 1999; } - m_scaled_sample_rate = (((m_reg + 1.0) / 2000.0) * 1000000.0); - writeRegister(DEC_RATE, m_reg); + m_scaled_sample_rate = (((decimationRate + 1.0) / 2000.0) * 1000000.0); + writeRegister(DEC_RATE, decimationRate); System.out.println("Decimation register: " + readRegister(DEC_RATE)); if (!switchToAutoSPI()) { DriverStation.reportError("Failed to configure/reconfigure auto SPI.", false); @@ -593,29 +698,6 @@ public void calibrate() { if (!switchToAutoSPI()) { DriverStation.reportError("Failed to configure/reconfigure auto SPI.", false); } - ; - } - - /** - * Sets the yaw axis - * - * @param yaw_axis The new yaw axis to use - * @return 1 if the new yaw axis is the same as the current one, 2 if the switch to Standard SPI - * failed, else 0. - */ - public int setYawAxis(IMUAxis yaw_axis) { - if (m_yaw_axis == yaw_axis) { - return 1; - } - if (!switchToStandardSPI()) { - DriverStation.reportError("Failed to configure/reconfigure standard SPI.", false); - return 2; - } - m_yaw_axis = yaw_axis; - if (!switchToAutoSPI()) { - DriverStation.reportError("Failed to configure/reconfigure auto SPI.", false); - } - return 0; } /** @@ -641,7 +723,7 @@ private int readRegister(int reg) { private void writeRegister(int reg, int val) { ByteBuffer buf = ByteBuffer.allocateDirect(2); // low byte - buf.put(0, (byte) ((0x80 | reg))); + buf.put(0, (byte) (0x80 | reg)); buf.put(1, (byte) (val & 0xff)); m_spi.write(buf, 2); // high byte @@ -650,12 +732,6 @@ private void writeRegister(int reg, int val) { m_spi.write(buf, 2); } - public void reset() { - synchronized (this) { - m_integ_angle = 0.0; - } - } - /** Delete (free) the spi port used for the IMU. */ @Override public void close() { @@ -691,7 +767,7 @@ public void close() { /** */ private void acquire() { // Set data packet length - final int dataset_len = 19; // 18 data points + timestamp + final int dataset_len = 27; // 26 data points + timestamp final int BUFFER_SIZE = 4000; // Set up buffers and variables @@ -700,7 +776,9 @@ private void acquire() { int data_remainder = 0; int data_to_read = 0; double previous_timestamp = 0.0; - double delta_angle = 0.0; + double delta_angle_x = 0.0; + double delta_angle_y = 0.0; + double delta_angle_z = 0.0; double gyro_rate_x = 0.0; double gyro_rate_y = 0.0; double gyro_rate_z = 0.0; @@ -730,8 +808,8 @@ private void acquire() { data_count = m_spi.readAutoReceivedData( - buffer, 0, 0); // Read number of bytes currently stored in the - // buffer + buffer, 0, 0); // Read number of bytes currently stored in the buffer + data_remainder = data_count % dataset_len; // Check if frame is incomplete. Add 1 because of timestamp data_to_read = data_count - data_remainder; // Remove incomplete data from read count @@ -772,18 +850,27 @@ private void acquire() { */ /* - * Get delta angle value for selected yaw axis and scale by the elapsed time + * Get delta angle value for all 3 axes and scale by the elapsed time * (based on timestamp) */ - delta_angle = + delta_angle_x = (toInt(buffer[i + 3], buffer[i + 4], buffer[i + 5], buffer[i + 6]) * delta_angle_sf) / (m_scaled_sample_rate / (buffer[i] - previous_timestamp)); - gyro_rate_x = (toShort(buffer[i + 7], buffer[i + 8]) / 10.0); - gyro_rate_y = (toShort(buffer[i + 9], buffer[i + 10]) / 10.0); - gyro_rate_z = (toShort(buffer[i + 11], buffer[i + 12]) / 10.0); - accel_x = (toShort(buffer[i + 13], buffer[i + 14]) / 800.0); - accel_y = (toShort(buffer[i + 15], buffer[i + 16]) / 800.0); - accel_z = (toShort(buffer[i + 17], buffer[i + 18]) / 800.0); + delta_angle_y = + (toInt(buffer[i + 7], buffer[i + 8], buffer[i + 9], buffer[i + 10]) * delta_angle_sf) + / (m_scaled_sample_rate / (buffer[i] - previous_timestamp)); + delta_angle_z = + (toInt(buffer[i + 11], buffer[i + 12], buffer[i + 13], buffer[i + 14]) + * delta_angle_sf) + / (m_scaled_sample_rate / (buffer[i] - previous_timestamp)); + + gyro_rate_x = (toShort(buffer[i + 15], buffer[i + 16]) / 10.0); + gyro_rate_y = (toShort(buffer[i + 17], buffer[i + 18]) / 10.0); + gyro_rate_z = (toShort(buffer[i + 19], buffer[i + 20]) / 10.0); + + accel_x = (toShort(buffer[i + 21], buffer[i + 22]) / 800.0); + accel_y = (toShort(buffer[i + 23], buffer[i + 24]) / 800.0); + accel_z = (toShort(buffer[i + 25], buffer[i + 26]) / 800.0); // Convert scaled sensor data to SI units (for tilt calculations) // TODO: Should the unit outputs be selectable? @@ -809,6 +896,10 @@ private void acquire() { accel_y_si, Math.sqrt((accel_x_si * accel_x_si) + (accel_z_si * accel_z_si))); compAngleX = accelAngleX; compAngleY = accelAngleY; + + m_average_gyro_rate_x = 0.0; + m_average_gyro_rate_y = 0.0; + m_average_gyro_rate_z = 0.0; } else { // Run inclinometer calculations accelAngleX = @@ -830,9 +921,13 @@ private void acquire() { * Don't accumulate first run. previous_timestamp will be "very" old and the * integration will end up way off */ - m_integ_angle = 0.0; + m_integ_angle_x = 0.0; + m_integ_angle_y = 0.0; + m_integ_angle_z = 0.0; } else { - m_integ_angle += delta_angle; + m_integ_angle_x += delta_angle_x; + m_integ_angle_y += delta_angle_y; + m_integ_angle_z += delta_angle_z; } m_gyro_rate_x = gyro_rate_x; m_gyro_rate_y = gyro_rate_y; @@ -844,16 +939,28 @@ private void acquire() { m_compAngleY = compAngleY * rad_to_deg; m_accelAngleX = accelAngleX * rad_to_deg; m_accelAngleY = accelAngleY * rad_to_deg; + m_average_gyro_rate_x += gyro_rate_x; + m_average_gyro_rate_y += gyro_rate_y; + m_average_gyro_rate_z += gyro_rate_z; } m_first_run = false; } + + // The inverse of data to read divided by dataset length, his is the number of iterations + // of the for loop inverted (so multiplication can be used instead of division) + double invTotalIterations = (double) dataset_len / data_to_read; + m_average_gyro_rate_x *= invTotalIterations; + m_average_gyro_rate_y *= invTotalIterations; + m_average_gyro_rate_z *= invTotalIterations; } else { m_thread_idle = true; data_count = 0; data_remainder = 0; data_to_read = 0; previous_timestamp = 0.0; - delta_angle = 0.0; + delta_angle_x = 0.0; + delta_angle_y = 0.0; + delta_angle_z = 0.0; gyro_rate_x = 0.0; gyro_rate_y = 0.0; gyro_rate_z = 0.0; @@ -933,7 +1040,136 @@ private double compFilterProcess(double compAngle, double accelAngle, double ome } /** - * @return Yaw axis angle in degrees (CCW positive) + * Reset the gyro. + * + *

Resets the gyro accumulations to a heading of zero. This can be used if there is significant + * drift in the gyro and it needs to be recalibrated after running. + */ + public void reset() { + synchronized (this) { + m_integ_angle_x = 0.0; + m_integ_angle_y = 0.0; + m_integ_angle_z = 0.0; + } + } + + /** + * Allow the designated gyro angle to be set to a given value. This may happen with unread values + * in the buffer, it is suggested that the IMU is not moving when this method is run. + * + * @param axis IMUAxis that will be changed + * @param angle A double in degrees (CCW positive) + */ + public void setGyroAngle(IMUAxis axis, double angle) { + switch (axis) { + case kYaw: + axis = m_yaw_axis; + break; + case kPitch: + axis = m_pitch_axis; + break; + case kRoll: + axis = m_roll_axis; + break; + default: + } + + switch (axis) { + case kX: + this.setGyroAngleX(angle); + break; + case kY: + this.setGyroAngleY(angle); + break; + case kZ: + this.setGyroAngleZ(angle); + break; + default: + } + } + + /** + * Allow the gyro angle X to be set to a given value. This may happen with unread values in the + * buffer, it is suggested that the IMU is not moving when this method is run. + * + * @param angle A double in degrees (CCW positive) + */ + public void setGyroAngleX(double angle) { + synchronized (this) { + m_integ_angle_x = angle; + } + } + + /** + * Allow the gyro angle Y to be set to a given value. This may happen with unread values in the + * buffer, it is suggested that the IMU is not moving when this method is run. + * + * @param angle A double in degrees (CCW positive) + */ + public void setGyroAngleY(double angle) { + synchronized (this) { + m_integ_angle_y = angle; + } + } + + /** + * Allow the gyro angle Z to be set to a given value. This may happen with unread values in the + * buffer, it is suggested that the IMU is not moving when this method is run. + * + * @param angle A double in degrees (CCW positive) + */ + public void setGyroAngleZ(double angle) { + synchronized (this) { + m_integ_angle_z = angle; + } + } + + /** + * Returns the axis angle in degrees (CCW positive). + * + * @param axis The IMUAxis whose angle to return. + * @return The axis angle in degrees (CCW positive). + */ + public synchronized double getAngle(IMUAxis axis) { + switch (axis) { + case kYaw: + axis = m_yaw_axis; + break; + case kPitch: + axis = m_pitch_axis; + break; + case kRoll: + axis = m_roll_axis; + break; + default: + } + + switch (axis) { + case kX: + if (m_simGyroAngleX != null) { + return m_simGyroAngleX.get(); + } + return m_integ_angle_x; + case kY: + if (m_simGyroAngleY != null) { + return m_simGyroAngleY.get(); + } + return m_integ_angle_y; + case kZ: + if (m_simGyroAngleZ != null) { + return m_simGyroAngleZ.get(); + } + return m_integ_angle_z; + default: + } + + return 0.0; + } + + /** + * Returns the Yaw axis angle in degrees (CCW positive). + * + * @return The Yaw axis angle in degrees (CCW positive). */ public synchronized double getAngle() { switch (m_yaw_axis) { @@ -941,103 +1177,184 @@ public synchronized double getAngle() { if (m_simGyroAngleX != null) { return m_simGyroAngleX.get(); } - break; + return m_integ_angle_x; case kY: if (m_simGyroAngleY != null) { return m_simGyroAngleY.get(); } - break; + return m_integ_angle_y; case kZ: if (m_simGyroAngleZ != null) { return m_simGyroAngleZ.get(); } + return m_integ_angle_z; + default: + } + return 0.0; + } + + /** + * Returns the axis angular rate in degrees per second (CCW positive). + * + * @param axis The IMUAxis whose rate to return. + * @return Axis angular rate in degrees per second (CCW positive). + */ + public synchronized double getRate(IMUAxis axis) { + switch (axis) { + case kYaw: + axis = m_yaw_axis; + break; + case kPitch: + axis = m_pitch_axis; break; + case kRoll: + axis = m_roll_axis; + break; + default: + } + + switch (axis) { + case kX: + if (m_simGyroRateX != null) { + return m_simGyroRateX.get(); + } + return m_gyro_rate_x; + case kY: + if (m_simGyroRateY != null) { + return m_simGyroRateY.get(); + } + return m_gyro_rate_y; + case kZ: + if (m_simGyroRateZ != null) { + return m_simGyroRateZ.get(); + } + return m_gyro_rate_z; + default: } - return m_integ_angle; + return 0.0; } /** - * @return Yaw axis angular rate in degrees per second (CCW positive) + * Returns the Yaw axis angular rate in degrees per second (CCW positive). + * + * @return Yaw axis angular rate in degrees per second (CCW positive). */ public synchronized double getRate() { - if (m_yaw_axis == IMUAxis.kX) { - if (m_simGyroRateX != null) { - return m_simGyroRateX.get(); - } - return m_gyro_rate_x; - } else if (m_yaw_axis == IMUAxis.kY) { - if (m_simGyroRateY != null) { - return m_simGyroRateY.get(); - } - return m_gyro_rate_y; - } else if (m_yaw_axis == IMUAxis.kZ) { - if (m_simGyroRateZ != null) { - return m_simGyroRateZ.get(); - } - return m_gyro_rate_z; - } else { - return 0.0; + switch (m_yaw_axis) { + case kX: + if (m_simGyroRateX != null) { + return m_simGyroRateX.get(); + } + return m_gyro_rate_x; + case kY: + if (m_simGyroRateY != null) { + return m_simGyroRateY.get(); + } + return m_gyro_rate_y; + case kZ: + if (m_simGyroRateZ != null) { + return m_simGyroRateZ.get(); + } + return m_gyro_rate_z; + default: } + return 0.0; } /** - * @return Yaw Axis + * Returns which axis, kX, kY, or kZ, is set to the yaw axis. + * + * @return IMUAxis Yaw Axis */ public IMUAxis getYawAxis() { return m_yaw_axis; } /** - * @return current acceleration in the X axis + * Returns which axis, kX, kY, or kZ, is set to the pitch axis. + * + * @return IMUAxis Pitch Axis + */ + public IMUAxis getPitchAxis() { + return m_pitch_axis; + } + + /** + * Returns which axis, kX, kY, or kZ, is set to the roll axis. + * + * @return IMUAxis Roll Axis + */ + public IMUAxis getRollAxis() { + return m_roll_axis; + } + + /** + * Returns the acceleration in the X axis in meters per second squared. + * + * @return The acceleration in the X axis in meters per second squared. */ public synchronized double getAccelX() { return m_accel_x * 9.81; } /** - * @return current acceleration in the Y axis + * Returns the acceleration in the Y axis in meters per second squared. + * + * @return The acceleration in the Y axis in meters per second squared. */ public synchronized double getAccelY() { return m_accel_y * 9.81; } /** - * @return current acceleration in the Z axis + * Returns the acceleration in the Z axis in meters per second squared. + * + * @return The acceleration in the Z axis in meters per second squared. */ public synchronized double getAccelZ() { return m_accel_z * 9.81; } /** - * @return X-axis complementary angle + * Returns the complementary angle around the X axis computed from accelerometer and gyro rate + * measurements. + * + * @return The X-axis complementary angle in degrees. */ public synchronized double getXComplementaryAngle() { return m_compAngleX; } /** - * @return Y-axis complementary angle + * Returns the complementary angle around the Y axis computed from accelerometer and gyro rate + * measurements. + * + * @return The Y-axis complementary angle in degrees. */ public synchronized double getYComplementaryAngle() { return m_compAngleY; } /** - * @return X-axis filtered acceleration angle + * Returns the X-axis filtered acceleration angle in degrees. + * + * @return The X-axis filtered acceleration angle in degrees. */ public synchronized double getXFilteredAccelAngle() { return m_accelAngleX; } /** - * @return Y-axis filtered acceleration angle + * Returns the Y-axis filtered acceleration angle in degrees. + * + * @return The Y-axis filtered acceleration angle in degrees. */ public synchronized double getYFilteredAccelAngle() { return m_accelAngleY; } /** - * Get the SPI port number. + * Gets the SPI port number. * * @return The SPI port number. */ @@ -1048,6 +1365,6 @@ public int getPort() { @Override public void initSendable(SendableBuilder builder) { builder.setSmartDashboardType("Gyro"); - builder.addDoubleProperty("Value", this::getAngle, null); + builder.addDoubleProperty("Value", () -> getAngle(m_yaw_axis), null); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXL345_I2C.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXL345_I2C.java index 7ceff95a960..357618b7f4a 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXL345_I2C.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXL345_I2C.java @@ -25,34 +25,46 @@ * href="https://docs.wpilib.org/en/stable/docs/yearly-overview/known-issues.html#onboard-i2c-causing-system-lockups"> * WPILib Known Issues page for details. */ -@SuppressWarnings({"TypeName", "PMD.UnusedPrivateField"}) +@SuppressWarnings("TypeName") public class ADXL345_I2C implements NTSendable, AutoCloseable { - private static final byte kAddress = 0x1D; + /** Default I2C device address. */ + public static final byte kAddress = 0x1D; + private static final byte kPowerCtlRegister = 0x2D; private static final byte kDataFormatRegister = 0x31; private static final byte kDataRegister = 0x32; private static final double kGsPerLSB = 0.00390625; - private static final byte kPowerCtl_Link = 0x20; - private static final byte kPowerCtl_AutoSleep = 0x10; + // private static final byte kPowerCtl_Link = 0x20; + // private static final byte kPowerCtl_AutoSleep = 0x10; private static final byte kPowerCtl_Measure = 0x08; - private static final byte kPowerCtl_Sleep = 0x04; + // private static final byte kPowerCtl_Sleep = 0x04; - private static final byte kDataFormat_SelfTest = (byte) 0x80; - private static final byte kDataFormat_SPI = 0x40; - private static final byte kDataFormat_IntInvert = 0x20; + // private static final byte kDataFormat_SelfTest = (byte) 0x80; + // private static final byte kDataFormat_SPI = 0x40; + // private static final byte kDataFormat_IntInvert = 0x20; private static final byte kDataFormat_FullRes = 0x08; - private static final byte kDataFormat_Justify = 0x04; + // private static final byte kDataFormat_Justify = 0x04; + + /** Accelerometer range. */ public enum Range { + /** 2 Gs max. */ k2G, + /** 4 Gs max. */ k4G, + /** 8 Gs max. */ k8G, + /** 16 Gs max. */ k16G } + /** Accelerometer axes. */ public enum Axes { + /** X axis. */ kX((byte) 0x00), + /** Y axis. */ kY((byte) 0x02), + /** Z axis. */ kZ((byte) 0x04); /** The integer value representing this enumeration. */ @@ -63,20 +75,29 @@ public enum Axes { } } + /** Container type for accelerations from all axes. */ @SuppressWarnings("MemberName") public static class AllAxes { + /** Acceleration along the X axis in g-forces. */ public double XAxis; + + /** Acceleration along the Y axis in g-forces. */ public double YAxis; + + /** Acceleration along the Z axis in g-forces. */ public double ZAxis; + + /** Default constructor. */ + public AllAxes() {} } - protected I2C m_i2c; + private I2C m_i2c; - protected SimDevice m_simDevice; - protected SimEnum m_simRange; - protected SimDouble m_simX; - protected SimDouble m_simY; - protected SimDouble m_simZ; + private SimDevice m_simDevice; + private SimEnum m_simRange; + private SimDouble m_simX; + private SimDouble m_simY; + private SimDouble m_simZ; /** * Constructs the ADXL345 Accelerometer with I2C address 0x1D. @@ -95,6 +116,7 @@ public ADXL345_I2C(I2C.Port port, Range range) { * @param range The range (+ or -) that the accelerometer will measure. * @param deviceAddress I2C address of the accelerometer (0x1D or 0x53) */ + @SuppressWarnings("this-escape") public ADXL345_I2C(I2C.Port port, Range range, int deviceAddress) { m_i2c = new I2C(port, deviceAddress); @@ -122,10 +144,20 @@ public ADXL345_I2C(I2C.Port port, Range range, int deviceAddress) { SendableRegistry.addLW(this, "ADXL345_I2C", port.value); } + /** + * Returns the I2C port. + * + * @return The I2C port. + */ public int getPort() { return m_i2c.getPort(); } + /** + * Returns the I2C device address. + * + * @return The I2C device address. + */ public int getDeviceAddress() { return m_i2c.getDeviceAddress(); } @@ -149,7 +181,7 @@ public void close() { * @param range The maximum acceleration, positive or negative, that the accelerometer will * measure. */ - public void setRange(Range range) { + public final void setRange(Range range) { final byte value; switch (range) { case k2G: diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXL345_SPI.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXL345_SPI.java index 729144305a2..29a20cbd5c3 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXL345_SPI.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXL345_SPI.java @@ -19,7 +19,7 @@ import java.nio.ByteOrder; /** ADXL345 SPI Accelerometer. */ -@SuppressWarnings({"TypeName", "PMD.UnusedPrivateField"}) +@SuppressWarnings("TypeName") public class ADXL345_SPI implements NTSendable, AutoCloseable { private static final int kPowerCtlRegister = 0x2D; private static final int kDataFormatRegister = 0x31; @@ -29,27 +29,37 @@ public class ADXL345_SPI implements NTSendable, AutoCloseable { private static final int kAddress_Read = 0x80; private static final int kAddress_MultiByte = 0x40; - private static final int kPowerCtl_Link = 0x20; - private static final int kPowerCtl_AutoSleep = 0x10; + // private static final int kPowerCtl_Link = 0x20; + // private static final int kPowerCtl_AutoSleep = 0x10; private static final int kPowerCtl_Measure = 0x08; - private static final int kPowerCtl_Sleep = 0x04; + // private static final int kPowerCtl_Sleep = 0x04; - private static final int kDataFormat_SelfTest = 0x80; - private static final int kDataFormat_SPI = 0x40; - private static final int kDataFormat_IntInvert = 0x20; + // private static final int kDataFormat_SelfTest = 0x80; + // private static final int kDataFormat_SPI = 0x40; + // private static final int kDataFormat_IntInvert = 0x20; private static final int kDataFormat_FullRes = 0x08; - private static final int kDataFormat_Justify = 0x04; + // private static final int kDataFormat_Justify = 0x04; + + /** Accelerometer range. */ public enum Range { + /** 2 Gs max. */ k2G, + /** 4 Gs max. */ k4G, + /** 8 Gs max. */ k8G, + /** 16 Gs max. */ k16G } + /** Accelerometer axes. */ public enum Axes { + /** X axis. */ kX((byte) 0x00), + /** Y axis. */ kY((byte) 0x02), + /** Z axis. */ kZ((byte) 0x04); /** The integer value representing this enumeration. */ @@ -60,20 +70,29 @@ public enum Axes { } } + /** Container type for accelerations from all axes. */ @SuppressWarnings("MemberName") public static class AllAxes { + /** Acceleration along the X axis in g-forces. */ public double XAxis; + + /** Acceleration along the Y axis in g-forces. */ public double YAxis; + + /** Acceleration along the Z axis in g-forces. */ public double ZAxis; + + /** Default constructor. */ + public AllAxes() {} } - protected SPI m_spi; + private SPI m_spi; - protected SimDevice m_simDevice; - protected SimEnum m_simRange; - protected SimDouble m_simX; - protected SimDouble m_simY; - protected SimDouble m_simZ; + private SimDevice m_simDevice; + private SimEnum m_simRange; + private SimDouble m_simX; + private SimDouble m_simY; + private SimDouble m_simZ; /** * Constructor. @@ -81,6 +100,7 @@ public static class AllAxes { * @param port The SPI port that the accelerometer is connected to * @param range The range (+ or -) that the accelerometer will measure. */ + @SuppressWarnings("this-escape") public ADXL345_SPI(SPI.Port port, Range range) { m_spi = new SPI(port); // simulation @@ -101,6 +121,11 @@ public ADXL345_SPI(SPI.Port port, Range range) { SendableRegistry.addLW(this, "ADXL345_SPI", port.value); } + /** + * Returns the SPI port. + * + * @return The SPI port. + */ public int getPort() { return m_spi.getPort(); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXL362.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXL362.java index b094be374f1..b00ea2b8f6a 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXL362.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXL362.java @@ -38,22 +38,31 @@ public class ADXL362 implements NTSendable, AutoCloseable { private static final byte kPowerCtl_UltraLowNoise = 0x20; - @SuppressWarnings("PMD.UnusedPrivateField") - private static final byte kPowerCtl_AutoSleep = 0x04; + // @SuppressWarnings("PMD.UnusedPrivateField") + // private static final byte kPowerCtl_AutoSleep = 0x04; private static final byte kPowerCtl_Measure = 0x02; + /** Accelerometer range. */ public enum Range { + /** 2 Gs max. */ k2G, + /** 4 Gs max. */ k4G, + /** 8 Gs max. */ k8G } + /** Accelerometer axes. */ public enum Axes { + /** X axis. */ kX((byte) 0x00), + /** Y axis. */ kY((byte) 0x02), + /** Z axis. */ kZ((byte) 0x04); + /** Axis value. */ public final byte value; Axes(byte value) { @@ -61,11 +70,20 @@ public enum Axes { } } + /** Container type for accelerations from all axes. */ @SuppressWarnings("MemberName") public static class AllAxes { + /** Acceleration along the X axis in g-forces. */ public double XAxis; + + /** Acceleration along the Y axis in g-forces. */ public double YAxis; + + /** Acceleration along the Z axis in g-forces. */ public double ZAxis; + + /** Default constructor. */ + public AllAxes() {} } private SPI m_spi; @@ -93,6 +111,7 @@ public ADXL362(Range range) { * @param port The SPI port that the accelerometer is connected to * @param range The range (+ or -) that the accelerometer will measure. */ + @SuppressWarnings("this-escape") public ADXL362(SPI.Port port, Range range) { m_spi = new SPI(port); @@ -141,6 +160,11 @@ public ADXL362(SPI.Port port, Range range) { SendableRegistry.addLW(this, "ADXL362", port.value); } + /** + * Returns the SPI port. + * + * @return The SPI port. + */ public int getPort() { return m_spi.getPort(); } @@ -164,7 +188,7 @@ public void close() { * @param range The maximum acceleration, positive or negative, that the accelerometer will * measure. */ - public void setRange(Range range) { + public final void setRange(Range range) { if (m_spi == null) { return; } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXRS450_Gyro.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXRS450_Gyro.java index cbe34c83370..d574a24824a 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXRS450_Gyro.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/ADXRS450_Gyro.java @@ -26,21 +26,21 @@ *

This class is for the digital ADXRS450 gyro sensor that connects via SPI. Only one instance of * an ADXRS Gyro is supported. */ -@SuppressWarnings({"TypeName", "PMD.UnusedPrivateField"}) +@SuppressWarnings("TypeName") public class ADXRS450_Gyro implements Sendable, AutoCloseable { private static final double kSamplePeriod = 0.0005; private static final double kCalibrationSampleTime = 5.0; private static final double kDegreePerSecondPerLSB = 0.0125; - private static final int kRateRegister = 0x00; - private static final int kTemRegister = 0x02; - private static final int kLoCSTRegister = 0x04; - private static final int kHiCSTRegister = 0x06; - private static final int kQuadRegister = 0x08; - private static final int kFaultRegister = 0x0A; + // private static final int kRateRegister = 0x00; + // private static final int kTemRegister = 0x02; + // private static final int kLoCSTRegister = 0x04; + // private static final int kHiCSTRegister = 0x06; + // private static final int kQuadRegister = 0x08; + // private static final int kFaultRegister = 0x0A; private static final int kPIDRegister = 0x0C; - private static final int kSNHighRegister = 0x0E; - private static final int kSNLowRegister = 0x10; + // private static final int kSNHighRegister = 0x0E; + // private static final int kSNLowRegister = 0x10; private SPI m_spi; @@ -59,6 +59,7 @@ public ADXRS450_Gyro() { * * @param port The SPI port that the gyro is connected to */ + @SuppressWarnings("this-escape") public ADXRS450_Gyro(SPI.Port port) { m_spi = new SPI(port); @@ -113,7 +114,7 @@ public boolean isConnected() { * are in progress, this is typically done when the robot is first turned on while it's sitting at * rest before the competition starts. */ - public void calibrate() { + public final void calibrate() { if (m_spi == null) { return; } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AddressableLED.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AddressableLED.java index 61a2fa65604..bb097ab94f8 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AddressableLED.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AddressableLED.java @@ -14,7 +14,8 @@ * *

By default, the timing supports WS2812B LEDs, but is configurable using setBitTiming() * - *

Only 1 LED driver is currently supported by the roboRIO. + *

Only 1 LED driver is currently supported by the roboRIO. However, multiple LED strips can be + * connected in series and controlled from the single driver. */ public class AddressableLED implements AutoCloseable { private final int m_pwmHandle; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AddressableLEDBuffer.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AddressableLEDBuffer.java index a19773e1f8f..68644a05839 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AddressableLEDBuffer.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AddressableLEDBuffer.java @@ -131,8 +131,7 @@ public int getLength() { * @return the LED color at the specified index */ public Color8Bit getLED8Bit(int index) { - return new Color8Bit( - m_buffer[index * 4 + 2] & 0xFF, m_buffer[index * 4 + 1] & 0xFF, m_buffer[index * 4] & 0xFF); + return new Color8Bit(getRed(index), getGreen(index), getBlue(index)); } /** @@ -142,9 +141,70 @@ public Color8Bit getLED8Bit(int index) { * @return the LED color at the specified index */ public Color getLED(int index) { - return new Color( - (m_buffer[index * 4 + 2] & 0xFF) / 255.0, - (m_buffer[index * 4 + 1] & 0xFF) / 255.0, - (m_buffer[index * 4] & 0xFF) / 255.0); + return new Color(getRed(index) / 255.0, getGreen(index) / 255.0, getBlue(index) / 255.0); + } + + /** + * Gets the red channel of the color at the specified index. + * + * @param index the index of the LED to read + * @return the value of the red channel, from [0, 255] + */ + public int getRed(int index) { + return m_buffer[index * 4 + 2] & 0xFF; + } + + /** + * Gets the green channel of the color at the specified index. + * + * @param index the index of the LED to read + * @return the value of the green channel, from [0, 255] + */ + public int getGreen(int index) { + return m_buffer[index * 4 + 1] & 0xFF; + } + + /** + * Gets the blue channel of the color at the specified index. + * + * @param index the index of the LED to read + * @return the value of the blue channel, from [0, 255] + */ + public int getBlue(int index) { + return m_buffer[index * 4] & 0xFF; + } + + /** + * A functional interface that allows for iteration over an LED buffer without manually writing an + * indexed for-loop. + */ + @FunctionalInterface + public interface IndexedColorIterator { + /** + * Accepts an index of an LED in the buffer and the red, green, and blue components of the + * currently stored color for that LED. + * + * @param index the index of the LED in the buffer that the red, green, and blue channels + * corresponds to + * @param r the value of the red channel of the color currently in the buffer at index {@code i} + * @param g the value of the green channel of the color currently in the buffer at index {@code + * i} + * @param b the value of the blue channel of the color currently in the buffer at index {@code + * i} + */ + void accept(int index, int r, int g, int b); + } + + /** + * Iterates over the LEDs in the buffer, starting from index 0. The iterator function is passed + * the current index of iteration, along with the values for the red, green, and blue components + * of the color written to the LED at that index. + * + * @param iterator the iterator function to call for each LED in the buffer. + */ + public void forEach(IndexedColorIterator iterator) { + for (int i = 0; i < getLength(); i++) { + iterator.accept(i, getRed(i), getGreen(i), getBlue(i)); + } } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogAccelerometer.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogAccelerometer.java index 3ea9ef7947e..0bdb2ffa2f6 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogAccelerometer.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogAccelerometer.java @@ -36,6 +36,7 @@ private void initAccelerometer() { * * @param channel The channel number for the analog input the accelerometer is connected to */ + @SuppressWarnings("this-escape") public AnalogAccelerometer(final int channel) { this(new AnalogInput(channel), true); SendableRegistry.addChild(this, m_analogChannel); @@ -49,10 +50,12 @@ public AnalogAccelerometer(final int channel) { * @param channel The existing AnalogInput object for the analog input the accelerometer is * connected to */ + @SuppressWarnings("this-escape") public AnalogAccelerometer(final AnalogInput channel) { this(channel, false); } + @SuppressWarnings("this-escape") private AnalogAccelerometer(final AnalogInput channel, final boolean allocatedChannel) { requireNonNullParam(channel, "channel", "AnalogAccelerometer"); m_allocatedChannel = allocatedChannel; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogEncoder.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogEncoder.java index 8e458694e05..727ad2cd3de 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogEncoder.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogEncoder.java @@ -22,9 +22,9 @@ public class AnalogEncoder implements Sendable, AutoCloseable { private double m_distancePerRotation = 1.0; private double m_lastPosition; - protected SimDevice m_simDevice; - protected SimDouble m_simPosition; - protected SimDouble m_simAbsolutePosition; + private SimDevice m_simDevice; + private SimDouble m_simPosition; + private SimDouble m_simAbsolutePosition; /** * Construct a new AnalogEncoder attached to a specific AnalogIn channel. @@ -40,6 +40,7 @@ public AnalogEncoder(int channel) { * * @param analogInput the analog input to attach to */ + @SuppressWarnings("this-escape") public AnalogEncoder(AnalogInput analogInput) { m_analogInput = analogInput; init(); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogGyro.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogGyro.java index f5be4ad2d9f..29a17bbed0e 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogGyro.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogGyro.java @@ -25,13 +25,13 @@ */ public class AnalogGyro implements Sendable, AutoCloseable { private static final double kDefaultVoltsPerDegreePerSecond = 0.007; - protected AnalogInput m_analog; + private AnalogInput m_analog; private boolean m_channelAllocated; private int m_gyroHandle; /** Initialize the gyro. Calibration is handled by calibrate(). */ - public void initGyro() { + private void initGyro() { if (m_gyroHandle == 0) { m_gyroHandle = AnalogGyroJNI.initializeAnalogGyro(m_analog.m_port); } @@ -78,6 +78,7 @@ public Rotation2d getRotation2d() { * @param channel The analog channel the gyro is connected to. Gyros can only be used on on-board * channels 0-1. */ + @SuppressWarnings("this-escape") public AnalogGyro(int channel) { this(new AnalogInput(channel)); m_channelAllocated = true; @@ -91,6 +92,7 @@ public AnalogGyro(int channel) { * @param channel The AnalogInput object that the gyro is connected to. Gyros can only be used on * on-board channels 0-1. */ + @SuppressWarnings("this-escape") public AnalogGyro(AnalogInput channel) { requireNonNullParam(channel, "channel", "AnalogGyro"); @@ -108,6 +110,7 @@ public AnalogGyro(AnalogInput channel) { * @param center Preset uncalibrated value to use as the accumulator center value. * @param offset Preset uncalibrated value to use as the gyro offset. */ + @SuppressWarnings("this-escape") public AnalogGyro(int channel, int center, double offset) { this(new AnalogInput(channel), center, offset); m_channelAllocated = true; @@ -123,6 +126,7 @@ public AnalogGyro(int channel, int center, double offset) { * @param center Preset uncalibrated value to use as the accumulator center value. * @param offset Preset uncalibrated value to use as the gyro offset. */ + @SuppressWarnings("this-escape") public AnalogGyro(AnalogInput channel, int center, double offset) { requireNonNullParam(channel, "channel", "AnalogGyro"); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogInput.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogInput.java index e90bfd26d5e..3c6458bfad4 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogInput.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogInput.java @@ -38,6 +38,7 @@ public class AnalogInput implements Sendable, AutoCloseable { * * @param channel The channel number to represent. 0-3 are on-board 4-7 are on the MXP port. */ + @SuppressWarnings("this-escape") public AnalogInput(final int channel) { AnalogJNI.checkAnalogInputChannel(channel); m_channel = channel; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogOutput.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogOutput.java index 299d89c2ec7..354cedc038d 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogOutput.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogOutput.java @@ -21,6 +21,7 @@ public class AnalogOutput implements Sendable, AutoCloseable { * * @param channel The channel number to represent. */ + @SuppressWarnings("this-escape") public AnalogOutput(final int channel) { SensorUtil.checkAnalogOutputChannel(channel); m_channel = channel; @@ -49,10 +50,20 @@ public int getChannel() { return m_channel; } + /** + * Set the value of the analog output. + * + * @param voltage The output value in Volts, from 0.0 to +5.0. + */ public void setVoltage(double voltage) { AnalogJNI.setAnalogOutput(m_port, voltage); } + /** + * Get the voltage of the analog output. + * + * @return The value in Volts, from 0.0 to +5.0. + */ public double getVoltage() { return AnalogJNI.getAnalogOutput(m_port); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java index 7d5858574dc..15473495528 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java @@ -33,6 +33,7 @@ public class AnalogPotentiometer implements Sendable, AutoCloseable { * @param fullRange The scaling to multiply the fraction by to get a meaningful unit. * @param offset The offset to add to the scaled value for controlling the zero value */ + @SuppressWarnings("this-escape") public AnalogPotentiometer(final int channel, double fullRange, double offset) { this(new AnalogInput(channel), fullRange, offset); m_initAnalogInput = true; @@ -53,6 +54,7 @@ public AnalogPotentiometer(final int channel, double fullRange, double offset) { * input. * @param offset The angular value (in desired units) representing the angular output at 0V. */ + @SuppressWarnings("this-escape") public AnalogPotentiometer(final AnalogInput input, double fullRange, double offset) { SendableRegistry.addLW(this, "AnalogPotentiometer", input.getChannel()); m_analogInput = input; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogTrigger.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogTrigger.java index 8baa508120b..1d4a404dd95 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogTrigger.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogTrigger.java @@ -12,33 +12,25 @@ import edu.wpi.first.util.sendable.SendableBuilder; import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.AnalogTriggerOutput.AnalogTriggerType; +import java.lang.ref.Reference; /** Class for creating and configuring Analog Triggers. */ public class AnalogTrigger implements Sendable, AutoCloseable { - /** Exceptions dealing with improper operation of the Analog trigger. */ - public static class AnalogTriggerException extends RuntimeException { - /** - * Create a new exception with the given message. - * - * @param message the message to pass with the exception - */ - public AnalogTriggerException(String message) { - super(message); - } - } - /** Where the analog trigger is attached. */ protected int m_port; - protected AnalogInput m_analogInput; - protected DutyCycle m_dutyCycle; - protected boolean m_ownsAnalog; + private AnalogInput m_analogInput; + + private DutyCycle m_dutyCycle; + + private boolean m_ownsAnalog; /** * Constructor for an analog trigger given a channel number. * * @param channel the port to use for the analog trigger */ + @SuppressWarnings("this-escape") public AnalogTrigger(final int channel) { this(new AnalogInput(channel)); m_ownsAnalog = true; @@ -51,6 +43,7 @@ public AnalogTrigger(final int channel) { * * @param channel the AnalogInput to use for the analog trigger */ + @SuppressWarnings("this-escape") public AnalogTrigger(AnalogInput channel) { m_analogInput = channel; @@ -67,6 +60,7 @@ public AnalogTrigger(AnalogInput channel) { * * @param input the DutyCycle to use for the analog trigger */ + @SuppressWarnings("this-escape") public AnalogTrigger(DutyCycle input) { m_dutyCycle = input; @@ -86,6 +80,7 @@ public void close() { if (m_ownsAnalog && m_analogInput != null) { m_analogInput.close(); } + Reference.reachabilityFence(m_dutyCycle); } /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogTriggerOutput.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogTriggerOutput.java index c80179b5c4d..4d459fc2c43 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogTriggerOutput.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AnalogTriggerOutput.java @@ -106,9 +106,13 @@ public boolean isAnalogTrigger() { /** Defines the state in which the AnalogTrigger triggers. */ public enum AnalogTriggerType { + /** In window. */ kInWindow(AnalogJNI.AnalogTriggerType.kInWindow), + /** State. */ kState(AnalogJNI.AnalogTriggerType.kState), + /** Rising pulse. */ kRisingPulse(AnalogJNI.AnalogTriggerType.kRisingPulse), + /** Falling pulse. */ kFallingPulse(AnalogJNI.AnalogTriggerType.kFallingPulse); private final int value; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AsynchronousInterrupt.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AsynchronousInterrupt.java index 4cb3cb56737..03bf1dc44b0 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/AsynchronousInterrupt.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/AsynchronousInterrupt.java @@ -6,6 +6,7 @@ import static edu.wpi.first.util.ErrorMessages.requireNonNullParam; +import edu.wpi.first.wpilibj.SynchronousInterrupt.WaitResult; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; @@ -127,14 +128,32 @@ public double getFallingTimestamp() { private void threadMain() { while (m_keepRunning.get()) { - var result = m_interrupt.waitForInterruptRaw(10, false); + var result = m_interrupt.waitForInterrupt(10, false); if (!m_keepRunning.get()) { break; } - if (result == 0) { + if (result == WaitResult.kTimeout) { continue; } - m_callback.accept((result & 0x1) != 0, (result & 0x100) != 0); + + boolean rising = false; + boolean falling = false; + switch (result) { + case kBoth: + rising = true; + falling = true; + break; + case kFallingEdge: + falling = true; + break; + case kRisingEdge: + rising = true; + break; + default: + break; + } + + m_callback.accept(rising, falling); } } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometer.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometer.java index 1a6b103a914..522ab88476a 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometer.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometer.java @@ -17,9 +17,13 @@ *

This class allows access to the roboRIO's internal accelerometer. */ public class BuiltInAccelerometer implements Sendable, AutoCloseable { + /** Accelerometer range. */ public enum Range { + /** 2 Gs max. */ k2G, + /** 4 Gs max. */ k4G, + /** 8 Gs max. */ k8G } @@ -28,6 +32,7 @@ public enum Range { * * @param range The range the accelerometer will measure */ + @SuppressWarnings("this-escape") public BuiltInAccelerometer(Range range) { setRange(range); HAL.report(tResourceType.kResourceType_Accelerometer, 0, 0, "Built-in accelerometer"); @@ -50,7 +55,7 @@ public void close() { * @param range The maximum acceleration, positive or negative, that the accelerometer will * measure. */ - public void setRange(Range range) { + public final void setRange(Range range) { AccelerometerJNI.setAccelerometerActive(false); switch (range) { diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/CAN.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/CAN.java index 8808a4b68b6..df0be482c26 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/CAN.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/CAN.java @@ -5,6 +5,7 @@ package edu.wpi.first.wpilibj; import edu.wpi.first.hal.CANAPIJNI; +import edu.wpi.first.hal.CANAPITypes; import edu.wpi.first.hal.CANData; import edu.wpi.first.hal.FRCNetComm.tResourceType; import edu.wpi.first.hal.HAL; @@ -21,8 +22,11 @@ * calls. */ public class CAN implements Closeable { - public static final int kTeamManufacturer = 8; - public static final int kTeamDeviceType = 10; + /** Team manufacturer. */ + public static final int kTeamManufacturer = CANAPITypes.CANManufacturer.kTeamUse.id; + + /** Team device type. */ + public static final int kTeamDeviceType = CANAPITypes.CANDeviceType.kMiscellaneous.id; private final int m_handle; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Compressor.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Compressor.java index f2cfeb39081..e7a14bd659a 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Compressor.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Compressor.java @@ -31,6 +31,7 @@ public class Compressor implements Sendable, AutoCloseable { * @param module The module ID to use. * @param moduleType The module type to use. */ + @SuppressWarnings("this-escape") public Compressor(int module, PneumaticsModuleType moduleType) { m_module = PneumaticsBase.getForType(module, moduleType); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/CompressorConfigType.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/CompressorConfigType.java index 48bb81ffcdb..7735cdd579c 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/CompressorConfigType.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/CompressorConfigType.java @@ -6,12 +6,18 @@ import edu.wpi.first.hal.REVPHJNI; +/** Compressor config type. */ public enum CompressorConfigType { + /** Disabled. */ Disabled(REVPHJNI.COMPRESSOR_CONFIG_TYPE_DISABLED), + /** Digital. */ Digital(REVPHJNI.COMPRESSOR_CONFIG_TYPE_DIGITAL), + /** Analog. */ Analog(REVPHJNI.COMPRESSOR_CONFIG_TYPE_ANALOG), + /** Hybrid. */ Hybrid(REVPHJNI.COMPRESSOR_CONFIG_TYPE_HYBRID); + /** CompressorConfigType value. */ public final int value; CompressorConfigType(int value) { @@ -37,6 +43,11 @@ public static CompressorConfigType fromValue(int value) { } } + /** + * Returns the CompressorConfigType's value. + * + * @return The CompressorConfigType's value. + */ public int getValue() { return value; } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Counter.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Counter.java index d8c5015f4ec..eca3dd5a8ff 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Counter.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Counter.java @@ -38,6 +38,7 @@ public enum Mode { /** mode: external direction. */ kExternalDirection(3); + /** Mode value. */ public final int value; Mode(int value) { @@ -45,19 +46,30 @@ public enum Mode { } } - protected DigitalSource m_upSource; // /< What makes the counter count up. - protected DigitalSource m_downSource; // /< What makes the counter count down. + /** What makes the counter count up. */ + protected DigitalSource m_upSource; + + /** What makes the counter count down. */ + protected DigitalSource m_downSource; + private boolean m_allocatedUpSource; private boolean m_allocatedDownSource; - int m_counter; // /< The FPGA counter object. - private int m_index; // /< The index of this counter. - private double m_distancePerPulse = 1; // distance of travel for each tick + + /** The FPGA counter object. */ + int m_counter; + + /** The index of this counter. */ + private int m_index; + + /** Distance of travel for each tick. */ + private double m_distancePerPulse = 1; /** * Create an instance of a counter with the given mode. * * @param mode The counter mode. */ + @SuppressWarnings("this-escape") public Counter(final Mode mode) { ByteBuffer index = ByteBuffer.allocateDirect(4); // set the byte order @@ -95,6 +107,7 @@ public Counter() { * * @param source the digital source to count */ + @SuppressWarnings("this-escape") public Counter(DigitalSource source) { this(); @@ -109,6 +122,7 @@ public Counter(DigitalSource source) { * * @param channel the DIO channel to use as the up source. 0-9 are on-board, 10-25 are on the MXP */ + @SuppressWarnings("this-escape") public Counter(int channel) { this(); setUpSource(channel); @@ -125,6 +139,7 @@ public Counter(int channel) { * @param downSource second source for direction * @param inverted true to invert the count */ + @SuppressWarnings("this-escape") public Counter( EncodingType encodingType, DigitalSource upSource, @@ -162,6 +177,7 @@ public Counter( * * @param trigger the analog trigger to count */ + @SuppressWarnings("this-escape") public Counter(AnalogTrigger trigger) { this(); @@ -200,7 +216,7 @@ public int getFPGAIndex() { * * @param channel the DIO channel to count 0-9 are on-board, 10-25 are on the MXP */ - public void setUpSource(int channel) { + public final void setUpSource(int channel) { setUpSource(new DigitalInput(channel)); m_allocatedUpSource = true; SendableRegistry.addChild(this, m_upSource); @@ -401,7 +417,7 @@ public void reset() { * @param maxPeriod The maximum period where the counted device is considered moving in seconds. */ @Override - public void setMaxPeriod(double maxPeriod) { + public final void setMaxPeriod(double maxPeriod) { CounterJNI.setCounterMaxPeriod(m_counter, maxPeriod); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/CounterBase.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/CounterBase.java index 60d56909d36..6e03b72356c 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/CounterBase.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/CounterBase.java @@ -22,6 +22,7 @@ enum EncodingType { /** Count rising and falling on both channels. */ k4X(2); + /** EncodingType value. */ public final int value; EncodingType(int value) { diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DMA.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DMA.java index a919da55f09..bd26a7bf5de 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DMA.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DMA.java @@ -7,9 +7,11 @@ import edu.wpi.first.hal.DMAJNI; import edu.wpi.first.wpilibj.motorcontrol.PWMMotorController; +/** Class for configuring Direct Memory Access (DMA) of FPGA inputs. */ public class DMA implements AutoCloseable { final int m_dmaHandle; + /** Default constructor. */ public DMA() { m_dmaHandle = DMAJNI.initialize(); } @@ -19,50 +21,128 @@ public void close() { DMAJNI.free(m_dmaHandle); } + /** + * Sets whether DMA is paused. + * + * @param pause True pauses DMA. + */ public void setPause(boolean pause) { DMAJNI.setPause(m_dmaHandle, pause); } + /** + * Sets DMA to trigger at an interval. + * + * @param periodSeconds Period at which to trigger DMA in seconds. + */ public void setTimedTrigger(double periodSeconds) { DMAJNI.setTimedTrigger(m_dmaHandle, periodSeconds); } + /** + * Sets number of DMA cycles to trigger. + * + * @param cycles Number of cycles. + */ public void setTimedTriggerCycles(int cycles) { DMAJNI.setTimedTriggerCycles(m_dmaHandle, cycles); } + /** + * Adds position data for an encoder to be collected by DMA. + * + *

This can only be called if DMA is not started. + * + * @param encoder Encoder to add to DMA. + */ public void addEncoder(Encoder encoder) { DMAJNI.addEncoder(m_dmaHandle, encoder.m_encoder); } + /** + * Adds timer data for an encoder to be collected by DMA. + * + *

This can only be called if DMA is not started. + * + * @param encoder Encoder to add to DMA. + */ public void addEncoderPeriod(Encoder encoder) { DMAJNI.addEncoderPeriod(m_dmaHandle, encoder.m_encoder); } + /** + * Adds position data for an counter to be collected by DMA. + * + *

This can only be called if DMA is not started. + * + * @param counter Counter to add to DMA. + */ public void addCounter(Counter counter) { DMAJNI.addCounter(m_dmaHandle, counter.m_counter); } + /** + * Adds timer data for an counter to be collected by DMA. + * + *

This can only be called if DMA is not started. + * + * @param counter Counter to add to DMA. + */ public void addCounterPeriod(Counter counter) { DMAJNI.addCounterPeriod(m_dmaHandle, counter.m_counter); } + /** + * Adds a digital source to be collected by DMA. + * + *

This can only be called if DMA is not started. + * + * @param digitalSource DigitalSource to add to DMA. + */ public void addDigitalSource(DigitalSource digitalSource) { DMAJNI.addDigitalSource(m_dmaHandle, digitalSource.getPortHandleForRouting()); } + /** + * Adds a duty cycle input to be collected by DMA. + * + *

This can only be called if DMA is not started. + * + * @param dutyCycle DutyCycle to add to DMA. + */ public void addDutyCycle(DutyCycle dutyCycle) { DMAJNI.addDutyCycle(m_dmaHandle, dutyCycle.m_handle); } + /** + * Adds an analog input to be collected by DMA. + * + *

This can only be called if DMA is not started. + * + * @param analogInput AnalogInput to add to DMA. + */ public void addAnalogInput(AnalogInput analogInput) { DMAJNI.addAnalogInput(m_dmaHandle, analogInput.m_port); } + /** + * Adds averaged data of an analog input to be collected by DMA. + * + *

This can only be called if DMA is not started. + * + * @param analogInput AnalogInput to add to DMA. + */ public void addAveragedAnalogInput(AnalogInput analogInput) { DMAJNI.addAveragedAnalogInput(m_dmaHandle, analogInput.m_port); } + /** + * Adds accumulator data of an analog input to be collected by DMA. + * + *

This can only be called if DMA is not started. + * + * @param analogInput AnalogInput to add to DMA. + */ public void addAnalogAccumulator(AnalogInput analogInput) { DMAJNI.addAnalogAccumulator(m_dmaHandle, analogInput.m_port); } @@ -84,26 +164,58 @@ public int setExternalTrigger(DigitalSource source, boolean rising, boolean fall falling); } - public int setPwmEdgeTrigger(PWMMotorController pwm, boolean rising, boolean falling) { - return DMAJNI.setExternalTrigger(m_dmaHandle, pwm.getPwmHandle(), 0, rising, falling); - } - + /** + * Sets a DMA PWM edge trigger. + * + * @param pwm the PWM to trigger from. + * @param rising trigger on rising edge. + * @param falling trigger on falling edge. + * @return the index of the trigger + */ public int setPwmEdgeTrigger(PWM pwm, boolean rising, boolean falling) { return DMAJNI.setExternalTrigger(m_dmaHandle, pwm.getHandle(), 0, rising, falling); } + /** + * Sets a DMA PWMMotorController edge trigger. + * + * @param pwm the PWMMotorController to trigger from. + * @param rising trigger on rising edge. + * @param falling trigger on falling edge. + * @return the index of the trigger + */ + public int setPwmEdgeTrigger(PWMMotorController pwm, boolean rising, boolean falling) { + return DMAJNI.setExternalTrigger(m_dmaHandle, pwm.getPwmHandle(), 0, rising, falling); + } + + /** + * Clear all sensors from the DMA collection list. + * + *

This can only be called if DMA is not started. + */ public void clearSensors() { DMAJNI.clearSensors(m_dmaHandle); } + /** + * Clear all external triggers from the DMA trigger list. + * + *

This can only be called if DMA is not started. + */ public void clearExternalTriggers() { DMAJNI.clearExternalTriggers(m_dmaHandle); } + /** + * Starts DMA Collection. + * + * @param queueDepth The number of objects to be able to queue. + */ public void start(int queueDepth) { DMAJNI.startDMA(m_dmaHandle, queueDepth); } + /** Stops DMA Collection. */ public void stop() { DMAJNI.stopDMA(m_dmaHandle); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DMASample.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DMASample.java index 1055dbcc406..1435cd36d9d 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DMASample.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DMASample.java @@ -7,10 +7,15 @@ import edu.wpi.first.hal.AnalogJNI; import edu.wpi.first.hal.DMAJNISample; +/** DMA sample. */ public class DMASample { + /** DMA read status. */ public enum DMAReadStatus { + /** OK status. */ kOk(1), + /** Timeout status. */ kTimeout(2), + /** Error status. */ kError(3); private final int value; @@ -19,6 +24,11 @@ public enum DMAReadStatus { this.value = value; } + /** + * Returns the DMAReadStatus value. + * + * @return The DMAReadStatus value. + */ public int getValue() { return value; } @@ -41,39 +51,80 @@ public static DMAReadStatus getValue(int value) { private final DMAJNISample m_dmaSample = new DMAJNISample(); + /** Default constructor. */ + public DMASample() {} + + /** + * Retrieves a new DMA sample. + * + * @param dma DMA object. + * @param timeoutSeconds Timeout in seconds for retrieval. + * @return DMA read status. + */ public DMAReadStatus update(DMA dma, double timeoutSeconds) { return DMAReadStatus.getValue(m_dmaSample.update(dma.m_dmaHandle, timeoutSeconds)); } + /** + * Returns the DMA sample time in microseconds. + * + * @return The DMA sample time in microseconds. + */ + public long getTime() { + return m_dmaSample.getTime(); + } + + /** + * Returns the DMA sample timestamp in seconds. + * + * @return The DMA sample timestamp in seconds. + */ + public double getTimeStamp() { + return getTime() * 1.0e-6; + } + + /** + * Returns the DMA sample capture size. + * + * @return The DMA sample capture size. + */ public int getCaptureSize() { return m_dmaSample.getCaptureSize(); } + /** + * Returns the number of DMA trigger channels. + * + * @return The number of DMA trigger channels. + */ public int getTriggerChannels() { return m_dmaSample.getTriggerChannels(); } + /** + * Returns the number of remaining samples. + * + * @return The number of remaining samples. + */ public int getRemaining() { return m_dmaSample.getRemaining(); } - public long getTime() { - return m_dmaSample.getTime(); - } - - public double getTimeStamp() { - return getTime() * 1.0e-6; - } - + /** + * Returns raw encoder value from DMA. + * + * @param encoder Encoder used for DMA. + * @return Raw encoder value from DMA. + */ public int getEncoderRaw(Encoder encoder) { return m_dmaSample.getEncoder(encoder.m_encoder); } /** - * Gets the scaled encoder distance for this sample. + * Returns encoder distance from DMA. * - * @param encoder the encoder to use to read - * @return the distance + * @param encoder Encoder used for DMA. + * @return Encoder distance from DMA. */ public double getEncoderDistance(Encoder encoder) { double val = getEncoderRaw(encoder); @@ -82,43 +133,103 @@ public double getEncoderDistance(Encoder encoder) { return val; } + /** + * Returns raw encoder period from DMA. + * + * @param encoder Encoder used for DMA. + * @return Raw encoder period from DMA. + */ public int getEncoderPeriodRaw(Encoder encoder) { return m_dmaSample.getEncoderPeriod(encoder.m_encoder); } + /** + * Returns counter value from DMA. + * + * @param counter Counter used for DMA. + * @return Counter value from DMA. + */ public int getCounter(Counter counter) { return m_dmaSample.getCounter(counter.m_counter); } + /** + * Returns counter period from DMA. + * + * @param counter Counter used for DMA. + * @return Counter period from DMA. + */ public int getCounterPeriod(Counter counter) { return m_dmaSample.getCounterPeriod(counter.m_counter); } + /** + * Returns digital source value from DMA. + * + * @param digitalSource DigitalSource used for DMA. + * @return DigitalSource value from DMA. + */ public boolean getDigitalSource(DigitalSource digitalSource) { return m_dmaSample.getDigitalSource(digitalSource.getPortHandleForRouting()); } + /** + * Returns raw analog input value from DMA. + * + * @param analogInput AnalogInput used for DMA. + * @return Raw analog input value from DMA. + */ public int getAnalogInputRaw(AnalogInput analogInput) { return m_dmaSample.getAnalogInput(analogInput.m_port); } + /** + * Returns analog input voltage from DMA. + * + * @param analogInput AnalogInput used for DMA. + * @return Analog input voltage from DMA. + */ public double getAnalogInputVoltage(AnalogInput analogInput) { return AnalogJNI.getAnalogValueToVolts(analogInput.m_port, getAnalogInputRaw(analogInput)); } + /** + * Returns averaged raw analog input value from DMA. + * + * @param analogInput AnalogInput used for DMA. + * @return Averaged raw analog input value from DMA. + */ public int getAveragedAnalogInputRaw(AnalogInput analogInput) { return m_dmaSample.getAnalogInputAveraged(analogInput.m_port); } + /** + * Returns averaged analog input voltage from DMA. + * + * @param analogInput AnalogInput used for DMA. + * @return Averaged analog input voltage from DMA. + */ public double getAveragedAnalogInputVoltage(AnalogInput analogInput) { return AnalogJNI.getAnalogValueToVolts( analogInput.m_port, getAveragedAnalogInputRaw(analogInput)); } + /** + * Returns raw duty cycle output from DMA. + * + * @param dutyCycle DutyCycle used for DMA. + * @return Raw duty cycle output from DMA. + */ public int getDutyCycleOutputRaw(DutyCycle dutyCycle) { return m_dmaSample.getDutyCycleOutput(dutyCycle.m_handle); } + /** + * Returns duty cycle output (0-1) from DMA. + * + * @param dutyCycle DutyCycle used for DMA. + * @return Duty cycle output (0-1) from DMA. + */ public double getDutyCycleOutput(DutyCycle dutyCycle) { return m_dmaSample.getDutyCycleOutput(dutyCycle.m_handle) / (double) dutyCycle.getOutputScaleFactor(); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DSControlWord.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DSControlWord.java index 8837d4167af..a656d9c700f 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DSControlWord.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DSControlWord.java @@ -20,7 +20,7 @@ public DSControlWord() { } /** Update internal Driver Station control word. */ - public void refresh() { + public final void refresh() { DriverStation.refreshControlWordFromCache(m_controlWord); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DataLogManager.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DataLogManager.java index d588d4049a8..8543b05cc1a 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DataLogManager.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DataLogManager.java @@ -8,6 +8,7 @@ import edu.wpi.first.util.WPIUtilJNI; import edu.wpi.first.util.concurrent.Event; import edu.wpi.first.util.datalog.DataLog; +import edu.wpi.first.util.datalog.DataLogBackgroundWriter; import edu.wpi.first.util.datalog.IntegerLogEntry; import edu.wpi.first.util.datalog.StringLogEntry; import java.io.File; @@ -25,8 +26,8 @@ /** * Centralized data log that provides automatic data log file management. It automatically cleans up * old files when disk space is low and renames the file based either on current date/time or (if - * available) competition match number. The deta file will be saved to a USB flash drive if one is - * attached, or to /home/lvuser otherwise. + * available) competition match number. The data file will be saved to a USB flash drive in a folder + * named "logs" if one is attached, or to /home/lvuser/logs otherwise. * *

Log files are initially named "FRC_TBD_{random}.wpilog" until the DS connects. After the DS * connects, the log file is renamed to "FRC_yyyyMMdd_HHmmss.wpilog" (where the date/time is UTC). @@ -40,7 +41,7 @@ *

By default, all NetworkTables value changes are stored to the data log. */ public final class DataLogManager { - private static DataLog m_log; + private static DataLogBackgroundWriter m_log; private static boolean m_stopped; private static String m_logDir; private static boolean m_filenameOverride; @@ -113,7 +114,7 @@ public static synchronized void start(String dir, String filename, double period } } } - m_log = new DataLog(m_logDir, makeLogFilename(filename), period); + m_log = new DataLogBackgroundWriter(m_logDir, makeLogFilename(filename), period); m_messageLog = new StringLogEntry(m_log, "messages"); // Log all NT entries and connections @@ -214,7 +215,10 @@ private static String makeLogDir(String dir) { // prefer a mounted USB drive if one is accessible Path usbDir = Paths.get("/u").toRealPath(); if (Files.isWritable(usbDir)) { - return usbDir.toString(); + if (!new File("/u/logs").mkdir()) { + // ignored + } + return "/u/logs"; } } catch (IOException ex) { // ignored @@ -230,7 +234,11 @@ private static String makeLogDir(String dir) { } return "/home/lvuser/logs"; } - return Filesystem.getOperatingDirectory().getAbsolutePath(); + String logDir = Filesystem.getOperatingDirectory().getAbsolutePath() + "/logs"; + if (!new File(logDir).mkdir()) { + // ignored + } + return logDir; } private static String makeLogFilename(String filenameOverride) { @@ -262,7 +270,7 @@ private static void logMain() { // based on free disk space, scan for "old" FRC_*.wpilog files and remove { File logDir = new File(m_logDir); - long freeSpace = logDir.getFreeSpace(); + long freeSpace = logDir.getUsableSpace(); if (freeSpace < kFreeSpaceThreshold) { // Delete oldest FRC_*.wpilog files (ignore FRC_TBD_*.wpilog as we just created one) File[] files = @@ -297,7 +305,7 @@ private static void logMain() { + freeSpace / 1000000 + " MB of free space remaining! Logs will get deleted below " + kFreeSpaceThreshold / 1000000 - + " MB of free space." + + " MB of free space. " + "Consider deleting logs off the storage device.", false); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalGlitchFilter.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalGlitchFilter.java index 3422d34a97c..2fcc9dd7a9a 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalGlitchFilter.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalGlitchFilter.java @@ -20,6 +20,7 @@ */ public class DigitalGlitchFilter implements Sendable, AutoCloseable { /** Configures the Digital Glitch Filter to its default settings. */ + @SuppressWarnings("this-escape") public DigitalGlitchFilter() { m_mutex.lock(); try { diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalInput.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalInput.java index 5b4cf5e8291..ab3d5e5e4c7 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalInput.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalInput.java @@ -27,6 +27,7 @@ public class DigitalInput extends DigitalSource implements Sendable { * * @param channel the DIO channel for the digital input 0-9 are on-board, 10-25 are on the MXP */ + @SuppressWarnings("this-escape") public DigitalInput(int channel) { SensorUtil.checkDigitalChannel(channel); m_channel = channel; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalOutput.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalOutput.java index 78e8bedbe2b..a7446f6068b 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalOutput.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalOutput.java @@ -29,6 +29,7 @@ public class DigitalOutput extends DigitalSource implements Sendable { * @param channel the DIO channel to use for the digital output. 0-9 are on-board, 10-25 are on * the MXP */ + @SuppressWarnings("this-escape") public DigitalOutput(int channel) { SensorUtil.checkDigitalChannel(channel); m_channel = channel; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalSource.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalSource.java index cb8b02475bb..494efe95bf8 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalSource.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DigitalSource.java @@ -11,8 +11,21 @@ * source. The source can either be a digital input or analog trigger but not both. */ public abstract class DigitalSource implements AutoCloseable { + /** Default constructor. */ + public DigitalSource() {} + + /** + * Returns true if this DigitalSource is an AnalogTrigger. + * + * @return True if this DigitalSource is an AnalogTrigger. + */ public abstract boolean isAnalogTrigger(); + /** + * The DigitalSource channel. + * + * @return The DigitalSource channel. + */ public abstract int getChannel(); /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DoubleSolenoid.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DoubleSolenoid.java index d749ccc579f..de0697ccdec 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DoubleSolenoid.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DoubleSolenoid.java @@ -21,8 +21,11 @@ public class DoubleSolenoid implements Sendable, AutoCloseable { /** Possible values for a DoubleSolenoid. */ public enum Value { + /** Off position. */ kOff, + /** Forward position. */ kForward, + /** Reverse position. */ kReverse } @@ -53,7 +56,7 @@ public DoubleSolenoid( * @param forwardChannel The forward channel on the module to control. * @param reverseChannel The reverse channel on the module to control. */ - @SuppressWarnings("PMD.UseTryWithResources") + @SuppressWarnings({"PMD.UseTryWithResources", "this-escape"}) public DoubleSolenoid( final int module, final PneumaticsModuleType moduleType, diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DriverStation.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DriverStation.java index ce3a3e0a6a5..cbe4da8ac30 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DriverStation.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DriverStation.java @@ -29,7 +29,7 @@ /** Provide access to the network communication data to / from the Driver Station. */ public final class DriverStation { - /** Number of Joystick Ports. */ + /** Number of Joystick ports. */ public static final int kJoystickPorts = 6; private static class HALJoystickButtons { @@ -48,6 +48,8 @@ private static class HALJoystickAxes { private static class HALJoystickAxesRaw { public int[] m_axes; + + @SuppressWarnings("unused") public int m_count; HALJoystickAxesRaw(int count) { @@ -69,14 +71,21 @@ private static class HALJoystickPOVs { /** The robot alliance that the robot is a part of. */ public enum Alliance { + /** Red alliance. */ Red, + /** Blue alliance. */ Blue } + /** The type of robot match that the robot is part of. */ public enum MatchType { + /** None. */ None, + /** Practice. */ Practice, + /** Qualification. */ Qualification, + /** Elimination. */ Elimination } @@ -239,6 +248,7 @@ public void send(long timestamp) { for (int i = 0; i < count; i++) { if (axes.m_axes[i] != m_prevAxes.m_axes[i]) { needToLog = true; + break; } } } @@ -255,6 +265,7 @@ public void send(long timestamp) { for (int i = 0; i < count; i++) { if (povs.m_povs[i] != m_prevPOVs.m_povs[i]) { needToLog = true; + break; } } } @@ -1113,7 +1124,7 @@ public static int getReplayNumber() { * *

If the FMS is not connected, it is set from the team alliance setting on the driver station. * - * @return the current alliance + * @return The alliance (red or blue) or an empty optional if the alliance is invalid */ public static Optional getAlliance() { AllianceStationID allianceStationID = DriverStationJNI.getAllianceStation(); @@ -1312,10 +1323,20 @@ public static void refreshData() { } } + /** + * Registers the given handle for DS data refresh notifications. + * + * @param handle The event handle. + */ public static void provideRefreshedDataEventHandle(int handle) { m_refreshEvents.add(handle); } + /** + * Unregisters the given handle from DS data refresh notifications. + * + * @param handle The event handle. + */ public static void removeRefreshedDataEventHandle(int handle) { m_refreshEvents.remove(handle); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DutyCycle.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DutyCycle.java index d500ba7b454..8c26d55b80b 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DutyCycle.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DutyCycle.java @@ -33,6 +33,7 @@ public class DutyCycle implements Sendable, AutoCloseable { * * @param digitalSource The DigitalSource to use. */ + @SuppressWarnings("this-escape") public DutyCycle(DigitalSource digitalSource) { m_handle = DutyCycleJNI.initialize( @@ -102,6 +103,11 @@ public final int getFPGAIndex() { return DutyCycleJNI.getFPGAIndex(m_handle); } + /** + * Get the channel of the source. + * + * @return the source channel + */ public int getSourceChannel() { return m_source.getChannel(); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DutyCycleEncoder.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DutyCycleEncoder.java index afdcb3f3bec..a0858cef922 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/DutyCycleEncoder.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/DutyCycleEncoder.java @@ -30,17 +30,18 @@ public class DutyCycleEncoder implements Sendable, AutoCloseable { private double m_sensorMin; private double m_sensorMax = 1.0; - protected SimDevice m_simDevice; - protected SimDouble m_simPosition; - protected SimDouble m_simAbsolutePosition; - protected SimDouble m_simDistancePerRotation; - protected SimBoolean m_simIsConnected; + private SimDevice m_simDevice; + private SimDouble m_simPosition; + private SimDouble m_simAbsolutePosition; + private SimDouble m_simDistancePerRotation; + private SimBoolean m_simIsConnected; /** * Construct a new DutyCycleEncoder on a specific channel. * * @param channel the channel to attach to */ + @SuppressWarnings("this-escape") public DutyCycleEncoder(int channel) { m_digitalInput = new DigitalInput(channel); m_ownsDutyCycle = true; @@ -53,6 +54,7 @@ public DutyCycleEncoder(int channel) { * * @param dutyCycle the duty cycle to attach to */ + @SuppressWarnings("this-escape") public DutyCycleEncoder(DutyCycle dutyCycle) { m_dutyCycle = dutyCycle; init(); @@ -63,6 +65,7 @@ public DutyCycleEncoder(DutyCycle dutyCycle) { * * @param source the digital source to attach to */ + @SuppressWarnings("this-escape") public DutyCycleEncoder(DigitalSource source) { m_ownsDutyCycle = true; m_dutyCycle = new DutyCycle(source); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Encoder.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Encoder.java index 2cbb5c769c9..0aa667ea1fe 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Encoder.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Encoder.java @@ -29,12 +29,18 @@ * before use. */ public class Encoder implements CounterBase, Sendable, AutoCloseable { + /** Encoder indexing types. */ public enum IndexingType { + /** Reset while the signal is high. */ kResetWhileHigh(0), + /** Reset while the signal is low. */ kResetWhileLow(1), + /** Reset on falling edge of the signal. */ kResetOnFallingEdge(2), + /** Reset on rising edge of the signal. */ kResetOnRisingEdge(3); + /** IndexingType value. */ public final int value; IndexingType(int value) { @@ -122,6 +128,7 @@ public Encoder(final int channelA, final int channelB) { * selected, then a counter object will be used and the returned value will either exactly * match the spec'd count or be double (2x) the spec'd count. */ + @SuppressWarnings("this-escape") public Encoder( final int channelA, final int channelB, @@ -152,6 +159,7 @@ public Encoder( * @param reverseDirection represents the orientation of the encoder and inverts the output values * if necessary so forward represents positive values. */ + @SuppressWarnings("this-escape") public Encoder( final int channelA, final int channelB, final int indexChannel, boolean reverseDirection) { this(channelA, channelB, reverseDirection); @@ -222,6 +230,7 @@ public Encoder(DigitalSource sourceA, DigitalSource sourceB) { * selected then a counter object will be used and the returned value will either exactly * match the spec'd count or be double (2x) the spec'd count. */ + @SuppressWarnings("this-escape") public Encoder( DigitalSource sourceA, DigitalSource sourceB, @@ -492,7 +501,7 @@ public int getSamplesToAverage() { * * @param channel A DIO channel to set as the encoder index */ - public void setIndexSource(int channel) { + public final void setIndexSource(int channel) { setIndexSource(channel, IndexingType.kResetOnRisingEdge); } @@ -502,7 +511,7 @@ public void setIndexSource(int channel) { * * @param source A digital source to set as the encoder index */ - public void setIndexSource(DigitalSource source) { + public final void setIndexSource(DigitalSource source) { setIndexSource(source, IndexingType.kResetOnRisingEdge); } @@ -513,7 +522,7 @@ public void setIndexSource(DigitalSource source) { * @param channel A DIO channel to set as the encoder index * @param type The state that will cause the encoder to reset */ - public void setIndexSource(int channel, IndexingType type) { + public final void setIndexSource(int channel, IndexingType type) { if (m_allocatedI) { throw new AllocationException("Digital Input for Indexing already allocated"); } @@ -530,7 +539,7 @@ public void setIndexSource(int channel, IndexingType type) { * @param source A digital source to set as the encoder index * @param type The state that will cause the encoder to reset */ - public void setIndexSource(DigitalSource source, IndexingType type) { + public final void setIndexSource(DigitalSource source, IndexingType type) { EncoderJNI.setEncoderIndexSource( m_encoder, source.getPortHandleForRouting(), diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/GenericHID.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/GenericHID.java index 58e55f02425..ded73f0226f 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/GenericHID.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/GenericHID.java @@ -19,32 +19,54 @@ * the mapping of ports to hardware buttons depends on the code in the Driver Station. */ public class GenericHID { - /** Represents a rumble output on the JoyStick. */ + /** Represents a rumble output on the Joystick. */ public enum RumbleType { + /** Left rumble motor. */ kLeftRumble, + /** Right rumble motor. */ kRightRumble, + /** Both left and right rumble motors. */ kBothRumble } + /** USB HID interface type. */ public enum HIDType { + /** Unknown. */ kUnknown(-1), + /** XInputUnknown. */ kXInputUnknown(0), + /** XInputGamepad. */ kXInputGamepad(1), + /** XInputWheel. */ kXInputWheel(2), + /** XInputArcadeStick. */ kXInputArcadeStick(3), + /** XInputFlightStick. */ kXInputFlightStick(4), + /** XInputDancePad. */ kXInputDancePad(5), + /** XInputGuitar. */ kXInputGuitar(6), + /** XInputGuitar2. */ kXInputGuitar2(7), + /** XInputDrumKit. */ kXInputDrumKit(8), + /** XInputGuitar3. */ kXInputGuitar3(11), + /** XInputArcadePad. */ kXInputArcadePad(19), + /** HIDJoystick. */ kHIDJoystick(20), + /** HIDGamepad. */ kHIDGamepad(21), + /** HIDDriving. */ kHIDDriving(22), + /** HIDFlight. */ kHIDFlight(23), + /** HID1stPerson. */ kHID1stPerson(24); + /** HIDType value. */ public final int value; @SuppressWarnings("PMD.UseConcurrentHashMap") @@ -60,6 +82,12 @@ public enum HIDType { } } + /** + * Creates an HIDType with the given value. + * + * @param value HIDType's value. + * @return HIDType with the given value. + */ public static HIDType of(int value) { return map.get(value); } @@ -67,8 +95,8 @@ public static HIDType of(int value) { private final int m_port; private int m_outputs; - private short m_leftRumble; - private short m_rightRumble; + private int m_leftRumble; + private int m_rightRumble; /** * Construct an instance of a device. @@ -427,8 +455,7 @@ public void setOutputs(int value) { */ public void setRumble(RumbleType type, double value) { value = MathUtil.clamp(value, 0, 1); - short rumbleValue = (short) (value * 65535); - + int rumbleValue = (int) (value * 65535); switch (type) { case kLeftRumble: this.m_leftRumble = rumbleValue; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/I2C.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/I2C.java index 1c37ecf27a2..1ed131b2c70 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/I2C.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/I2C.java @@ -23,10 +23,14 @@ * WPILib Known Issues page for details. */ public class I2C implements AutoCloseable { + /** I2C connection ports. */ public enum Port { + /** Onboard I2C port. */ kOnboard(0), + /** MXP (roboRIO MXP) I2C port. */ kMXP(1); + /** Port value. */ public final int value; Port(int value) { @@ -58,10 +62,20 @@ public I2C(Port port, int deviceAddress) { HAL.report(tResourceType.kResourceType_I2C, deviceAddress); } + /** + * Returns I2C port. + * + * @return I2C port. + */ public int getPort() { return m_port; } + /** + * Returns I2C device address. + * + * @return I2C device address. + */ public int getDeviceAddress() { return m_deviceAddress; } @@ -369,7 +383,7 @@ public boolean verifySensor(int registerAddress, int count, byte[] expected) { byte[] deviceData = new byte[4]; for (int i = 0; i < count; i += 4) { - int toRead = count - i < 4 ? count - i : 4; + int toRead = Math.min(count - i, 4); // Read the chunk of data. Return false if the sensor does not // respond. dataToSend[0] = (byte) (registerAddress + i); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/IterativeRobotBase.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/IterativeRobotBase.java index 4afece468d9..ee4b34012a3 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/IterativeRobotBase.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/IterativeRobotBase.java @@ -5,6 +5,8 @@ package edu.wpi.first.wpilibj; import edu.wpi.first.hal.DriverStationJNI; +import edu.wpi.first.hal.FRCNetComm.tInstances; +import edu.wpi.first.hal.FRCNetComm.tResourceType; import edu.wpi.first.hal.HAL; import edu.wpi.first.networktables.NetworkTableInstance; import edu.wpi.first.wpilibj.livewindow.LiveWindow; @@ -70,7 +72,7 @@ private enum Mode { private final double m_period; private final Watchdog m_watchdog; private boolean m_ntFlushEnabled = true; - private boolean m_lwEnabledInTest = true; + private boolean m_lwEnabledInTest; private boolean m_calledDsConnected; /** @@ -257,16 +259,22 @@ public void setNetworkTablesFlushEnabled(boolean enabled) { m_ntFlushEnabled = enabled; } + private boolean m_reportedLw; + /** * Sets whether LiveWindow operation is enabled during test mode. Calling * - * @param testLW True to enable, false to disable. Defaults to true. + * @param testLW True to enable, false to disable. Defaults to false. * @throws ConcurrentModificationException if this is called during test mode. */ public void enableLiveWindowInTest(boolean testLW) { if (isTestEnabled()) { throw new ConcurrentModificationException("Can't configure test mode while in test mode!"); } + if (!m_reportedLw && testLW) { + HAL.report(tResourceType.kResourceType_SmartDashboard, tInstances.kSmartDashboard_LiveWindow); + m_reportedLw = true; + } m_lwEnabledInTest = testLW; } @@ -288,6 +296,7 @@ public double getPeriod() { return m_period; } + /** Loop function. */ protected void loopFunc() { DriverStation.refreshData(); m_watchdog.reset(); @@ -399,6 +408,11 @@ protected void loopFunc() { } } + /** Prints list of epochs added so far and their times. */ + public void printWatchdogEpochs() { + m_watchdog.printEpochs(); + } + private void printLoopOverrunMessage() { DriverStation.reportWarning("Loop time of " + m_period + "s overrun\n", false); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Joystick.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Joystick.java index d73b7bbc258..5536009e320 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Joystick.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Joystick.java @@ -17,20 +17,35 @@ * and the mapping of ports to hardware buttons depends on the code in the Driver Station. */ public class Joystick extends GenericHID { + /** Default X axis channel. */ public static final byte kDefaultXChannel = 0; + + /** Default Y axis channel. */ public static final byte kDefaultYChannel = 1; + + /** Default Z axis channel. */ public static final byte kDefaultZChannel = 2; + + /** Default twist axis channel. */ public static final byte kDefaultTwistChannel = 2; + + /** Default throttle axis channel. */ public static final byte kDefaultThrottleChannel = 3; /** Represents an analog axis on a joystick. */ public enum AxisType { + /** X axis. */ kX(0), + /** Y axis. */ kY(1), + /** Z axis. */ kZ(2), + /** Twist axis. */ kTwist(3), + /** Throttle axis. */ kThrottle(4); + /** AxisType value. */ public final int value; AxisType(int value) { @@ -40,9 +55,12 @@ public enum AxisType { /** Represents a digital button on a joystick. */ public enum ButtonType { + /** kTrigger. */ kTrigger(1), + /** kTop. */ kTop(2); + /** ButtonType value. */ public final int value; ButtonType(int value) { @@ -184,7 +202,7 @@ public final double getY() { * * @return the z position */ - public double getZ() { + public final double getZ() { return getRawAxis(m_axes[AxisType.kZ.value]); } @@ -194,7 +212,7 @@ public double getZ() { * * @return The Twist value of the joystick. */ - public double getTwist() { + public final double getTwist() { return getRawAxis(m_axes[AxisType.kTwist.value]); } @@ -204,7 +222,7 @@ public double getTwist() { * * @return The Throttle value of the joystick. */ - public double getThrottle() { + public final double getThrottle() { return getRawAxis(m_axes[AxisType.kThrottle.value]); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/MotorSafety.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/MotorSafety.java index c1bf04b8911..dc969a9c96f 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/MotorSafety.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/MotorSafety.java @@ -62,11 +62,12 @@ private static void threadMain() { } /** MotorSafety constructor. */ + @SuppressWarnings("this-escape") public MotorSafety() { synchronized (m_listMutex) { m_instanceList.add(this); if (m_safetyThread == null) { - m_safetyThread = new Thread(() -> threadMain(), "MotorSafety Thread"); + m_safetyThread = new Thread(MotorSafety::threadMain, "MotorSafety Thread"); m_safetyThread.setDaemon(true); m_safetyThread.start(); } @@ -185,7 +186,13 @@ public static void checkMotors() { } } + /** Called to stop the motor when the timeout expires. */ public abstract void stopMotor(); + /** + * Returns a description to print when an error occurs. + * + * @return Description to print when an error occurs. + */ public abstract String getDescription(); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Notifier.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Notifier.java index 7ed61621d5a..1529af5bc69 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Notifier.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Notifier.java @@ -113,7 +113,7 @@ public Notifier(Runnable callback) { updateAlarm(); } else { // Need to update the alarm to cause it to wait again - updateAlarm((long) -1); + updateAlarm(-1); } } finally { m_processLock.unlock(); @@ -134,7 +134,7 @@ public Notifier(Runnable callback) { error = cause; } DriverStation.reportError( - "Unhandled exception in Notifier thread: " + error.toString(), error.getStackTrace()); + "Unhandled exception in Notifier thread: " + error, error.getStackTrace()); DriverStation.reportError( "The Runnable for this Notifier (or methods called by it) should have handled " + "the exception above.\n" @@ -155,22 +155,6 @@ public void setName(String name) { NotifierJNI.setNotifierName(m_notifier.get(), name); } - /** - * Change the callback function. - * - * @param callback The callback function. - * @deprecated Use setCallback() instead. - */ - @Deprecated(forRemoval = true, since = "2024") - public void setHandler(Runnable callback) { - m_processLock.lock(); - try { - m_callback = callback; - } finally { - m_processLock.unlock(); - } - } - /** * Change the callback function. * diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PS4Controller.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PS4Controller.java index 2359b7b8308..e000c6f51d3 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PS4Controller.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PS4Controller.java @@ -4,6 +4,8 @@ package edu.wpi.first.wpilibj; +import edu.wpi.first.hal.FRCNetComm.tResourceType; +import edu.wpi.first.hal.HAL; import edu.wpi.first.wpilibj.event.BooleanEvent; import edu.wpi.first.wpilibj.event.EventLoop; @@ -13,6 +15,10 @@ *

This class handles PS4 input that comes from the Driver Station. Each time a value is * requested the most recent value is returned. There is a single class instance for each controller * and the mapping of ports to hardware buttons depends on the code in the Driver Station. + * + *

Only first party controllers from Sony are guaranteed to have the correct mapping, and only + * through the official NI DS. Sim is not guaranteed to have the same mapping, as well as any 3rd + * party controllers. */ public class PS4Controller extends GenericHID { /** @@ -23,27 +29,41 @@ public class PS4Controller extends GenericHID { public PS4Controller(int port) { super(port); - // re-enable when PS4Controller is added to Usage Reporting - // HAL.report(tResourceType.kResourceType_PS4Controller, port + 1); / + HAL.report(tResourceType.kResourceType_PS4Controller, port + 1); } /** Represents a digital button on a PS4Controller. */ public enum Button { + /** Square button. */ kSquare(1), + /** X button. */ kCross(2), + /** Circle button. */ kCircle(3), + /** Triangle button. */ kTriangle(4), + /** Left Trigger 1 button. */ kL1(5), + /** Right Trigger 1 button. */ kR1(6), + /** Left Trigger 2 button. */ kL2(7), + /** Right Trigger 2 button. */ kR2(8), + /** Share button. */ kShare(9), + /** Option button. */ kOptions(10), + /** Left stick button. */ kL3(11), + /** Right stick button. */ kR3(12), + /** PlayStation button. */ kPS(13), + /** Touchpad click button. */ kTouchpad(14); + /** Button value. */ public final int value; Button(int index) { @@ -70,13 +90,20 @@ public String toString() { /** Represents an axis on a PS4Controller. */ public enum Axis { + /** Left X axis. */ kLeftX(0), + /** Left Y axis. */ kLeftY(1), + /** Right X axis. */ kRightX(2), + /** Right Y axis. */ kRightY(5), + /** Left Trigger 2. */ kL2(3), + /** Right Trigger 2. */ kR2(4); + /** Axis value. */ public final int value; Axis(int index) { diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PS5Controller.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PS5Controller.java index 8af98a52295..18cb738e883 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PS5Controller.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PS5Controller.java @@ -13,6 +13,10 @@ *

This class handles PS5 input that comes from the Driver Station. Each time a value is * requested the most recent value is returned. There is a single class instance for each controller * and the mapping of ports to hardware buttons depends on the code in the Driver Station. + * + *

Only first party controllers from Sony are guaranteed to have the correct mapping, and only + * through the official NI DS. Sim is not guaranteed to have the same mapping, as well as any 3rd + * party controllers. */ public class PS5Controller extends GenericHID { /** @@ -27,21 +31,36 @@ public PS5Controller(int port) { /** Represents a digital button on a PS5Controller. */ public enum Button { - kCross(1), - kCircle(2), - kSquare(3), + /** Square button. */ + kSquare(1), + /** X button. */ + kCross(2), + /** Circle button. */ + kCircle(3), + /** Triangle button. */ kTriangle(4), + /** Left trigger 1 button. */ kL1(5), + /** Right trigger 1 button. */ kR1(6), + /** Left trigger 2 button. */ kL2(7), + /** Right trigger 2 button. */ kR2(8), + /** Create button. */ kCreate(9), + /** Options button. */ kOptions(10), - kPS(11), - kL3(12), - kR3(13), + /** Left stick button. */ + kL3(11), + /** Right stick button. */ + kR3(12), + /** PlayStation button. */ + kPS(13), + /** Touchpad click button. */ kTouchpad(14); + /** Button value. */ public final int value; Button(int index) { @@ -68,13 +87,20 @@ public String toString() { /** Represents an axis on a PS5Controller. */ public enum Axis { + /** Left X axis. */ kLeftX(0), + /** Left Y axis. */ kLeftY(1), - kL2(2), - kRightX(3), - kRightY(4), - kR2(5); - + /** Right X axis. */ + kRightX(2), + /** Right Y axis. */ + kRightY(5), + /** Left Trigger 2. */ + kL2(3), + /** Right Trigger 2. */ + kR2(4); + + /** Axis value. */ public final int value; Axis(int index) { diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PWM.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PWM.java index b0b3810c9de..af600eca0a6 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PWM.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PWM.java @@ -54,6 +54,7 @@ public PWM(final int channel) { * @param channel The PWM channel number. 0-9 are on-board, 10-19 are on the MXP port * @param registerSendable If true, adds this instance to SendableRegistry and LiveWindow */ + @SuppressWarnings("this-escape") public PWM(final int channel, final boolean registerSendable) { SensorUtil.checkPWMChannel(channel); m_channel = channel; @@ -200,7 +201,7 @@ public int getPulseTimeMicroseconds() { } /** Temporarily disables the PWM output. The next set call will re-enable the output. */ - public void setDisabled() { + public final void setDisabled() { PWMJNI.setPWMDisabled(m_handle); } @@ -228,6 +229,7 @@ public void setPeriodMultiplier(PeriodMultiplier mult) { } } + /** Latches PWM to zero. */ public void setZeroLatch() { PWMJNI.latchPWMZero(m_handle); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticHub.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticHub.java index b7df47f0f34..32d2ec5aee2 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticHub.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticHub.java @@ -59,8 +59,7 @@ private static class DataStore implements AutoCloseable { output.write(("currentVersion=" + fwVersion).getBytes(StandardCharsets.UTF_8)); } } catch (IOException ex) { - DriverStation.reportError( - "Could not write " + fileName + ": " + ex.toString(), ex.getStackTrace()); + DriverStation.reportError("Could not write " + fileName + ": " + ex, ex.getStackTrace()); } } @@ -115,14 +114,12 @@ private static void freeModule(DataStore store) { /** Converts volts to PSI per the REV Analog Pressure Sensor datasheet. */ private static double voltsToPsi(double sensorVoltage, double supplyVoltage) { - double pressure = 250 * (sensorVoltage / supplyVoltage) - 25; - return pressure; + return 250 * (sensorVoltage / supplyVoltage) - 25; } /** Converts PSI to volts per the REV Analog Pressure Sensor datasheet. */ private static double psiToVolts(double pressure, double supplyVoltage) { - double voltage = supplyVoltage * (0.004 * pressure + 0.1); - return voltage; + return supplyVoltage * (0.004 * pressure + 0.1); } private final DataStore m_dataStore; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsBase.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsBase.java index d9b493b47cb..90f49f53b44 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsBase.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsBase.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj; +/** Interface for pneumatics devices. */ public interface PneumaticsBase extends AutoCloseable { /** * For internal use to get a module for a specific type. diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsControlModule.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsControlModule.java index aac16a37c0f..4f1d70c5161 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsControlModule.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsControlModule.java @@ -186,10 +186,23 @@ public int getSolenoidDisabledList() { return CTREPCMJNI.getSolenoidDisabledList(m_handle); } + /** + * Returns whether the solenoid is currently reporting a voltage fault. + * + * @return True if solenoid is reporting a fault, otherwise false. + * @see #getSolenoidVoltageStickyFault() + */ public boolean getSolenoidVoltageFault() { return CTREPCMJNI.getSolenoidVoltageFault(m_handle); } + /** + * Returns whether the solenoid has reported a voltage fault since sticky faults were last + * cleared. This fault is persistent and can be cleared by ClearAllStickyFaults() + * + * @return True if solenoid is reporting a fault, otherwise false. + * @see #getSolenoidVoltageFault() + */ public boolean getSolenoidVoltageStickyFault() { return CTREPCMJNI.getSolenoidVoltageStickyFault(m_handle); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsModuleType.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsModuleType.java index a7951e8b5c1..e1525c39e21 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsModuleType.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PneumaticsModuleType.java @@ -4,7 +4,10 @@ package edu.wpi.first.wpilibj; +/** Pneumatics module type. */ public enum PneumaticsModuleType { + /** CTRE PCM. */ CTREPCM, - REVPH; + /** REV PH. */ + REVPH } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PowerDistribution.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PowerDistribution.java index a0c21042ca9..9aa1b7c743d 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/PowerDistribution.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/PowerDistribution.java @@ -22,12 +22,17 @@ public class PowerDistribution implements Sendable, AutoCloseable { private final int m_handle; private final int m_module; + /** Default module number. */ public static final int kDefaultModule = PowerDistributionJNI.DEFAULT_MODULE; + /** Power distribution module type. */ public enum ModuleType { + /** CTRE (Cross The Road Electronics) CTRE Power Distribution Panel (PDP). */ kCTRE(PowerDistributionJNI.CTRE_TYPE), + /** REV Power Distribution Hub (PDH). */ kRev(PowerDistributionJNI.REV_TYPE); + /** ModuleType value. */ public final int value; ModuleType(int value) { @@ -41,6 +46,7 @@ public enum ModuleType { * @param module The CAN ID of the PDP/PDH. * @param moduleType Module type (CTRE or REV). */ + @SuppressWarnings("this-escape") public PowerDistribution(int module, ModuleType moduleType) { m_handle = PowerDistributionJNI.initialize(module, moduleType.value); m_module = PowerDistributionJNI.getModuleNumber(m_handle); @@ -54,6 +60,7 @@ public PowerDistribution(int module, ModuleType moduleType) { * *

Detects the connected PDP/PDH using the default CAN ID (0 for CTRE and 1 for REV). */ + @SuppressWarnings("this-escape") public PowerDistribution() { m_handle = PowerDistributionJNI.initialize(kDefaultModule, PowerDistributionJNI.AUTOMATIC_TYPE); m_module = PowerDistributionJNI.getModuleNumber(m_handle); @@ -86,7 +93,9 @@ public double getVoltage() { } /** - * Query the temperature of the PDP/PDH. + * Query the temperature of the PDP. + * + *

Not supported on the Rev PDH and returns 0. * * @return The temperature in degrees Celsius */ @@ -101,9 +110,7 @@ public double getTemperature() { * @return The current of the channel in Amperes */ public double getCurrent(int channel) { - double current = PowerDistributionJNI.getChannelCurrent(m_handle, channel); - - return current; + return PowerDistributionJNI.getChannelCurrent(m_handle, channel); } /** @@ -116,7 +123,9 @@ public double getTotalCurrent() { } /** - * Query the total power drawn from the monitored channels. + * Query the total power drawn from the monitored channels of the PDP. + * + *

Not supported on the Rev PDH and returns 0. * * @return the total power in Watts */ @@ -125,7 +134,9 @@ public double getTotalPower() { } /** - * Query the total energy drawn from the monitored channels. + * Query the total energy drawn from the monitored channels of the PDP. + * + *

Not supported on the Rev PDH and returns 0. * * @return the total energy in Joules */ @@ -133,7 +144,11 @@ public double getTotalEnergy() { return PowerDistributionJNI.getTotalEnergy(m_handle); } - /** Reset the total energy to 0. */ + /** + * Reset the total energy to 0 of the PDP. + * + *

Not supported on the Rev PDH and does nothing. + */ public void resetTotalEnergy() { PowerDistributionJNI.resetTotalEnergy(m_handle); } @@ -184,14 +199,29 @@ public void setSwitchableChannel(boolean enabled) { PowerDistributionJNI.setSwitchableChannel(m_handle, enabled); } + /** + * Returns the power distribution version number. + * + * @return The power distribution version number. + */ public PowerDistributionVersion getVersion() { return PowerDistributionJNI.getVersion(m_handle); } + /** + * Returns the power distribution faults. + * + * @return The power distribution faults. + */ public PowerDistributionFaults getFaults() { return PowerDistributionJNI.getFaults(m_handle); } + /** + * Returns the power distribution sticky faults. + * + * @return The power distribution sticky faults. + */ public PowerDistributionStickyFaults getStickyFaults() { return PowerDistributionJNI.getStickyFaults(m_handle); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Preferences.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Preferences.java index 087c1566026..69d0fb32e75 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Preferences.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Preferences.java @@ -230,7 +230,7 @@ public static void initBoolean(String key, boolean value) { */ public static void setLong(String key, long value) { NetworkTableEntry entry = m_table.getEntry(key); - entry.setDouble(value); + entry.setInteger(value); entry.setPersistent(); } @@ -242,7 +242,7 @@ public static void setLong(String key, long value) { */ public static void initLong(String key, long value) { NetworkTableEntry entry = m_table.getEntry(key); - entry.setDefaultDouble(value); + entry.setDefaultInteger(value); entry.setPersistent(); } @@ -345,6 +345,6 @@ public static float getFloat(String key, float backup) { * @return either the value in the table, or the backup */ public static long getLong(String key, long backup) { - return (long) m_table.getEntry(key).getDouble(backup); + return m_table.getEntry(key).getInteger(backup); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Relay.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Relay.java index a2a58d3e538..dce3096cc85 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Relay.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Relay.java @@ -44,9 +44,13 @@ public InvalidValueException(String message) { /** The state to drive a Relay to. */ public enum Value { + /** Off. */ kOff("Off"), + /** On. */ kOn("On"), + /** Forward. */ kForward("Forward"), + /** Reverse. */ kReverse("Reverse"); private final String m_prettyValue; @@ -55,10 +59,21 @@ public enum Value { m_prettyValue = prettyValue; } + /** + * Returns the pretty string representation of the value. + * + * @return The pretty string representation of the value. + */ public String getPrettyValue() { return m_prettyValue; } + /** + * Returns the value for a given pretty string. + * + * @param value The pretty string. + * @return The value or an empty optional if there is no corresponding value. + */ public static Optional getValueOf(String value) { return Arrays.stream(Value.values()).filter(v -> v.m_prettyValue.equals(value)).findFirst(); } @@ -66,11 +81,11 @@ public static Optional getValueOf(String value) { /** The Direction(s) that a relay is configured to operate in. */ public enum Direction { - /** direction: both directions are valid. */ + /** Both directions are valid. */ kBoth, - /** direction: Only forward is valid. */ + /** Only forward is valid. */ kForward, - /** direction: only reverse is valid. */ + /** Only reverse is valid. */ kReverse } @@ -110,6 +125,7 @@ private void initRelay() { * @param channel The channel number for this relay (0 - 3). * @param direction The direction that the Relay object will control. */ + @SuppressWarnings("this-escape") public Relay(final int channel, Direction direction) { m_channel = channel; m_direction = requireNonNullParam(direction, "direction", "Relay"); @@ -279,6 +295,7 @@ public String getDescription() { * * @param direction The direction for the relay to operate in */ + @SuppressWarnings("this-escape") public void setDirection(Direction direction) { requireNonNullParam(direction, "direction", "setDirection"); if (m_direction == direction) { diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotBase.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotBase.java index 2f59a3db7c2..3c3035ce139 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotBase.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotBase.java @@ -6,7 +6,6 @@ import edu.wpi.first.cameraserver.CameraServerShared; import edu.wpi.first.cameraserver.CameraServerSharedStore; -import edu.wpi.first.cscore.CameraServerJNI; import edu.wpi.first.hal.FRCNetComm.tInstances; import edu.wpi.first.hal.FRCNetComm.tResourceType; import edu.wpi.first.hal.HAL; @@ -178,6 +177,11 @@ protected RobotBase() { Shuffleboard.disableActuatorWidgets(); } + /** + * Returns the main thread ID. + * + * @return The main thread ID. + */ public static long getMainThreadId() { return m_threadId; } @@ -321,8 +325,7 @@ private static void runRobot(Supplier robotSupplier) { robotName = elements[0].getClassName(); } DriverStation.reportError( - "Unhandled exception instantiating robot " + robotName + " " + throwable.toString(), - elements); + "Unhandled exception instantiating robot " + robotName + " " + throwable, elements); DriverStation.reportError( "The robot program quit unexpectedly." + " This is usually due to a code error.\n" @@ -353,8 +356,7 @@ private static void runRobot(Supplier robotSupplier) { output.write(WPILibVersion.Version.getBytes(StandardCharsets.UTF_8)); } } catch (IOException ex) { - DriverStation.reportError( - "Could not write FRC_Lib_Version.ini: " + ex.toString(), ex.getStackTrace()); + DriverStation.reportError("Could not write FRC_Lib_Version.ini: " + ex, ex.getStackTrace()); } } @@ -366,8 +368,7 @@ private static void runRobot(Supplier robotSupplier) { if (cause != null) { throwable = cause; } - DriverStation.reportError( - "Unhandled exception: " + throwable.toString(), throwable.getStackTrace()); + DriverStation.reportError("Unhandled exception: " + throwable, throwable.getStackTrace()); errorOnExit = true; } finally { m_runMutex.lock(); @@ -418,10 +419,6 @@ public static void startRobot(Supplier robotSupplier) { // Force refresh DS data DriverStation.refreshData(); - // Call a CameraServer JNI function to force OpenCV native library loading - // Needed because all the OpenCV JNI functions don't have built in loading - CameraServerJNI.enumerateSinks(); - HAL.report( tResourceType.kResourceType_Language, tInstances.kLanguage_Java, 0, WPILibVersion.Version); @@ -456,6 +453,11 @@ public static void startRobot(Supplier robotSupplier) { runRobot(robotSupplier); } + // On RIO, this will just terminate rather than shutting down cleanly (it's a no-op in sim). + // It's not worth the risk of hanging on shutdown when we want the code to restart as quickly + // as possible. + HAL.terminate(); + HAL.shutdown(); System.exit(0); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotController.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotController.java index 29bcad87bd0..d8faafa6d37 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotController.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotController.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.HAL; import edu.wpi.first.hal.HALUtil; +import edu.wpi.first.hal.LEDJNI; import edu.wpi.first.hal.PowerJNI; import edu.wpi.first.hal.can.CANJNI; import edu.wpi.first.hal.can.CANStatus; @@ -33,7 +34,7 @@ public static int getFPGAVersion() { * @return FPGA Revision number. */ public static long getFPGARevision() { - return (long) HALUtil.getFPGARevision(); + return HALUtil.getFPGARevision(); } /** @@ -78,6 +79,10 @@ public static long getFPGATime() { /** * Get the state of the "USER" button on the roboRIO. * + *

Warning: the User Button is used to stop user programs from automatically loading if it is + * held for more then 5 seconds. Because of this, it's not recommended to be used by teams for any + * other purpose. + * * @return true if the button is currently pressed down */ public static boolean getUserButton() { @@ -315,6 +320,66 @@ public static double getCPUTemp() { return PowerJNI.getCPUTemp(); } + /** State for the radio led. */ + public enum RadioLEDState { + /** Off. */ + kOff(LEDJNI.RADIO_LED_STATE_OFF), + /** Green. */ + kGreen(LEDJNI.RADIO_LED_STATE_GREEN), + /** Red. */ + kRed(LEDJNI.RADIO_LED_STATE_RED), + /** Orange. */ + kOrange(LEDJNI.RADIO_LED_STATE_ORANGE); + + /** The native value for this state. */ + public final int value; + + RadioLEDState(int value) { + this.value = value; + } + + /** + * Gets a state from an int value. + * + * @param value int value + * @return state + */ + public static RadioLEDState fromValue(int value) { + switch (value) { + case LEDJNI.RADIO_LED_STATE_OFF: + return RadioLEDState.kOff; + case LEDJNI.RADIO_LED_STATE_GREEN: + return RadioLEDState.kGreen; + case LEDJNI.RADIO_LED_STATE_RED: + return RadioLEDState.kRed; + case LEDJNI.RADIO_LED_STATE_ORANGE: + return RadioLEDState.kOrange; + default: + return RadioLEDState.kOff; + } + } + } + + /** + * Set the state of the "Radio" LED. On the RoboRIO, this writes to sysfs, so this function should + * not be called multiple times per loop cycle to avoid overruns. + * + * @param state The state to set the LED to. + */ + public static void setRadioLEDState(RadioLEDState state) { + LEDJNI.setRadioLEDState(state.value); + } + + /** + * Get the state of the "Radio" LED. On the RoboRIO, this reads from sysfs, so this function + * should not be called multiple times per loop cycle to avoid overruns. + * + * @return The state of the LED. + */ + public static RadioLEDState getRadioLEDState() { + return RadioLEDState.fromValue(LEDJNI.getRadioLEDState()); + } + /** * Get the current status of the CAN bus. * diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotState.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotState.java index 44198df1a1f..405dfc4bc3f 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotState.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/RobotState.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj; +/** Robot state utility functions. */ public final class RobotState { /** * Returns true if the robot is disabled. diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/RuntimeType.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/RuntimeType.java index e7af118bfdd..cad1c51b836 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/RuntimeType.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/RuntimeType.java @@ -6,11 +6,16 @@ import edu.wpi.first.hal.HALUtil; +/** Runtime type. */ public enum RuntimeType { + /** roboRIO 1.0. */ kRoboRIO(HALUtil.RUNTIME_ROBORIO), + /** roboRIO 2.0. */ kRoboRIO2(HALUtil.RUNTIME_ROBORIO2), + /** Simulation runtime. */ kSimulation(HALUtil.RUNTIME_SIMULATION); + /** RuntimeType value. */ public final int value; RuntimeType(int value) { diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/SPI.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/SPI.java index 632770c80d5..1a3bb345a0f 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/SPI.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/SPI.java @@ -14,13 +14,20 @@ /** Represents an SPI bus port. */ public class SPI implements AutoCloseable { + /** SPI port. */ public enum Port { + /** Onboard SPI bus port CS0. */ kOnboardCS0(SPIJNI.ONBOARD_CS0_PORT), + /** Onboard SPI bus port CS1. */ kOnboardCS1(SPIJNI.ONBOARD_CS1_PORT), + /** Onboard SPI bus port CS2. */ kOnboardCS2(SPIJNI.ONBOARD_CS2_PORT), + /** Onboard SPI bus port CS3. */ kOnboardCS3(SPIJNI.ONBOARD_CS3_PORT), + /** MXP (roboRIO MXP) SPI bus port. */ kMXP(SPIJNI.MXP_PORT); + /** SPI port value. */ public final int value; Port(int value) { @@ -28,6 +35,7 @@ public enum Port { } } + /** SPI mode. */ public enum Mode { /** Clock idle low, data sampled on rising edge. */ kMode0(SPIJNI.SPI_MODE0), @@ -38,6 +46,7 @@ public enum Mode { /** Clock idle high, data sampled on rising edge. */ kMode3(SPIJNI.SPI_MODE3); + /** SPI mode value. */ public final int value; Mode(int value) { @@ -64,6 +73,11 @@ public SPI(Port port) { HAL.report(tResourceType.kResourceType_SPI, port.value + 1); } + /** + * Returns the SPI port value. + * + * @return SPI port value. + */ public int getPort() { return m_port; } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/SensorUtil.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/SensorUtil.java index bcedd81fea7..258fbc7c606 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/SensorUtil.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/SensorUtil.java @@ -47,8 +47,10 @@ public final class SensorUtil { /** Number of PCM Modules. */ public static final int kCTREPCMModules = PortsJNI.getNumCTREPCMModules(); + /** Number of power distribution channels per PH. */ public static final int kREVPHChannels = PortsJNI.getNumREVPHChannels(); + /** Number of PH modules. */ public static final int kREVPHModules = PortsJNI.getNumREVPHModules(); /** @@ -59,12 +61,12 @@ public final class SensorUtil { */ public static void checkDigitalChannel(final int channel) { if (!DIOJNI.checkDIOChannel(channel)) { - StringBuilder buf = new StringBuilder(); - buf.append("Requested DIO channel is out of range. Minimum: 0, Maximum: ") - .append(kDigitalChannels) - .append(", Requested: ") - .append(channel); - throw new IllegalArgumentException(buf.toString()); + String buf = + "Requested DIO channel is out of range. Minimum: 0, Maximum: " + + kDigitalChannels + + ", Requested: " + + channel; + throw new IllegalArgumentException(buf); } } @@ -76,12 +78,12 @@ public static void checkDigitalChannel(final int channel) { */ public static void checkRelayChannel(final int channel) { if (!RelayJNI.checkRelayChannel(channel)) { - StringBuilder buf = new StringBuilder(); - buf.append("Requested relay channel is out of range. Minimum: 0, Maximum: ") - .append(kRelayChannels) - .append(", Requested: ") - .append(channel); - throw new IllegalArgumentException(buf.toString()); + String buf = + "Requested relay channel is out of range. Minimum: 0, Maximum: " + + kRelayChannels + + ", Requested: " + + channel; + throw new IllegalArgumentException(buf); } } @@ -93,12 +95,12 @@ public static void checkRelayChannel(final int channel) { */ public static void checkPWMChannel(final int channel) { if (!PWMJNI.checkPWMChannel(channel)) { - StringBuilder buf = new StringBuilder(); - buf.append("Requested PWM channel is out of range. Minimum: 0, Maximum: ") - .append(kPwmChannels) - .append(", Requested: ") - .append(channel); - throw new IllegalArgumentException(buf.toString()); + String buf = + "Requested PWM channel is out of range. Minimum: 0, Maximum: " + + kPwmChannels + + ", Requested: " + + channel; + throw new IllegalArgumentException(buf); } } @@ -110,12 +112,12 @@ public static void checkPWMChannel(final int channel) { */ public static void checkAnalogInputChannel(final int channel) { if (!AnalogJNI.checkAnalogInputChannel(channel)) { - StringBuilder buf = new StringBuilder(); - buf.append("Requested analog input channel is out of range. Minimum: 0, Maximum: ") - .append(kAnalogInputChannels) - .append(", Requested: ") - .append(channel); - throw new IllegalArgumentException(buf.toString()); + String buf = + "Requested analog input channel is out of range. Minimum: 0, Maximum: " + + kAnalogInputChannels + + ", Requested: " + + channel; + throw new IllegalArgumentException(buf); } } @@ -127,12 +129,12 @@ public static void checkAnalogInputChannel(final int channel) { */ public static void checkAnalogOutputChannel(final int channel) { if (!AnalogJNI.checkAnalogOutputChannel(channel)) { - StringBuilder buf = new StringBuilder(); - buf.append("Requested analog output channel is out of range. Minimum: 0, Maximum: ") - .append(kAnalogOutputChannels) - .append(", Requested: ") - .append(channel); - throw new IllegalArgumentException(buf.toString()); + String buf = + "Requested analog output channel is out of range. Minimum: 0, Maximum: " + + kAnalogOutputChannels + + ", Requested: " + + channel; + throw new IllegalArgumentException(buf); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/SerialPort.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/SerialPort.java index 1a05c8af4da..d978d783daf 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/SerialPort.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/SerialPort.java @@ -13,13 +13,20 @@ public class SerialPort implements AutoCloseable { private int m_portHandle; + /** Serial port. */ public enum Port { + /** Onboard serial port on the roboRIO. */ kOnboard(0), + /** MXP (roboRIO MXP) serial port. */ kMXP(1), + /** USB serial port (same as KUSB1). */ kUSB(2), + /** USB serial port 1. */ kUSB1(2), + /** USB serial port 2. */ kUSB2(3); + /** Port value. */ public final int value; Port(int value) { @@ -29,12 +36,18 @@ public enum Port { /** Represents the parity to use for serial communications. */ public enum Parity { + /** No parity. */ kNone(0), + /** Odd parity. */ kOdd(1), + /** Even parity. */ kEven(2), + /** Parity bit always on. */ kMark(3), + /** Parity bit always off. */ kSpace(4); + /** Parity value. */ public final int value; Parity(int value) { @@ -44,10 +57,14 @@ public enum Parity { /** Represents the number of stop bits to use for Serial Communication. */ public enum StopBits { + /** One stop bit. */ kOne(10), + /** One and a half stop bits. */ kOnePointFive(15), + /** Two stop bits. */ kTwo(20); + /** StopBits value. */ public final int value; StopBits(int value) { @@ -57,11 +74,16 @@ public enum StopBits { /** Represents what type of flow control to use for serial communication. */ public enum FlowControl { + /** No flow control. */ kNone(0), + /** XON/XOFF flow control. */ kXonXoff(1), + /** RTS/CTS flow control. */ kRtsCts(2), + /** DTS/DSR flow control. */ kDtsDsr(4); + /** FlowControl value. */ public final int value; FlowControl(int value) { @@ -71,9 +93,12 @@ public enum FlowControl { /** Represents which type of buffer mode to use when writing to a serial port. */ public enum WriteBufferMode { + /** Flush the buffer on each access. */ kFlushOnAccess(1), + /** Flush the buffer when it is full. */ kFlushWhenFull(2); + /** WriteBufferMode value. */ public final int value; WriteBufferMode(int value) { @@ -186,7 +211,7 @@ public void enableTermination() { } /** Disable termination behavior. */ - public void disableTermination() { + public final void disableTermination() { SerialPortJNI.serialDisableTermination(m_portHandle); } @@ -216,7 +241,7 @@ public String readString() { */ public String readString(int count) { byte[] out = read(count); - return new String(out, 0, out.length, StandardCharsets.US_ASCII); + return new String(out, StandardCharsets.US_ASCII); } /** @@ -268,7 +293,7 @@ public int writeString(String data) { * * @param timeout The number of seconds to wait for I/O. */ - public void setTimeout(double timeout) { + public final void setTimeout(double timeout) { SerialPortJNI.serialSetTimeout(m_portHandle, timeout); } @@ -283,7 +308,7 @@ public void setTimeout(double timeout) { * * @param size The read buffer size. */ - public void setReadBufferSize(int size) { + public final void setReadBufferSize(int size) { SerialPortJNI.serialSetReadBufferSize(m_portHandle, size); } @@ -309,7 +334,7 @@ public void setWriteBufferSize(int size) { * * @param mode The write buffer mode. */ - public void setWriteBufferMode(WriteBufferMode mode) { + public final void setWriteBufferMode(WriteBufferMode mode) { SerialPortJNI.serialSetWriteMode(m_portHandle, (byte) mode.value); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Servo.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Servo.java index 1f1c7475657..6ba3ed7d57a 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Servo.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Servo.java @@ -19,18 +19,19 @@ public class Servo extends PWM { private static final double kMaxServoAngle = 180.0; private static final double kMinServoAngle = 0.0; - protected static final int kDefaultMaxServoPWM = 2400; - protected static final int kDefaultMinServoPWM = 600; + private static final int kDefaultMaxServoPWM = 2400; + private static final int kDefaultMinServoPWM = 600; /** - * Constructor.
+ * Constructor. * - *

By default {@value #kDefaultMaxServoPWM} ms is used as the maxPWM value
- * By default {@value #kDefaultMinServoPWM} ms is used as the minPWM value
+ *

By default, {@value #kDefaultMaxServoPWM} ms is used as the max PWM value and {@value + * #kDefaultMinServoPWM} ms is used as the minPWM value. * * @param channel The PWM channel to which the servo is attached. 0-9 are on-board, 10-19 are on * the MXP port */ + @SuppressWarnings("this-escape") public Servo(final int channel) { super(channel); setBoundsMicroseconds(kDefaultMaxServoPWM, 0, 0, 0, kDefaultMinServoPWM); @@ -83,7 +84,7 @@ public void setAngle(double degrees) { degrees = kMaxServoAngle; } - setPosition(((degrees - kMinServoAngle)) / getServoAngleRange()); + setPosition((degrees - kMinServoAngle) / getServoAngleRange()); } /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Solenoid.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Solenoid.java index be87444ae57..9c516da72f2 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Solenoid.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Solenoid.java @@ -39,6 +39,7 @@ public Solenoid(final PneumaticsModuleType moduleType, final int channel) { * @param moduleType The module type to use. * @param channel The channel the solenoid is on. */ + @SuppressWarnings("this-escape") public Solenoid(final int module, final PneumaticsModuleType moduleType, final int channel) { m_module = PneumaticsBase.getForType(module, moduleType); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/StadiaController.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/StadiaController.java new file mode 100644 index 00000000000..d092d8b9375 --- /dev/null +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/StadiaController.java @@ -0,0 +1,737 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.wpilibj; + +// import edu.wpi.first.hal.FRCNetComm.tResourceType; +// import edu.wpi.first.hal.HAL; +import edu.wpi.first.wpilibj.event.BooleanEvent; +import edu.wpi.first.wpilibj.event.EventLoop; + +/** + * Handle input from Stadia controllers connected to the Driver Station. + * + *

This class handles Stadia input that comes from the Driver Station. Each time a value is + * requested the most recent value is returned. There is a single class instance for each controller + * and the mapping of ports to hardware buttons depends on the code in the Driver Station. + */ +public class StadiaController extends GenericHID { + /** Represents a digital button on a StadiaController. */ + public enum Button { + /** A button. */ + kA(1), + /** B button. */ + kB(2), + /** X Button. */ + kX(3), + /** Y Button. */ + kY(4), + /** Left bumper button. */ + kLeftBumper(5), + /** Right bumper button. */ + kRightBumper(6), + /** Left stick button. */ + kLeftStick(7), + /** Right stick button. */ + kRightStick(8), + /** Ellipses button. */ + kEllipses(9), + /** Hamburger button. */ + kHamburger(10), + /** Stadia button. */ + kStadia(11), + /** Right trigger button. */ + kRightTrigger(12), + /** Left trigger button. */ + kLeftTrigger(13), + /** Google button. */ + kGoogle(14), + /** Frame button. */ + kFrame(15); + + /** Button value. */ + public final int value; + + Button(int value) { + this.value = value; + } + + /** + * Get the human-friendly name of the button, matching the relevant methods. This is done by + * stripping the leading `k`, and if not a Bumper button append `Button`. + * + *

Primarily used for automated unit tests. + * + * @return the human-friendly name of the button. + */ + @Override + public String toString() { + var name = this.name().substring(1); // Remove leading `k` + if (name.endsWith("Bumper")) { + return name; + } + return name + "Button"; + } + } + + /** Represents an axis on a StadiaController. */ + public enum Axis { + /** Left X axis. */ + kLeftX(0), + /** Right X axis. */ + kRightX(3), + /** Left Y axis. */ + kLeftY(1), + /** Right Y axis. */ + kRightY(4); + + /** Axis value. */ + public final int value; + + Axis(int value) { + this.value = value; + } + + /** + * Get the human-friendly name of the axis, matching the relevant methods. This is done by + * stripping the leading `k`, and if a trigger axis append `Axis`. + * + *

Primarily used for automated unit tests. + * + * @return the human-friendly name of the axis. + */ + @Override + public String toString() { + var name = this.name().substring(1); // Remove leading `k` + if (name.endsWith("Trigger")) { + return name + "Axis"; + } + return name; + } + } + + /** + * Construct an instance of a controller. + * + * @param port The port index on the Driver Station that the controller is plugged into. + */ + public StadiaController(final int port) { + super(port); + // re-enable when StadiaController is added to Usage Reporting + // HAL.report(tResourceType.kResourceType_Joystick, port + 1); + } + + /** + * Get the X axis value of left side of the controller. + * + * @return The axis value. + */ + public double getLeftX() { + return getRawAxis(Axis.kLeftX.value); + } + + /** + * Get the X axis value of right side of the controller. + * + * @return The axis value. + */ + public double getRightX() { + return getRawAxis(Axis.kRightX.value); + } + + /** + * Get the Y axis value of left side of the controller. + * + * @return The axis value. + */ + public double getLeftY() { + return getRawAxis(Axis.kLeftY.value); + } + + /** + * Get the Y axis value of right side of the controller. + * + * @return The axis value. + */ + public double getRightY() { + return getRawAxis(Axis.kRightY.value); + } + + /** + * Read the value of the left bumper (LB) button on the controller. + * + * @return The state of the button. + */ + public boolean getLeftBumper() { + return getRawButton(Button.kLeftBumper.value); + } + + /** + * Read the value of the right bumper (RB) button on the controller. + * + * @return The state of the button. + */ + public boolean getRightBumper() { + return getRawButton(Button.kRightBumper.value); + } + + /** + * Whether the left bumper (LB) was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getLeftBumperPressed() { + return getRawButtonPressed(Button.kLeftBumper.value); + } + + /** + * Whether the right bumper (RB) was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getRightBumperPressed() { + return getRawButtonPressed(Button.kRightBumper.value); + } + + /** + * Whether the left bumper (LB) was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getLeftBumperReleased() { + return getRawButtonReleased(Button.kLeftBumper.value); + } + + /** + * Whether the right bumper (RB) was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getRightBumperReleased() { + return getRawButtonReleased(Button.kRightBumper.value); + } + + /** + * Constructs an event instance around the right bumper's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the right bumper's digital signal attached to the given + * loop. + */ + public BooleanEvent leftBumper(EventLoop loop) { + return new BooleanEvent(loop, this::getLeftBumper); + } + + /** + * Constructs an event instance around the left bumper's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the left bumper's digital signal attached to the given + * loop. + */ + public BooleanEvent rightBumper(EventLoop loop) { + return new BooleanEvent(loop, this::getRightBumper); + } + + /** + * Read the value of the left stick button (LSB) on the controller. + * + * @return The state of the button. + */ + public boolean getLeftStickButton() { + return getRawButton(Button.kLeftStick.value); + } + + /** + * Read the value of the right stick button (RSB) on the controller. + * + * @return The state of the button. + */ + public boolean getRightStickButton() { + return getRawButton(Button.kRightStick.value); + } + + /** + * Whether the left stick button (LSB) was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getLeftStickButtonPressed() { + return getRawButtonPressed(Button.kLeftStick.value); + } + + /** + * Whether the right stick button (RSB) was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getRightStickButtonPressed() { + return getRawButtonPressed(Button.kRightStick.value); + } + + /** + * Whether the left stick button (LSB) was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getLeftStickButtonReleased() { + return getRawButtonReleased(Button.kLeftStick.value); + } + + /** + * Whether the right stick (RSB) button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getRightStickButtonReleased() { + return getRawButtonReleased(Button.kRightStick.value); + } + + /** + * Constructs an event instance around the left stick button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the left stick button's digital signal attached to the + * given loop. + */ + public BooleanEvent leftStick(EventLoop loop) { + return new BooleanEvent(loop, this::getLeftStickButton); + } + + /** + * Constructs an event instance around the right stick button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the right stick button's digital signal attached to the + * given loop. + */ + public BooleanEvent rightStick(EventLoop loop) { + return new BooleanEvent(loop, this::getRightStickButton); + } + + /** + * Read the value of the left trigger button (LTB) on the controller. + * + * @return The state of the button. + */ + public boolean getLeftTriggerButton() { + return getRawButton(Button.kLeftTrigger.value); + } + + /** + * Read the value of the right trigger button (RTB) on the controller. + * + * @return The state of the button. + */ + public boolean getRightTriggerButton() { + return getRawButton(Button.kRightTrigger.value); + } + + /** + * Whether the left trigger button (LTB) was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getLeftTriggerButtonPressed() { + return getRawButtonPressed(Button.kLeftTrigger.value); + } + + /** + * Whether the right trigger button (RTB) was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getRightTriggerButtonPressed() { + return getRawButtonPressed(Button.kRightTrigger.value); + } + + /** + * Whether the left trigger button (LTB) was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getLeftTriggerButtonReleased() { + return getRawButtonReleased(Button.kLeftTrigger.value); + } + + /** + * Whether the right trigger (RTB) button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getRightTriggerButtonReleased() { + return getRawButtonReleased(Button.kRightTrigger.value); + } + + /** + * Constructs an event instance around the left trigger button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the left trigger button's digital signal attached to the + * given loop. + */ + public BooleanEvent leftTrigger(EventLoop loop) { + return new BooleanEvent(loop, this::getLeftTriggerButton); + } + + /** + * Constructs an event instance around the right trigger button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the right trigger button's digital signal attached to + * the given loop. + */ + public BooleanEvent rightTrigger(EventLoop loop) { + return new BooleanEvent(loop, this::getRightTriggerButton); + } + + /** + * Read the value of the A button on the controller. + * + * @return The state of the button. + */ + public boolean getAButton() { + return getRawButton(Button.kA.value); + } + + /** + * Whether the A button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getAButtonPressed() { + return getRawButtonPressed(Button.kA.value); + } + + /** + * Whether the A button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getAButtonReleased() { + return getRawButtonReleased(Button.kA.value); + } + + /** + * Constructs an event instance around the A button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the A button's digital signal attached to the given + * loop. + */ + @SuppressWarnings("MethodName") + public BooleanEvent a(EventLoop loop) { + return new BooleanEvent(loop, this::getAButton); + } + + /** + * Read the value of the B button on the controller. + * + * @return The state of the button. + */ + public boolean getBButton() { + return getRawButton(Button.kB.value); + } + + /** + * Whether the B button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getBButtonPressed() { + return getRawButtonPressed(Button.kB.value); + } + + /** + * Whether the B button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getBButtonReleased() { + return getRawButtonReleased(Button.kB.value); + } + + /** + * Constructs an event instance around the B button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the B button's digital signal attached to the given + * loop. + */ + @SuppressWarnings("MethodName") + public BooleanEvent b(EventLoop loop) { + return new BooleanEvent(loop, this::getBButton); + } + + /** + * Read the value of the X button on the controller. + * + * @return The state of the button. + */ + public boolean getXButton() { + return getRawButton(Button.kX.value); + } + + /** + * Whether the X button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getXButtonPressed() { + return getRawButtonPressed(Button.kX.value); + } + + /** + * Whether the X button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getXButtonReleased() { + return getRawButtonReleased(Button.kX.value); + } + + /** + * Constructs an event instance around the X button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the X button's digital signal attached to the given + * loop. + */ + @SuppressWarnings("MethodName") + public BooleanEvent x(EventLoop loop) { + return new BooleanEvent(loop, this::getXButton); + } + + /** + * Read the value of the Y button on the controller. + * + * @return The state of the button. + */ + public boolean getYButton() { + return getRawButton(Button.kY.value); + } + + /** + * Whether the Y button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getYButtonPressed() { + return getRawButtonPressed(Button.kY.value); + } + + /** + * Whether the Y button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getYButtonReleased() { + return getRawButtonReleased(Button.kY.value); + } + + /** + * Constructs an event instance around the Y button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the Y button's digital signal attached to the given + * loop. + */ + @SuppressWarnings("MethodName") + public BooleanEvent y(EventLoop loop) { + return new BooleanEvent(loop, this::getYButton); + } + + /** + * Read the value of the ellipses button on the controller. + * + * @return The state of the button. + */ + public boolean getEllipsesButton() { + return getRawButton(Button.kEllipses.value); + } + + /** + * Whether the ellipses button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getEllipsesButtonPressed() { + return getRawButtonPressed(Button.kEllipses.value); + } + + /** + * Whether the ellipses button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getEllipsesButtonReleased() { + return getRawButtonReleased(Button.kEllipses.value); + } + + /** + * Constructs an event instance around the ellipses button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the ellipses button's digital signal attached to the + * given loop. + */ + public BooleanEvent ellipses(EventLoop loop) { + return new BooleanEvent(loop, this::getEllipsesButton); + } + + /** + * Read the value of the hamburger button on the controller. + * + * @return The state of the button. + */ + public boolean getHamburgerButton() { + return getRawButton(Button.kHamburger.value); + } + + /** + * Whether the hamburger button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getHamburgerButtonPressed() { + return getRawButtonPressed(Button.kHamburger.value); + } + + /** + * Whether the hamburger button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getHamburgerButtonReleased() { + return getRawButtonReleased(Button.kHamburger.value); + } + + /** + * Constructs an event instance around the hamburger button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the hamburger button's digital signal attached to the + * given loop. + */ + public BooleanEvent hamburger(EventLoop loop) { + return new BooleanEvent(loop, this::getHamburgerButton); + } + + /** + * Read the value of the stadia button on the controller. + * + * @return The state of the button. + */ + public boolean getStadiaButton() { + return getRawButton(Button.kStadia.value); + } + + /** + * Whether the stadia button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getStadiaButtonPressed() { + return getRawButtonPressed(Button.kStadia.value); + } + + /** + * Whether the stadia button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getStadiaButtonReleased() { + return getRawButtonReleased(Button.kStadia.value); + } + + /** + * Constructs an event instance around the stadia button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the stadia button's digital signal attached to the given + * loop. + */ + @SuppressWarnings("MethodName") + public BooleanEvent stadia(EventLoop loop) { + return new BooleanEvent(loop, this::getStadiaButton); + } + + /** + * Read the value of the google button on the controller. + * + * @return The state of the button. + */ + public boolean getGoogleButton() { + return getRawButton(Button.kGoogle.value); + } + + /** + * Whether the google button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getGoogleButtonPressed() { + return getRawButtonPressed(Button.kGoogle.value); + } + + /** + * Whether the google button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getGoogleButtonReleased() { + return getRawButtonReleased(Button.kGoogle.value); + } + + /** + * Constructs an event instance around the google button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the google button's digital signal attached to the given + * loop. + */ + @SuppressWarnings("MethodName") + public BooleanEvent google(EventLoop loop) { + return new BooleanEvent(loop, this::getGoogleButton); + } + + /** + * Read the value of the frame button on the controller. + * + * @return The state of the button. + */ + public boolean getFrameButton() { + return getRawButton(Button.kFrame.value); + } + + /** + * Whether the frame button was pressed since the last check. + * + * @return Whether the button was pressed since the last check. + */ + public boolean getFrameButtonPressed() { + return getRawButtonPressed(Button.kFrame.value); + } + + /** + * Whether the frame button was released since the last check. + * + * @return Whether the button was released since the last check. + */ + public boolean getFrameButtonReleased() { + return getRawButtonReleased(Button.kFrame.value); + } + + /** + * Constructs an event instance around the frame button's digital signal. + * + * @param loop the event loop instance to attach the event to. + * @return an event instance representing the frame button's digital signal attached to the given + * loop. + */ + @SuppressWarnings("MethodName") + public BooleanEvent frame(EventLoop loop) { + return new BooleanEvent(loop, this::getFrameButton); + } +} diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/SynchronousInterrupt.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/SynchronousInterrupt.java index 705d6b1a7c7..449402c6cdf 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/SynchronousInterrupt.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/SynchronousInterrupt.java @@ -23,11 +23,16 @@ public class SynchronousInterrupt implements AutoCloseable { /** Event trigger combinations for a synchronous interrupt. */ public enum WaitResult { + /** Timeout event. */ kTimeout(0x0), + /** Rising edge event. */ kRisingEdge(0x1), + /** Falling edge event. */ kFallingEdge(0x100), + /** Both rising and falling edge events. */ kBoth(0x101); + /** WaitResult value. */ public final int value; WaitResult(int value) { @@ -79,21 +84,6 @@ public void close() { InterruptJNI.cleanInterrupts(m_handle); } - /** - * Wait for interrupt that returns the raw result value from the hardware. - * - *

Used by AsynchronousInterrupt. Users should use waitForInterrupt. - * - * @param timeoutSeconds The timeout in seconds. 0 or less will return immediately. - * @param ignorePrevious True to ignore if a previous interrupt has occurred, and only wait for a - * new trigger. False will consider if an interrupt has occurred since the last time the - * interrupt was read. - * @return The raw hardware interrupt result - */ - long waitForInterruptRaw(double timeoutSeconds, boolean ignorePrevious) { - return InterruptJNI.waitForInterrupt(m_handle, timeoutSeconds, ignorePrevious); - } - /** * Wait for an interrupt. * diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Threads.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Threads.java index 8b0d1670f9f..5ff0540dbfc 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Threads.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Threads.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.ThreadsJNI; +/** Thread utility functions. */ public final class Threads { /** * Get the thread priority for the current thread. diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/TimedRobot.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/TimedRobot.java index 5a53b145f01..12346c445a7 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/TimedRobot.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/TimedRobot.java @@ -65,6 +65,7 @@ public int compareTo(Callback rhs) { } } + /** Default loop period. */ public static final double kDefaultPeriod = 0.02; // The C pointer to the notifier object. We don't use it directly, it is @@ -159,7 +160,7 @@ public void endCompetition() { * @param callback The callback to run. * @param periodSeconds The period at which to run the callback in seconds. */ - public void addPeriodic(Runnable callback, double periodSeconds) { + public final void addPeriodic(Runnable callback, double periodSeconds) { m_callbacks.add(new Callback(callback, m_startTime, periodSeconds, 0.0)); } @@ -174,7 +175,7 @@ public void addPeriodic(Runnable callback, double periodSeconds) { * @param offsetSeconds The offset from the common starting time in seconds. This is useful for * scheduling a callback in a different timeslot relative to TimedRobot. */ - public void addPeriodic(Runnable callback, double periodSeconds, double offsetSeconds) { + public final void addPeriodic(Runnable callback, double periodSeconds, double offsetSeconds) { m_callbacks.add(new Callback(callback, m_startTime, periodSeconds, offsetSeconds)); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Timer.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Timer.java index 4f948f5ae13..63e5ed4c99a 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Timer.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Timer.java @@ -83,7 +83,7 @@ public double get() { * *

Make the timer startTime the current time so new requests will be relative now. */ - public void reset() { + public final void reset() { m_accumulatedTime = 0; m_startTime = getMsClock(); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Tracer.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Tracer.java index 2415079b243..15ca7fff81f 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Tracer.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Tracer.java @@ -36,7 +36,7 @@ public void clearEpochs() { } /** Restarts the epoch timer. */ - public void resetTimer() { + public final void resetTimer() { m_startTime = RobotController.getFPGATime(); } @@ -75,9 +75,7 @@ public void printEpochs(Consumer output) { StringBuilder sb = new StringBuilder(); m_lastEpochsPrintTime = now; m_epochs.forEach( - (key, value) -> { - sb.append(String.format("\t%s: %.6fs\n", key, value / 1.0e6)); - }); + (key, value) -> sb.append(String.format("\t%s: %.6fs\n", key, value / 1.0e6))); if (sb.length() > 0) { output.accept(sb.toString()); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Ultrasonic.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Ultrasonic.java index fd2b05bf45d..a7b5e71b56e 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Ultrasonic.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Ultrasonic.java @@ -108,6 +108,11 @@ private synchronized void initialize() { SendableRegistry.addLW(this, "Ultrasonic", m_echoChannel.getChannel()); } + /** + * Returns the echo channel. + * + * @return The echo channel. + */ public int getEchoChannel() { return m_echoChannel.getChannel(); } @@ -121,6 +126,7 @@ public int getEchoChannel() { * @param echoChannel The digital input channel that receives the echo. The length of time that * the echo is high represents the round trip time of the ping, and the distance. */ + @SuppressWarnings("this-escape") public Ultrasonic(final int pingChannel, final int echoChannel) { m_pingChannel = new DigitalOutput(pingChannel); m_echoChannel = new DigitalInput(echoChannel); @@ -138,6 +144,7 @@ public Ultrasonic(final int pingChannel, final int echoChannel) { * 10uS pulse to start. * @param echoChannel The digital input object that times the return pulse to determine the range. */ + @SuppressWarnings("this-escape") public Ultrasonic(DigitalOutput pingChannel, DigitalInput echoChannel) { requireNonNullParam(pingChannel, "pingChannel", "Ultrasonic"); requireNonNullParam(echoChannel, "echoChannel", "Ultrasonic"); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Watchdog.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Watchdog.java index f7bf85b6347..e1860e38db3 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/Watchdog.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/Watchdog.java @@ -208,8 +208,9 @@ public void suppressTimeoutMessage(boolean suppress) { m_suppressTimeoutMessage = suppress; } + @SuppressWarnings("resource") private static void updateAlarm() { - if (m_watchdogs.size() == 0) { + if (m_watchdogs.isEmpty()) { NotifierJNI.cancelNotifierAlarm(m_notifier); } else { NotifierJNI.updateNotifierAlarm( @@ -233,7 +234,7 @@ private static void schedulerFunc() { m_queueMutex.lock(); try { - if (m_watchdogs.size() == 0) { + if (m_watchdogs.isEmpty()) { continue; } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/XboxController.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/XboxController.java index c346ae3c825..5bd7a019274 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/XboxController.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/XboxController.java @@ -15,21 +15,36 @@ *

This class handles Xbox input that comes from the Driver Station. Each time a value is * requested the most recent value is returned. There is a single class instance for each controller * and the mapping of ports to hardware buttons depends on the code in the Driver Station. + * + *

Only first party controllers from Microsoft are guaranteed to have the correct mapping, and + * only through the official NI DS. Sim is not guaranteed to have the same mapping, as well as any + * 3rd party controllers. */ public class XboxController extends GenericHID { /** Represents a digital button on an XboxController. */ public enum Button { + /** Left bumper. */ kLeftBumper(5), + /** Right bumper. */ kRightBumper(6), + /** Left stick. */ kLeftStick(9), + /** Right stick. */ kRightStick(10), + /** A. */ kA(1), + /** B. */ kB(2), + /** X. */ kX(3), + /** Y. */ kY(4), + /** Back. */ kBack(7), + /** Start. */ kStart(8); + /** Button value. */ public final int value; Button(int value) { @@ -56,13 +71,20 @@ public String toString() { /** Represents an axis on an XboxController. */ public enum Axis { + /** Left X. */ kLeftX(0), + /** Right X. */ kRightX(4), + /** Left Y. */ kLeftY(1), + /** Right Y. */ kRightY(5), + /** Left trigger. */ kLeftTrigger(2), + /** Right trigger. */ kRightTrigger(3); + /** Axis value. */ public final int value; Axis(int value) { diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/EdgeConfiguration.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/EdgeConfiguration.java index 9d58fbf1db1..c969249aaf5 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/EdgeConfiguration.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/EdgeConfiguration.java @@ -4,15 +4,22 @@ package edu.wpi.first.wpilibj.counter; +/** Edge configuration. */ public enum EdgeConfiguration { + /** No edge configuration (neither rising nor falling). */ kNone(false, false), + /** Rising edge configuration. */ kRisingEdge(true, false), + /** Falling edge configuration. */ kFallingEdge(false, true), + /** Both rising and falling edge configuration. */ kBoth(true, true); + /** True if triggering on rising edge. */ @SuppressWarnings("MemberName") public final boolean rising; + /** True if triggering on falling edge. */ @SuppressWarnings("MemberName") public final boolean falling; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/ExternalDirectionCounter.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/ExternalDirectionCounter.java index 6828b9a53a6..97fbf5b464d 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/ExternalDirectionCounter.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/ExternalDirectionCounter.java @@ -34,6 +34,7 @@ public class ExternalDirectionCounter implements Sendable, AutoCloseable { * @param countSource The source for counting. * @param directionSource The source for selecting count direction. */ + @SuppressWarnings("this-escape") public ExternalDirectionCounter(DigitalSource countSource, DigitalSource directionSource) { m_countSource = requireNonNullParam(countSource, "countSource", "ExternalDirectionCounter"); m_directionSource = diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/Tachometer.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/Tachometer.java index 5bd8e7ea785..6bef24deaa7 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/Tachometer.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/Tachometer.java @@ -34,6 +34,7 @@ public class Tachometer implements Sendable, AutoCloseable { * * @param source The DigitalSource (e.g. DigitalInput) of the Tachometer. */ + @SuppressWarnings("this-escape") public Tachometer(DigitalSource source) { m_source = requireNonNullParam(source, "source", "Tachometer"); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/UpDownCounter.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/UpDownCounter.java index c89c11811c9..ed9f35e971f 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/UpDownCounter.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/counter/UpDownCounter.java @@ -32,6 +32,7 @@ public class UpDownCounter implements Sendable, AutoCloseable { * @param upSource The up count source (can be null). * @param downSource The down count source (can be null). */ + @SuppressWarnings("this-escape") public UpDownCounter(DigitalSource upSource, DigitalSource downSource) { ByteBuffer index = ByteBuffer.allocateDirect(4); // set the byte order @@ -92,7 +93,7 @@ public void setDownEdgeConfiguration(EdgeConfiguration configuration) { } /** Resets the current count. */ - public void reset() { + public final void reset() { CounterJNI.resetCounter(m_handle); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/drive/DifferentialDrive.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/drive/DifferentialDrive.java index 9a1f2ba46c1..40e34a803da 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/drive/DifferentialDrive.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/drive/DifferentialDrive.java @@ -14,49 +14,16 @@ import edu.wpi.first.util.sendable.SendableBuilder; import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.motorcontrol.MotorController; +import java.util.function.DoubleConsumer; /** * A class for driving differential drive/skid-steer drive platforms such as the Kit of Parts drive * base, "tank drive", or West Coast Drive. * *

These drive bases typically have drop-center / skid-steer with two or more wheels per side - * (e.g., 6WD or 8WD). This class takes a MotorController per side. For four and six motor - * drivetrains, construct and pass in {@link - * edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup} instances as follows. - * - *

Four motor drivetrain: - * - *


- * public class Robot {
- *   MotorController m_frontLeft = new PWMVictorSPX(1);
- *   MotorController m_rearLeft = new PWMVictorSPX(2);
- *   MotorControllerGroup m_left = new MotorControllerGroup(m_frontLeft, m_rearLeft);
- *
- *   MotorController m_frontRight = new PWMVictorSPX(3);
- *   MotorController m_rearRight = new PWMVictorSPX(4);
- *   MotorControllerGroup m_right = new MotorControllerGroup(m_frontRight, m_rearRight);
- *
- *   DifferentialDrive m_drive = new DifferentialDrive(m_left, m_right);
- * }
- * 
- * - *

Six motor drivetrain: - * - *


- * public class Robot {
- *   MotorController m_frontLeft = new PWMVictorSPX(1);
- *   MotorController m_midLeft = new PWMVictorSPX(2);
- *   MotorController m_rearLeft = new PWMVictorSPX(3);
- *   MotorControllerGroup m_left = new MotorControllerGroup(m_frontLeft, m_midLeft, m_rearLeft);
- *
- *   MotorController m_frontRight = new PWMVictorSPX(4);
- *   MotorController m_midRight = new PWMVictorSPX(5);
- *   MotorController m_rearRight = new PWMVictorSPX(6);
- *   MotorControllerGroup m_right = new MotorControllerGroup(m_frontRight, m_midRight, m_rearRight);
- *
- *   DifferentialDrive m_drive = new DifferentialDrive(m_left, m_right);
- * }
- * 
+ * (e.g., 6WD or 8WD). This class takes a setter per side. For four and six motor drivetrains, use + * CAN motor controller followers or {@link + * edu.wpi.first.wpilibj.motorcontrol.PWMMotorController#addFollower(PWMMotorController)}. * *

A differential drive robot has left and right wheels separated by an arbitrary width. * @@ -88,8 +55,12 @@ public class DifferentialDrive extends RobotDriveBase implements Sendable, AutoCloseable { private static int instances; - private final MotorController m_leftMotor; - private final MotorController m_rightMotor; + private final DoubleConsumer m_leftMotor; + private final DoubleConsumer m_rightMotor; + + // Used for Sendable property getters + private double m_leftOutput; + private double m_rightOutput; private boolean m_reported; @@ -100,7 +71,10 @@ public class DifferentialDrive extends RobotDriveBase implements Sendable, AutoC */ @SuppressWarnings("MemberName") public static class WheelSpeeds { + /** Left wheel speed. */ public double left; + + /** Right wheel speed. */ public double right; /** Constructs a WheelSpeeds with zeroes for left and right speeds. */ @@ -121,21 +95,37 @@ public WheelSpeeds(double left, double right) { /** * Construct a DifferentialDrive. * - *

To pass multiple motors per side, use a {@link - * edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup}. If a motor needs to be inverted, do - * so before passing it in. + *

To pass multiple motors per side, use CAN motor controller followers or {@link + * edu.wpi.first.wpilibj.motorcontrol.PWMMotorController#addFollower(PWMMotorController)}. If a + * motor needs to be inverted, do so before passing it in. * * @param leftMotor Left motor. * @param rightMotor Right motor. */ + @SuppressWarnings({"removal", "this-escape"}) public DifferentialDrive(MotorController leftMotor, MotorController rightMotor) { + this((double output) -> leftMotor.set(output), (double output) -> rightMotor.set(output)); + SendableRegistry.addChild(this, leftMotor); + SendableRegistry.addChild(this, rightMotor); + } + + /** + * Construct a DifferentialDrive. + * + *

To pass multiple motors per side, use CAN motor controller followers or {@link + * edu.wpi.first.wpilibj.motorcontrol.PWMMotorController#addFollower(PWMMotorController)}. If a + * motor needs to be inverted, do so before passing it in. + * + * @param leftMotor Left motor setter. + * @param rightMotor Right motor setter. + */ + @SuppressWarnings("this-escape") + public DifferentialDrive(DoubleConsumer leftMotor, DoubleConsumer rightMotor) { requireNonNullParam(leftMotor, "leftMotor", "DifferentialDrive"); requireNonNullParam(rightMotor, "rightMotor", "DifferentialDrive"); m_leftMotor = leftMotor; m_rightMotor = rightMotor; - SendableRegistry.addChild(this, m_leftMotor); - SendableRegistry.addChild(this, m_rightMotor); instances++; SendableRegistry.addLW(this, "DifferentialDrive", instances); } @@ -177,8 +167,11 @@ public void arcadeDrive(double xSpeed, double zRotation, boolean squareInputs) { var speeds = arcadeDriveIK(xSpeed, zRotation, squareInputs); - m_leftMotor.set(speeds.left * m_maxOutput); - m_rightMotor.set(speeds.right * m_maxOutput); + m_leftOutput = speeds.left * m_maxOutput; + m_rightOutput = speeds.right * m_maxOutput; + + m_leftMotor.accept(m_leftOutput); + m_rightMotor.accept(m_rightOutput); feed(); } @@ -206,8 +199,11 @@ public void curvatureDrive(double xSpeed, double zRotation, boolean allowTurnInP var speeds = curvatureDriveIK(xSpeed, zRotation, allowTurnInPlace); - m_leftMotor.set(speeds.left * m_maxOutput); - m_rightMotor.set(speeds.right * m_maxOutput); + m_leftOutput = speeds.left * m_maxOutput; + m_rightOutput = speeds.right * m_maxOutput; + + m_leftMotor.accept(m_leftOutput); + m_rightMotor.accept(m_rightOutput); feed(); } @@ -244,8 +240,11 @@ public void tankDrive(double leftSpeed, double rightSpeed, boolean squareInputs) var speeds = tankDriveIK(leftSpeed, rightSpeed, squareInputs); - m_leftMotor.set(speeds.left * m_maxOutput); - m_rightMotor.set(speeds.right * m_maxOutput); + m_leftOutput = speeds.left * m_maxOutput; + m_rightOutput = speeds.right * m_maxOutput; + + m_leftMotor.accept(m_leftOutput); + m_rightMotor.accept(m_rightOutput); feed(); } @@ -350,8 +349,12 @@ public static WheelSpeeds tankDriveIK(double leftSpeed, double rightSpeed, boole @Override public void stopMotor() { - m_leftMotor.stopMotor(); - m_rightMotor.stopMotor(); + m_leftOutput = 0.0; + m_rightOutput = 0.0; + + m_leftMotor.accept(0.0); + m_rightMotor.accept(0.0); + feed(); } @@ -365,7 +368,7 @@ public void initSendable(SendableBuilder builder) { builder.setSmartDashboardType("DifferentialDrive"); builder.setActuator(true); builder.setSafeState(this::stopMotor); - builder.addDoubleProperty("Left Motor Speed", m_leftMotor::get, m_leftMotor::set); - builder.addDoubleProperty("Right Motor Speed", m_rightMotor::get, m_rightMotor::set); + builder.addDoubleProperty("Left Motor Speed", () -> m_leftOutput, m_leftMotor); + builder.addDoubleProperty("Right Motor Speed", () -> m_rightOutput, m_rightMotor); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/drive/MecanumDrive.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/drive/MecanumDrive.java index 181e2753b0c..0e9731a2d63 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/drive/MecanumDrive.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/drive/MecanumDrive.java @@ -16,6 +16,7 @@ import edu.wpi.first.util.sendable.SendableBuilder; import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.motorcontrol.MotorController; +import java.util.function.DoubleConsumer; /** * A class for driving Mecanum drive platforms. @@ -56,10 +57,16 @@ public class MecanumDrive extends RobotDriveBase implements Sendable, AutoCloseable { private static int instances; - private final MotorController m_frontLeftMotor; - private final MotorController m_rearLeftMotor; - private final MotorController m_frontRightMotor; - private final MotorController m_rearRightMotor; + private final DoubleConsumer m_frontLeftMotor; + private final DoubleConsumer m_rearLeftMotor; + private final DoubleConsumer m_frontRightMotor; + private final DoubleConsumer m_rearRightMotor; + + // Used for Sendable property getters + private double m_frontLeftOutput; + private double m_rearLeftOutput; + private double m_frontRightOutput; + private double m_rearRightOutput; private boolean m_reported; @@ -70,9 +77,16 @@ public class MecanumDrive extends RobotDriveBase implements Sendable, AutoClosea */ @SuppressWarnings("MemberName") public static class WheelSpeeds { + /** Front-left wheel speed. */ public double frontLeft; + + /** Front-right wheel speed. */ public double frontRight; + + /** Rear-left wheel speed. */ public double rearLeft; + + /** Rear-right wheel speed. */ public double rearRight; /** Constructs a WheelSpeeds with zeroes for all four speeds. */ @@ -104,11 +118,39 @@ public WheelSpeeds(double frontLeft, double frontRight, double rearLeft, double * @param frontRightMotor The motor on the front-right corner. * @param rearRightMotor The motor on the rear-right corner. */ + @SuppressWarnings({"removal", "this-escape"}) public MecanumDrive( MotorController frontLeftMotor, MotorController rearLeftMotor, MotorController frontRightMotor, MotorController rearRightMotor) { + this( + (double output) -> frontLeftMotor.set(output), + (double output) -> rearLeftMotor.set(output), + (double output) -> frontRightMotor.set(output), + (double output) -> rearRightMotor.set(output)); + SendableRegistry.addChild(this, frontLeftMotor); + SendableRegistry.addChild(this, rearLeftMotor); + SendableRegistry.addChild(this, frontRightMotor); + SendableRegistry.addChild(this, rearRightMotor); + } + + /** + * Construct a MecanumDrive. + * + *

If a motor needs to be inverted, do so before passing it in. + * + * @param frontLeftMotor The setter for the motor on the front-left corner. + * @param rearLeftMotor The setter for the motor on the rear-left corner. + * @param frontRightMotor The setter for the motor on the front-right corner. + * @param rearRightMotor The setter for the motor on the rear-right corner. + */ + @SuppressWarnings("this-escape") + public MecanumDrive( + DoubleConsumer frontLeftMotor, + DoubleConsumer rearLeftMotor, + DoubleConsumer frontRightMotor, + DoubleConsumer rearRightMotor) { requireNonNullParam(frontLeftMotor, "frontLeftMotor", "MecanumDrive"); requireNonNullParam(rearLeftMotor, "rearLeftMotor", "MecanumDrive"); requireNonNullParam(frontRightMotor, "frontRightMotor", "MecanumDrive"); @@ -118,10 +160,6 @@ public MecanumDrive( m_rearLeftMotor = rearLeftMotor; m_frontRightMotor = frontRightMotor; m_rearRightMotor = rearRightMotor; - SendableRegistry.addChild(this, m_frontLeftMotor); - SendableRegistry.addChild(this, m_rearLeftMotor); - SendableRegistry.addChild(this, m_frontRightMotor); - SendableRegistry.addChild(this, m_rearRightMotor); instances++; SendableRegistry.addLW(this, "MecanumDrive", instances); } @@ -143,7 +181,7 @@ public void close() { * positive. */ public void driveCartesian(double xSpeed, double ySpeed, double zRotation) { - driveCartesian(xSpeed, ySpeed, zRotation, new Rotation2d()); + driveCartesian(xSpeed, ySpeed, zRotation, Rotation2d.kZero); } /** @@ -171,10 +209,15 @@ public void driveCartesian(double xSpeed, double ySpeed, double zRotation, Rotat var speeds = driveCartesianIK(xSpeed, ySpeed, zRotation, gyroAngle); - m_frontLeftMotor.set(speeds.frontLeft * m_maxOutput); - m_frontRightMotor.set(speeds.frontRight * m_maxOutput); - m_rearLeftMotor.set(speeds.rearLeft * m_maxOutput); - m_rearRightMotor.set(speeds.rearRight * m_maxOutput); + m_frontLeftOutput = speeds.frontLeft * m_maxOutput; + m_rearLeftOutput = speeds.rearLeft * m_maxOutput; + m_frontRightOutput = speeds.frontRight * m_maxOutput; + m_rearRightOutput = speeds.rearRight * m_maxOutput; + + m_frontLeftMotor.accept(m_frontLeftOutput); + m_frontRightMotor.accept(m_frontRightOutput); + m_rearLeftMotor.accept(m_rearLeftOutput); + m_rearRightMotor.accept(m_rearRightOutput); feed(); } @@ -197,7 +240,7 @@ public void drivePolar(double magnitude, Rotation2d angle, double zRotation) { } driveCartesian( - magnitude * angle.getCos(), magnitude * angle.getSin(), zRotation, new Rotation2d()); + magnitude * angle.getCos(), magnitude * angle.getSin(), zRotation, Rotation2d.kZero); } /** @@ -213,7 +256,7 @@ public void drivePolar(double magnitude, Rotation2d angle, double zRotation) { * @return Wheel speeds [-1.0..1.0]. */ public static WheelSpeeds driveCartesianIK(double xSpeed, double ySpeed, double zRotation) { - return driveCartesianIK(xSpeed, ySpeed, zRotation, new Rotation2d()); + return driveCartesianIK(xSpeed, ySpeed, zRotation, Rotation2d.kZero); } /** @@ -255,10 +298,16 @@ public static WheelSpeeds driveCartesianIK( @Override public void stopMotor() { - m_frontLeftMotor.stopMotor(); - m_frontRightMotor.stopMotor(); - m_rearLeftMotor.stopMotor(); - m_rearRightMotor.stopMotor(); + m_frontLeftOutput = 0.0; + m_frontRightOutput = 0.0; + m_rearLeftOutput = 0.0; + m_rearRightOutput = 0.0; + + m_frontLeftMotor.accept(0.0); + m_frontRightMotor.accept(0.0); + m_rearLeftMotor.accept(0.0); + m_rearRightMotor.accept(0.0); + feed(); } @@ -272,12 +321,10 @@ public void initSendable(SendableBuilder builder) { builder.setSmartDashboardType("MecanumDrive"); builder.setActuator(true); builder.setSafeState(this::stopMotor); + builder.addDoubleProperty("Front Left Motor Speed", () -> m_frontLeftOutput, m_frontLeftMotor); builder.addDoubleProperty( - "Front Left Motor Speed", m_frontLeftMotor::get, m_frontLeftMotor::set); - builder.addDoubleProperty( - "Front Right Motor Speed", m_frontRightMotor::get, m_frontRightMotor::set); - builder.addDoubleProperty("Rear Left Motor Speed", m_rearLeftMotor::get, m_rearLeftMotor::set); - builder.addDoubleProperty( - "Rear Right Motor Speed", m_rearRightMotor::get, m_rearRightMotor::set); + "Front Right Motor Speed", () -> m_frontRightOutput, m_frontRightMotor); + builder.addDoubleProperty("Rear Left Motor Speed", () -> m_rearLeftOutput, m_rearLeftMotor); + builder.addDoubleProperty("Rear Right Motor Speed", () -> m_rearRightOutput, m_rearRightMotor); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/drive/RobotDriveBase.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/drive/RobotDriveBase.java index c4e931d2f89..a952b2ecaa6 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/drive/RobotDriveBase.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/drive/RobotDriveBase.java @@ -12,22 +12,36 @@ *

{@link edu.wpi.first.wpilibj.MotorSafety} is enabled by default. */ public abstract class RobotDriveBase extends MotorSafety { + /** Default input deadband. */ public static final double kDefaultDeadband = 0.02; + + /** Default maximum output. */ public static final double kDefaultMaxOutput = 1.0; + /** Input deadband. */ protected double m_deadband = kDefaultDeadband; + + /** Maximum output. */ protected double m_maxOutput = kDefaultMaxOutput; /** The location of a motor on the robot for the purpose of driving. */ public enum MotorType { + /** Front left motor. */ kFrontLeft(0), + /** Front right motor. */ kFrontRight(1), + /** Rear left motor. */ kRearLeft(2), + /** Reat right motor. */ kRearRight(3), + /** Left motor. */ kLeft(0), + /** Right motor. */ kRight(1), + /** Back motor. */ kBack(2); + /** MotorType value. */ public final int value; MotorType(int value) { @@ -36,6 +50,7 @@ public enum MotorType { } /** RobotDriveBase constructor. */ + @SuppressWarnings("this-escape") public RobotDriveBase() { setSafetyEnabled(true); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/event/EventLoop.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/event/EventLoop.java index 3e220e06c2d..38d21cd990a 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/event/EventLoop.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/event/EventLoop.java @@ -5,6 +5,7 @@ package edu.wpi.first.wpilibj.event; import java.util.Collection; +import java.util.ConcurrentModificationException; import java.util.LinkedHashSet; /** @@ -12,6 +13,10 @@ */ public final class EventLoop { private final Collection m_bindings = new LinkedHashSet<>(); + private boolean m_running; + + /** Default constructor. */ + public EventLoop() {} /** * Bind a new action to run when the loop is polled. @@ -19,16 +24,27 @@ public final class EventLoop { * @param action the action to run. */ public void bind(Runnable action) { + if (m_running) { + throw new ConcurrentModificationException("Cannot bind EventLoop while it is running"); + } m_bindings.add(action); } /** Poll all bindings. */ public void poll() { - m_bindings.forEach(Runnable::run); + try { + m_running = true; + m_bindings.forEach(Runnable::run); + } finally { + m_running = false; + } } /** Clear all bindings. */ public void clear() { + if (m_running) { + throw new ConcurrentModificationException("Cannot clear EventLoop while it is running"); + } m_bindings.clear(); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/interfaces/Accelerometer.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/interfaces/Accelerometer.java deleted file mode 100644 index d33b7ae4c13..00000000000 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/interfaces/Accelerometer.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.interfaces; - -/** - * Interface for 3-axis accelerometers. - * - * @deprecated This interface is being removed with no replacement. - */ -@Deprecated(since = "2024", forRemoval = true) -public interface Accelerometer { - enum Range { - k2G, - k4G, - k8G, - k16G - } - - /** - * Common interface for setting the measuring range of an accelerometer. - * - * @param range The maximum acceleration, positive or negative, that the accelerometer will - * measure. Not all accelerometers support all ranges. - */ - void setRange(Range range); - - /** - * Common interface for getting the x-axis acceleration. - * - * @return The acceleration along the x-axis in g-forces - */ - double getX(); - - /** - * Common interface for getting the y-axis acceleration. - * - * @return The acceleration along the y-axis in g-forces - */ - double getY(); - - /** - * Common interface for getting the z axis acceleration. - * - * @return The acceleration along the z axis in g-forces - */ - double getZ(); -} diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/interfaces/Gyro.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/interfaces/Gyro.java deleted file mode 100644 index dad85ca3427..00000000000 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/interfaces/Gyro.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.interfaces; - -import edu.wpi.first.math.geometry.Rotation2d; - -/** - * Interface for yaw rate gyros. - * - * @deprecated This interface is being removed with no replacement. - */ -@Deprecated(since = "2024", forRemoval = true) -public interface Gyro extends AutoCloseable { - /** - * Calibrate the gyro. It's important to make sure that the robot is not moving while the - * calibration is in progress, this is typically done when the robot is first turned on while it's - * sitting at rest before the match starts. - */ - void calibrate(); - - /** - * Reset the gyro. Resets the gyro to a heading of zero. This can be used if there is significant - * drift in the gyro, and it needs to be recalibrated after it has been running. - */ - void reset(); - - /** - * Return the heading of the robot in degrees. - * - *

The angle is continuous, that is it will continue from 360 to 361 degrees. This allows - * algorithms that wouldn't want to see a discontinuity in the gyro output as it sweeps past from - * 360 to 0 on the second time around. - * - *

The angle is expected to increase as the gyro turns clockwise when looked at from the top. - * It needs to follow the NED axis convention. - * - *

This heading is based on integration of the returned rate from the gyro. - * - * @return the current heading of the robot in degrees. - */ - double getAngle(); - - /** - * Return the rate of rotation of the gyro. - * - *

The rate is based on the most recent reading of the gyro analog value - * - *

The rate is expected to be positive as the gyro turns clockwise when looked at from the top. - * It needs to follow the NED axis convention. - * - * @return the current rate in degrees per second - */ - double getRate(); - - /** - * Return the heading of the robot as a {@link edu.wpi.first.math.geometry.Rotation2d}. - * - *

The angle is continuous, that is it will continue from 360 to 361 degrees. This allows - * algorithms that wouldn't want to see a discontinuity in the gyro output as it sweeps past from - * 360 to 0 on the second time around. - * - *

The angle is expected to increase as the gyro turns counterclockwise when looked at from the - * top. It needs to follow the NWU axis convention. - * - *

This heading is based on integration of the returned rate from the gyro. - * - * @return the current heading of the robot as a {@link edu.wpi.first.math.geometry.Rotation2d}. - */ - default Rotation2d getRotation2d() { - return Rotation2d.fromDegrees(-getAngle()); - } -} diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/internal/DriverStationModeThread.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/internal/DriverStationModeThread.java index 03d63973940..57c6bf7ddf8 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/internal/DriverStationModeThread.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/internal/DriverStationModeThread.java @@ -9,9 +9,7 @@ import edu.wpi.first.wpilibj.DriverStation; import java.util.concurrent.atomic.AtomicBoolean; -/* - * For internal use only. - */ +/** For internal use only. */ public class DriverStationModeThread implements AutoCloseable { private final AtomicBoolean m_keepAlive = new AtomicBoolean(); private final Thread m_thread; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java index ac8ef1d3569..1b9d1ea24a6 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java @@ -50,7 +50,7 @@ public void close() { private static Runnable disabledListener; static { - SendableRegistry.setLiveWindowBuilderFactory(() -> new SendableBuilderImpl()); + SendableRegistry.setLiveWindowBuilderFactory(SendableBuilderImpl::new); enabledPub.set(false); } @@ -67,14 +67,29 @@ private LiveWindow() { throw new UnsupportedOperationException("This is a utility class!"); } + /** + * Sets function to be called when LiveWindow is enabled. + * + * @param runnable function (or null for none) + */ public static synchronized void setEnabledListener(Runnable runnable) { enabledListener = runnable; } + /** + * Sets function to be called when LiveWindow is disabled. + * + * @param runnable function (or null for none) + */ public static synchronized void setDisabledListener(Runnable runnable) { disabledListener = runnable; } + /** + * Returns true if LiveWindow is enabled. + * + * @return True if LiveWindow is enabled. + */ public static synchronized boolean isEnabled() { return liveWindowEnabled; } @@ -105,10 +120,7 @@ public static synchronized void setEnabled(boolean enabled) { } else { System.out.println("stopping live window mode."); SendableRegistry.foreachLiveWindow( - dataHandle, - cbdata -> { - ((SendableBuilderImpl) cbdata.builder).stopLiveWindowMode(); - }); + dataHandle, cbdata -> ((SendableBuilderImpl) cbdata.builder).stopLiveWindowMode()); if (disabledListener != null) { disabledListener.run(); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/DMC60.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/DMC60.java index 5f0f26b5969..9d669078bdd 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/DMC60.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/DMC60.java @@ -32,6 +32,7 @@ public class DMC60 extends PWMMotorController { * @param channel The PWM channel that the DMC60 is attached to. 0-9 are on-board, 10-19 are on * the MXP port */ + @SuppressWarnings("this-escape") public DMC60(final int channel) { super("DMC60", channel); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Jaguar.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Jaguar.java index f07206784e2..4a0ac855724 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Jaguar.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Jaguar.java @@ -31,6 +31,7 @@ public class Jaguar extends PWMMotorController { * @param channel The PWM channel that the Jaguar is attached to. 0-9 are on-board, 10-19 are on * the MXP port */ + @SuppressWarnings("this-escape") public Jaguar(final int channel) { super("Jaguar", channel); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/MotorControllerGroup.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/MotorControllerGroup.java index d9da3c8f1f2..c56496cd480 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/MotorControllerGroup.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/MotorControllerGroup.java @@ -9,7 +9,14 @@ import edu.wpi.first.util.sendable.SendableRegistry; import java.util.Arrays; -/** Allows multiple {@link MotorController} objects to be linked together. */ +/** + * Allows multiple {@link MotorController} objects to be linked together. + * + * @deprecated Use {@link PWMMotorController#addFollower(PWMMotorController)} or if using CAN motor + * controllers, use their method of following. + */ +@SuppressWarnings("removal") +@Deprecated(forRemoval = true, since = "2024") public class MotorControllerGroup implements MotorController, Sendable, AutoCloseable { private boolean m_isInverted; private final MotorController[] m_motorControllers; @@ -21,6 +28,7 @@ public class MotorControllerGroup implements MotorController, Sendable, AutoClos * @param motorController The first MotorController to add * @param motorControllers The MotorControllers to add */ + @SuppressWarnings("this-escape") public MotorControllerGroup( MotorController motorController, MotorController... motorControllers) { m_motorControllers = new MotorController[motorControllers.length + 1]; @@ -29,6 +37,12 @@ public MotorControllerGroup( init(); } + /** + * Create a new MotorControllerGroup with the provided MotorControllers. + * + * @param motorControllers The MotorControllers to add. + */ + @SuppressWarnings("this-escape") public MotorControllerGroup(MotorController[] motorControllers) { m_motorControllers = Arrays.copyOf(motorControllers, motorControllers.length); init(); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/NidecBrushless.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/NidecBrushless.java index 25c29acfdc1..01af76563cb 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/NidecBrushless.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/NidecBrushless.java @@ -14,6 +14,7 @@ import edu.wpi.first.wpilibj.PWM; /** Nidec Brushless Motor. */ +@SuppressWarnings("removal") public class NidecBrushless extends MotorSafety implements MotorController, Sendable, AutoCloseable { private boolean m_isInverted; @@ -30,6 +31,7 @@ public class NidecBrushless extends MotorSafety * @param dioChannel The DIO channel that the Nidec Brushless controller is attached to. 0-9 are * on-board, 10-25 are on the MXP port */ + @SuppressWarnings("this-escape") public NidecBrushless(final int pwmChannel, final int dioChannel) { setSafetyEnabled(false); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMMotorController.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMMotorController.java index 68817a1dad4..b72cee344fe 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMMotorController.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMMotorController.java @@ -9,11 +9,16 @@ import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.MotorSafety; import edu.wpi.first.wpilibj.PWM; +import java.util.ArrayList; /** Common base class for all PWM Motor Controllers. */ +@SuppressWarnings("removal") public abstract class PWMMotorController extends MotorSafety implements MotorController, Sendable, AutoCloseable { private boolean m_isInverted; + private final ArrayList m_followers = new ArrayList<>(); + + /** PWM instances for motor controller. */ protected PWM m_pwm; /** @@ -23,6 +28,7 @@ public abstract class PWMMotorController extends MotorSafety * @param channel The PWM channel that the controller is attached to. 0-9 are on-board, 10-19 are * on the MXP port */ + @SuppressWarnings("this-escape") protected PWMMotorController(final String name, final int channel) { m_pwm = new PWM(channel, false); SendableRegistry.addLW(this, name, channel); @@ -45,7 +51,15 @@ public void close() { */ @Override public void set(double speed) { - m_pwm.setSpeed(m_isInverted ? -speed : speed); + if (m_isInverted) { + speed = -speed; + } + m_pwm.setSpeed(speed); + + for (var follower : m_followers) { + follower.set(speed); + } + feed(); } @@ -116,6 +130,15 @@ public void enableDeadbandElimination(boolean eliminateDeadband) { m_pwm.enableDeadbandElimination(eliminateDeadband); } + /** + * Make the given PWM motor controller follow the output of this one. + * + * @param follower The motor controller follower. + */ + public void addFollower(PWMMotorController follower) { + m_followers.add(follower); + } + @Override public void initSendable(SendableBuilder builder) { builder.setSmartDashboardType("Motor Controller"); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMSparkFlex.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMSparkFlex.java new file mode 100644 index 00000000000..059b18af1d3 --- /dev/null +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMSparkFlex.java @@ -0,0 +1,45 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.wpilibj.motorcontrol; + +import edu.wpi.first.hal.FRCNetComm.tResourceType; +import edu.wpi.first.hal.HAL; +import edu.wpi.first.wpilibj.PWM; + +/** + * REV Robotics SPARK Flex Motor Controller with PWM control. + * + *

Note that the SPARK Flex uses the following bounds for PWM values. These values should work + * reasonably well for most controllers, but if users experience issues such as asymmetric behavior + * around the deadband or inability to saturate the controller in either direction, calibration is + * recommended. The calibration procedure can be found in the SPARK Flex User Manual available from + * REV Robotics. + * + *

    + *
  • 2.003ms = full "forward" + *
  • 1.550ms = the "high end" of the deadband range + *
  • 1.500ms = center of the deadband range (off) + *
  • 1.460ms = the "low end" of the deadband range + *
  • 0.999ms = full "reverse" + *
+ */ +public class PWMSparkFlex extends PWMMotorController { + /** + * Common initialization code called by all constructors. + * + * @param channel The PWM channel number. 0-9 are on-board, 10-19 are on the MXP port + */ + @SuppressWarnings("this-escape") + public PWMSparkFlex(final int channel) { + super("PWMSparkFlex", channel); + + m_pwm.setBoundsMicroseconds(2003, 1550, 1500, 1460, 999); + m_pwm.setPeriodMultiplier(PWM.PeriodMultiplier.k1X); + m_pwm.setSpeed(0.0); + m_pwm.setZeroLatch(); + + HAL.report(tResourceType.kResourceType_RevSparkFlexPWM, getChannel() + 1); + } +} diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMSparkMax.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMSparkMax.java index ede5f5de0bc..205d70a0de8 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMSparkMax.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMSparkMax.java @@ -31,6 +31,7 @@ public class PWMSparkMax extends PWMMotorController { * * @param channel The PWM channel number. 0-9 are on-board, 10-19 are on the MXP port */ + @SuppressWarnings("this-escape") public PWMSparkMax(final int channel) { super("PWMSparkMax", channel); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMTalonFX.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMTalonFX.java index 29ac7663be0..2211fa5269e 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMTalonFX.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMTalonFX.java @@ -32,6 +32,7 @@ public class PWMTalonFX extends PWMMotorController { * @param channel The PWM channel that the Talon FX is attached to. 0-9 are on-board, 10-19 are on * the MXP port */ + @SuppressWarnings("this-escape") public PWMTalonFX(final int channel) { super("PWMTalonFX", channel); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMTalonSRX.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMTalonSRX.java index 085cd869bf7..4677627f233 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMTalonSRX.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMTalonSRX.java @@ -32,6 +32,7 @@ public class PWMTalonSRX extends PWMMotorController { * @param channel The PWM channel that the Talon SRX is attached to. 0-9 are on-board, 10-19 are * on the MXP port */ + @SuppressWarnings("this-escape") public PWMTalonSRX(final int channel) { super("PWMTalonSRX", channel); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMVenom.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMVenom.java index a38e93691c0..f9960b02786 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMVenom.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMVenom.java @@ -31,6 +31,7 @@ public class PWMVenom extends PWMMotorController { * @param channel The PWM channel that the Venom is attached to. 0-9 are on-board, 10-19 are on * the MXP port */ + @SuppressWarnings("this-escape") public PWMVenom(final int channel) { super("PWMVenom", channel); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMVictorSPX.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMVictorSPX.java index 555614a9a64..daa70f34781 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMVictorSPX.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/PWMVictorSPX.java @@ -32,6 +32,7 @@ public class PWMVictorSPX extends PWMMotorController { * @param channel The PWM channel that the PWMVictorSPX is attached to. 0-9 are on-board, 10-19 * are on the MXP port */ + @SuppressWarnings("this-escape") public PWMVictorSPX(final int channel) { super("PWMVictorSPX", channel); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/SD540.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/SD540.java index 7cdb03573c8..31246bc5c1e 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/SD540.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/SD540.java @@ -32,6 +32,7 @@ public class SD540 extends PWMMotorController { * @param channel The PWM channel that the SD540 is attached to. 0-9 are on-board, 10-19 are on * the MXP port */ + @SuppressWarnings("this-escape") public SD540(final int channel) { super("SD540", channel); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Spark.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Spark.java index cc926215bac..d57b626a101 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Spark.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Spark.java @@ -32,6 +32,7 @@ public class Spark extends PWMMotorController { * @param channel The PWM channel that the SPARK is attached to. 0-9 are on-board, 10-19 are on * the MXP port */ + @SuppressWarnings("this-escape") public Spark(final int channel) { super("Spark", channel); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Talon.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Talon.java index dd9e473a92c..bcbad607380 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Talon.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Talon.java @@ -31,6 +31,7 @@ public class Talon extends PWMMotorController { * @param channel The PWM channel that the Talon is attached to. 0-9 are on-board, 10-19 are on * the MXP port */ + @SuppressWarnings("this-escape") public Talon(final int channel) { super("Talon", channel); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Victor.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Victor.java index 5265a8e4ad5..1a816add185 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Victor.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/Victor.java @@ -17,7 +17,8 @@ * 884 controllers also but if users experience issues such as asymmetric behavior around the * deadband or inability to saturate the controller in either direction, calibration is recommended. * The calibration procedure can be found in the Victor 884 User Manual available from VEX Robotics: - * http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf + * http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf * *
    *
  • 2.027ms = full "forward" @@ -34,6 +35,7 @@ public class Victor extends PWMMotorController { * @param channel The PWM channel that the Victor is attached to. 0-9 are on-board, 10-19 are on * the MXP port */ + @SuppressWarnings("this-escape") public Victor(final int channel) { super("Victor", channel); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/VictorSP.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/VictorSP.java index aa262d042e9..09ba3c6290f 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/VictorSP.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/motorcontrol/VictorSP.java @@ -32,6 +32,7 @@ public class VictorSP extends PWMMotorController { * @param channel The PWM channel that the VictorSP is attached to. 0-9 are on-board, 10-19 are on * the MXP port */ + @SuppressWarnings("this-escape") public VictorSP(final int channel) { super("VictorSP", channel); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/EventImportance.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/EventImportance.java index 4d64efe55dd..0d85ce69dc7 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/EventImportance.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/EventImportance.java @@ -38,6 +38,11 @@ public enum EventImportance { m_simpleName = simpleName; } + /** + * Returns name of the given enum. + * + * @return Name of the given enum. + */ public String getSimpleName() { return m_simpleName; } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/SendableCameraWrapper.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/SendableCameraWrapper.java index 150f0dbb6cb..bd428cdd00b 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/SendableCameraWrapper.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/SendableCameraWrapper.java @@ -74,7 +74,7 @@ public void close() { } } - /* + /** * Sets NetworkTable instance used for camera publisher entries. * * @param inst NetworkTable instance diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardComponent.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardComponent.java index 39078f439eb..3e1f75acd89 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardComponent.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardComponent.java @@ -26,25 +26,53 @@ public abstract class ShuffleboardComponent> private int m_width = -1; private int m_height = -1; + /** + * Constructs a ShuffleboardComponent. + * + * @param parent The parent container. + * @param title The component title. + * @param type The component type. + */ protected ShuffleboardComponent(ShuffleboardContainer parent, String title, String type) { m_parent = requireNonNullParam(parent, "parent", "ShuffleboardComponent"); m_title = requireNonNullParam(title, "title", "ShuffleboardComponent"); m_type = type; } + /** + * Constructs a ShuffleboardComponent. + * + * @param parent The parent container. + * @param title The component title. + */ protected ShuffleboardComponent(ShuffleboardContainer parent, String title) { this(parent, title, null); } + /** + * Returns the parent container. + * + * @return The parent container. + */ public final ShuffleboardContainer getParent() { return m_parent; } + /** + * Sets the component type. + * + * @param type The component type. + */ protected final void setType(String type) { m_type = type; m_metadataDirty = true; } + /** + * Returns the component type. + * + * @return The component type. + */ public final String getType() { return m_type; } @@ -109,6 +137,11 @@ public final C withSize(int width, int height) { return (C) this; } + /** + * Builds NT metadata. + * + * @param metaTable The NT metadata table. + */ protected final void buildMetadata(NetworkTable metaTable) { if (!m_metadataDirty) { return; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardInstance.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardInstance.java index df2f117e1dc..88e1e495e18 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardInstance.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardInstance.java @@ -18,7 +18,7 @@ final class ShuffleboardInstance implements ShuffleboardRoot { private final Map m_tabs = new LinkedHashMap<>(); - + private boolean m_reported = false; // NOPMD redundant field initializer private boolean m_tabsChanged = false; // NOPMD redundant field initializer private final NetworkTable m_rootTable; private final NetworkTable m_rootMetaTable; @@ -35,12 +35,15 @@ final class ShuffleboardInstance implements ShuffleboardRoot { m_rootMetaTable = m_rootTable.getSubTable(".metadata"); m_selectedTabPub = m_rootMetaTable.getStringTopic("Selected").publish(PubSubOption.keepDuplicates(true)); - HAL.report(tResourceType.kResourceType_Shuffleboard, 0); } @Override public ShuffleboardTab getTab(String title) { requireNonNullParam(title, "title", "getTab"); + if (!m_reported) { + HAL.report(tResourceType.kResourceType_Shuffleboard, 0); + m_reported = true; + } if (!m_tabs.containsKey(title)) { m_tabs.put(title, new ShuffleboardTab(this, title)); m_tabsChanged = true; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/ADXL345Sim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/ADXL345Sim.java index c50c2f8124b..bcbf3e297d6 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/ADXL345Sim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/ADXL345Sim.java @@ -9,10 +9,11 @@ import edu.wpi.first.wpilibj.ADXL345_SPI; import java.util.Objects; +/** Class to control a simulated ADXL345. */ public class ADXL345Sim { - protected SimDouble m_simX; - protected SimDouble m_simY; - protected SimDouble m_simZ; + private SimDouble m_simX; + private SimDouble m_simY; + private SimDouble m_simZ; /** * Constructor. @@ -48,15 +49,30 @@ private void initSim(SimDeviceSim simDevice) { Objects.requireNonNull(m_simZ); } - public void setX(double x) { - m_simX.set(x); + /** + * Sets the X acceleration. + * + * @param accel The X acceleration. + */ + public void setX(double accel) { + m_simX.set(accel); } - public void setY(double y) { - m_simY.set(y); + /** + * Sets the Y acceleration. + * + * @param accel The Y acceleration. + */ + public void setY(double accel) { + m_simY.set(accel); } - public void setZ(double z) { - m_simZ.set(z); + /** + * Sets the Z acceleration. + * + * @param accel The Z acceleration. + */ + public void setZ(double accel) { + m_simZ.set(accel); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/ADXL362Sim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/ADXL362Sim.java index 76df8bd6096..148f914699e 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/ADXL362Sim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/ADXL362Sim.java @@ -8,10 +8,11 @@ import edu.wpi.first.wpilibj.ADXL362; import java.util.Objects; +/** Class to control a simulated ADXL362. */ public class ADXL362Sim { - protected SimDouble m_simX; - protected SimDouble m_simY; - protected SimDouble m_simZ; + private SimDouble m_simX; + private SimDouble m_simY; + private SimDouble m_simZ; /** * Constructor. @@ -34,15 +35,30 @@ private void initSim(SimDeviceSim wrappedSimDevice) { Objects.requireNonNull(m_simZ); } - public void setX(double x) { - m_simX.set(x); + /** + * Sets the X acceleration. + * + * @param accel The X acceleration. + */ + public void setX(double accel) { + m_simX.set(accel); } - public void setY(double y) { - m_simY.set(y); + /** + * Sets the Y acceleration. + * + * @param accel The Y acceleration. + */ + public void setY(double accel) { + m_simY.set(accel); } - public void setZ(double z) { - m_simZ.set(z); + /** + * Sets the Z acceleration. + * + * @param accel The Z acceleration. + */ + public void setZ(double accel) { + m_simZ.set(accel); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/DCMotorSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/DCMotorSim.java index 5561fc10570..0a86c11f68b 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/DCMotorSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/DCMotorSim.java @@ -4,7 +4,6 @@ package edu.wpi.first.wpilibj.simulation; -import edu.wpi.first.math.Matrix; import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.numbers.N1; import edu.wpi.first.math.numbers.N2; @@ -12,6 +11,7 @@ import edu.wpi.first.math.system.plant.DCMotor; import edu.wpi.first.math.system.plant.LinearSystemId; import edu.wpi.first.math.util.Units; +import edu.wpi.first.wpilibj.RobotController; /** Represents a simulated DC motor mechanism. */ public class DCMotorSim extends LinearSystemSim { @@ -25,30 +25,17 @@ public class DCMotorSim extends LinearSystemSim { * Creates a simulated DC motor mechanism. * * @param plant The linear system representing the DC motor. This system can be created with - * {@link edu.wpi.first.math.system.plant.LinearSystemId#createDCMotorSystem(DCMotor, double, - * double)}. * @param gearbox The type of and number of motors in the DC motor gearbox. * @param gearing The gearing of the DC motor (numbers greater than 1 represent reductions). - */ - public DCMotorSim(LinearSystem plant, DCMotor gearbox, double gearing) { - super(plant); - m_gearbox = gearbox; - m_gearing = gearing; - } - - /** - * Creates a simulated DC motor mechanism. - * - * @param plant The linear system representing the DC motor. This system can be created with - * @param gearbox The type of and number of motors in the DC motor gearbox. - * @param gearing The gearing of the DC motor (numbers greater than 1 represent reductions). - * @param measurementStdDevs The standard deviations of the measurements. + * @param measurementStdDevs The standard deviations of the measurements. Can be omitted if no + * noise is desired. If present must have 2 elements. The first element is for position. The + * second element is for velocity. */ public DCMotorSim( LinearSystem plant, DCMotor gearbox, double gearing, - Matrix measurementStdDevs) { + double... measurementStdDevs) { super(plant, measurementStdDevs); m_gearbox = gearbox; m_gearing = gearing; @@ -60,25 +47,13 @@ public DCMotorSim( * @param gearbox The type of and number of motors in the DC motor gearbox. * @param gearing The gearing of the DC motor (numbers greater than 1 represent reductions). * @param jKgMetersSquared The moment of inertia of the DC motor. If this is unknown, use the - * {@link #DCMotorSim(LinearSystem, DCMotor, double, Matrix)} constructor. - */ - public DCMotorSim(DCMotor gearbox, double gearing, double jKgMetersSquared) { - super(LinearSystemId.createDCMotorSystem(gearbox, jKgMetersSquared, gearing)); - m_gearbox = gearbox; - m_gearing = gearing; - } - - /** - * Creates a simulated DC motor mechanism. - * - * @param gearbox The type of and number of motors in the DC motor gearbox. - * @param gearing The gearing of the DC motor (numbers greater than 1 represent reductions). - * @param jKgMetersSquared The moment of inertia of the DC motor. If this is unknown, use the - * {@link #DCMotorSim(LinearSystem, DCMotor, double, Matrix)} constructor. - * @param measurementStdDevs The standard deviations of the measurements. + * {@link #DCMotorSim(LinearSystem, DCMotor, double, double...)} constructor. + * @param measurementStdDevs The standard deviations of the measurements. Can be omitted if no + * noise is desired. If present must have 2 elements. The first element is for position. The + * second element is for velocity. */ public DCMotorSim( - DCMotor gearbox, double gearing, double jKgMetersSquared, Matrix measurementStdDevs) { + DCMotor gearbox, double gearing, double jKgMetersSquared, double... measurementStdDevs) { super( LinearSystemId.createDCMotorSystem(gearbox, jKgMetersSquared, gearing), measurementStdDevs); m_gearbox = gearbox; @@ -136,12 +111,11 @@ public double getAngularVelocityRPM() { * * @return The DC motor current draw. */ - @Override public double getCurrentDrawAmps() { // I = V / R - omega / (Kv * R) // Reductions are output over input, so a reduction of 2:1 means the motor is spinning // 2x faster than the output - return m_gearbox.getCurrent(getAngularVelocityRadPerSec() * m_gearing, m_u.get(0, 0)) + return m_gearbox.getCurrent(m_x.get(1, 0) * m_gearing, m_u.get(0, 0)) * Math.signum(m_u.get(0, 0)); } @@ -152,5 +126,6 @@ public double getCurrentDrawAmps() { */ public void setInputVoltage(double volts) { setInput(volts); + clampInput(RobotController.getBatteryVoltage()); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/DifferentialDrivetrainSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/DifferentialDrivetrainSim.java index 67133f6e9ca..a1216598f25 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/DifferentialDrivetrainSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/DifferentialDrivetrainSim.java @@ -236,12 +236,9 @@ public double getLeftVelocityMetersPerSecond() { * @return the drivetrain's left side current draw, in amps */ public double getLeftCurrentDrawAmps() { - var loadIleft = - m_motor.getCurrent( - getState(State.kLeftVelocity) * m_currentGearing / m_wheelRadiusMeters, - m_u.get(0, 0)) - * Math.signum(m_u.get(0, 0)); - return loadIleft; + return m_motor.getCurrent( + getState(State.kLeftVelocity) * m_currentGearing / m_wheelRadiusMeters, m_u.get(0, 0)) + * Math.signum(m_u.get(0, 0)); } /** @@ -250,13 +247,9 @@ public double getLeftCurrentDrawAmps() { * @return the drivetrain's right side current draw, in amps */ public double getRightCurrentDrawAmps() { - var loadIright = - m_motor.getCurrent( - getState(State.kRightVelocity) * m_currentGearing / m_wheelRadiusMeters, - m_u.get(1, 0)) - * Math.signum(m_u.get(1, 0)); - - return loadIright; + return m_motor.getCurrent( + getState(State.kRightVelocity) * m_currentGearing / m_wheelRadiusMeters, m_u.get(1, 0)) + * Math.signum(m_u.get(1, 0)); } /** @@ -308,6 +301,13 @@ public void setPose(Pose2d pose) { m_x.set(State.kRightPosition.value, 0, 0); } + /** + * The differential drive dynamics function. + * + * @param x The state. + * @param u The input. + * @return The state derivative with respect to time. + */ protected Matrix getDynamics(Matrix x, Matrix u) { // Because G can be factored out of B, we can divide by the old ratio and multiply // by the new ratio to get a new drivetrain model. @@ -376,12 +376,18 @@ enum State { * and 16:48 8.45:1 -- 14:50 and 19:45 7.31:1 -- 14:50 and 21:43 5.95:1 -- 14:50 and 24:40 */ public enum KitbotGearing { + /** Gear ratio of 12.75:1. */ k12p75(12.75), + /** Gear ratio of 10.71:1. */ k10p71(10.71), + /** Gear ratio of 8.45:1. */ k8p45(8.45), + /** Gear ratio of 7.31:1. */ k7p31(7.31), + /** Gear ratio of 5.95:1. */ k5p95(5.95); + /** KitbotGearing value. */ public final double value; KitbotGearing(double i) { @@ -391,15 +397,24 @@ public enum KitbotGearing { /** Represents common motor layouts of the kit drivetrain. */ public enum KitbotMotor { + /** One CIM motor per drive side. */ kSingleCIMPerSide(DCMotor.getCIM(1)), + /** Two CIM motors per drive side. */ kDualCIMPerSide(DCMotor.getCIM(2)), + /** One Mini CIM motor per drive side. */ kSingleMiniCIMPerSide(DCMotor.getMiniCIM(1)), + /** Two Mini CIM motors per drive side. */ kDualMiniCIMPerSide(DCMotor.getMiniCIM(2)), + /** One Falcon 500 motor per drive side. */ kSingleFalcon500PerSide(DCMotor.getFalcon500(1)), + /** Two Falcon 500 motors per drive side. */ kDoubleFalcon500PerSide(DCMotor.getFalcon500(2)), + /** One NEO motor per drive side. */ kSingleNEOPerSide(DCMotor.getNEO(1)), + /** Two NEO motors per drive side. */ kDoubleNEOPerSide(DCMotor.getNEO(2)); + /** KitbotMotor value. */ public final DCMotor value; KitbotMotor(DCMotor i) { @@ -409,10 +424,14 @@ public enum KitbotMotor { /** Represents common wheel sizes of the kit drivetrain. */ public enum KitbotWheelSize { + /** Six inch diameter wheels. */ kSixInch(Units.inchesToMeters(6)), + /** Eight inch diameter wheels. */ kEightInch(Units.inchesToMeters(8)), + /** Ten inch diameter wheels. */ kTenInch(Units.inchesToMeters(10)); + /** KitbotWheelSize value. */ public final double value; KitbotWheelSize(double i) { diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/ElevatorSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/ElevatorSim.java index 322d897479c..2f7ce3e768d 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/ElevatorSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/ElevatorSim.java @@ -13,9 +13,10 @@ import edu.wpi.first.math.system.NumericalIntegration; import edu.wpi.first.math.system.plant.DCMotor; import edu.wpi.first.math.system.plant.LinearSystemId; +import edu.wpi.first.wpilibj.RobotController; /** Represents a simulated elevator mechanism. */ -public class ElevatorSim extends LinearSystemSim { +public class ElevatorSim extends LinearSystemSim { // Gearbox for the elevator. private final DCMotor m_gearbox; @@ -39,16 +40,18 @@ public class ElevatorSim extends LinearSystemSim { * @param maxHeightMeters The max allowable height of the elevator. * @param simulateGravity Whether gravity should be simulated or not. * @param startingHeightMeters The starting height of the elevator. - * @param measurementStdDevs The standard deviations of the measurements. + * @param measurementStdDevs The standard deviations of the measurements. Can be omitted if no + * noise is desired. If present must have 1 element for position. */ + @SuppressWarnings("this-escape") public ElevatorSim( - LinearSystem plant, + LinearSystem plant, DCMotor gearbox, double minHeightMeters, double maxHeightMeters, boolean simulateGravity, double startingHeightMeters, - Matrix measurementStdDevs) { + double... measurementStdDevs) { super(plant, measurementStdDevs); m_gearbox = gearbox; m_minHeight = minHeightMeters; @@ -58,65 +61,6 @@ public ElevatorSim( setState(startingHeightMeters, 0); } - /** - * Creates a simulated elevator mechanism. - * - * @param plant The linear system that represents the elevator. This system can be created with - * {@link edu.wpi.first.math.system.plant.LinearSystemId#createElevatorSystem(DCMotor, double, - * double, double)}. - * @param gearbox The type of and number of motors in the elevator gearbox. - * @param minHeightMeters The min allowable height of the elevator. - * @param maxHeightMeters The max allowable height of the elevator. - * @param startingHeightMeters The starting height of the elevator. - * @param simulateGravity Whether gravity should be simulated or not. - */ - public ElevatorSim( - LinearSystem plant, - DCMotor gearbox, - double minHeightMeters, - double maxHeightMeters, - boolean simulateGravity, - double startingHeightMeters) { - this( - plant, - gearbox, - minHeightMeters, - maxHeightMeters, - simulateGravity, - startingHeightMeters, - null); - } - - /** - * Creates a simulated elevator mechanism. - * - * @param kV The velocity gain. - * @param kA The acceleration gain. - * @param gearbox The type of and number of motors in the elevator gearbox. - * @param minHeightMeters The min allowable height of the elevator. - * @param maxHeightMeters The max allowable height of the elevator. - * @param simulateGravity Whether gravity should be simulated or not. - * @param startingHeightMeters The starting height of the elevator. - */ - public ElevatorSim( - double kV, - double kA, - DCMotor gearbox, - double minHeightMeters, - double maxHeightMeters, - boolean simulateGravity, - double startingHeightMeters) { - this( - kV, - kA, - gearbox, - minHeightMeters, - maxHeightMeters, - simulateGravity, - startingHeightMeters, - null); - } - /** * Creates a simulated elevator mechanism. * @@ -127,7 +71,8 @@ public ElevatorSim( * @param maxHeightMeters The max allowable height of the elevator. * @param simulateGravity Whether gravity should be simulated or not. * @param startingHeightMeters The starting height of the elevator. - * @param measurementStdDevs The standard deviations of the measurements. + * @param measurementStdDevs The standard deviations of the measurements. Can be omitted if no + * noise is desired. If present must have 1 element for position. */ public ElevatorSim( double kV, @@ -137,7 +82,7 @@ public ElevatorSim( double maxHeightMeters, boolean simulateGravity, double startingHeightMeters, - Matrix measurementStdDevs) { + double... measurementStdDevs) { this( LinearSystemId.identifyPositionSystem(kV, kA), gearbox, @@ -159,7 +104,8 @@ public ElevatorSim( * @param maxHeightMeters The max allowable height of the elevator. * @param simulateGravity Whether gravity should be simulated or not. * @param startingHeightMeters The starting height of the elevator. - * @param measurementStdDevs The standard deviations of the measurements. + * @param measurementStdDevs The standard deviations of the measurements. Can be omitted if no + * noise is desired. If present must have 1 element for position. */ public ElevatorSim( DCMotor gearbox, @@ -170,7 +116,7 @@ public ElevatorSim( double maxHeightMeters, boolean simulateGravity, double startingHeightMeters, - Matrix measurementStdDevs) { + double... measurementStdDevs) { this( LinearSystemId.createElevatorSystem(gearbox, carriageMassKg, drumRadiusMeters, gearing), gearbox, @@ -181,39 +127,6 @@ public ElevatorSim( measurementStdDevs); } - /** - * Creates a simulated elevator mechanism. - * - * @param gearbox The type of and number of motors in the elevator gearbox. - * @param gearing The gearing of the elevator (numbers greater than 1 represent reductions). - * @param carriageMassKg The mass of the elevator carriage. - * @param drumRadiusMeters The radius of the drum that the elevator spool is wrapped around. - * @param minHeightMeters The min allowable height of the elevator. - * @param maxHeightMeters The max allowable height of the elevator. - * @param simulateGravity Whether gravity should be simulated or not. - * @param startingHeightMeters The starting height of the elevator. - */ - public ElevatorSim( - DCMotor gearbox, - double gearing, - double carriageMassKg, - double drumRadiusMeters, - double minHeightMeters, - double maxHeightMeters, - boolean simulateGravity, - double startingHeightMeters) { - this( - gearbox, - gearing, - carriageMassKg, - drumRadiusMeters, - minHeightMeters, - maxHeightMeters, - simulateGravity, - startingHeightMeters, - null); - } - /** * Sets the elevator's state. The new position will be limited between the minimum and maximum * allowed heights. @@ -221,7 +134,7 @@ public ElevatorSim( * @param positionMeters The new position in meters. * @param velocityMetersPerSecond New velocity in meters per second. */ - public void setState(double positionMeters, double velocityMetersPerSecond) { + public final void setState(double positionMeters, double velocityMetersPerSecond) { setState( VecBuilder.fill( MathUtil.clamp(positionMeters, m_minHeight, m_maxHeight), velocityMetersPerSecond)); @@ -280,7 +193,7 @@ public double getPositionMeters() { * @return The velocity of the elevator. */ public double getVelocityMetersPerSecond() { - return m_x.get(1, 0); + return getOutput(1); } /** @@ -288,7 +201,6 @@ public double getVelocityMetersPerSecond() { * * @return The elevator current draw. */ - @Override public double getCurrentDrawAmps() { // I = V / R - omega / (Kv * R) // Reductions are greater than 1, so a reduction of 10:1 would mean the motor is @@ -296,8 +208,7 @@ public double getCurrentDrawAmps() { // v = r w, so w = v/r double kA = 1 / m_plant.getB().get(1, 0); double kV = -m_plant.getA().get(1, 1) * kA; - double motorVelocityRadPerSec = - getVelocityMetersPerSecond() * kV * m_gearbox.KvRadPerSecPerVolt; + double motorVelocityRadPerSec = m_x.get(1, 0) * kV * m_gearbox.KvRadPerSecPerVolt; var appliedVoltage = m_u.get(0, 0); return m_gearbox.getCurrent(motorVelocityRadPerSec, appliedVoltage) * Math.signum(appliedVoltage); @@ -310,6 +221,7 @@ public double getCurrentDrawAmps() { */ public void setInputVoltage(double volts) { setInput(volts); + clampInput(RobotController.getBatteryVoltage()); } /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/EncoderSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/EncoderSim.java index 310dbf6c49e..4bc12dc8e1f 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/EncoderSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/EncoderSim.java @@ -329,10 +329,10 @@ public double getDistancePerPulse() { /** * Set the distance per pulse value. * - * @param samplesToAverage the new value + * @param distancePerPulse the new distancePerPulse */ - public void setDistancePerPulse(double samplesToAverage) { - EncoderDataJNI.setDistancePerPulse(m_index, samplesToAverage); + public void setDistancePerPulse(double distancePerPulse) { + EncoderDataJNI.setDistancePerPulse(m_index, distancePerPulse); } /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/FlywheelSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/FlywheelSim.java index 9c224880fd5..eb3d8e63907 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/FlywheelSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/FlywheelSim.java @@ -4,13 +4,13 @@ package edu.wpi.first.wpilibj.simulation; -import edu.wpi.first.math.Matrix; import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.numbers.N1; import edu.wpi.first.math.system.LinearSystem; import edu.wpi.first.math.system.plant.DCMotor; import edu.wpi.first.math.system.plant.LinearSystemId; import edu.wpi.first.math.util.Units; +import edu.wpi.first.wpilibj.RobotController; /** Represents a simulated flywheel mechanism. */ public class FlywheelSim extends LinearSystemSim { @@ -20,34 +20,20 @@ public class FlywheelSim extends LinearSystemSim { // The gearing from the motors to the output. private final double m_gearing; - /** - * Creates a simulated flywheel mechanism. - * - * @param plant The linear system that represents the flywheel. This system can be created with - * {@link edu.wpi.first.math.system.plant.LinearSystemId#createFlywheelSystem(DCMotor, double, - * double)}. - * @param gearbox The type of and number of motors in the flywheel gearbox. - * @param gearing The gearing of the flywheel (numbers greater than 1 represent reductions). - */ - public FlywheelSim(LinearSystem plant, DCMotor gearbox, double gearing) { - super(plant); - m_gearbox = gearbox; - m_gearing = gearing; - } - /** * Creates a simulated flywheel mechanism. * * @param plant The linear system that represents the flywheel. * @param gearbox The type of and number of motors in the flywheel gearbox. * @param gearing The gearing of the flywheel (numbers greater than 1 represent reductions). - * @param measurementStdDevs The standard deviations of the measurements. + * @param measurementStdDevs The standard deviations of the measurements. Can be omitted if no + * noise is desired. If present must have 1 element for velocity. */ public FlywheelSim( LinearSystem plant, DCMotor gearbox, double gearing, - Matrix measurementStdDevs) { + double... measurementStdDevs) { super(plant, measurementStdDevs); m_gearbox = gearbox; m_gearing = gearing; @@ -59,25 +45,12 @@ public FlywheelSim( * @param gearbox The type of and number of motors in the flywheel gearbox. * @param gearing The gearing of the flywheel (numbers greater than 1 represent reductions). * @param jKgMetersSquared The moment of inertia of the flywheel. If this is unknown, use the - * {@link #FlywheelSim(LinearSystem, DCMotor, double, Matrix)} constructor. - */ - public FlywheelSim(DCMotor gearbox, double gearing, double jKgMetersSquared) { - super(LinearSystemId.createFlywheelSystem(gearbox, jKgMetersSquared, gearing)); - m_gearbox = gearbox; - m_gearing = gearing; - } - - /** - * Creates a simulated flywheel mechanism. - * - * @param gearbox The type of and number of motors in the flywheel gearbox. - * @param gearing The gearing of the flywheel (numbers greater than 1 represent reductions). - * @param jKgMetersSquared The moment of inertia of the flywheel. If this is unknown, use the - * {@link #FlywheelSim(LinearSystem, DCMotor, double, Matrix)} constructor. - * @param measurementStdDevs The standard deviations of the measurements. + * {@link #FlywheelSim(LinearSystem, DCMotor, double, double...)} constructor. + * @param measurementStdDevs The standard deviations of the measurements. Can be omitted if no + * noise is desired. If present must have 1 element for velocity. */ public FlywheelSim( - DCMotor gearbox, double gearing, double jKgMetersSquared, Matrix measurementStdDevs) { + DCMotor gearbox, double gearing, double jKgMetersSquared, double... measurementStdDevs) { super( LinearSystemId.createFlywheelSystem(gearbox, jKgMetersSquared, gearing), measurementStdDevs); @@ -117,7 +90,6 @@ public double getAngularVelocityRPM() { * * @return The flywheel current draw. */ - @Override public double getCurrentDrawAmps() { // I = V / R - omega / (Kv * R) // Reductions are output over input, so a reduction of 2:1 means the motor is spinning @@ -133,5 +105,6 @@ public double getCurrentDrawAmps() { */ public void setInputVoltage(double volts) { setInput(volts); + clampInput(RobotController.getBatteryVoltage()); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/GenericHIDSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/GenericHIDSim.java index 8a81f53247a..9c81be88bd9 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/GenericHIDSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/GenericHIDSim.java @@ -8,6 +8,7 @@ /** Class to control a simulated generic joystick. */ public class GenericHIDSim { + /** GenericHID port. */ protected final int m_port; /** @@ -135,7 +136,7 @@ public void setAxisType(int axis, int type) { */ public boolean getOutput(int outputNumber) { long outputs = getOutputs(); - return (outputs & (1 << (outputNumber - 1))) != 0; + return (outputs & (1L << (outputNumber - 1))) != 0; } /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/JoystickSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/JoystickSim.java index f55b0384999..b6f21e313cf 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/JoystickSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/JoystickSim.java @@ -15,6 +15,7 @@ public class JoystickSim extends GenericHIDSim { * * @param joystick joystick to simulate */ + @SuppressWarnings("this-escape") public JoystickSim(Joystick joystick) { super(joystick); m_joystick = joystick; @@ -29,6 +30,7 @@ public JoystickSim(Joystick joystick) { * * @param port port number */ + @SuppressWarnings("this-escape") public JoystickSim(int port) { super(port); // default to a reasonable joystick configuration diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/LinearSystemSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/LinearSystemSim.java index 73b1170eab4..ec296fde3d8 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/LinearSystemSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/LinearSystemSim.java @@ -9,7 +9,6 @@ import edu.wpi.first.math.StateSpaceUtil; import edu.wpi.first.math.numbers.N1; import edu.wpi.first.math.system.LinearSystem; -import edu.wpi.first.wpilibj.RobotController; import org.ejml.MatrixDimensionException; import org.ejml.simple.SimpleMatrix; @@ -23,44 +22,48 @@ * *

    Set simulated sensor readings with the simulated positions in {@link #getOutput()} * - * @param The number of states of the system. - * @param The number of inputs to the system. - * @param The number of outputs of the system. + * @param Number of states of the system. + * @param Number of inputs to the system. + * @param Number of outputs of the system. */ public class LinearSystemSim { - // The plant that represents the linear system. + /** The plant that represents the linear system. */ protected final LinearSystem m_plant; - // Variables for state, output, and input. + /** State vector. */ protected Matrix m_x; - protected Matrix m_y; + + /** Input vector. */ protected Matrix m_u; - // The standard deviations of measurements, used for adding noise - // to the measurements. - protected final Matrix m_measurementStdDevs; + /** Output vector. */ + protected Matrix m_y; - /** - * Creates a simulated generic linear system. - * - * @param system The system to simulate. - */ - public LinearSystemSim(LinearSystem system) { - this(system, null); - } + /** The standard deviations of measurements, used for adding noise to the measurements. */ + protected final Matrix m_measurementStdDevs; /** * Creates a simulated generic linear system with measurement noise. * * @param system The system being controlled. - * @param measurementStdDevs Standard deviations of measurements. Can be null if no noise is - * desired. + * @param measurementStdDevs Standard deviations of measurements. Can be empty if no noise is + * desired. If present must have same number of items as Outputs */ public LinearSystemSim( - LinearSystem system, Matrix measurementStdDevs) { + LinearSystem system, double... measurementStdDevs) { + if (measurementStdDevs.length != 0 && measurementStdDevs.length != system.getC().getNumRows()) { + throw new MatrixDimensionException( + "Malformed measurementStdDevs! Got " + + measurementStdDevs.length + + " elements instead of " + + system.getC().getNumRows()); + } this.m_plant = system; - this.m_measurementStdDevs = measurementStdDevs; - + if (measurementStdDevs.length == 0) { + m_measurementStdDevs = new Matrix<>(new SimpleMatrix(system.getC().getNumRows(), 1)); + } else { + m_measurementStdDevs = new Matrix<>(new SimpleMatrix(measurementStdDevs)); + } m_x = new Matrix<>(new SimpleMatrix(system.getA().getNumRows(), 1)); m_u = new Matrix<>(new SimpleMatrix(system.getB().getNumCols(), 1)); m_y = new Matrix<>(new SimpleMatrix(system.getC().getNumRows(), 1)); @@ -109,7 +112,7 @@ public double getOutput(int row) { * @param u The system inputs. */ public void setInput(Matrix u) { - this.m_u = clampInput(u); + this.m_u = u; } /** @@ -120,7 +123,6 @@ public void setInput(Matrix u) { */ public void setInput(int row, double value) { m_u.set(row, 0, value); - m_u = clampInput(m_u); } /** @@ -137,22 +139,31 @@ public void setInput(double... u) { } /** - * Sets the system state. + * Returns the current input of the plant. * - * @param state The new state. + * @return The current input of the plant. */ - public void setState(Matrix state) { - m_x = state; + public Matrix getInput() { + return m_u; } /** - * Returns the current drawn by this simulated system. Override this method to add a custom - * current calculation. + * Returns an element of the current input of the plant. * - * @return The current drawn by this simulated mechanism. + * @param row The row to return. + * @return An element of the current input of the plant. */ - public double getCurrentDrawAmps() { - return 0.0; + public double getInput(int row) { + return m_u.get(row, 0); + } + + /** + * Sets the system state. + * + * @param state The new state. + */ + public void setState(Matrix state) { + m_x = state; } /** @@ -169,13 +180,12 @@ protected Matrix updateX( } /** - * Clamp the input vector such that no element exceeds the given voltage. If any does, the + * Clamp the input vector such that no element exceeds the maximum allowed value. If any does, the * relative magnitudes of the input will be maintained. * - * @param u The input vector. - * @return The normalized input. + * @param maxInput The maximum magnitude of the input vector after clamping. */ - protected Matrix clampInput(Matrix u) { - return StateSpaceUtil.desaturateInputVector(u, RobotController.getBatteryVoltage()); + protected void clampInput(double maxInput) { + m_u = StateSpaceUtil.desaturateInputVector(m_u, maxInput); } } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/PS4ControllerSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/PS4ControllerSim.java index fa19760974b..822b1db58f1 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/PS4ControllerSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/PS4ControllerSim.java @@ -13,6 +13,7 @@ public class PS4ControllerSim extends GenericHIDSim { * * @param joystick controller to simulate */ + @SuppressWarnings("this-escape") public PS4ControllerSim(PS4Controller joystick) { super(joystick); setAxisCount(6); @@ -25,6 +26,7 @@ public PS4ControllerSim(PS4Controller joystick) { * * @param port port number */ + @SuppressWarnings("this-escape") public PS4ControllerSim(int port) { super(port); setAxisCount(6); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/PS5ControllerSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/PS5ControllerSim.java index d886bd6e71b..e11cdd084ce 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/PS5ControllerSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/PS5ControllerSim.java @@ -13,6 +13,7 @@ public class PS5ControllerSim extends GenericHIDSim { * * @param joystick controller to simulate */ + @SuppressWarnings("this-escape") public PS5ControllerSim(PS5Controller joystick) { super(joystick); setAxisCount(6); @@ -25,6 +26,7 @@ public PS5ControllerSim(PS5Controller joystick) { * * @param port port number */ + @SuppressWarnings("this-escape") public PS5ControllerSim(int port) { super(port); setAxisCount(6); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/PneumaticsBaseSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/PneumaticsBaseSim.java index 156562b48a4..dde69c1891c 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/PneumaticsBaseSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/PneumaticsBaseSim.java @@ -10,6 +10,7 @@ /** Common base class for pneumatics module simulation classes. */ public abstract class PneumaticsBaseSim { + /** PneumaticsBase index. */ protected final int m_index; /** @@ -30,10 +31,20 @@ public static PneumaticsBaseSim getForType(int module, PneumaticsModuleType type } } + /** + * Constructs a PneumaticsBaseSim with the given index. + * + * @param index The index. + */ protected PneumaticsBaseSim(int index) { m_index = index; } + /** + * Constructs a PneumaticsBaseSim for the given module. + * + * @param module The module. + */ protected PneumaticsBaseSim(PneumaticsBase module) { this(module.getModuleNumber()); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/RoboRioSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/RoboRioSim.java index 8b28b6ddf53..e2bc895127b 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/RoboRioSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/RoboRioSim.java @@ -6,6 +6,8 @@ import edu.wpi.first.hal.simulation.NotifyCallback; import edu.wpi.first.hal.simulation.RoboRioDataJNI; +import edu.wpi.first.wpilibj.RobotController; +import edu.wpi.first.wpilibj.RobotController.RadioLEDState; /** A utility class to control a simulated RoboRIO. */ public final class RoboRioSim { @@ -625,6 +627,38 @@ public static void setComments(String comments) { RoboRioDataJNI.setComments(comments); } + /** + * Register a callback to be run whenever the Radio led state changes. + * + * @param callback the callback + * @param initialNotify whether to call the callback with the initial state + * @return the {@link CallbackStore} object associated with this callback. Save a reference to + * this object so GC doesn't cancel the callback. + */ + public static CallbackStore registerRadioLEDStateCallback( + NotifyCallback callback, boolean initialNotify) { + int uid = RoboRioDataJNI.registerRadioLEDStateCallback(callback, initialNotify); + return new CallbackStore(uid, RoboRioDataJNI::cancelRadioLEDStateCallback); + } + + /** + * Get the state of the radio led. + * + * @return The state of the radio led. + */ + public static RadioLEDState getRadioLEDState() { + return RadioLEDState.fromValue(RoboRioDataJNI.getRadioLEDState()); + } + + /** + * Set the state of the radio led. + * + * @param state The state of the radio led. + */ + public static void setRadioLEDState(RobotController.RadioLEDState state) { + RoboRioDataJNI.setRadioLEDState(state.value); + } + /** Reset all simulation data. */ public static void resetData() { RoboRioDataJNI.resetData(); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/SPISim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/SPISim.java index 6c0b9e99b5c..8ce955418a2 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/SPISim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/SPISim.java @@ -74,6 +74,13 @@ public CallbackStore registerWriteCallback(ConstBufferCallback callback) { return new CallbackStore(m_index, uid, SPIDataJNI::cancelWriteCallback); } + /** + * Register a callback to be run whenever an auto receive buffer is received. + * + * @param callback the callback + * @return the {@link CallbackStore} object associated with this callback. Save a reference to + * this object so GC doesn't cancel the callback. + */ public CallbackStore registerReadAutoReceiveBufferCallback( SpiReadAutoReceiveBufferCallback callback) { int uid = SPIDataJNI.registerReadAutoReceiveBufferCallback(m_index, callback); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/SimHooks.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/SimHooks.java index 1664081de98..f637b01d708 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/SimHooks.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/SimHooks.java @@ -6,6 +6,7 @@ import edu.wpi.first.hal.simulation.SimulatorJNI; +/** Simulation hooks. */ public final class SimHooks { private SimHooks() {} @@ -18,14 +19,21 @@ public static void setHALRuntimeType(int type) { SimulatorJNI.setRuntimeType(type); } + /** Waits until the user program has started. */ public static void waitForProgramStart() { SimulatorJNI.waitForProgramStart(); } + /** Sets that the user program has started. */ public static void setProgramStarted() { SimulatorJNI.setProgramStarted(); } + /** + * Returns true if the user program has started. + * + * @return True if the user program has started. + */ public static boolean getProgramStarted() { return SimulatorJNI.getProgramStarted(); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/SingleJointedArmSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/SingleJointedArmSim.java index af2ee85b87d..ba0442f7829 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/SingleJointedArmSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/SingleJointedArmSim.java @@ -13,9 +13,10 @@ import edu.wpi.first.math.system.NumericalIntegration; import edu.wpi.first.math.system.plant.DCMotor; import edu.wpi.first.math.system.plant.LinearSystemId; +import edu.wpi.first.wpilibj.RobotController; /** Represents a simulated single jointed arm mechanism. */ -public class SingleJointedArmSim extends LinearSystemSim { +public class SingleJointedArmSim extends LinearSystemSim { // The gearbox for the arm. private final DCMotor m_gearbox; @@ -47,10 +48,12 @@ public class SingleJointedArmSim extends LinearSystemSim { * @param maxAngleRads The maximum angle that the arm is capable of. * @param simulateGravity Whether gravity should be simulated or not. * @param startingAngleRads The initial position of the Arm simulation in radians. - * @param measurementStdDevs The standard deviations of the measurements. + * @param measurementStdDevs The standard deviations of the measurements. Can be omitted if no + * noise is desired. If present must have 1 element for position. */ + @SuppressWarnings("this-escape") public SingleJointedArmSim( - LinearSystem plant, + LinearSystem plant, DCMotor gearbox, double gearing, double armLengthMeters, @@ -58,7 +61,7 @@ public SingleJointedArmSim( double maxAngleRads, boolean simulateGravity, double startingAngleRads, - Matrix measurementStdDevs) { + double... measurementStdDevs) { super(plant, measurementStdDevs); m_gearbox = gearbox; m_gearing = gearing; @@ -70,74 +73,6 @@ public SingleJointedArmSim( setState(startingAngleRads, 0.0); } - /** - * Creates a simulated arm mechanism. - * - * @param plant The linear system that represents the arm. This system can be created with {@link - * edu.wpi.first.math.system.plant.LinearSystemId#createSingleJointedArmSystem(DCMotor, - * double, double)}. - * @param gearbox The type of and number of motors in the arm gearbox. - * @param gearing The gearing of the arm (numbers greater than 1 represent reductions). - * @param armLengthMeters The length of the arm. - * @param minAngleRads The minimum angle that the arm is capable of. - * @param maxAngleRads The maximum angle that the arm is capable of. - * @param simulateGravity Whether gravity should be simulated or not. - * @param startingAngleRads The initial position of the Arm simulation in radians. - */ - public SingleJointedArmSim( - LinearSystem plant, - DCMotor gearbox, - double gearing, - double armLengthMeters, - double minAngleRads, - double maxAngleRads, - boolean simulateGravity, - double startingAngleRads) { - this( - plant, - gearbox, - gearing, - armLengthMeters, - minAngleRads, - maxAngleRads, - simulateGravity, - startingAngleRads, - null); - } - - /** - * Creates a simulated arm mechanism. - * - * @param gearbox The type of and number of motors in the arm gearbox. - * @param gearing The gearing of the arm (numbers greater than 1 represent reductions). - * @param jKgMetersSquared The moment of inertia of the arm, can be calculated from CAD software. - * @param armLengthMeters The length of the arm. - * @param minAngleRads The minimum angle that the arm is capable of. - * @param maxAngleRads The maximum angle that the arm is capable of. - * @param simulateGravity Whether gravity should be simulated or not. - * @param startingAngleRads The initial position of the Arm simulation in radians. - */ - public SingleJointedArmSim( - DCMotor gearbox, - double gearing, - double jKgMetersSquared, - double armLengthMeters, - double minAngleRads, - double maxAngleRads, - boolean simulateGravity, - double startingAngleRads) { - this( - gearbox, - gearing, - jKgMetersSquared, - armLengthMeters, - minAngleRads, - maxAngleRads, - simulateGravity, - startingAngleRads, - null); - } - /** * Creates a simulated arm mechanism. * @@ -149,7 +84,8 @@ public SingleJointedArmSim( * @param maxAngleRads The maximum angle that the arm is capable of. * @param simulateGravity Whether gravity should be simulated or not. * @param startingAngleRads The initial position of the Arm simulation in radians. - * @param measurementStdDevs The standard deviations of the measurements. + * @param measurementStdDevs The standard deviations of the measurements. Can be omitted if no + * noise is desired. If present must have 1 element for position. */ public SingleJointedArmSim( DCMotor gearbox, @@ -160,7 +96,7 @@ public SingleJointedArmSim( double maxAngleRads, boolean simulateGravity, double startingAngleRads, - Matrix measurementStdDevs) { + double... measurementStdDevs) { this( LinearSystemId.createSingleJointedArmSystem(gearbox, jKgMetersSquared, gearing), gearbox, @@ -180,7 +116,7 @@ public SingleJointedArmSim( * @param angleRadians The new angle in radians. * @param velocityRadPerSec The new angular velocity in radians per second. */ - public void setState(double angleRadians, double velocityRadPerSec) { + public final void setState(double angleRadians, double velocityRadPerSec) { setState( VecBuilder.fill(MathUtil.clamp(angleRadians, m_minAngle, m_maxAngle), velocityRadPerSec)); } @@ -229,7 +165,7 @@ public boolean hasHitUpperLimit() { * @return The current arm angle. */ public double getAngleRads() { - return m_y.get(0, 0); + return getOutput(0); } /** @@ -238,7 +174,7 @@ public double getAngleRads() { * @return The current arm velocity. */ public double getVelocityRadPerSec() { - return m_x.get(1, 0); + return getOutput(1); } /** @@ -246,7 +182,6 @@ public double getVelocityRadPerSec() { * * @return The aram current draw. */ - @Override public double getCurrentDrawAmps() { // Reductions are greater than 1, so a reduction of 10:1 would mean the motor is // spinning 10x faster than the output @@ -261,6 +196,7 @@ public double getCurrentDrawAmps() { */ public void setInputVoltage(double volts) { setInput(volts); + clampInput(RobotController.getBatteryVoltage()); } /** diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/UltrasonicSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/UltrasonicSim.java index dc4ebaade19..2ad42e7afaf 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/UltrasonicSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/UltrasonicSim.java @@ -36,14 +36,29 @@ public UltrasonicSim(@SuppressWarnings("unused") int ping, int echo) { m_simRange = simDevice.getDouble("Range (in)"); } + /** + * Sets if the range measurement is valid. + * + * @param valid True if valid + */ public void setRangeValid(boolean valid) { m_simRangeValid.set(valid); } + /** + * Sets the range measurement. + * + * @param inches The range in inches. + */ public void setRangeInches(double inches) { m_simRange.set(inches); } + /** + * Sets the range measurement. + * + * @param meters The range in meters. + */ public void setRangeMeters(double meters) { m_simRange.set(Units.metersToInches(meters)); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/XboxControllerSim.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/XboxControllerSim.java index 41d200e1617..37e0bda32d8 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/XboxControllerSim.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/simulation/XboxControllerSim.java @@ -13,6 +13,7 @@ public class XboxControllerSim extends GenericHIDSim { * * @param joystick controller to simulate */ + @SuppressWarnings("this-escape") public XboxControllerSim(XboxController joystick) { super(joystick); setAxisCount(6); @@ -25,6 +26,7 @@ public XboxControllerSim(XboxController joystick) { * * @param port port number */ + @SuppressWarnings("this-escape") public XboxControllerSim(int port) { super(port); setAxisCount(6); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/Field2d.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/Field2d.java index bfacb428cd9..7ce6af8c3e8 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/Field2d.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/Field2d.java @@ -31,9 +31,10 @@ */ public class Field2d implements NTSendable, AutoCloseable { /** Constructor. */ + @SuppressWarnings("this-escape") public Field2d() { FieldObject2d obj = new FieldObject2d("Robot"); - obj.setPose(new Pose2d()); + obj.setPose(Pose2d.kZero); m_objects.add(obj); SendableRegistry.add(this, "Field"); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/FieldObject2d.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/FieldObject2d.java index 9ffccde047b..f3627a6bef1 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/FieldObject2d.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/FieldObject2d.java @@ -10,6 +10,7 @@ import edu.wpi.first.math.trajectory.Trajectory; import edu.wpi.first.networktables.DoubleArrayEntry; import java.util.ArrayList; +import java.util.Collections; import java.util.List; /** Game field object on a Field2d. */ @@ -58,7 +59,7 @@ public synchronized void setPose(double xMeters, double yMeters, Rotation2d rota public synchronized Pose2d getPose() { updateFromEntry(); if (m_poses.isEmpty()) { - return new Pose2d(); + return Pose2d.kZero; } return m_poses.get(0); } @@ -70,9 +71,7 @@ public synchronized Pose2d getPose() { */ public synchronized void setPoses(List poses) { m_poses.clear(); - for (Pose2d pose : poses) { - m_poses.add(pose); - } + m_poses.addAll(poses); updateEntry(); } @@ -83,9 +82,7 @@ public synchronized void setPoses(List poses) { */ public synchronized void setPoses(Pose2d... poses) { m_poses.clear(); - for (Pose2d pose : poses) { - m_poses.add(pose); - } + Collections.addAll(m_poses, poses); updateEntry(); } @@ -109,7 +106,7 @@ public synchronized void setTrajectory(Trajectory trajectory) { */ public synchronized List getPoses() { updateFromEntry(); - return new ArrayList(m_poses); + return new ArrayList<>(m_poses); } void updateEntry() { @@ -143,7 +140,7 @@ private synchronized void updateFromEntry() { return; } - double[] arr = m_entry.get((double[]) null); + double[] arr = m_entry.get(null); if (arr != null) { if ((arr.length % 3) != 0) { return; diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/ListenerExecutor.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/ListenerExecutor.java index 19a3fc107f8..9d0efa24f28 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/ListenerExecutor.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/ListenerExecutor.java @@ -31,9 +31,9 @@ public void execute(Runnable task) { /** Runs all posted tasks. Called periodically from main thread. */ public void runListenerTasks() { // Locally copy tasks from internal list; minimizes blocking time - Collection tasks = new ArrayList<>(); + Collection tasks; synchronized (m_lock) { - tasks.addAll(m_tasks); + tasks = new ArrayList<>(m_tasks); m_tasks.clear(); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/MechanismLigament2d.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/MechanismLigament2d.java index 28484a39e4f..ea7fda38bf7 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/MechanismLigament2d.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/MechanismLigament2d.java @@ -82,7 +82,7 @@ public void close() { * * @param degrees the angle in degrees */ - public synchronized void setAngle(double degrees) { + public final synchronized void setAngle(double degrees) { m_angle = degrees; if (m_angleEntry != null) { m_angleEntry.set(degrees); @@ -115,7 +115,7 @@ public synchronized double getAngle() { * * @param length the line length */ - public synchronized void setLength(double length) { + public final synchronized void setLength(double length) { m_length = length; if (m_lengthEntry != null) { m_lengthEntry.set(length); @@ -139,7 +139,7 @@ public synchronized double getLength() { * * @param color the color of the line */ - public synchronized void setColor(Color8Bit color) { + public final synchronized void setColor(Color8Bit color) { m_color = String.format("#%02X%02X%02X", color.red, color.green, color.blue); if (m_colorEntry != null) { m_colorEntry.set(m_color); @@ -177,7 +177,7 @@ public synchronized Color8Bit getColor() { * * @param weight the line thickness */ - public synchronized void setLineWeight(double weight) { + public final synchronized void setLineWeight(double weight) { m_weight = weight; if (m_weightEntry != null) { m_weightEntry.set(weight); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/MechanismObject2d.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/MechanismObject2d.java index 754bd9256cf..3dbcf5c11c3 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/MechanismObject2d.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/MechanismObject2d.java @@ -74,6 +74,11 @@ final synchronized void update(NetworkTable table) { */ protected abstract void updateEntries(NetworkTable table); + /** + * Retrieve the object's name. + * + * @return the object's name relative to its parent. + */ public final String getName() { return m_name; } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SendableBuilderImpl.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SendableBuilderImpl.java index 2c409e8314c..f15198fd102 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SendableBuilderImpl.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SendableBuilderImpl.java @@ -57,6 +57,7 @@ import java.util.function.LongSupplier; import java.util.function.Supplier; +/** Implementation detail for SendableBuilder. */ @SuppressWarnings("PMD.CompareObjectsWithEquals") public class SendableBuilderImpl implements NTSendableBuilder { @FunctionalInterface @@ -109,6 +110,9 @@ void update(boolean controllable, long time) { private final List m_closeables = new ArrayList<>(); + /** Default constructor. */ + public SendableBuilderImpl() {} + @Override @SuppressWarnings("PMD.AvoidCatchingGenericException") public void close() { diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooser.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooser.java index 7f3b93c1f4a..e905ebc6350 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooser.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooser.java @@ -53,6 +53,7 @@ public class SendableChooser implements Sendable, AutoCloseable { private static final AtomicInteger s_instances = new AtomicInteger(); /** Instantiates a {@link SendableChooser}. */ + @SuppressWarnings("this-escape") public SendableChooser() { m_instance = s_instances.getAndIncrement(); SendableRegistry.add(this, "SendableChooser", m_instance); diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboard.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboard.java index 8a8f147964e..7da170b84ea 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboard.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboard.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj.smartdashboard; +import edu.wpi.first.hal.FRCNetComm.tInstances; import edu.wpi.first.hal.FRCNetComm.tResourceType; import edu.wpi.first.hal.HAL; import edu.wpi.first.networktables.NetworkTable; @@ -35,9 +36,10 @@ public final class SmartDashboard { /** The executor for listener tasks; calls listener tasks synchronously from main thread. */ private static final ListenerExecutor listenerExecutor = new ListenerExecutor(); + private static boolean m_reported = false; // NOPMD redundant field initializer + static { setNetworkTableInstance(NetworkTableInstance.getDefault()); - HAL.report(tResourceType.kResourceType_SmartDashboard, 0); } private SmartDashboard() { @@ -64,6 +66,10 @@ public static synchronized void setNetworkTableInstance(NetworkTableInstance ins */ @SuppressWarnings("PMD.CompareObjectsWithEquals") public static synchronized void putData(String key, Sendable data) { + if (!m_reported) { + HAL.report(tResourceType.kResourceType_SmartDashboard, tInstances.kSmartDashboard_Instance); + m_reported = true; + } Sendable sddata = tablesToData.get(key); if (sddata == null || sddata != data) { tablesToData.put(key, data); @@ -114,6 +120,10 @@ public static synchronized Sendable getData(String key) { * @return Network table entry. */ public static NetworkTableEntry getEntry(String key) { + if (!m_reported) { + HAL.report(tResourceType.kResourceType_SmartDashboard, tInstances.kSmartDashboard_Instance); + m_reported = true; + } return table.getEntry(key); } diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/sysid/SysIdRoutineLog.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/sysid/SysIdRoutineLog.java new file mode 100644 index 00000000000..a8d7d940e8d --- /dev/null +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/sysid/SysIdRoutineLog.java @@ -0,0 +1,227 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.wpilibj.sysid; + +import static edu.wpi.first.units.Units.Amps; +import static edu.wpi.first.units.Units.Meters; +import static edu.wpi.first.units.Units.MetersPerSecond; +import static edu.wpi.first.units.Units.Rotations; +import static edu.wpi.first.units.Units.RotationsPerSecond; +import static edu.wpi.first.units.Units.Second; +import static edu.wpi.first.units.Units.Volts; + +import edu.wpi.first.units.Angle; +import edu.wpi.first.units.Current; +import edu.wpi.first.units.Distance; +import edu.wpi.first.units.Measure; +import edu.wpi.first.units.Velocity; +import edu.wpi.first.units.Voltage; +import edu.wpi.first.util.datalog.DoubleLogEntry; +import edu.wpi.first.util.datalog.StringLogEntry; +import edu.wpi.first.wpilibj.DataLogManager; +import java.util.HashMap; +import java.util.Map; + +/** + * Utility for logging data from a SysId test routine. Each complete routine (quasistatic and + * dynamic, forward and reverse) should have its own SysIdRoutineLog instance, with a unique log + * name. + */ +public class SysIdRoutineLog { + private final Map> m_logEntries = new HashMap<>(); + private final String m_logName; + private StringLogEntry m_state; + + /** + * Create a new logging utility for a SysId test routine. + * + * @param logName The name for the test routine in the log. Should be unique between complete test + * routines (quasistatic and dynamic, forward and reverse). The current state of this test + * (e.g. "quasistatic-forward") will appear in WPILog under the "sysid-test-state-logName" + * entry. + */ + public SysIdRoutineLog(String logName) { + m_logName = logName; + } + + /** Possible state of a SysId routine. */ + public enum State { + /** Quasistatic forward test. */ + kQuasistaticForward("quasistatic-forward"), + /** Quasistatic reverse test. */ + kQuasistaticReverse("quasistatic-reverse"), + /** Dynamic forward test. */ + kDynamicForward("dynamic-forward"), + /** Dynamic reverse test. */ + kDynamicReverse("dynamic-reverse"), + /** No test. */ + kNone("none"); + + private final String m_state; + + State(String state) { + m_state = state; + } + + @Override + public String toString() { + return m_state; + } + } + + /** Logs data from a single motor during a SysIdRoutine. */ + public class MotorLog { + private final String m_motorName; + + /** + * Create a new SysId motor log handle. + * + * @param motorName The name of the motor whose data is being logged. + */ + private MotorLog(String motorName) { + m_motorName = motorName; + m_logEntries.put(motorName, new HashMap<>()); + } + + /** + * Log a generic data value from the motor. + * + * @param name The name of the data field being recorded. + * @param value The numeric value of the data field. + * @param unit The unit string of the data field. + * @return The motor log (for call chaining). + */ + public MotorLog value(String name, double value, String unit) { + var motorEntries = m_logEntries.get(m_motorName); + var entry = motorEntries.get(name); + + if (entry == null) { + var log = DataLogManager.getLog(); + + entry = new DoubleLogEntry(log, name + "-" + m_motorName + "-" + m_logName, unit); + motorEntries.put(name, entry); + } + + entry.append(value); + return this; + } + + /** + * Log the voltage applied to the motor. + * + * @param voltage The voltage to record. + * @return The motor log (for call chaining). + */ + public MotorLog voltage(Measure voltage) { + return value("voltage", voltage.in(Volts), Volts.name()); + } + + /** + * Log the linear position of the motor. + * + * @param position The linear position to record. + * @return The motor log (for call chaining). + */ + public MotorLog linearPosition(Measure position) { + return value("position", position.in(Meters), Meters.name()); + } + + /** + * Log the angular position of the motor. + * + * @param position The angular position to record. + * @return The motor log (for call chaining). + */ + public MotorLog angularPosition(Measure position) { + return value("position", position.in(Rotations), Rotations.name()); + } + + /** + * Log the linear velocity of the motor. + * + * @param velocity The linear velocity to record. + * @return The motor log (for call chaining). + */ + public MotorLog linearVelocity(Measure> velocity) { + return value("velocity", velocity.in(MetersPerSecond), MetersPerSecond.name()); + } + + /** + * Log the angular velocity of the motor. + * + * @param velocity The angular velocity to record. + * @return The motor log (for call chaining). + */ + public MotorLog angularVelocity(Measure> velocity) { + return value("velocity", velocity.in(RotationsPerSecond), RotationsPerSecond.name()); + } + + /** + * Log the linear acceleration of the motor. + * + *

    This is optional; SysId can perform an accurate fit without it. + * + * @param acceleration The linear acceleration to record. + * @return The motor log (for call chaining). + */ + public MotorLog linearAcceleration(Measure>> acceleration) { + return value( + "acceleration", + acceleration.in(MetersPerSecond.per(Second)), + MetersPerSecond.per(Second).name()); + } + + /** + * Log the angular acceleration of the motor. + * + *

    This is optional; SysId can perform an accurate fit without it. + * + * @param acceleration The angular acceleration to record. + * @return The motor log (for call chaining). + */ + public MotorLog angularAcceleration(Measure>> acceleration) { + return value( + "acceleration", + acceleration.in(RotationsPerSecond.per(Second)), + RotationsPerSecond.per(Second).name()); + } + + /** + * Log the current applied to the motor. + * + *

    This is optional; SysId can perform an accurate fit without it. + * + * @param current The current to record. + * @return The motor log (for call chaining). + */ + public MotorLog current(Measure current) { + value("current", current.in(Amps), Amps.name()); + return this; + } + } + + /** + * Log data from a motor during a SysId routine. + * + * @param motorName The name of the motor. + * @return Handle with chainable callbacks to log individual data fields. + */ + public MotorLog motor(String motorName) { + return new MotorLog(motorName); + } + + /** + * Records the current state of the SysId test routine. Should be called once per iteration during + * tests with the type of the current test, and once upon test end with state `none`. + * + * @param state The current state of the SysId test routine. + */ + public void recordState(State state) { + if (m_state == null) { + m_state = new StringLogEntry(DataLogManager.getLog(), "sysid-test-state-" + m_logName); + } + m_state.append(state.toString()); + } +} diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/util/Color.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/util/Color.java index 2defbd8ad36..50605676f75 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/util/Color.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/util/Color.java @@ -14,13 +14,24 @@ */ @SuppressWarnings("MemberName") public class Color { - private static final double kPrecision = Math.pow(2, -12); - + /** Red component (0-1). */ public final double red; + + /** Green component (0-1). */ public final double green; + + /** Blue component (0-1). */ public final double blue; + private String m_name; + /** Constructs a default color (black). */ + public Color() { + red = 0.0; + green = 0.0; + blue = 0.0; + } + /** * Constructs a Color from doubles. * @@ -69,6 +80,22 @@ private Color(double red, double green, double blue, String name) { this.m_name = name; } + /** + * Constructs a Color from a hex string. + * + * @param hexString a string of the format #RRGGBB + * @throws IllegalArgumentException if the hex string is invalid. + */ + public Color(String hexString) { + if (hexString.length() != 7 || !hexString.startsWith("#")) { + throw new IllegalArgumentException("Invalid hex string \"" + hexString + "\""); + } + + this.red = Integer.valueOf(hexString.substring(1, 3), 16) / 255.0; + this.green = Integer.valueOf(hexString.substring(3, 5), 16) / 255.0; + this.blue = Integer.valueOf(hexString.substring(5, 7), 16) / 255.0; + } + /** * Creates a Color from HSV values. * @@ -155,8 +182,7 @@ public String toHexString() { } private static double roundAndClamp(double value) { - final var rounded = Math.round((value + kPrecision / 2) / kPrecision) * kPrecision; - return MathUtil.clamp(rounded, 0.0, 1.0); + return MathUtil.clamp(Math.ceil(value * (1 << 12)) / (1 << 12), 0.0, 1.0); } /* diff --git a/wpilibj/src/main/java/edu/wpi/first/wpilibj/util/Color8Bit.java b/wpilibj/src/main/java/edu/wpi/first/wpilibj/util/Color8Bit.java index 32606731006..132ea64a417 100644 --- a/wpilibj/src/main/java/edu/wpi/first/wpilibj/util/Color8Bit.java +++ b/wpilibj/src/main/java/edu/wpi/first/wpilibj/util/Color8Bit.java @@ -10,10 +10,22 @@ /** Represents colors with 8 bits of precision. */ @SuppressWarnings("MemberName") public class Color8Bit { + /** Red component (0-255). */ public final int red; + + /** Green component (0-255). */ public final int green; + + /** Blue component (0-255). */ public final int blue; + /** Constructs a default color (black). */ + public Color8Bit() { + red = 0; + green = 0; + blue = 0; + } + /** * Constructs a Color8Bit. * @@ -36,6 +48,22 @@ public Color8Bit(Color color) { this((int) (color.red * 255), (int) (color.green * 255), (int) (color.blue * 255)); } + /** + * Constructs a Color8Bit from a hex string. + * + * @param hexString a string of the format #RRGGBB + * @throws IllegalArgumentException if the hex string is invalid. + */ + public Color8Bit(String hexString) { + if (hexString.length() != 7 || !hexString.startsWith("#")) { + throw new IllegalArgumentException("Invalid hex string \"" + hexString + "\""); + } + + this.red = Integer.valueOf(hexString.substring(1, 3), 16); + this.green = Integer.valueOf(hexString.substring(3, 5), 16); + this.blue = Integer.valueOf(hexString.substring(5, 7), 16); + } + @Override public boolean equals(Object other) { if (this == other) { diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/AddressableLEDBufferTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/AddressableLEDBufferTest.java index 9bf5d88aebd..6c6c145f1d9 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/AddressableLEDBufferTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/AddressableLEDBufferTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.params.provider.Arguments.arguments; import edu.wpi.first.wpilibj.util.Color; @@ -70,4 +71,73 @@ void getColorTest() { assertEquals(firstRedColor8Bit, buffer.getLED8Bit(2)); assertEquals(firstBlueColor8Bit, buffer.getLED8Bit(3)); } + + @Test + void getRed() { + var buffer = new AddressableLEDBuffer(1); + buffer.setRGB(0, 127, 128, 129); + assertEquals(127, buffer.getRed(0)); + } + + @Test + void getGreen() { + var buffer = new AddressableLEDBuffer(1); + buffer.setRGB(0, 127, 128, 129); + assertEquals(128, buffer.getGreen(0)); + } + + @Test + void getBlue() { + var buffer = new AddressableLEDBuffer(1); + buffer.setRGB(0, 127, 128, 129); + assertEquals(129, buffer.getBlue(0)); + } + + @Test + void forEach() { + var buffer = new AddressableLEDBuffer(3); + buffer.setRGB(0, 1, 2, 3); + buffer.setRGB(1, 4, 5, 6); + buffer.setRGB(2, 7, 8, 9); + + buffer.forEach( + (index, r, g, b) -> { + switch (index) { + case 0: + { + assertAll( + () -> assertEquals(1, r, "red at index 0"), + () -> assertEquals(2, g, "green at index 0"), + () -> assertEquals(3, b, "blue at index 0")); + } + break; + case 1: + { + assertAll( + () -> assertEquals(4, r, "red at index 1"), + () -> assertEquals(5, g, "green at index 1"), + () -> assertEquals(6, b, "blue at index 1")); + } + break; + case 2: + { + assertAll( + () -> assertEquals(7, r, "red at index 2"), + () -> assertEquals(8, g, "green at index 2"), + () -> assertEquals(9, b, "blue at index 2")); + } + break; + default: + fail("Unexpected index " + index); + break; + } + }); + } + + @Test + void forEachOnEmptyBuffer() { + var buffer = new AddressableLEDBuffer(0); + + buffer.forEach((i, r, g, b) -> fail("Iterator should not be called on an empty buffer")); + } } diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/GenericHIDTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/GenericHIDTest.java new file mode 100644 index 00000000000..c22037668d6 --- /dev/null +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/GenericHIDTest.java @@ -0,0 +1,56 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.wpilibj; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import edu.wpi.first.wpilibj.GenericHID.RumbleType; +import edu.wpi.first.wpilibj.simulation.GenericHIDSim; +import org.junit.jupiter.api.Test; + +class GenericHIDTest { + private static final double kEpsilon = 0.0001; + + @Test + void testRumbleRange() { + GenericHID hid = new GenericHID(0); + GenericHIDSim sim = new GenericHIDSim(0); + + for (int i = 0; i <= 100; i++) { + double rumbleValue = i / 100.0; + hid.setRumble(RumbleType.kBothRumble, rumbleValue); + assertEquals(rumbleValue, sim.getRumble(RumbleType.kLeftRumble), kEpsilon); + assertEquals(rumbleValue, sim.getRumble(RumbleType.kRightRumble), kEpsilon); + } + } + + @Test + void testRumbleTypes() { + GenericHID hid = new GenericHID(0); + GenericHIDSim sim = new GenericHIDSim(0); + + // Make sure both are off + hid.setRumble(RumbleType.kBothRumble, 0); + assertEquals(0, sim.getRumble(RumbleType.kBothRumble), kEpsilon); + + // test both + hid.setRumble(RumbleType.kBothRumble, 1); + assertEquals(1, sim.getRumble(RumbleType.kLeftRumble), kEpsilon); + assertEquals(1, sim.getRumble(RumbleType.kRightRumble), kEpsilon); + hid.setRumble(RumbleType.kBothRumble, 0); + + // test left only + hid.setRumble(RumbleType.kLeftRumble, 1); + assertEquals(1, sim.getRumble(RumbleType.kLeftRumble), kEpsilon); + assertEquals(0, sim.getRumble(RumbleType.kRightRumble), kEpsilon); + hid.setRumble(RumbleType.kLeftRumble, 0); + + // test right only + hid.setRumble(RumbleType.kRightRumble, 1); + assertEquals(0, sim.getRumble(RumbleType.kLeftRumble), kEpsilon); + assertEquals(1, sim.getRumble(RumbleType.kRightRumble), kEpsilon); + hid.setRumble(RumbleType.kRightRumble, 0); + } +} diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimedRobotTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimedRobotTest.java index c1c5f3c1286..920fb546e8c 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimedRobotTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimedRobotTest.java @@ -144,11 +144,7 @@ void cleanup() { void disabledModeTest() { MockRobot robot = new MockRobot(); - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(false); @@ -231,11 +227,7 @@ void disabledModeTest() { void autonomousModeTest() { MockRobot robot = new MockRobot(); - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(true); @@ -320,11 +312,7 @@ void autonomousModeTest() { void teleopModeTest() { MockRobot robot = new MockRobot(); - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(true); @@ -411,11 +399,7 @@ void testModeTest(boolean isLW) { MockRobot robot = new MockRobot(); robot.enableLiveWindowInTest(isLW); - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(true); @@ -531,11 +515,7 @@ void testModeTest(boolean isLW) { void modeChangeTest() { MockRobot robot = new MockRobot(); - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); // Start in disabled @@ -655,17 +635,9 @@ void addPeriodicTest() { MockRobot robot = new MockRobot(); final AtomicInteger callbackCount = new AtomicInteger(0); - robot.addPeriodic( - () -> { - callbackCount.addAndGet(1); - }, - kPeriod / 2.0); - - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + robot.addPeriodic(() -> callbackCount.addAndGet(1), kPeriod / 2.0); + + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(false); @@ -704,12 +676,7 @@ void addPeriodicWithOffsetTest() { MockRobot robot = new MockRobot(); final AtomicInteger callbackCount = new AtomicInteger(0); - robot.addPeriodic( - () -> { - callbackCount.addAndGet(1); - }, - kPeriod / 2.0, - kPeriod / 4.0); + robot.addPeriodic(() -> callbackCount.addAndGet(1), kPeriod / 2.0, kPeriod / 4.0); // Expirations in this test (ms) // @@ -720,11 +687,7 @@ void addPeriodicWithOffsetTest() { // p | 0.75p // 2p | 1.25p - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(false); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimesliceRobotTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimesliceRobotTest.java index ee4860deb7f..5cff0d0dc9a 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimesliceRobotTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/TimesliceRobotTest.java @@ -54,22 +54,10 @@ void scheduleTest() { // | RobotPeriodic() | 0 | 2 | // | Callback 1 | 2 | 0.5 | // | Callback 2 | 2.5 | 1 | - robot.schedule( - () -> { - callbackCount1.addAndGet(1); - }, - 0.0005); - robot.schedule( - () -> { - callbackCount2.addAndGet(1); - }, - 0.001); - - Thread robotThread = - new Thread( - () -> { - robot.startCompetition(); - }); + robot.schedule(() -> callbackCount1.addAndGet(1), 0.0005); + robot.schedule(() -> callbackCount2.addAndGet(1), 0.001); + + Thread robotThread = new Thread(robot::startCompetition); robotThread.start(); DriverStationSim.setEnabled(false); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/WatchdogTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/WatchdogTest.java index c1676e0c36e..5e9e1229418 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/WatchdogTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/WatchdogTest.java @@ -33,12 +33,7 @@ void cleanup() { void enableDisableTest() { final AtomicInteger watchdogCounter = new AtomicInteger(0); - try (Watchdog watchdog = - new Watchdog( - 0.4, - () -> { - watchdogCounter.addAndGet(1); - })) { + try (Watchdog watchdog = new Watchdog(0.4, () -> watchdogCounter.addAndGet(1))) { // Run 1 watchdog.enable(); SimHooks.stepTiming(0.2); @@ -71,12 +66,7 @@ void enableDisableTest() { void resetTest() { final AtomicInteger watchdogCounter = new AtomicInteger(0); - try (Watchdog watchdog = - new Watchdog( - 0.4, - () -> { - watchdogCounter.addAndGet(1); - })) { + try (Watchdog watchdog = new Watchdog(0.4, () -> watchdogCounter.addAndGet(1))) { watchdog.enable(); SimHooks.stepTiming(0.2); watchdog.reset(); @@ -92,12 +82,7 @@ void resetTest() { void setTimeoutTest() { final AtomicInteger watchdogCounter = new AtomicInteger(0); - try (Watchdog watchdog = - new Watchdog( - 1.0, - () -> { - watchdogCounter.addAndGet(1); - })) { + try (Watchdog watchdog = new Watchdog(1.0, () -> watchdogCounter.addAndGet(1))) { watchdog.enable(); SimHooks.stepTiming(0.2); watchdog.setTimeout(0.2); @@ -137,12 +122,7 @@ void isExpiredTest() { void epochsTest() { final AtomicInteger watchdogCounter = new AtomicInteger(0); - try (Watchdog watchdog = - new Watchdog( - 0.4, - () -> { - watchdogCounter.addAndGet(1); - })) { + try (Watchdog watchdog = new Watchdog(0.4, () -> watchdogCounter.addAndGet(1))) { // Run 1 watchdog.enable(); watchdog.addEpoch("Epoch 1"); @@ -173,18 +153,8 @@ void multiWatchdogTest() { final AtomicInteger watchdogCounter1 = new AtomicInteger(0); final AtomicInteger watchdogCounter2 = new AtomicInteger(0); - try (Watchdog watchdog1 = - new Watchdog( - 0.2, - () -> { - watchdogCounter1.addAndGet(1); - }); - Watchdog watchdog2 = - new Watchdog( - 0.6, - () -> { - watchdogCounter2.addAndGet(1); - })) { + try (Watchdog watchdog1 = new Watchdog(0.2, () -> watchdogCounter1.addAndGet(1)); + Watchdog watchdog2 = new Watchdog(0.6, () -> watchdogCounter2.addAndGet(1))) { watchdog2.enable(); SimHooks.stepTiming(0.25); assertEquals(0, watchdogCounter1.get(), "Watchdog triggered early"); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/drive/DifferentialDriveTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/drive/DifferentialDriveTest.java index 4675a7f2be0..0546a4ce890 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/drive/DifferentialDriveTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/drive/DifferentialDriveTest.java @@ -6,9 +6,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import edu.wpi.first.wpilibj.motorcontrol.MockMotorController; +import edu.wpi.first.wpilibj.motorcontrol.MockPWMMotorController; import org.junit.jupiter.api.Test; +@SuppressWarnings("resource") class DifferentialDriveTest { @Test void testArcadeDriveIK() { @@ -250,9 +251,9 @@ void testTankDriveIKSquared() { @Test void testArcadeDrive() { - var left = new MockMotorController(); - var right = new MockMotorController(); - var drive = new DifferentialDrive(left, right); + var left = new MockPWMMotorController(); + var right = new MockPWMMotorController(); + var drive = new DifferentialDrive(left::set, right::set); drive.setDeadband(0.0); // Forward @@ -288,9 +289,9 @@ void testArcadeDrive() { @Test void testArcadeDriveSquared() { - var left = new MockMotorController(); - var right = new MockMotorController(); - var drive = new DifferentialDrive(left, right); + var left = new MockPWMMotorController(); + var right = new MockPWMMotorController(); + var drive = new DifferentialDrive(left::set, right::set); drive.setDeadband(0.0); // Forward @@ -326,9 +327,9 @@ void testArcadeDriveSquared() { @Test void testCurvatureDrive() { - var left = new MockMotorController(); - var right = new MockMotorController(); - var drive = new DifferentialDrive(left, right); + var left = new MockPWMMotorController(); + var right = new MockPWMMotorController(); + var drive = new DifferentialDrive(left::set, right::set); drive.setDeadband(0.0); // Forward @@ -364,9 +365,9 @@ void testCurvatureDrive() { @Test void testCurvatureDriveTurnInPlace() { - var left = new MockMotorController(); - var right = new MockMotorController(); - var drive = new DifferentialDrive(left, right); + var left = new MockPWMMotorController(); + var right = new MockPWMMotorController(); + var drive = new DifferentialDrive(left::set, right::set); drive.setDeadband(0.0); // Forward @@ -402,9 +403,9 @@ void testCurvatureDriveTurnInPlace() { @Test void testTankDrive() { - var left = new MockMotorController(); - var right = new MockMotorController(); - var drive = new DifferentialDrive(left, right); + var left = new MockPWMMotorController(); + var right = new MockPWMMotorController(); + var drive = new DifferentialDrive(left::set, right::set); drive.setDeadband(0.0); // Forward @@ -440,9 +441,9 @@ void testTankDrive() { @Test void testTankDriveSquared() { - var left = new MockMotorController(); - var right = new MockMotorController(); - var drive = new DifferentialDrive(left, right); + var left = new MockPWMMotorController(); + var right = new MockPWMMotorController(); + var drive = new DifferentialDrive(left::set, right::set); drive.setDeadband(0.0); // Forward diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/drive/MecanumDriveTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/drive/MecanumDriveTest.java index 034ba10c0cd..8236693446e 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/drive/MecanumDriveTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/drive/MecanumDriveTest.java @@ -7,9 +7,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import edu.wpi.first.math.geometry.Rotation2d; -import edu.wpi.first.wpilibj.motorcontrol.MockMotorController; +import edu.wpi.first.wpilibj.motorcontrol.MockPWMMotorController; import org.junit.jupiter.api.Test; +@SuppressWarnings("resource") class MecanumDriveTest { @Test void testCartesianIK() { @@ -52,35 +53,35 @@ void testCartesianIK() { @Test void testCartesianIKGyro90CW() { // Forward in global frame; left in robot frame - var speeds = MecanumDrive.driveCartesianIK(1.0, 0.0, 0.0, Rotation2d.fromDegrees(90.0)); + var speeds = MecanumDrive.driveCartesianIK(1.0, 0.0, 0.0, Rotation2d.kCCW_Pi_2); assertEquals(-1.0, speeds.frontLeft, 1e-9); assertEquals(1.0, speeds.frontRight, 1e-9); assertEquals(1.0, speeds.rearLeft, 1e-9); assertEquals(-1.0, speeds.rearRight, 1e-9); // Left in global frame; backward in robot frame - speeds = MecanumDrive.driveCartesianIK(0.0, -1.0, 0.0, Rotation2d.fromDegrees(90.0)); + speeds = MecanumDrive.driveCartesianIK(0.0, -1.0, 0.0, Rotation2d.kCCW_Pi_2); assertEquals(-1.0, speeds.frontLeft, 1e-9); assertEquals(-1.0, speeds.frontRight, 1e-9); assertEquals(-1.0, speeds.rearLeft, 1e-9); assertEquals(-1.0, speeds.rearRight, 1e-9); // Right in global frame; forward in robot frame - speeds = MecanumDrive.driveCartesianIK(0.0, 1.0, 0.0, Rotation2d.fromDegrees(90.0)); + speeds = MecanumDrive.driveCartesianIK(0.0, 1.0, 0.0, Rotation2d.kCCW_Pi_2); assertEquals(1.0, speeds.frontLeft, 1e-9); assertEquals(1.0, speeds.frontRight, 1e-9); assertEquals(1.0, speeds.rearLeft, 1e-9); assertEquals(1.0, speeds.rearRight, 1e-9); // Rotate CCW - speeds = MecanumDrive.driveCartesianIK(0.0, 0.0, -1.0, Rotation2d.fromDegrees(90.0)); + speeds = MecanumDrive.driveCartesianIK(0.0, 0.0, -1.0, Rotation2d.kCCW_Pi_2); assertEquals(-1.0, speeds.frontLeft, 1e-9); assertEquals(1.0, speeds.frontRight, 1e-9); assertEquals(-1.0, speeds.rearLeft, 1e-9); assertEquals(1.0, speeds.rearRight, 1e-9); // Rotate CW - speeds = MecanumDrive.driveCartesianIK(0.0, 0.0, 1.0, Rotation2d.fromDegrees(90.0)); + speeds = MecanumDrive.driveCartesianIK(0.0, 0.0, 1.0, Rotation2d.kCCW_Pi_2); assertEquals(1.0, speeds.frontLeft, 1e-9); assertEquals(-1.0, speeds.frontRight, 1e-9); assertEquals(1.0, speeds.rearLeft, 1e-9); @@ -89,11 +90,11 @@ void testCartesianIKGyro90CW() { @Test void testCartesian() { - var fl = new MockMotorController(); - var fr = new MockMotorController(); - var rl = new MockMotorController(); - var rr = new MockMotorController(); - var drive = new MecanumDrive(fl, rl, fr, rr); + var fl = new MockPWMMotorController(); + var rl = new MockPWMMotorController(); + var fr = new MockPWMMotorController(); + var rr = new MockPWMMotorController(); + var drive = new MecanumDrive(fl::set, rl::set, fr::set, rr::set); drive.setDeadband(0.0); // Forward @@ -134,43 +135,43 @@ void testCartesian() { @Test void testCartesianGyro90CW() { - var fl = new MockMotorController(); - var fr = new MockMotorController(); - var rl = new MockMotorController(); - var rr = new MockMotorController(); - var drive = new MecanumDrive(fl, rl, fr, rr); + var fl = new MockPWMMotorController(); + var rl = new MockPWMMotorController(); + var fr = new MockPWMMotorController(); + var rr = new MockPWMMotorController(); + var drive = new MecanumDrive(fl::set, rl::set, fr::set, rr::set); drive.setDeadband(0.0); // Forward in global frame; left in robot frame - drive.driveCartesian(1.0, 0.0, 0.0, Rotation2d.fromDegrees(90.0)); + drive.driveCartesian(1.0, 0.0, 0.0, Rotation2d.kCCW_Pi_2); assertEquals(-1.0, fl.get(), 1e-9); assertEquals(1.0, fr.get(), 1e-9); assertEquals(1.0, rl.get(), 1e-9); assertEquals(-1.0, rr.get(), 1e-9); // Left in global frame; backward in robot frame - drive.driveCartesian(0.0, -1.0, 0.0, Rotation2d.fromDegrees(90.0)); + drive.driveCartesian(0.0, -1.0, 0.0, Rotation2d.kCCW_Pi_2); assertEquals(-1.0, fl.get(), 1e-9); assertEquals(-1.0, fr.get(), 1e-9); assertEquals(-1.0, rl.get(), 1e-9); assertEquals(-1.0, rr.get(), 1e-9); // Right in global frame; forward in robot frame - drive.driveCartesian(0.0, 1.0, 0.0, Rotation2d.fromDegrees(90.0)); + drive.driveCartesian(0.0, 1.0, 0.0, Rotation2d.kCCW_Pi_2); assertEquals(1.0, fl.get(), 1e-9); assertEquals(1.0, fr.get(), 1e-9); assertEquals(1.0, rl.get(), 1e-9); assertEquals(1.0, rr.get(), 1e-9); // Rotate CCW - drive.driveCartesian(0.0, 0.0, -1.0, Rotation2d.fromDegrees(90.0)); + drive.driveCartesian(0.0, 0.0, -1.0, Rotation2d.kCCW_Pi_2); assertEquals(-1.0, fl.get(), 1e-9); assertEquals(1.0, fr.get(), 1e-9); assertEquals(-1.0, rl.get(), 1e-9); assertEquals(1.0, rr.get(), 1e-9); // Rotate CW - drive.driveCartesian(0.0, 0.0, 1.0, Rotation2d.fromDegrees(90.0)); + drive.driveCartesian(0.0, 0.0, 1.0, Rotation2d.kCCW_Pi_2); assertEquals(1.0, fl.get(), 1e-9); assertEquals(-1.0, fr.get(), 1e-9); assertEquals(1.0, rl.get(), 1e-9); @@ -179,43 +180,43 @@ void testCartesianGyro90CW() { @Test void testPolar() { - var fl = new MockMotorController(); - var fr = new MockMotorController(); - var rl = new MockMotorController(); - var rr = new MockMotorController(); - var drive = new MecanumDrive(fl, rl, fr, rr); + var fl = new MockPWMMotorController(); + var rl = new MockPWMMotorController(); + var fr = new MockPWMMotorController(); + var rr = new MockPWMMotorController(); + var drive = new MecanumDrive(fl::set, rl::set, fr::set, rr::set); drive.setDeadband(0.0); // Forward - drive.drivePolar(1.0, Rotation2d.fromDegrees(0.0), 0.0); + drive.drivePolar(1.0, Rotation2d.kZero, 0.0); assertEquals(1.0, fl.get(), 1e-9); assertEquals(1.0, fr.get(), 1e-9); assertEquals(1.0, rl.get(), 1e-9); assertEquals(1.0, rr.get(), 1e-9); // Left - drive.drivePolar(1.0, Rotation2d.fromDegrees(-90.0), 0.0); + drive.drivePolar(1.0, Rotation2d.kCW_Pi_2, 0.0); assertEquals(-1.0, fl.get(), 1e-9); assertEquals(1.0, fr.get(), 1e-9); assertEquals(1.0, rl.get(), 1e-9); assertEquals(-1.0, rr.get(), 1e-9); // Right - drive.drivePolar(1.0, Rotation2d.fromDegrees(90.0), 0.0); + drive.drivePolar(1.0, Rotation2d.kCCW_Pi_2, 0.0); assertEquals(1.0, fl.get(), 1e-9); assertEquals(-1.0, fr.get(), 1e-9); assertEquals(-1.0, rl.get(), 1e-9); assertEquals(1.0, rr.get(), 1e-9); // Rotate CCW - drive.drivePolar(0.0, Rotation2d.fromDegrees(0.0), -1.0); + drive.drivePolar(0.0, Rotation2d.kZero, -1.0); assertEquals(-1.0, fl.get(), 1e-9); assertEquals(1.0, fr.get(), 1e-9); assertEquals(-1.0, rl.get(), 1e-9); assertEquals(1.0, rr.get(), 1e-9); // Rotate CW - drive.drivePolar(0.0, Rotation2d.fromDegrees(0.0), 1.0); + drive.drivePolar(0.0, Rotation2d.kZero, 1.0); assertEquals(1.0, fl.get(), 1e-9); assertEquals(-1.0, fr.get(), 1e-9); assertEquals(1.0, rl.get(), 1e-9); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/event/EventLoopTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/event/EventLoopTest.java index ea3c569e656..644c18e15e5 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/event/EventLoopTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/event/EventLoopTest.java @@ -5,7 +5,9 @@ package edu.wpi.first.wpilibj.event; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import java.util.ConcurrentModificationException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; @@ -58,4 +60,33 @@ void testClear() { // shouldn't change assertEquals(1, counter.get()); } + + @Test + void testConcurrentModification() { + var loop = new EventLoop(); + + loop.bind( + () -> { + assertThrows( + ConcurrentModificationException.class, + () -> { + loop.bind(() -> {}); + }); + }); + + loop.poll(); + + loop.clear(); + + loop.bind( + () -> { + assertThrows( + ConcurrentModificationException.class, + () -> { + loop.clear(); + }); + }); + + loop.poll(); + } } diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/motorcontrol/MockMotorController.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/motorcontrol/MockMotorController.java index e7a6b8eb365..4ac3dc8f56f 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/motorcontrol/MockMotorController.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/motorcontrol/MockMotorController.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj.motorcontrol; +@SuppressWarnings("removal") public class MockMotorController implements MotorController { private double m_speed; private boolean m_isInverted; diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/motorcontrol/MockMotorController.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/motorcontrol/MockPWMMotorController.java similarity index 83% rename from wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/motorcontrol/MockMotorController.java rename to wpilibj/src/test/java/edu/wpi/first/wpilibj/motorcontrol/MockPWMMotorController.java index e7a6b8eb365..bf2c287f692 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/motorcontrol/MockMotorController.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/motorcontrol/MockPWMMotorController.java @@ -4,36 +4,30 @@ package edu.wpi.first.wpilibj.motorcontrol; -public class MockMotorController implements MotorController { +public class MockPWMMotorController { private double m_speed; private boolean m_isInverted; - @Override public void set(double speed) { m_speed = m_isInverted ? -speed : speed; } - @Override public double get() { return m_speed; } - @Override public void setInverted(boolean isInverted) { m_isInverted = isInverted; } - @Override public boolean getInverted() { return m_isInverted; } - @Override public void disable() { m_speed = 0; } - @Override public void stopMotor() { disable(); } diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/motorcontrol/MotorControllerGroupTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/motorcontrol/MotorControllerGroupTest.java index 6efb3def8b2..a8f71f6b6a9 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/motorcontrol/MotorControllerGroupTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/motorcontrol/MotorControllerGroupTest.java @@ -15,6 +15,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +@SuppressWarnings("removal") class MotorControllerGroupTest { private static Stream motorControllerArguments() { return IntStream.of(1, 2, 3) diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/shuffleboard/MockActuatorSendable.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/shuffleboard/MockActuatorSendable.java index 04397c2c4c5..a630c3e1afb 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/shuffleboard/MockActuatorSendable.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/shuffleboard/MockActuatorSendable.java @@ -10,6 +10,7 @@ /** A mock sendable that marks itself as an actuator. */ public class MockActuatorSendable implements Sendable { + @SuppressWarnings("this-escape") public MockActuatorSendable(String name) { SendableRegistry.add(this, name); } diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardInstanceTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardInstanceTest.java index 6283c68b40a..25b545b9713 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardInstanceTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/shuffleboard/ShuffleboardInstanceTest.java @@ -136,7 +136,7 @@ void testDuplicateSelectTabs() { try (StringSubscriber subscriber = m_ntInstance .getStringTopic("/Shuffleboard/.metadata/Selected") - .subscribe("", PubSubOption.keepDuplicates(true)); ) { + .subscribe("", PubSubOption.keepDuplicates(true))) { listener = m_ntInstance.addListener( subscriber, diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/AddressableLEDSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/AddressableLEDSimTest.java index 096f77e4c43..4ddadf1481d 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/AddressableLEDSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/AddressableLEDSimTest.java @@ -79,7 +79,7 @@ void testSetData() { BufferCallback callback = new BufferCallback(); try (AddressableLED led = new AddressableLED(0); - CallbackStore cb = sim.registerDataCallback(callback); ) { + CallbackStore cb = sim.registerDataCallback(callback)) { assertFalse(sim.getRunning()); assertEquals(1, sim.getLength()); // Defaults to 1 led diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/AnalogEncoderSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/AnalogEncoderSimTest.java index a04ce10bb0d..765420dac3c 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/AnalogEncoderSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/AnalogEncoderSimTest.java @@ -18,7 +18,7 @@ void testBasic() { var analogEncoder = new AnalogEncoder(analogInput)) { var encoderSim = new AnalogEncoderSim(analogEncoder); - encoderSim.setPosition(Rotation2d.fromDegrees(180)); + encoderSim.setPosition(Rotation2d.kPi); assertEquals(analogEncoder.get(), 0.5, 1E-8); assertEquals(encoderSim.getTurns(), 0.5, 1E-8); assertEquals(encoderSim.getPosition().getRadians(), Math.PI, 1E-8); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DCMotorSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DCMotorSimTest.java index fbe3af0a43f..681e6b41c5e 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DCMotorSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DCMotorSimTest.java @@ -63,7 +63,7 @@ void testPositionFeedbackControl() { try (var motor = new PWMVictorSPX(0); var encoder = new Encoder(0, 1); - var controller = new PIDController(0.04, 0.0, 0.001); ) { + var controller = new PIDController(0.04, 0.0, 0.001)) { var encoderSim = new EncoderSim(encoder); encoderSim.resetData(); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DifferentialDrivetrainSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DifferentialDrivetrainSimTest.java index cbb8d18c86f..25bbdb59834 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DifferentialDrivetrainSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DifferentialDrivetrainSimTest.java @@ -11,8 +11,8 @@ import edu.wpi.first.math.Nat; import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.Vector; +import edu.wpi.first.math.controller.LTVUnicycleController; import edu.wpi.first.math.controller.LinearPlantInversionFeedforward; -import edu.wpi.first.math.controller.RamseteController; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.kinematics.DifferentialDriveKinematics; @@ -47,7 +47,7 @@ void testConvergence() { VecBuilder.fill(0, 0, 0.0001, 0.1, 0.1, 0.005, 0.005)); var feedforward = new LinearPlantInversionFeedforward<>(plant, 0.020); - var ramsete = new RamseteController(); + var feedback = new LTVUnicycleController(0.020); feedforward.reset(VecBuilder.fill(0, 0)); // ground truth @@ -55,17 +55,17 @@ void testConvergence() { var traj = TrajectoryGenerator.generateTrajectory( - new Pose2d(), + Pose2d.kZero, List.of(), - new Pose2d(2, 2, new Rotation2d()), + new Pose2d(2, 2, Rotation2d.kZero), new TrajectoryConfig(1, 1) .addConstraint(new DifferentialDriveKinematicsConstraint(kinematics, 1))); for (double t = 0; t < traj.getTotalTimeSeconds(); t += 0.020) { var state = traj.sample(t); - var ramseteOut = ramsete.calculate(sim.getPose(), state); + var feedbackOut = feedback.calculate(sim.getPose(), state); - var wheelSpeeds = kinematics.toWheelSpeeds(ramseteOut); + var wheelSpeeds = kinematics.toWheelSpeeds(feedbackOut); var voltages = feedforward.calculate( diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DigitalPWMSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DigitalPWMSimTest.java index 9f29aaccdb4..8a0fc7cad43 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DigitalPWMSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DigitalPWMSimTest.java @@ -25,7 +25,7 @@ void testInitialization() { BooleanCallback initializeCallback = new BooleanCallback(); DoubleCallback dutyCycleCallback = new DoubleCallback(); try (CallbackStore initCb = sim.registerInitializedCallback(initializeCallback, false); - CallbackStore dutyCycleCb = sim.registerDutyCycleCallback(dutyCycleCallback, false); ) { + CallbackStore dutyCycleCb = sim.registerDutyCycleCallback(dutyCycleCallback, false)) { final double kTestDutyCycle = 0.191; output.enablePWM(kTestDutyCycle); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DriverStationSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DriverStationSimTest.java index 9a324d51538..54699e00363 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DriverStationSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/DriverStationSimTest.java @@ -108,14 +108,18 @@ void testFmsAttached() { void testDsAttached() { HAL.initialize(500, 0); DriverStationSim.resetData(); + DriverStation.refreshData(); + assertFalse(DriverStationSim.getDsAttached()); + assertFalse(DriverStation.isDSAttached()); DriverStationSim.notifyNewData(); + assertTrue(DriverStationSim.getDsAttached()); assertTrue(DriverStation.isDSAttached()); BooleanCallback callback = new BooleanCallback(); try (CallbackStore cb = DriverStationSim.registerDsAttachedCallback(callback, false)) { DriverStationSim.setDsAttached(false); - DriverStationSim.notifyNewData(); + DriverStation.refreshData(); assertFalse(DriverStationSim.getDsAttached()); assertFalse(DriverStation.isDSAttached()); assertTrue(callback.wasTriggered()); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/ElevatorSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/ElevatorSimTest.java index 336489a3340..deade245fa1 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/ElevatorSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/ElevatorSimTest.java @@ -22,6 +22,7 @@ class ElevatorSimTest { void testStateSpaceSimWithElevator() { RoboRioSim.resetData(); + @SuppressWarnings("resource") var controller = new PIDController(10, 0, 0); var sim = @@ -34,7 +35,8 @@ void testStateSpaceSimWithElevator() { 3.0, true, 0.0, - VecBuilder.fill(0.01)); + 0.01, + 0.0); try (var motor = new PWMVictorSPX(0); var encoder = new Encoder(0, 1)) { @@ -73,7 +75,8 @@ void testMinMax() { 1.0, true, 0.0, - VecBuilder.fill(0.01)); + 0.01, + 0.0); for (int i = 0; i < 100; i++) { sim.setInput(VecBuilder.fill(0)); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/RelaySimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/RelaySimTest.java index 3918361fd4b..c7538cc5b5a 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/RelaySimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/RelaySimTest.java @@ -58,7 +58,7 @@ void testInitializationForwardOnly() { try (CallbackStore fwdCb = sim.registerInitializedForwardCallback(forwardCallback, false); CallbackStore revCb = sim.registerInitializedReverseCallback(reverseCallback, false); - Relay relay = new Relay(0, Relay.Direction.kForward); ) { + Relay relay = new Relay(0, Relay.Direction.kForward)) { assertTrue(sim.getInitializedForward()); assertFalse(sim.getInitializedReverse()); @@ -84,7 +84,7 @@ void testInitializationReverseOnly() { try (CallbackStore fwdCb = sim.registerInitializedForwardCallback(forwardCallback, false); CallbackStore revCb = sim.registerInitializedReverseCallback(reverseCallback, false); - Relay relay = new Relay(0, Relay.Direction.kReverse); ) { + Relay relay = new Relay(0, Relay.Direction.kReverse)) { assertFalse(sim.getInitializedForward()); assertTrue(sim.getInitializedReverse()); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/RoboRioSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/RoboRioSimTest.java index c016ec420c4..01029cd793e 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/RoboRioSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/RoboRioSimTest.java @@ -10,8 +10,10 @@ import edu.wpi.first.hal.HALUtil; import edu.wpi.first.wpilibj.RobotController; +import edu.wpi.first.wpilibj.RobotController.RadioLEDState; import edu.wpi.first.wpilibj.simulation.testutils.BooleanCallback; import edu.wpi.first.wpilibj.simulation.testutils.DoubleCallback; +import edu.wpi.first.wpilibj.simulation.testutils.EnumCallback; import edu.wpi.first.wpilibj.simulation.testutils.IntCallback; import org.junit.jupiter.api.Test; @@ -279,4 +281,26 @@ void testComments() { assertEquals(kCommentsTruncated, RoboRioSim.getComments()); assertEquals(kCommentsTruncated, RobotController.getComments()); } + + @Test + void testRadioLEDState() { + RoboRioSim.resetData(); + + EnumCallback callback = new EnumCallback(); + try (CallbackStore cb = RoboRioSim.registerRadioLEDStateCallback(callback, false)) { + RobotController.setRadioLEDState(RadioLEDState.kGreen); + assertTrue(callback.wasTriggered()); + assertEquals(RadioLEDState.kGreen.value, callback.getSetValue()); + assertEquals(RadioLEDState.kGreen, RoboRioSim.getRadioLEDState()); + assertEquals(RadioLEDState.kGreen, RobotController.getRadioLEDState()); + + callback.reset(); + + RoboRioSim.setRadioLEDState(RadioLEDState.kOrange); + assertTrue(callback.wasTriggered()); + assertEquals(RadioLEDState.kOrange.value, callback.getSetValue()); + assertEquals(RadioLEDState.kOrange, RoboRioSim.getRadioLEDState()); + assertEquals(RadioLEDState.kOrange, RobotController.getRadioLEDState()); + } + } } diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/SimDeviceSimTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/SimDeviceSimTest.java index 62a24d1d75a..89b4333e609 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/SimDeviceSimTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/simulation/SimDeviceSimTest.java @@ -41,18 +41,10 @@ void testDeviceCreatedCallback() { SimDevice dev1 = SimDevice.create("testDC1")) { try (CallbackStore callback1 = SimDeviceSim.registerDeviceCreatedCallback( - "testDC", - (name, handle) -> { - callback1Counter.addAndGet(1); - }, - false); + "testDC", (name, handle) -> callback1Counter.addAndGet(1), false); CallbackStore callback2 = SimDeviceSim.registerDeviceCreatedCallback( - "testDC", - (name, handle) -> { - callback2Counter.addAndGet(1); - }, - true)) { + "testDC", (name, handle) -> callback2Counter.addAndGet(1), true)) { assertEquals(0, callback1Counter.get(), "Callback 1 called early"); assertEquals( 1, @@ -82,11 +74,7 @@ void testDeviceFreedCallback() { SimDevice dev1 = SimDevice.create("testDF1"); try (CallbackStore callback = SimDeviceSim.registerDeviceFreedCallback( - "testDF", - (name, handle) -> { - counter.addAndGet(1); - }, - false)) { + "testDF", (name, handle) -> counter.addAndGet(1), false)) { assertEquals(0, counter.get(), "Callback called early"); dev1.close(); assertEquals(1, counter.get(), "Callback called either more than once or not at all"); @@ -108,16 +96,10 @@ void testValueCreatedCallback() { SimDeviceSim sim = new SimDeviceSim("testVM1"); try (CallbackStore callback1 = sim.registerValueCreatedCallback( - (name, handle, readonly, value) -> { - callback1Counter.addAndGet(1); - }, - false); + (name, handle, readonly, value) -> callback1Counter.addAndGet(1), false); CallbackStore callback2 = sim.registerValueCreatedCallback( - (name, handle, readonly, value) -> { - callback2Counter.addAndGet(1); - }, - true)) { + (name, handle, readonly, value) -> callback2Counter.addAndGet(1), true)) { assertEquals(0, callback1Counter.get(), "Callback 1 called early"); assertEquals( 1, @@ -148,18 +130,10 @@ void testValueChangedCallback() { SimValue simVal = sim.getValue("v1"); try (CallbackStore callback1 = sim.registerValueChangedCallback( - simVal, - (name, handle, readonly, value) -> { - callback1Counter.addAndGet(1); - }, - false); + simVal, (name, handle, readonly, value) -> callback1Counter.addAndGet(1), false); CallbackStore callback2 = sim.registerValueChangedCallback( - simVal, - (name, handle, readonly, value) -> { - callback2Counter.addAndGet(1); - }, - true)) { + simVal, (name, handle, readonly, value) -> callback2Counter.addAndGet(1), true)) { assertEquals(0, callback1Counter.get(), "Callback 1 called early"); assertEquals( 1, diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooserTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooserTest.java index 07f09af3cd2..d97d54c243c 100644 --- a/wpilibj/src/test/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooserTest.java +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooserTest.java @@ -75,7 +75,7 @@ void testChangeListener() { chooser.addOption(String.valueOf(i), i); } AtomicInteger currentVal = new AtomicInteger(); - chooser.onChange(val -> currentVal.set(val)); + chooser.onChange(currentVal::set); SmartDashboard.putData("changeListenerChooser", chooser); SmartDashboard.updateValues(); diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/util/Color8BitTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/util/Color8BitTest.java new file mode 100644 index 00000000000..499ecbde80c --- /dev/null +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/util/Color8BitTest.java @@ -0,0 +1,65 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.wpilibj.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class Color8BitTest { + @Test + void testConstructDefault() { + var color = new Color8Bit(); + + assertEquals(0, color.red); + assertEquals(0, color.green); + assertEquals(0, color.blue); + } + + @Test + void testConstructFromInts() { + var color = new Color8Bit(255, 128, 64); + + assertEquals(255, color.red); + assertEquals(128, color.green); + assertEquals(64, color.blue); + } + + @Test + void testConstructFromColor() { + var color = new Color8Bit(new Color(255, 128, 64)); + + assertEquals(255, color.red); + assertEquals(128, color.green); + assertEquals(64, color.blue); + } + + @Test + void testConstructFromHexString() { + var color = new Color8Bit("#FF8040"); + + assertEquals(255, color.red); + assertEquals(128, color.green); + assertEquals(64, color.blue); + + // No leading # + assertThrows(IllegalArgumentException.class, () -> new Color8Bit("112233")); + + // Too long + assertThrows(IllegalArgumentException.class, () -> new Color8Bit("#11223344")); + + // Invalid hex characters + assertThrows(IllegalArgumentException.class, () -> new Color8Bit("#$$$$$$")); + } + + @Test + void testToHexString() { + var color = new Color8Bit(255, 128, 64); + + assertEquals("#FF8040", color.toHexString()); + assertEquals("#FF8040", color.toString()); + } +} diff --git a/wpilibj/src/test/java/edu/wpi/first/wpilibj/util/ColorTest.java b/wpilibj/src/test/java/edu/wpi/first/wpilibj/util/ColorTest.java new file mode 100644 index 00000000000..1b32afdaa9d --- /dev/null +++ b/wpilibj/src/test/java/edu/wpi/first/wpilibj/util/ColorTest.java @@ -0,0 +1,85 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.wpilibj.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class ColorTest { + @Test + void testConstructDefault() { + var color = new Color(); + + assertEquals(0.0, color.red); + assertEquals(0.0, color.green); + assertEquals(0.0, color.blue); + } + + @Test + void testConstructFromDoubles() { + { + var color = new Color(1.0, 0.5, 0.25); + + assertEquals(1.0, color.red, 1e-2); + assertEquals(0.5, color.green, 1e-2); + assertEquals(0.25, color.blue, 1e-2); + } + + { + var color = new Color(1.0, 0.0, 0.0); + + // Check for exact match to ensure round-and-clamp is correct + assertEquals(1.0, color.red); + assertEquals(0.0, color.green); + assertEquals(0.0, color.blue); + } + } + + @Test + void testConstructFromInts() { + var color = new Color(255, 128, 64); + + assertEquals(1.0, color.red, 1e-2); + assertEquals(0.5, color.green, 1e-2); + assertEquals(0.25, color.blue, 1e-2); + } + + @Test + void testConstructFromHexString() { + var color = new Color("#FF8040"); + + assertEquals(1.0, color.red, 1e-2); + assertEquals(0.5, color.green, 1e-2); + assertEquals(0.25, color.blue, 1e-2); + + // No leading # + assertThrows(IllegalArgumentException.class, () -> new Color("112233")); + + // Too long + assertThrows(IllegalArgumentException.class, () -> new Color("#11223344")); + + // Invalid hex characters + assertThrows(IllegalArgumentException.class, () -> new Color("#$$$$$$")); + } + + @Test + void testFromHSV() { + var color = Color.fromHSV(90, 128, 64); + + assertEquals(0.125732421875, color.red); + assertEquals(0.251220703125, color.green); + assertEquals(0.251220703125, color.blue); + } + + @Test + void testToHexString() { + var color = new Color(255, 128, 64); + + assertEquals("#FF8040", color.toHexString()); + assertEquals("#FF8040", color.toString()); + } +} diff --git a/wpilibjExamples/build.gradle b/wpilibjExamples/build.gradle index d5f71e98403..4caafc2571e 100644 --- a/wpilibjExamples/build.gradle +++ b/wpilibjExamples/build.gradle @@ -25,9 +25,8 @@ dependencies { implementation project(':romiVendordep') implementation project(':xrpVendordep') - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.0' - testImplementation 'org.junit.jupiter:junit-jupiter-params:5.10.0' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.0' + testImplementation 'org.junit.jupiter:junit-jupiter:5.10.1' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } jacoco { @@ -95,11 +94,8 @@ model { } } binaries.all { binary -> - lib project: ':wpilibNewCommands', library: 'wpilibNewCommands', linkage: 'shared' - lib project: ':romiVendordep', library: 'romiVendordep', linkage: 'shared' - lib project: ':xrpVendordep', library: 'xrpVendordep', linkage: 'shared' lib project: ':apriltag', library: 'apriltag', linkage: 'shared' - lib project: ':wpilibc', library: 'wpilibc', linkage: 'shared' + lib project: ':apriltag', library: 'apriltagJNIShared', linkage: 'shared' lib project: ':wpimath', library: 'wpimath', linkage: 'shared' lib project: ':wpimath', library: 'wpimathJNIShared', linkage: 'shared' project(':ntcore').addNtcoreDependency(binary, 'shared') @@ -112,7 +108,6 @@ model { lib project: ':wpiutil', library: 'wpiutilJNIShared', linkage: 'shared' lib project: ':wpinet', library: 'wpinet', linkage: 'shared' lib project: ':wpinet', library: 'wpinetJNIShared', linkage: 'shared' - lib project: ':cameraserver', library: 'cameraserver', linkage: 'shared' if (binary.targetPlatform.name == nativeUtils.wpi.platforms.roborio) { nativeUtils.useRequiredLibrary(binary, 'ni_link_libraries', 'ni_runtime_libraries') } else { diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/commands/trapezoidprofilecommand/ReplaceMeTrapezoidProfileCommand.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/commands/trapezoidprofilecommand/ReplaceMeTrapezoidProfileCommand.java index 5ed9fda3d28..fa55f451d2a 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/commands/trapezoidprofilecommand/ReplaceMeTrapezoidProfileCommand.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/commands/trapezoidprofilecommand/ReplaceMeTrapezoidProfileCommand.java @@ -22,8 +22,8 @@ public ReplaceMeTrapezoidProfileCommand() { // Use current trajectory state here }, // Goal state - () -> new TrapezoidProfile.State(), + TrapezoidProfile.State::new, // Current state - () -> new TrapezoidProfile.State()); + TrapezoidProfile.State::new); } } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/apriltagsvision/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/apriltagsvision/Robot.java index a73ea0beb56..8609cf7e47c 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/apriltagsvision/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/apriltagsvision/Robot.java @@ -32,21 +32,23 @@ public class Robot extends TimedRobot { @Override public void robotInit() { - var visionThread = new Thread(() -> apriltagVisionThreadProc()); + var visionThread = new Thread(this::apriltagVisionThreadProc); visionThread.setDaemon(true); visionThread.start(); } void apriltagVisionThreadProc() { var detector = new AprilTagDetector(); - // look for tag16h5, don't correct any error bits - detector.addFamily("tag16h5", 0); + // look for tag36h11, correct 1 error bit (hamming distance 1) + // hamming 1 allocates 781KB, 2 allocates 27.4 MB, 3 allocates 932 MB + // max of 1 recommended for RoboRIO 1, while hamming 2 is feasible on the RoboRIO 2 + detector.addFamily("tag36h11", 1); // Set up Pose Estimator - parameters are for a Microsoft Lifecam HD-3000 // (https://www.chiefdelphi.com/t/wpilib-apriltagdetector-sample-code/421411/21) var poseEstConfig = new AprilTagPoseEstimator.Config( - 0.1524, 699.3778103158814, 677.7161226393544, 345.6059345433618, 207.12741326228522); + 0.1651, 699.3778103158814, 677.7161226393544, 345.6059345433618, 207.12741326228522); var estimator = new AprilTagPoseEstimator(poseEstConfig); // Get the UsbCamera from CameraServer diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/arcadedrive/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/arcadedrive/Robot.java index 45333a5e3cf..aa343799a01 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/arcadedrive/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/arcadedrive/Robot.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj.examples.arcadedrive; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.drive.DifferentialDrive; @@ -16,9 +17,15 @@ public class Robot extends TimedRobot { private final PWMSparkMax m_leftMotor = new PWMSparkMax(0); private final PWMSparkMax m_rightMotor = new PWMSparkMax(1); - private final DifferentialDrive m_robotDrive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_robotDrive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); private final Joystick m_stick = new Joystick(0); + public Robot() { + SendableRegistry.addChild(m_robotDrive, m_leftMotor); + SendableRegistry.addChild(m_robotDrive, m_rightMotor); + } + @Override public void robotInit() { // We need to invert one side of the drivetrain so that positive voltages diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/arcadedrivexboxcontroller/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/arcadedrivexboxcontroller/Robot.java index aa0f9a20ea2..a376fe0ae48 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/arcadedrivexboxcontroller/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/arcadedrivexboxcontroller/Robot.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj.examples.arcadedrivexboxcontroller; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj.drive.DifferentialDrive; @@ -16,9 +17,15 @@ public class Robot extends TimedRobot { private final PWMSparkMax m_leftMotor = new PWMSparkMax(0); private final PWMSparkMax m_rightMotor = new PWMSparkMax(1); - private final DifferentialDrive m_robotDrive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_robotDrive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); private final XboxController m_driverController = new XboxController(0); + public Robot() { + SendableRegistry.addChild(m_robotDrive, m_leftMotor); + SendableRegistry.addChild(m_robotDrive, m_rightMotor); + } + @Override public void robotInit() { // We need to invert one side of the drivetrain so that positive voltages diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armbot/subsystems/DriveSubsystem.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armbot/subsystems/DriveSubsystem.java index 4ecaa77231b..246b5c41185 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armbot/subsystems/DriveSubsystem.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armbot/subsystems/DriveSubsystem.java @@ -4,28 +4,25 @@ package edu.wpi.first.wpilibj.examples.armbot.subsystems; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj.examples.armbot.Constants.DriveConstants; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj2.command.SubsystemBase; public class DriveSubsystem extends SubsystemBase { // The motors on the left side of the drive. - private final MotorControllerGroup m_leftMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kLeftMotor1Port), - new PWMSparkMax(DriveConstants.kLeftMotor2Port)); + private final PWMSparkMax m_leftLeader = new PWMSparkMax(DriveConstants.kLeftMotor1Port); + private final PWMSparkMax m_leftFollower = new PWMSparkMax(DriveConstants.kLeftMotor2Port); // The motors on the right side of the drive. - private final MotorControllerGroup m_rightMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kRightMotor1Port), - new PWMSparkMax(DriveConstants.kRightMotor2Port)); + private final PWMSparkMax m_rightLeader = new PWMSparkMax(DriveConstants.kRightMotor1Port); + private final PWMSparkMax m_rightFollower = new PWMSparkMax(DriveConstants.kRightMotor2Port); // The robot's drive - private final DifferentialDrive m_drive = new DifferentialDrive(m_leftMotors, m_rightMotors); + private final DifferentialDrive m_drive = + new DifferentialDrive(m_leftLeader::set, m_rightLeader::set); // The left-side drive encoder private final Encoder m_leftEncoder = @@ -43,14 +40,20 @@ public class DriveSubsystem extends SubsystemBase { /** Creates a new DriveSubsystem. */ public DriveSubsystem() { + SendableRegistry.addChild(m_drive, m_leftLeader); + SendableRegistry.addChild(m_drive, m_rightLeader); + // Sets the distance per pulse for the encoders m_leftEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); m_rightEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); + m_leftLeader.addFollower(m_leftFollower); + m_rightLeader.addFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.setInverted(true); + m_rightLeader.setInverted(true); } /** diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armbotoffboard/ExampleSmartMotorController.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armbotoffboard/ExampleSmartMotorController.java index 4f95b4003e6..7801a1fa8a5 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armbotoffboard/ExampleSmartMotorController.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armbotoffboard/ExampleSmartMotorController.java @@ -4,14 +4,12 @@ package edu.wpi.first.wpilibj.examples.armbotoffboard; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; - /** * A simplified stub class that simulates the API of a common "smart" motor controller. * *

    Has no actual functionality. */ -public class ExampleSmartMotorController implements MotorController { +public class ExampleSmartMotorController { public enum PIDMode { kPosition, kVelocity, @@ -72,25 +70,19 @@ public double getEncoderRate() { /** Resets the encoder to zero distance. */ public void resetEncoder() {} - @Override public void set(double speed) {} - @Override public double get() { return 0; } - @Override public void setInverted(boolean isInverted) {} - @Override public boolean getInverted() { return false; } - @Override public void disable() {} - @Override public void stopMotor() {} } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armbotoffboard/subsystems/DriveSubsystem.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armbotoffboard/subsystems/DriveSubsystem.java index e3c91595370..f01ad9987d7 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armbotoffboard/subsystems/DriveSubsystem.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armbotoffboard/subsystems/DriveSubsystem.java @@ -4,10 +4,10 @@ package edu.wpi.first.wpilibj.examples.armbotoffboard.subsystems; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj.examples.armbotoffboard.Constants.DriveConstants; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Commands; @@ -16,19 +16,16 @@ public class DriveSubsystem extends SubsystemBase { // The motors on the left side of the drive. - private final MotorControllerGroup m_leftMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kLeftMotor1Port), - new PWMSparkMax(DriveConstants.kLeftMotor2Port)); + private final PWMSparkMax m_leftLeader = new PWMSparkMax(DriveConstants.kLeftMotor1Port); + private final PWMSparkMax m_leftFollower = new PWMSparkMax(DriveConstants.kLeftMotor2Port); // The motors on the right side of the drive. - private final MotorControllerGroup m_rightMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kRightMotor1Port), - new PWMSparkMax(DriveConstants.kRightMotor2Port)); + private final PWMSparkMax m_rightLeader = new PWMSparkMax(DriveConstants.kRightMotor1Port); + private final PWMSparkMax m_rightFollower = new PWMSparkMax(DriveConstants.kRightMotor2Port); // The robot's drive - private final DifferentialDrive m_drive = new DifferentialDrive(m_leftMotors, m_rightMotors); + private final DifferentialDrive m_drive = + new DifferentialDrive(m_leftLeader::set, m_rightLeader::set); // The left-side drive encoder private final Encoder m_leftEncoder = @@ -46,14 +43,20 @@ public class DriveSubsystem extends SubsystemBase { /** Creates a new DriveSubsystem. */ public DriveSubsystem() { + SendableRegistry.addChild(m_drive, m_leftLeader); + SendableRegistry.addChild(m_drive, m_rightLeader); + // Sets the distance per pulse for the encoders m_leftEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); m_rightEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); + m_leftLeader.addFollower(m_leftFollower); + m_rightLeader.addFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.setInverted(true); + m_rightLeader.setInverted(true); } /** diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armsimulation/subsystems/Arm.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armsimulation/subsystems/Arm.java index 3cce47d58c6..3c92370019e 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armsimulation/subsystems/Arm.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/armsimulation/subsystems/Arm.java @@ -4,7 +4,6 @@ package edu.wpi.first.wpilibj.examples.armsimulation.subsystems; -import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.controller.PIDController; import edu.wpi.first.math.system.plant.DCMotor; import edu.wpi.first.math.util.Units; @@ -51,7 +50,8 @@ public class Arm implements AutoCloseable { Constants.kMaxAngleRads, true, 0, - VecBuilder.fill(Constants.kArmEncoderDistPerPulse) // Add noise with a std-dev of 1 tick + Constants.kArmEncoderDistPerPulse, + 0.0 // Add noise with a std-dev of 1 tick ); private final EncoderSim m_encoderSim = new EncoderSim(m_encoder); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/differentialdrivebot/Drivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/differentialdrivebot/Drivetrain.java index 8b4734a0f7b..adc52e2ef67 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/differentialdrivebot/Drivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/differentialdrivebot/Drivetrain.java @@ -12,8 +12,6 @@ import edu.wpi.first.math.kinematics.DifferentialDriveWheelSpeeds; import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.Encoder; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; /** Represents a differential drive style drivetrain. */ @@ -25,19 +23,14 @@ public class Drivetrain { private static final double kWheelRadius = 0.0508; // meters private static final int kEncoderResolution = 4096; - private final MotorController m_leftLeader = new PWMSparkMax(1); - private final MotorController m_leftFollower = new PWMSparkMax(2); - private final MotorController m_rightLeader = new PWMSparkMax(3); - private final MotorController m_rightFollower = new PWMSparkMax(4); + private final PWMSparkMax m_leftLeader = new PWMSparkMax(1); + private final PWMSparkMax m_leftFollower = new PWMSparkMax(2); + private final PWMSparkMax m_rightLeader = new PWMSparkMax(3); + private final PWMSparkMax m_rightFollower = new PWMSparkMax(4); private final Encoder m_leftEncoder = new Encoder(0, 1); private final Encoder m_rightEncoder = new Encoder(2, 3); - private final MotorControllerGroup m_leftGroup = - new MotorControllerGroup(m_leftLeader, m_leftFollower); - private final MotorControllerGroup m_rightGroup = - new MotorControllerGroup(m_rightLeader, m_rightFollower); - private final AnalogGyro m_gyro = new AnalogGyro(0); private final PIDController m_leftPIDController = new PIDController(1, 0, 0); @@ -58,10 +51,13 @@ public class Drivetrain { public Drivetrain() { m_gyro.reset(); + m_leftLeader.addFollower(m_leftFollower); + m_rightLeader.addFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightGroup.setInverted(true); + m_rightLeader.setInverted(true); // Set the distance per pulse for the drive encoders. We can simply use the // distance traveled for one rotation of the wheel divided by the encoder @@ -90,8 +86,8 @@ public void setSpeeds(DifferentialDriveWheelSpeeds speeds) { m_leftPIDController.calculate(m_leftEncoder.getRate(), speeds.leftMetersPerSecond); final double rightOutput = m_rightPIDController.calculate(m_rightEncoder.getRate(), speeds.rightMetersPerSecond); - m_leftGroup.setVoltage(leftOutput + leftFeedforward); - m_rightGroup.setVoltage(rightOutput + rightFeedforward); + m_leftLeader.setVoltage(leftOutput + leftFeedforward); + m_rightLeader.setVoltage(rightOutput + rightFeedforward); } /** diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/differentialdriveposeestimator/Drivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/differentialdriveposeestimator/Drivetrain.java index ceceaf32676..4fc38ca525f 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/differentialdriveposeestimator/Drivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/differentialdriveposeestimator/Drivetrain.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj.examples.differentialdriveposeestimator; +import edu.wpi.first.apriltag.AprilTagFieldLayout; import edu.wpi.first.apriltag.AprilTagFields; import edu.wpi.first.math.ComputerVisionUtil; import edu.wpi.first.math.VecBuilder; @@ -30,8 +31,6 @@ import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.RobotController; import edu.wpi.first.wpilibj.Timer; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj.simulation.AnalogGyroSim; import edu.wpi.first.wpilibj.simulation.DifferentialDrivetrainSim; @@ -48,19 +47,14 @@ public class Drivetrain { private static final double kWheelRadius = 0.0508; // meters private static final int kEncoderResolution = 4096; - private final MotorController m_leftLeader = new PWMSparkMax(1); - private final MotorController m_leftFollower = new PWMSparkMax(2); - private final MotorController m_rightLeader = new PWMSparkMax(3); - private final MotorController m_rightFollower = new PWMSparkMax(4); + private final PWMSparkMax m_leftLeader = new PWMSparkMax(1); + private final PWMSparkMax m_leftFollower = new PWMSparkMax(2); + private final PWMSparkMax m_rightLeader = new PWMSparkMax(3); + private final PWMSparkMax m_rightFollower = new PWMSparkMax(4); private final Encoder m_leftEncoder = new Encoder(0, 1); private final Encoder m_rightEncoder = new Encoder(2, 3); - private final MotorControllerGroup m_leftGroup = - new MotorControllerGroup(m_leftLeader, m_leftFollower); - private final MotorControllerGroup m_rightGroup = - new MotorControllerGroup(m_rightLeader, m_rightFollower); - private final AnalogGyro m_gyro = new AnalogGyro(0); private final PIDController m_leftPIDController = new PIDController(1, 0, 0); @@ -89,7 +83,7 @@ public class Drivetrain { m_gyro.getRotation2d(), m_leftEncoder.getDistance(), m_rightEncoder.getDistance(), - new Pose2d(), + Pose2d.kZero, VecBuilder.fill(0.05, 0.05, Units.degreesToRadians(5)), VecBuilder.fill(0.5, 0.5, Units.degreesToRadians(30))); @@ -113,10 +107,13 @@ public class Drivetrain { public Drivetrain(DoubleArrayTopic cameraToObjectTopic) { m_gyro.reset(); + m_leftLeader.addFollower(m_leftFollower); + m_rightLeader.addFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightGroup.setInverted(true); + m_rightLeader.setInverted(true); // Set the distance per pulse for the drive encoders. We can simply use the // distance traveled for one rotation of the wheel divided by the encoder @@ -129,7 +126,8 @@ public Drivetrain(DoubleArrayTopic cameraToObjectTopic) { m_cameraToObjectEntry = cameraToObjectTopic.getEntry(m_defaultVal); - m_objectInField = AprilTagFields.k2022RapidReact.loadAprilTagLayoutField().getTagPose(0).get(); + m_objectInField = + AprilTagFieldLayout.loadField(AprilTagFields.k2024Crescendo).getTagPose(0).get(); SmartDashboard.putData("Field", m_fieldSim); SmartDashboard.putData("FieldEstimation", m_fieldApproximation); @@ -148,8 +146,8 @@ public void setSpeeds(DifferentialDriveWheelSpeeds speeds) { m_leftPIDController.calculate(m_leftEncoder.getRate(), speeds.leftMetersPerSecond); final double rightOutput = m_rightPIDController.calculate(m_rightEncoder.getRate(), speeds.rightMetersPerSecond); - m_leftGroup.setVoltage(leftOutput + leftFeedforward); - m_rightGroup.setVoltage(rightOutput + rightFeedforward); + m_leftLeader.setVoltage(leftOutput + leftFeedforward); + m_rightLeader.setVoltage(rightOutput + rightFeedforward); } /** @@ -251,8 +249,8 @@ public void simulationPeriodic() { // simulation, and write the simulated positions and velocities to our // simulated encoder and gyro. m_drivetrainSimulator.setInputs( - m_leftGroup.get() * RobotController.getInputVoltage(), - m_rightGroup.get() * RobotController.getInputVoltage()); + m_leftLeader.get() * RobotController.getInputVoltage(), + m_rightLeader.get() * RobotController.getInputVoltage()); m_drivetrainSimulator.update(0.02); m_leftEncoderSim.setDistance(m_drivetrainSimulator.getLeftPositionMeters()); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/ExampleSmartMotorController.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/ExampleSmartMotorController.java index 487974cadbc..12c51ab4414 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/ExampleSmartMotorController.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/ExampleSmartMotorController.java @@ -4,14 +4,12 @@ package edu.wpi.first.wpilibj.examples.drivedistanceoffboard; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; - /** * A simplified stub class that simulates the API of a common "smart" motor controller. * *

    Has no actual functionality. */ -public class ExampleSmartMotorController implements MotorController { +public class ExampleSmartMotorController { public enum PIDMode { kPosition, kVelocity, @@ -74,27 +72,21 @@ public double getEncoderRate() { /** Resets the encoder to zero distance. */ public void resetEncoder() {} - @Override public void set(double speed) { m_value = speed; } - @Override public double get() { return m_value; } - @Override public void setInverted(boolean isInverted) {} - @Override public boolean getInverted() { return false; } - @Override public void disable() {} - @Override public void stopMotor() {} } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/RobotContainer.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/RobotContainer.java index ab71ff442f3..ba2ed047102 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/RobotContainer.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/RobotContainer.java @@ -78,7 +78,7 @@ private void configureButtonBindings() { // End at desired position in meters; implicitly starts at 0 () -> new TrapezoidProfile.State(3, 0), // Current position - () -> new TrapezoidProfile.State(), + TrapezoidProfile.State::new, // Require the drive m_robotDrive) .beforeStarting(m_robotDrive::resetEncoders) diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/commands/DriveDistanceProfiled.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/commands/DriveDistanceProfiled.java index 5c107d23757..951cde30edf 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/commands/DriveDistanceProfiled.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/commands/DriveDistanceProfiled.java @@ -29,7 +29,7 @@ public DriveDistanceProfiled(double meters, DriveSubsystem drive) { // End at desired position in meters; implicitly starts at 0 () -> new TrapezoidProfile.State(meters, 0), // Current position - () -> new TrapezoidProfile.State(), + TrapezoidProfile.State::new, // Require the drive drive); // Reset drive encoders since we're starting at 0 diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/subsystems/DriveSubsystem.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/subsystems/DriveSubsystem.java index 520261d4028..59d700bb1ed 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/subsystems/DriveSubsystem.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/drivedistanceoffboard/subsystems/DriveSubsystem.java @@ -6,6 +6,7 @@ import edu.wpi.first.math.controller.SimpleMotorFeedforward; import edu.wpi.first.math.trajectory.TrapezoidProfile; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj.examples.drivedistanceoffboard.Constants.DriveConstants; import edu.wpi.first.wpilibj.examples.drivedistanceoffboard.ExampleSmartMotorController; @@ -34,20 +35,19 @@ public class DriveSubsystem extends SubsystemBase { DriveConstants.kaVoltSecondsSquaredPerMeter); // The robot's drive - private final DifferentialDrive m_drive = new DifferentialDrive(m_leftLeader, m_rightLeader); + private final DifferentialDrive m_drive = + new DifferentialDrive(m_leftLeader::set, m_rightLeader::set); /** Creates a new DriveSubsystem. */ public DriveSubsystem() { + SendableRegistry.addChild(m_drive, m_leftLeader); + SendableRegistry.addChild(m_drive, m_rightLeader); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. m_rightLeader.setInverted(true); - // You might need to not do this depending on the specific motor controller - // that you are using -- contact the respective vendor's documentation for - // more details. - m_rightFollower.setInverted(true); - m_leftFollower.follow(m_leftLeader); m_rightFollower.follow(m_rightLeader); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorexponentialprofile/ExampleSmartMotorController.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorexponentialprofile/ExampleSmartMotorController.java index e252f850039..2b37b967893 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorexponentialprofile/ExampleSmartMotorController.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorexponentialprofile/ExampleSmartMotorController.java @@ -4,14 +4,12 @@ package edu.wpi.first.wpilibj.examples.elevatorexponentialprofile; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; - /** * A simplified stub class that simulates the API of a common "smart" motor controller. * *

    Has no actual functionality. */ -public class ExampleSmartMotorController implements MotorController { +public class ExampleSmartMotorController { public enum PIDMode { kPosition, kVelocity, @@ -72,25 +70,19 @@ public double getEncoderRate() { /** Resets the encoder to zero distance. */ public void resetEncoder() {} - @Override public void set(double speed) {} - @Override public double get() { return 0; } - @Override public void setInverted(boolean isInverted) {} - @Override public boolean getInverted() { return false; } - @Override public void disable() {} - @Override public void stopMotor() {} } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorexponentialsimulation/subsystems/Elevator.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorexponentialsimulation/subsystems/Elevator.java index 6d176e8c35c..ac2423f4342 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorexponentialsimulation/subsystems/Elevator.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorexponentialsimulation/subsystems/Elevator.java @@ -4,7 +4,6 @@ package edu.wpi.first.wpilibj.examples.elevatorexponentialsimulation.subsystems; -import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.controller.ElevatorFeedforward; import edu.wpi.first.math.controller.PIDController; import edu.wpi.first.math.system.plant.DCMotor; @@ -60,7 +59,8 @@ public class Elevator implements AutoCloseable { Constants.kMaxElevatorHeightMeters, true, 0, - VecBuilder.fill(0.005)); + 0.005, + 0.0); private final EncoderSim m_encoderSim = new EncoderSim(m_encoder); private final PWMSim m_motorSim = new PWMSim(m_motor); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorprofiledpid/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorprofiledpid/Robot.java index b6228c9c9e7..670fd7b8ee9 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorprofiledpid/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorprofiledpid/Robot.java @@ -10,7 +10,6 @@ import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.TimedRobot; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; @SuppressWarnings("PMD.RedundantFieldInitializer") @@ -27,7 +26,7 @@ public class Robot extends TimedRobot { private final Joystick m_joystick = new Joystick(1); private final Encoder m_encoder = new Encoder(1, 2); - private final MotorController m_motor = new PWMSparkMax(1); + private final PWMSparkMax m_motor = new PWMSparkMax(1); // Create a PID controller whose setpoint's change is subject to maximum // velocity and acceleration constraints. diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorsimulation/subsystems/Elevator.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorsimulation/subsystems/Elevator.java index 1c9d8767645..d4f04fed26d 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorsimulation/subsystems/Elevator.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatorsimulation/subsystems/Elevator.java @@ -4,7 +4,6 @@ package edu.wpi.first.wpilibj.examples.elevatorsimulation.subsystems; -import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.controller.ElevatorFeedforward; import edu.wpi.first.math.controller.ProfiledPIDController; import edu.wpi.first.math.system.plant.DCMotor; @@ -55,7 +54,8 @@ public class Elevator implements AutoCloseable { Constants.kMaxElevatorHeightMeters, true, 0, - VecBuilder.fill(0.01)); + 0.01, + 0.0); private final EncoderSim m_encoderSim = new EncoderSim(m_encoder); private final PWMSim m_motorSim = new PWMSim(m_motor); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatortrapezoidprofile/ExampleSmartMotorController.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatortrapezoidprofile/ExampleSmartMotorController.java index a1366e6f356..6d9ac23743a 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatortrapezoidprofile/ExampleSmartMotorController.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/elevatortrapezoidprofile/ExampleSmartMotorController.java @@ -4,14 +4,12 @@ package edu.wpi.first.wpilibj.examples.elevatortrapezoidprofile; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; - /** * A simplified stub class that simulates the API of a common "smart" motor controller. * *

    Has no actual functionality. */ -public class ExampleSmartMotorController implements MotorController { +public class ExampleSmartMotorController { public enum PIDMode { kPosition, kVelocity, @@ -72,25 +70,19 @@ public double getEncoderRate() { /** Resets the encoder to zero distance. */ public void resetEncoder() {} - @Override public void set(double speed) {} - @Override public double get() { return 0; } - @Override public void setInverted(boolean isInverted) {} - @Override public boolean getInverted() { return false; } - @Override public void disable() {} - @Override public void stopMotor() {} } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/eventloop/Main.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/eventloop/Main.java index d6f3150a6c0..23a49cb2e13 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/eventloop/Main.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/eventloop/Main.java @@ -5,7 +5,6 @@ package edu.wpi.first.wpilibj.examples.eventloop; import edu.wpi.first.wpilibj.RobotBase; -import edu.wpi.first.wpilibj.examples.encoder.Robot; /** * Do NOT add any static variables to this class, or any initialization at all. Unless you know what diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/eventloop/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/eventloop/Robot.java index 03c5577157a..08de65c5919 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/eventloop/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/eventloop/Robot.java @@ -12,7 +12,6 @@ import edu.wpi.first.wpilibj.Ultrasonic; import edu.wpi.first.wpilibj.event.BooleanEvent; import edu.wpi.first.wpilibj.event.EventLoop; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; public class Robot extends TimedRobot { @@ -20,15 +19,15 @@ public class Robot extends TimedRobot { public static final int TOLERANCE = 8; // rpm public static final int KICKER_THRESHOLD = 15; // mm - private final MotorController m_shooter = new PWMSparkMax(0); + private final PWMSparkMax m_shooter = new PWMSparkMax(0); private final Encoder m_shooterEncoder = new Encoder(0, 1); private final PIDController m_controller = new PIDController(0.3, 0, 0); private final SimpleMotorFeedforward m_ff = new SimpleMotorFeedforward(0.1, 0.065); - private final MotorController m_kicker = new PWMSparkMax(1); + private final PWMSparkMax m_kicker = new PWMSparkMax(1); private final Ultrasonic m_kickerSensor = new Ultrasonic(2, 3); - private final MotorController m_intake = new PWMSparkMax(2); + private final PWMSparkMax m_intake = new PWMSparkMax(2); private final EventLoop m_loop = new EventLoop(); private final Joystick m_joystick = new Joystick(0); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/examples.json b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/examples.json index 750e4dc7c22..720ab3c0bec 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/examples.json +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/examples.json @@ -318,12 +318,12 @@ "commandversion": 2 }, { - "name": "Axis Camera Sample", - "description": "Acquire images from an Axis network camera and adds some annotation to the image (as you might do for showing operators the result of some image recognition), and sends it to the dashboard for display.", + "name": "HTTP Camera", + "description": "Acquire images from an HTTP network camera and adds some annotation to the image (as you might do for showing operators the result of some image recognition), and sends it to the dashboard for display.", "tags": [ "Vision" ], - "foldername": "axiscamera", + "foldername": "httpcamera", "gradlebase": "java", "mainclass": "Main", "commandversion": 2 @@ -504,25 +504,6 @@ "mainclass": "Main", "commandversion": 2 }, - { - "name": "RamseteCommand", - "description": "Follow a pre-generated trajectory with a differential drive using RamseteCommand.", - "tags": [ - "Differential Drive", - "Command-based", - "Ramsete", - "Trajectory", - "Path Following", - "Odometry", - "Encoder", - "Gyro", - "XboxController" - ], - "foldername": "ramsetecommand", - "gradlebase": "java", - "mainclass": "Main", - "commandversion": 2 - }, { "name": "Arcade Drive Xbox Controller", "description": "Control a differential drive with split-stick arcade drive in teleop.", @@ -685,24 +666,6 @@ "mainclass": "Main", "commandversion": 2 }, - { - "name": "RamseteController", - "description": "Follow a pre-generated trajectory with a differential drive using RamseteController.", - "tags": [ - "Basic Robot", - "Differential Drive", - "Ramsete", - "PID", - "Odometry", - "Path Following", - "Trajectory", - "XboxController" - ], - "foldername": "ramsetecontroller", - "gradlebase": "java", - "mainclass": "Main", - "commandversion": 2 - }, { "name": "StateSpaceFlywheel", "description": "Control a flywheel using a state-space model (based on values from CAD), with a Kalman Filter and LQR.", @@ -786,21 +749,6 @@ "mainclass": "Main", "commandversion": 2 }, - { - "name": "StateSpaceDriveSimulation", - "description": "Simulate a differential drivetrain and follow trajectories with RamseteCommand (command-based).", - "tags": [ - "Command-based", - "Differential Drive", - "State-Space", - "XboxController", - "Simulation" - ], - "foldername": "statespacedifferentialdrivesimulation", - "gradlebase": "java", - "mainclass": "Main", - "commandversion": 2 - }, { "name": "ElevatorSimulation", "description": "Simulate an elevator.", @@ -983,5 +931,18 @@ "gradlebase": "java", "commandversion": 2, "mainclass": "Main" + }, + { + "name": "SysIdRoutine", + "description": "A sample command-based robot demonstrating use of the SysIdRoutine command factory", + "tags": [ + "SysId", + "Command-based", + "DataLog" + ], + "foldername": "sysid", + "gradlebase": "java", + "commandversion": 2, + "mainclass": "Main" } ] diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/frisbeebot/subsystems/DriveSubsystem.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/frisbeebot/subsystems/DriveSubsystem.java index 5773da182db..dc3a3c6cc1b 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/frisbeebot/subsystems/DriveSubsystem.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/frisbeebot/subsystems/DriveSubsystem.java @@ -4,28 +4,25 @@ package edu.wpi.first.wpilibj.examples.frisbeebot.subsystems; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj.examples.frisbeebot.Constants.DriveConstants; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj2.command.SubsystemBase; public class DriveSubsystem extends SubsystemBase { // The motors on the left side of the drive. - private final MotorControllerGroup m_leftMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kLeftMotor1Port), - new PWMSparkMax(DriveConstants.kLeftMotor2Port)); + private final PWMSparkMax m_leftLeader = new PWMSparkMax(DriveConstants.kLeftMotor1Port); + private final PWMSparkMax m_leftFollower = new PWMSparkMax(DriveConstants.kLeftMotor2Port); // The motors on the right side of the drive. - private final MotorControllerGroup m_rightMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kRightMotor1Port), - new PWMSparkMax(DriveConstants.kRightMotor2Port)); + private final PWMSparkMax m_rightLeader = new PWMSparkMax(DriveConstants.kRightMotor1Port); + private final PWMSparkMax m_rightFollower = new PWMSparkMax(DriveConstants.kRightMotor2Port); // The robot's drive - private final DifferentialDrive m_drive = new DifferentialDrive(m_leftMotors, m_rightMotors); + private final DifferentialDrive m_drive = + new DifferentialDrive(m_leftLeader::set, m_rightLeader::set); // The left-side drive encoder private final Encoder m_leftEncoder = @@ -43,10 +40,16 @@ public class DriveSubsystem extends SubsystemBase { /** Creates a new DriveSubsystem. */ public DriveSubsystem() { + SendableRegistry.addChild(m_drive, m_leftLeader); + SendableRegistry.addChild(m_drive, m_rightLeader); + + m_leftLeader.addFollower(m_leftFollower); + m_rightLeader.addFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.setInverted(true); + m_rightLeader.setInverted(true); // Sets the distance per pulse for the encoders m_leftEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gearsbot/subsystems/Drivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gearsbot/subsystems/Drivetrain.java index ffde63d4026..b632f8d5cac 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gearsbot/subsystems/Drivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gearsbot/subsystems/Drivetrain.java @@ -4,34 +4,27 @@ package edu.wpi.first.wpilibj.examples.gearsbot.subsystems; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj.examples.gearsbot.Constants.DriveConstants; import edu.wpi.first.wpilibj.examples.gearsbot.Robot; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; public class Drivetrain extends SubsystemBase { - /** - * The Drivetrain subsystem incorporates the sensors and actuators attached to the robots chassis. - * These include four drive motors, a left and right encoder and a gyro. - */ - private final MotorController m_leftMotor = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kLeftMotorPort1), - new PWMSparkMax(DriveConstants.kLeftMotorPort1)); - - private final MotorController m_rightMotor = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kRightMotorPort2), - new PWMSparkMax(DriveConstants.kLeftMotorPort2)); + // The Drivetrain subsystem incorporates the sensors and actuators attached to the robots chassis. + // These include four drive motors, a left and right encoder and a gyro. + private final PWMSparkMax m_leftLeader = new PWMSparkMax(DriveConstants.kLeftMotorPort1); + private final PWMSparkMax m_leftFollower = new PWMSparkMax(DriveConstants.kLeftMotorPort2); + private final PWMSparkMax m_rightLeader = new PWMSparkMax(DriveConstants.kRightMotorPort1); + private final PWMSparkMax m_rightFollower = new PWMSparkMax(DriveConstants.kRightMotorPort2); - private final DifferentialDrive m_drive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_drive = + new DifferentialDrive(m_leftLeader::set, m_rightLeader::set); private final Encoder m_leftEncoder = new Encoder( @@ -50,10 +43,16 @@ public class Drivetrain extends SubsystemBase { public Drivetrain() { super(); + SendableRegistry.addChild(m_drive, m_leftLeader); + SendableRegistry.addChild(m_drive, m_rightLeader); + + m_leftLeader.addFollower(m_leftFollower); + m_rightLeader.addFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotor.setInverted(true); + m_rightLeader.setInverted(true); // Encoders may measure differently in the real world and in // simulation. In this example the robot moves 0.042 barleycorns diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gettingstarted/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gettingstarted/Robot.java index dd337e656a5..563235c2e1d 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gettingstarted/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gettingstarted/Robot.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj.examples.gettingstarted; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.XboxController; @@ -19,10 +20,16 @@ public class Robot extends TimedRobot { private final PWMSparkMax m_leftDrive = new PWMSparkMax(0); private final PWMSparkMax m_rightDrive = new PWMSparkMax(1); - private final DifferentialDrive m_robotDrive = new DifferentialDrive(m_leftDrive, m_rightDrive); + private final DifferentialDrive m_robotDrive = + new DifferentialDrive(m_leftDrive::set, m_rightDrive::set); private final XboxController m_controller = new XboxController(0); private final Timer m_timer = new Timer(); + public Robot() { + SendableRegistry.addChild(m_robotDrive, m_leftDrive); + SendableRegistry.addChild(m_robotDrive, m_rightDrive); + } + /** * This function is run when the robot is first started up and should be used for any * initialization code. diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gyro/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gyro/Robot.java index 1f9e41df523..7d00c274e57 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gyro/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gyro/Robot.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj.examples.gyro; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.TimedRobot; @@ -30,10 +31,16 @@ public class Robot extends TimedRobot { private final PWMSparkMax m_leftDrive = new PWMSparkMax(kLeftMotorPort); private final PWMSparkMax m_rightDrive = new PWMSparkMax(kRightMotorPort); - private final DifferentialDrive m_myRobot = new DifferentialDrive(m_leftDrive, m_rightDrive); + private final DifferentialDrive m_robotDrive = + new DifferentialDrive(m_leftDrive::set, m_rightDrive::set); private final AnalogGyro m_gyro = new AnalogGyro(kGyroPort); private final Joystick m_joystick = new Joystick(kJoystickPort); + public Robot() { + SendableRegistry.addChild(m_robotDrive, m_leftDrive); + SendableRegistry.addChild(m_robotDrive, m_rightDrive); + } + @Override public void robotInit() { m_gyro.setSensitivity(kVoltsPerDegreePerSecond); @@ -50,6 +57,6 @@ public void robotInit() { @Override public void teleopPeriodic() { double turningValue = (kAngleSetpoint - m_gyro.getAngle()) * kP; - m_myRobot.arcadeDrive(-m_joystick.getY(), -turningValue); + m_robotDrive.arcadeDrive(-m_joystick.getY(), -turningValue); } } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gyrodrivecommands/subsystems/DriveSubsystem.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gyrodrivecommands/subsystems/DriveSubsystem.java index 9adb6ec0f96..db874104b6b 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gyrodrivecommands/subsystems/DriveSubsystem.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gyrodrivecommands/subsystems/DriveSubsystem.java @@ -4,29 +4,26 @@ package edu.wpi.first.wpilibj.examples.gyrodrivecommands.subsystems; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.ADXRS450_Gyro; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj.examples.gyrodrivecommands.Constants.DriveConstants; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj2.command.SubsystemBase; public class DriveSubsystem extends SubsystemBase { // The motors on the left side of the drive. - private final MotorControllerGroup m_leftMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kLeftMotor1Port), - new PWMSparkMax(DriveConstants.kLeftMotor2Port)); + private final PWMSparkMax m_leftLeader = new PWMSparkMax(DriveConstants.kLeftMotor1Port); + private final PWMSparkMax m_leftFollower = new PWMSparkMax(DriveConstants.kLeftMotor2Port); // The motors on the right side of the drive. - private final MotorControllerGroup m_rightMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kRightMotor1Port), - new PWMSparkMax(DriveConstants.kRightMotor2Port)); + private final PWMSparkMax m_rightLeader = new PWMSparkMax(DriveConstants.kRightMotor1Port); + private final PWMSparkMax m_rightFollower = new PWMSparkMax(DriveConstants.kRightMotor2Port); // The robot's drive - private final DifferentialDrive m_drive = new DifferentialDrive(m_leftMotors, m_rightMotors); + private final DifferentialDrive m_drive = + new DifferentialDrive(m_leftLeader::set, m_rightLeader::set); // The left-side drive encoder private final Encoder m_leftEncoder = @@ -47,10 +44,16 @@ public class DriveSubsystem extends SubsystemBase { /** Creates a new DriveSubsystem. */ public DriveSubsystem() { + SendableRegistry.addChild(m_drive, m_leftLeader); + SendableRegistry.addChild(m_drive, m_rightLeader); + + m_leftLeader.addFollower(m_leftFollower); + m_rightLeader.addFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.setInverted(true); + m_rightLeader.setInverted(true); // Sets the distance per pulse for the encoders m_leftEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gyromecanum/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gyromecanum/Robot.java index b86277b8a88..a43523252c4 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gyromecanum/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/gyromecanum/Robot.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj.examples.gyromecanum; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.TimedRobot; @@ -37,12 +38,17 @@ public void robotInit() { PWMSparkMax frontRight = new PWMSparkMax(kFrontRightChannel); PWMSparkMax rearRight = new PWMSparkMax(kRearRightChannel); + SendableRegistry.addChild(m_robotDrive, frontLeft); + SendableRegistry.addChild(m_robotDrive, rearLeft); + SendableRegistry.addChild(m_robotDrive, frontRight); + SendableRegistry.addChild(m_robotDrive, rearRight); + // Invert the right side motors. // You may need to change or remove this to match your robot. frontRight.setInverted(true); rearRight.setInverted(true); - m_robotDrive = new MecanumDrive(frontLeft, rearLeft, frontRight, rearRight); + m_robotDrive = new MecanumDrive(frontLeft::set, rearLeft::set, frontRight::set, rearRight::set); m_gyro.setSensitivity(kVoltsPerDegreePerSecond); } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/hatchbotinlined/subsystems/DriveSubsystem.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/hatchbotinlined/subsystems/DriveSubsystem.java index 1376195dc15..8de4a90c294 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/hatchbotinlined/subsystems/DriveSubsystem.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/hatchbotinlined/subsystems/DriveSubsystem.java @@ -5,28 +5,25 @@ package edu.wpi.first.wpilibj.examples.hatchbotinlined.subsystems; import edu.wpi.first.util.sendable.SendableBuilder; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj.examples.hatchbotinlined.Constants.DriveConstants; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj2.command.SubsystemBase; public class DriveSubsystem extends SubsystemBase { // The motors on the left side of the drive. - private final MotorControllerGroup m_leftMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kLeftMotor1Port), - new PWMSparkMax(DriveConstants.kLeftMotor2Port)); + private final PWMSparkMax m_leftLeader = new PWMSparkMax(DriveConstants.kLeftMotor1Port); + private final PWMSparkMax m_leftFollower = new PWMSparkMax(DriveConstants.kLeftMotor2Port); // The motors on the right side of the drive. - private final MotorControllerGroup m_rightMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kRightMotor1Port), - new PWMSparkMax(DriveConstants.kRightMotor2Port)); + private final PWMSparkMax m_rightLeader = new PWMSparkMax(DriveConstants.kRightMotor1Port); + private final PWMSparkMax m_rightFollower = new PWMSparkMax(DriveConstants.kRightMotor2Port); // The robot's drive - private final DifferentialDrive m_drive = new DifferentialDrive(m_leftMotors, m_rightMotors); + private final DifferentialDrive m_drive = + new DifferentialDrive(m_leftLeader::set, m_rightLeader::set); // The left-side drive encoder private final Encoder m_leftEncoder = @@ -44,10 +41,16 @@ public class DriveSubsystem extends SubsystemBase { /** Creates a new DriveSubsystem. */ public DriveSubsystem() { + SendableRegistry.addChild(m_drive, m_leftLeader); + SendableRegistry.addChild(m_drive, m_rightLeader); + + m_leftLeader.addFollower(m_leftFollower); + m_rightLeader.addFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.setInverted(true); + m_rightLeader.setInverted(true); // Sets the distance per pulse for the encoders m_leftEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/hatchbottraditional/subsystems/DriveSubsystem.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/hatchbottraditional/subsystems/DriveSubsystem.java index 8a5296d8604..8942b41ca97 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/hatchbottraditional/subsystems/DriveSubsystem.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/hatchbottraditional/subsystems/DriveSubsystem.java @@ -5,28 +5,25 @@ package edu.wpi.first.wpilibj.examples.hatchbottraditional.subsystems; import edu.wpi.first.util.sendable.SendableBuilder; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj.examples.hatchbottraditional.Constants.DriveConstants; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj2.command.SubsystemBase; public class DriveSubsystem extends SubsystemBase { // The motors on the left side of the drive. - private final MotorControllerGroup m_leftMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kLeftMotor1Port), - new PWMSparkMax(DriveConstants.kLeftMotor2Port)); + private final PWMSparkMax m_leftLeader = new PWMSparkMax(DriveConstants.kLeftMotor1Port); + private final PWMSparkMax m_leftFollower = new PWMSparkMax(DriveConstants.kLeftMotor2Port); // The motors on the right side of the drive. - private final MotorControllerGroup m_rightMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kRightMotor1Port), - new PWMSparkMax(DriveConstants.kRightMotor2Port)); + private final PWMSparkMax m_rightLeader = new PWMSparkMax(DriveConstants.kRightMotor1Port); + private final PWMSparkMax m_rightFollower = new PWMSparkMax(DriveConstants.kRightMotor2Port); // The robot's drive - private final DifferentialDrive m_drive = new DifferentialDrive(m_leftMotors, m_rightMotors); + private final DifferentialDrive m_drive = + new DifferentialDrive(m_leftLeader::set, m_rightLeader::set); // The left-side drive encoder private final Encoder m_leftEncoder = @@ -44,10 +41,16 @@ public class DriveSubsystem extends SubsystemBase { /** Creates a new DriveSubsystem. */ public DriveSubsystem() { + SendableRegistry.addChild(m_drive, m_leftLeader); + SendableRegistry.addChild(m_drive, m_rightLeader); + + m_leftLeader.addFollower(m_leftFollower); + m_rightLeader.addFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.setInverted(true); + m_rightLeader.setInverted(true); // Sets the distance per pulse for the encoders m_leftEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/axiscamera/Main.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/httpcamera/Main.java similarity index 93% rename from wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/axiscamera/Main.java rename to wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/httpcamera/Main.java index cb1423d5e64..9af9e7d0688 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/axiscamera/Main.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/httpcamera/Main.java @@ -2,7 +2,7 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -package edu.wpi.first.wpilibj.examples.axiscamera; +package edu.wpi.first.wpilibj.examples.httpcamera; import edu.wpi.first.wpilibj.RobotBase; diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/axiscamera/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/httpcamera/Robot.java similarity index 80% rename from wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/axiscamera/Robot.java rename to wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/httpcamera/Robot.java index 65eafaaec29..dd4bcda3268 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/axiscamera/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/httpcamera/Robot.java @@ -2,12 +2,12 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -package edu.wpi.first.wpilibj.examples.axiscamera; +package edu.wpi.first.wpilibj.examples.httpcamera; import edu.wpi.first.cameraserver.CameraServer; -import edu.wpi.first.cscore.AxisCamera; import edu.wpi.first.cscore.CvSink; import edu.wpi.first.cscore.CvSource; +import edu.wpi.first.cscore.HttpCamera; import edu.wpi.first.wpilibj.TimedRobot; import org.opencv.core.Mat; import org.opencv.core.Point; @@ -16,7 +16,7 @@ /** * This is a demo program showing the use of OpenCV to do vision processing. The image is acquired - * from the Axis camera, then a rectangle is put on the image and sent to the dashboard. OpenCV has + * from an HTTP camera, then a rectangle is put on the image and sent to the dashboard. OpenCV has * many methods for different types of processing. */ public class Robot extends TimedRobot { @@ -27,8 +27,12 @@ public void robotInit() { m_visionThread = new Thread( () -> { - // Get the Axis camera from CameraServer - AxisCamera camera = CameraServer.addAxisCamera("axis-camera.local"); + // Create an HTTP camera. The address will need to be modified to have the correct + // team number. The exact path will depend on the source. + HttpCamera camera = + new HttpCamera("HTTP Camera", "http://10.x.y.11/video/stream.mjpg"); + // Start capturing images + CameraServer.startAutomaticCapture(camera); // Set the resolution camera.setResolution(640, 480); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumbot/Drivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumbot/Drivetrain.java index 15e813a0c30..c64c9b3958a 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumbot/Drivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumbot/Drivetrain.java @@ -14,7 +14,6 @@ import edu.wpi.first.math.kinematics.MecanumDriveWheelSpeeds; import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.Encoder; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; /** Represents a mecanum drive style drivetrain. */ @@ -22,10 +21,10 @@ public class Drivetrain { public static final double kMaxSpeed = 3.0; // 3 meters per second public static final double kMaxAngularSpeed = Math.PI; // 1/2 rotation per second - private final MotorController m_frontLeftMotor = new PWMSparkMax(1); - private final MotorController m_frontRightMotor = new PWMSparkMax(2); - private final MotorController m_backLeftMotor = new PWMSparkMax(3); - private final MotorController m_backRightMotor = new PWMSparkMax(4); + private final PWMSparkMax m_frontLeftMotor = new PWMSparkMax(1); + private final PWMSparkMax m_frontRightMotor = new PWMSparkMax(2); + private final PWMSparkMax m_backLeftMotor = new PWMSparkMax(3); + private final PWMSparkMax m_backRightMotor = new PWMSparkMax(4); private final Encoder m_frontLeftEncoder = new Encoder(0, 1); private final Encoder m_frontRightEncoder = new Encoder(2, 3); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumcontrollercommand/RobotContainer.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumcontrollercommand/RobotContainer.java index 74c088fba4b..5ceb363806e 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumcontrollercommand/RobotContainer.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumcontrollercommand/RobotContainer.java @@ -19,6 +19,7 @@ import edu.wpi.first.wpilibj.examples.mecanumcontrollercommand.Constants.OIConstants; import edu.wpi.first.wpilibj.examples.mecanumcontrollercommand.subsystems.DriveSubsystem; import edu.wpi.first.wpilibj2.command.Command; +import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.MecanumControllerCommand; import edu.wpi.first.wpilibj2.command.RunCommand; @@ -85,15 +86,15 @@ public Command getAutonomousCommand() { // Add kinematics to ensure max speed is actually obeyed .setKinematics(DriveConstants.kDriveKinematics); - // An example trajectory to follow. All units in meters. + // An example trajectory to follow. All units in meters. Trajectory exampleTrajectory = TrajectoryGenerator.generateTrajectory( // Start at the origin facing the +X direction - new Pose2d(0, 0, new Rotation2d(0)), + Pose2d.kZero, // Pass through these two interior waypoints, making an 's' curve path List.of(new Translation2d(1, 1), new Translation2d(2, -1)), // End 3 meters straight ahead of where we started, facing forward - new Pose2d(3, 0, new Rotation2d(0)), + new Pose2d(3, 0, Rotation2d.kZero), config); MecanumControllerCommand mecanumControllerCommand = @@ -121,10 +122,11 @@ public Command getAutonomousCommand() { m_robotDrive::setDriveMotorControllersVolts, // Consumer for the output motor voltages m_robotDrive); - // Reset odometry to the starting pose of the trajectory. - m_robotDrive.resetOdometry(exampleTrajectory.getInitialPose()); - - // Run path following command, then stop at the end. - return mecanumControllerCommand.andThen(() -> m_robotDrive.drive(0, 0, 0, false)); + // Reset odometry to the initial pose of the trajectory, run path following + // command, then stop at the end. + return Commands.sequence( + new InstantCommand(() -> m_robotDrive.resetOdometry(exampleTrajectory.getInitialPose())), + mecanumControllerCommand, + new InstantCommand(() -> m_robotDrive.drive(0, 0, 0, false))); } } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumcontrollercommand/subsystems/DriveSubsystem.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumcontrollercommand/subsystems/DriveSubsystem.java index 6d731bad428..b3f9b3462ab 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumcontrollercommand/subsystems/DriveSubsystem.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumcontrollercommand/subsystems/DriveSubsystem.java @@ -9,6 +9,7 @@ import edu.wpi.first.math.kinematics.MecanumDriveOdometry; import edu.wpi.first.math.kinematics.MecanumDriveWheelPositions; import edu.wpi.first.math.kinematics.MecanumDriveWheelSpeeds; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.ADXRS450_Gyro; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.drive.MecanumDrive; @@ -23,7 +24,7 @@ public class DriveSubsystem extends SubsystemBase { private final PWMSparkMax m_rearRight = new PWMSparkMax(DriveConstants.kRearRightMotorPort); private final MecanumDrive m_drive = - new MecanumDrive(m_frontLeft, m_rearLeft, m_frontRight, m_rearRight); + new MecanumDrive(m_frontLeft::set, m_rearLeft::set, m_frontRight::set, m_rearRight::set); // The front-left-side drive encoder private final Encoder m_frontLeftEncoder = @@ -65,6 +66,11 @@ public class DriveSubsystem extends SubsystemBase { /** Creates a new DriveSubsystem. */ public DriveSubsystem() { + SendableRegistry.addChild(m_drive, m_frontLeft); + SendableRegistry.addChild(m_drive, m_rearLeft); + SendableRegistry.addChild(m_drive, m_frontRight); + SendableRegistry.addChild(m_drive, m_rearRight); + // Sets the distance per pulse for the encoders m_frontLeftEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); m_rearLeftEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumdrive/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumdrive/Robot.java index f37654321da..77aa0cedb71 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumdrive/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumdrive/Robot.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj.examples.mecanumdrive; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.drive.MecanumDrive; @@ -28,12 +29,17 @@ public void robotInit() { PWMSparkMax frontRight = new PWMSparkMax(kFrontRightChannel); PWMSparkMax rearRight = new PWMSparkMax(kRearRightChannel); + SendableRegistry.addChild(m_robotDrive, frontLeft); + SendableRegistry.addChild(m_robotDrive, rearLeft); + SendableRegistry.addChild(m_robotDrive, frontRight); + SendableRegistry.addChild(m_robotDrive, rearRight); + // Invert the right side motors. // You may need to change or remove this to match your robot. frontRight.setInverted(true); rearRight.setInverted(true); - m_robotDrive = new MecanumDrive(frontLeft, rearLeft, frontRight, rearRight); + m_robotDrive = new MecanumDrive(frontLeft::set, rearLeft::set, frontRight::set, rearRight::set); m_stick = new Joystick(kJoystickChannel); } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumdriveposeestimator/Drivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumdriveposeestimator/Drivetrain.java index b5c34c47bf6..a534ae31b0e 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumdriveposeestimator/Drivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/mecanumdriveposeestimator/Drivetrain.java @@ -18,7 +18,6 @@ import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Timer; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; /** Represents a mecanum drive style drivetrain. */ @@ -26,10 +25,10 @@ public class Drivetrain { public static final double kMaxSpeed = 3.0; // 3 meters per second public static final double kMaxAngularSpeed = Math.PI; // 1/2 rotation per second - private final MotorController m_frontLeftMotor = new PWMSparkMax(1); - private final MotorController m_frontRightMotor = new PWMSparkMax(2); - private final MotorController m_backLeftMotor = new PWMSparkMax(3); - private final MotorController m_backRightMotor = new PWMSparkMax(4); + private final PWMSparkMax m_frontLeftMotor = new PWMSparkMax(1); + private final PWMSparkMax m_frontRightMotor = new PWMSparkMax(2); + private final PWMSparkMax m_backLeftMotor = new PWMSparkMax(3); + private final PWMSparkMax m_backRightMotor = new PWMSparkMax(4); private final Encoder m_frontLeftEncoder = new Encoder(0, 1); private final Encoder m_frontRightEncoder = new Encoder(2, 3); @@ -59,7 +58,7 @@ public class Drivetrain { m_kinematics, m_gyro.getRotation2d(), getCurrentDistances(), - new Pose2d(), + Pose2d.kZero, VecBuilder.fill(0.05, 0.05, Units.degreesToRadians(5)), VecBuilder.fill(0.5, 0.5, Units.degreesToRadians(30))); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/motorcontrol/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/motorcontrol/Robot.java index 82ced20919a..cbb4babbdf0 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/motorcontrol/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/motorcontrol/Robot.java @@ -7,7 +7,6 @@ import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.TimedRobot; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; @@ -27,7 +26,7 @@ public class Robot extends TimedRobot { private static final int kEncoderPortA = 0; private static final int kEncoderPortB = 1; - private MotorController m_motor; + private PWMSparkMax m_motor; private Joystick m_joystick; private Encoder m_encoder; diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/Constants.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/Constants.java deleted file mode 100644 index d5140ee13ac..00000000000 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/Constants.java +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.examples.ramsetecommand; - -import edu.wpi.first.math.kinematics.DifferentialDriveKinematics; - -/** - * The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean - * constants. This class should not be used for any other purpose. All constants should be declared - * globally (i.e. public static). Do not put anything functional in this class. - * - *

    It is advised to statically import this class (or one of its inner classes) wherever the - * constants are needed, to reduce verbosity. - */ -public final class Constants { - public static final class DriveConstants { - public static final int kLeftMotor1Port = 0; - public static final int kLeftMotor2Port = 1; - public static final int kRightMotor1Port = 2; - public static final int kRightMotor2Port = 3; - - public static final int[] kLeftEncoderPorts = new int[] {0, 1}; - public static final int[] kRightEncoderPorts = new int[] {2, 3}; - public static final boolean kLeftEncoderReversed = false; - public static final boolean kRightEncoderReversed = true; - - public static final double kTrackwidthMeters = 0.69; - public static final DifferentialDriveKinematics kDriveKinematics = - new DifferentialDriveKinematics(kTrackwidthMeters); - - public static final int kEncoderCPR = 1024; - public static final double kWheelDiameterMeters = 0.15; - public static final double kEncoderDistancePerPulse = - // Assumes the encoders are directly mounted on the wheel shafts - (kWheelDiameterMeters * Math.PI) / (double) kEncoderCPR; - - // These are example values only - DO NOT USE THESE FOR YOUR OWN ROBOT! - // These characterization values MUST be determined either experimentally or theoretically - // for *your* robot's drive. - // The Robot Characterization Toolsuite provides a convenient tool for obtaining these - // values for your robot. - public static final double ksVolts = 0.22; - public static final double kvVoltSecondsPerMeter = 1.98; - public static final double kaVoltSecondsSquaredPerMeter = 0.2; - - // Example value only - as above, this must be tuned for your drive! - public static final double kPDriveVel = 8.5; - } - - public static final class OIConstants { - public static final int kDriverControllerPort = 0; - } - - public static final class AutoConstants { - public static final double kMaxSpeedMetersPerSecond = 3; - public static final double kMaxAccelerationMetersPerSecondSquared = 1; - - // Reasonable baseline values for a RAMSETE follower in units of meters and seconds - public static final double kRamseteB = 2; - public static final double kRamseteZeta = 0.7; - } -} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/RobotContainer.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/RobotContainer.java deleted file mode 100644 index 9f0980a0e9f..00000000000 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/RobotContainer.java +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.examples.ramsetecommand; - -import static edu.wpi.first.wpilibj.XboxController.Button; - -import edu.wpi.first.math.controller.PIDController; -import edu.wpi.first.math.controller.RamseteController; -import edu.wpi.first.math.controller.SimpleMotorFeedforward; -import edu.wpi.first.math.geometry.Pose2d; -import edu.wpi.first.math.geometry.Rotation2d; -import edu.wpi.first.math.geometry.Translation2d; -import edu.wpi.first.math.trajectory.Trajectory; -import edu.wpi.first.math.trajectory.TrajectoryConfig; -import edu.wpi.first.math.trajectory.TrajectoryGenerator; -import edu.wpi.first.math.trajectory.constraint.DifferentialDriveVoltageConstraint; -import edu.wpi.first.wpilibj.XboxController; -import edu.wpi.first.wpilibj.examples.ramsetecommand.Constants.AutoConstants; -import edu.wpi.first.wpilibj.examples.ramsetecommand.Constants.DriveConstants; -import edu.wpi.first.wpilibj.examples.ramsetecommand.Constants.OIConstants; -import edu.wpi.first.wpilibj.examples.ramsetecommand.subsystems.DriveSubsystem; -import edu.wpi.first.wpilibj2.command.Command; -import edu.wpi.first.wpilibj2.command.InstantCommand; -import edu.wpi.first.wpilibj2.command.RamseteCommand; -import edu.wpi.first.wpilibj2.command.RunCommand; -import edu.wpi.first.wpilibj2.command.button.JoystickButton; -import java.util.List; - -/** - * This class is where the bulk of the robot should be declared. Since Command-based is a - * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} - * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including - * subsystems, commands, and button mappings) should be declared here. - */ -public class RobotContainer { - // The robot's subsystems - private final DriveSubsystem m_robotDrive = new DriveSubsystem(); - - // The driver's controller - XboxController m_driverController = new XboxController(OIConstants.kDriverControllerPort); - - /** The container for the robot. Contains subsystems, OI devices, and commands. */ - public RobotContainer() { - // Configure the button bindings - configureButtonBindings(); - - // Configure default commands - // Set the default drive command to split-stick arcade drive - m_robotDrive.setDefaultCommand( - // A split-stick arcade command, with forward/backward controlled by the left - // hand, and turning controlled by the right. - new RunCommand( - () -> - m_robotDrive.arcadeDrive( - -m_driverController.getLeftY(), -m_driverController.getRightX()), - m_robotDrive)); - } - - /** - * Use this method to define your button->command mappings. Buttons can be created by - * instantiating a {@link edu.wpi.first.wpilibj.GenericHID} or one of its subclasses ({@link - * edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then calling passing it to a - * {@link JoystickButton}. - */ - private void configureButtonBindings() { - // Drive at half speed when the right bumper is held - new JoystickButton(m_driverController, Button.kRightBumper.value) - .onTrue(new InstantCommand(() -> m_robotDrive.setMaxOutput(0.5))) - .onFalse(new InstantCommand(() -> m_robotDrive.setMaxOutput(1))); - } - - /** - * Use this to pass the autonomous command to the main {@link Robot} class. - * - * @return the command to run in autonomous - */ - public Command getAutonomousCommand() { - // Create a voltage constraint to ensure we don't accelerate too fast - var autoVoltageConstraint = - new DifferentialDriveVoltageConstraint( - new SimpleMotorFeedforward( - DriveConstants.ksVolts, - DriveConstants.kvVoltSecondsPerMeter, - DriveConstants.kaVoltSecondsSquaredPerMeter), - DriveConstants.kDriveKinematics, - 10); - - // Create config for trajectory - TrajectoryConfig config = - new TrajectoryConfig( - AutoConstants.kMaxSpeedMetersPerSecond, - AutoConstants.kMaxAccelerationMetersPerSecondSquared) - // Add kinematics to ensure max speed is actually obeyed - .setKinematics(DriveConstants.kDriveKinematics) - // Apply the voltage constraint - .addConstraint(autoVoltageConstraint); - - // An example trajectory to follow. All units in meters. - Trajectory exampleTrajectory = - TrajectoryGenerator.generateTrajectory( - // Start at the origin facing the +X direction - new Pose2d(0, 0, new Rotation2d(0)), - // Pass through these two interior waypoints, making an 's' curve path - List.of(new Translation2d(1, 1), new Translation2d(2, -1)), - // End 3 meters straight ahead of where we started, facing forward - new Pose2d(3, 0, new Rotation2d(0)), - // Pass config - config); - - RamseteCommand ramseteCommand = - new RamseteCommand( - exampleTrajectory, - m_robotDrive::getPose, - new RamseteController(AutoConstants.kRamseteB, AutoConstants.kRamseteZeta), - new SimpleMotorFeedforward( - DriveConstants.ksVolts, - DriveConstants.kvVoltSecondsPerMeter, - DriveConstants.kaVoltSecondsSquaredPerMeter), - DriveConstants.kDriveKinematics, - m_robotDrive::getWheelSpeeds, - new PIDController(DriveConstants.kPDriveVel, 0, 0), - new PIDController(DriveConstants.kPDriveVel, 0, 0), - // RamseteCommand passes volts to the callback - m_robotDrive::tankDriveVolts, - m_robotDrive); - - // Reset odometry to the starting pose of the trajectory. - m_robotDrive.resetOdometry(exampleTrajectory.getInitialPose()); - - // Run path following command, then stop at the end. - return ramseteCommand.andThen(() -> m_robotDrive.tankDriveVolts(0, 0)); - } -} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/subsystems/DriveSubsystem.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/subsystems/DriveSubsystem.java deleted file mode 100644 index 288baeda4b4..00000000000 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/subsystems/DriveSubsystem.java +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.examples.ramsetecommand.subsystems; - -import edu.wpi.first.math.geometry.Pose2d; -import edu.wpi.first.math.kinematics.DifferentialDriveOdometry; -import edu.wpi.first.math.kinematics.DifferentialDriveWheelSpeeds; -import edu.wpi.first.wpilibj.ADXRS450_Gyro; -import edu.wpi.first.wpilibj.Encoder; -import edu.wpi.first.wpilibj.drive.DifferentialDrive; -import edu.wpi.first.wpilibj.examples.ramsetecommand.Constants.DriveConstants; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; -import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; -import edu.wpi.first.wpilibj2.command.SubsystemBase; - -public class DriveSubsystem extends SubsystemBase { - // The motors on the left side of the drive. - private final MotorControllerGroup m_leftMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kLeftMotor1Port), - new PWMSparkMax(DriveConstants.kLeftMotor2Port)); - - // The motors on the right side of the drive. - private final MotorControllerGroup m_rightMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kRightMotor1Port), - new PWMSparkMax(DriveConstants.kRightMotor2Port)); - - // The robot's drive - private final DifferentialDrive m_drive = new DifferentialDrive(m_leftMotors, m_rightMotors); - - // The left-side drive encoder - private final Encoder m_leftEncoder = - new Encoder( - DriveConstants.kLeftEncoderPorts[0], - DriveConstants.kLeftEncoderPorts[1], - DriveConstants.kLeftEncoderReversed); - - // The right-side drive encoder - private final Encoder m_rightEncoder = - new Encoder( - DriveConstants.kRightEncoderPorts[0], - DriveConstants.kRightEncoderPorts[1], - DriveConstants.kRightEncoderReversed); - - // The gyro sensor - private final ADXRS450_Gyro m_gyro = new ADXRS450_Gyro(); - - // Odometry class for tracking robot pose - private final DifferentialDriveOdometry m_odometry; - - /** Creates a new DriveSubsystem. */ - public DriveSubsystem() { - // We need to invert one side of the drivetrain so that positive voltages - // result in both sides moving forward. Depending on how your robot's - // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.setInverted(true); - - // Sets the distance per pulse for the encoders - m_leftEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); - m_rightEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); - - resetEncoders(); - m_odometry = - new DifferentialDriveOdometry( - m_gyro.getRotation2d(), m_leftEncoder.getDistance(), m_rightEncoder.getDistance()); - } - - @Override - public void periodic() { - // Update the odometry in the periodic block - m_odometry.update( - m_gyro.getRotation2d(), m_leftEncoder.getDistance(), m_rightEncoder.getDistance()); - } - - /** - * Returns the currently-estimated pose of the robot. - * - * @return The pose. - */ - public Pose2d getPose() { - return m_odometry.getPoseMeters(); - } - - /** - * Returns the current wheel speeds of the robot. - * - * @return The current wheel speeds. - */ - public DifferentialDriveWheelSpeeds getWheelSpeeds() { - return new DifferentialDriveWheelSpeeds(m_leftEncoder.getRate(), m_rightEncoder.getRate()); - } - - /** - * Resets the odometry to the specified pose. - * - * @param pose The pose to which to set the odometry. - */ - public void resetOdometry(Pose2d pose) { - resetEncoders(); - m_odometry.resetPosition( - m_gyro.getRotation2d(), m_leftEncoder.getDistance(), m_rightEncoder.getDistance(), pose); - } - - /** - * Drives the robot using arcade controls. - * - * @param fwd the commanded forward movement - * @param rot the commanded rotation - */ - public void arcadeDrive(double fwd, double rot) { - m_drive.arcadeDrive(fwd, rot); - } - - /** - * Controls the left and right sides of the drive directly with voltages. - * - * @param leftVolts the commanded left output - * @param rightVolts the commanded right output - */ - public void tankDriveVolts(double leftVolts, double rightVolts) { - m_leftMotors.setVoltage(leftVolts); - m_rightMotors.setVoltage(rightVolts); - m_drive.feed(); - } - - /** Resets the drive encoders to currently read a position of 0. */ - public void resetEncoders() { - m_leftEncoder.reset(); - m_rightEncoder.reset(); - } - - /** - * Gets the average distance of the two encoders. - * - * @return the average of the two encoder readings - */ - public double getAverageEncoderDistance() { - return (m_leftEncoder.getDistance() + m_rightEncoder.getDistance()) / 2.0; - } - - /** - * Gets the left drive encoder. - * - * @return the left drive encoder - */ - public Encoder getLeftEncoder() { - return m_leftEncoder; - } - - /** - * Gets the right drive encoder. - * - * @return the right drive encoder - */ - public Encoder getRightEncoder() { - return m_rightEncoder; - } - - /** - * Sets the max output of the drive. Useful for scaling the drive to drive more slowly. - * - * @param maxOutput the maximum output to which the drive will be constrained - */ - public void setMaxOutput(double maxOutput) { - m_drive.setMaxOutput(maxOutput); - } - - /** Zeroes the heading of the robot. */ - public void zeroHeading() { - m_gyro.reset(); - } - - /** - * Returns the heading of the robot. - * - * @return the robot's heading in degrees, from -180 to 180 - */ - public double getHeading() { - return m_gyro.getRotation2d().getDegrees(); - } - - /** - * Returns the turn rate of the robot. - * - * @return The turn rate of the robot, in degrees per second - */ - public double getTurnRate() { - return -m_gyro.getRate(); - } -} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecontroller/Drivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecontroller/Drivetrain.java deleted file mode 100644 index 69288a15a99..00000000000 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecontroller/Drivetrain.java +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.examples.ramsetecontroller; - -import edu.wpi.first.math.controller.PIDController; -import edu.wpi.first.math.controller.SimpleMotorFeedforward; -import edu.wpi.first.math.geometry.Pose2d; -import edu.wpi.first.math.kinematics.ChassisSpeeds; -import edu.wpi.first.math.kinematics.DifferentialDriveKinematics; -import edu.wpi.first.math.kinematics.DifferentialDriveOdometry; -import edu.wpi.first.math.kinematics.DifferentialDriveWheelSpeeds; -import edu.wpi.first.wpilibj.AnalogGyro; -import edu.wpi.first.wpilibj.Encoder; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; -import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; - -/** Represents a differential drive style drivetrain. */ -public class Drivetrain { - public static final double kMaxSpeed = 3.0; // meters per second - public static final double kMaxAngularSpeed = 2 * Math.PI; // one rotation per second - - private static final double kTrackWidth = 0.381 * 2; // meters - private static final double kWheelRadius = 0.0508; // meters - private static final int kEncoderResolution = 4096; - - private final MotorController m_leftLeader = new PWMSparkMax(1); - private final MotorController m_leftFollower = new PWMSparkMax(2); - private final MotorController m_rightLeader = new PWMSparkMax(3); - private final MotorController m_rightFollower = new PWMSparkMax(4); - - private final Encoder m_leftEncoder = new Encoder(0, 1); - private final Encoder m_rightEncoder = new Encoder(2, 3); - - private final MotorControllerGroup m_leftGroup = - new MotorControllerGroup(m_leftLeader, m_leftFollower); - private final MotorControllerGroup m_rightGroup = - new MotorControllerGroup(m_rightLeader, m_rightFollower); - - private final AnalogGyro m_gyro = new AnalogGyro(0); - - private final PIDController m_leftPIDController = new PIDController(1, 0, 0); - private final PIDController m_rightPIDController = new PIDController(1, 0, 0); - - private final DifferentialDriveKinematics m_kinematics = - new DifferentialDriveKinematics(kTrackWidth); - - private final DifferentialDriveOdometry m_odometry; - - // Gains are for example purposes only - must be determined for your own robot! - private final SimpleMotorFeedforward m_feedforward = new SimpleMotorFeedforward(1, 3); - - /** - * Constructs a differential drive object. Sets the encoder distance per pulse and resets the - * gyro. - */ - public Drivetrain() { - m_gyro.reset(); - - // We need to invert one side of the drivetrain so that positive voltages - // result in both sides moving forward. Depending on how your robot's - // gearbox is constructed, you might have to invert the left side instead. - m_rightGroup.setInverted(true); - - // Set the distance per pulse for the drive encoders. We can simply use the - // distance traveled for one rotation of the wheel divided by the encoder - // resolution. - m_leftEncoder.setDistancePerPulse(2 * Math.PI * kWheelRadius / kEncoderResolution); - m_rightEncoder.setDistancePerPulse(2 * Math.PI * kWheelRadius / kEncoderResolution); - - m_leftEncoder.reset(); - m_rightEncoder.reset(); - - m_odometry = - new DifferentialDriveOdometry( - m_gyro.getRotation2d(), m_leftEncoder.getDistance(), m_rightEncoder.getDistance()); - } - - /** - * Sets the desired wheel speeds. - * - * @param speeds The desired wheel speeds. - */ - public void setSpeeds(DifferentialDriveWheelSpeeds speeds) { - final double leftFeedforward = m_feedforward.calculate(speeds.leftMetersPerSecond); - final double rightFeedforward = m_feedforward.calculate(speeds.rightMetersPerSecond); - - final double leftOutput = - m_leftPIDController.calculate(m_leftEncoder.getRate(), speeds.leftMetersPerSecond); - final double rightOutput = - m_rightPIDController.calculate(m_rightEncoder.getRate(), speeds.rightMetersPerSecond); - m_leftGroup.setVoltage(leftOutput + leftFeedforward); - m_rightGroup.setVoltage(rightOutput + rightFeedforward); - } - - /** - * Drives the robot with the given linear velocity and angular velocity. - * - * @param xSpeed Linear velocity in m/s. - * @param rot Angular velocity in rad/s. - */ - public void drive(double xSpeed, double rot) { - var wheelSpeeds = m_kinematics.toWheelSpeeds(new ChassisSpeeds(xSpeed, 0.0, rot)); - setSpeeds(wheelSpeeds); - } - - /** Updates the field-relative position. */ - public void updateOdometry() { - m_odometry.update( - m_gyro.getRotation2d(), m_leftEncoder.getDistance(), m_rightEncoder.getDistance()); - } - - /** - * Resets the field-relative position to a specific location. - * - * @param pose The position to reset to. - */ - public void resetOdometry(Pose2d pose) { - m_odometry.resetPosition( - m_gyro.getRotation2d(), m_leftEncoder.getDistance(), m_rightEncoder.getDistance(), pose); - } - - /** - * Returns the pose of the robot. - * - * @return The pose of the robot. - */ - public Pose2d getPose() { - return m_odometry.getPoseMeters(); - } -} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecontroller/Main.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecontroller/Main.java deleted file mode 100644 index 0b59d82f954..00000000000 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecontroller/Main.java +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.examples.ramsetecontroller; - -import edu.wpi.first.wpilibj.RobotBase; - -/** - * Do NOT add any static variables to this class, or any initialization at all. Unless you know what - * you are doing, do not modify this file except to change the parameter class to the startRobot - * call. - */ -public final class Main { - private Main() {} - - /** - * Main initialization function. Do not perform any initialization here. - * - *

    If you change your main robot class, change the parameter type. - */ - public static void main(String... args) { - RobotBase.startRobot(Robot::new); - } -} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecontroller/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecontroller/Robot.java deleted file mode 100644 index ef73d106da6..00000000000 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecontroller/Robot.java +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.examples.ramsetecontroller; - -import edu.wpi.first.math.controller.RamseteController; -import edu.wpi.first.math.filter.SlewRateLimiter; -import edu.wpi.first.math.geometry.Pose2d; -import edu.wpi.first.math.geometry.Rotation2d; -import edu.wpi.first.math.geometry.Translation2d; -import edu.wpi.first.math.trajectory.Trajectory; -import edu.wpi.first.math.trajectory.TrajectoryConfig; -import edu.wpi.first.math.trajectory.TrajectoryGenerator; -import edu.wpi.first.math.util.Units; -import edu.wpi.first.wpilibj.TimedRobot; -import edu.wpi.first.wpilibj.Timer; -import edu.wpi.first.wpilibj.XboxController; -import edu.wpi.first.wpilibj.smartdashboard.Field2d; -import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; -import java.util.List; - -public class Robot extends TimedRobot { - private final XboxController m_controller = new XboxController(0); - private final Drivetrain m_drive = new Drivetrain(); - - // Slew rate limiters to make joystick inputs more gentle; 1/3 sec from 0 to 1. - private final SlewRateLimiter m_speedLimiter = new SlewRateLimiter(3); - private final SlewRateLimiter m_rotLimiter = new SlewRateLimiter(3); - - // An example trajectory to follow during the autonomous period. - private Trajectory m_trajectory; - - // The Ramsete Controller to follow the trajectory. - private final RamseteController m_ramseteController = new RamseteController(); - - // The timer to use during the autonomous period. - private Timer m_timer; - - // Create Field2d for robot and trajectory visualizations. - private Field2d m_field; - - @Override - public void robotInit() { - // Create the trajectory to follow in autonomous. It is best to initialize - // trajectories here to avoid wasting time in autonomous. - m_trajectory = - TrajectoryGenerator.generateTrajectory( - new Pose2d(0, 0, Rotation2d.fromDegrees(0)), - List.of(new Translation2d(1, 1), new Translation2d(2, -1)), - new Pose2d(3, 0, Rotation2d.fromDegrees(0)), - new TrajectoryConfig(Units.feetToMeters(3.0), Units.feetToMeters(3.0))); - - // Create and push Field2d to SmartDashboard. - m_field = new Field2d(); - SmartDashboard.putData(m_field); - - // Push the trajectory to Field2d. - m_field.getObject("traj").setTrajectory(m_trajectory); - } - - @Override - public void autonomousInit() { - // Initialize the timer. - m_timer = new Timer(); - m_timer.start(); - - // Reset the drivetrain's odometry to the starting pose of the trajectory. - m_drive.resetOdometry(m_trajectory.getInitialPose()); - } - - @Override - public void autonomousPeriodic() { - // Update odometry. - m_drive.updateOdometry(); - - // Update robot position on Field2d. - m_field.setRobotPose(m_drive.getPose()); - - if (m_timer.get() < m_trajectory.getTotalTimeSeconds()) { - // Get the desired pose from the trajectory. - var desiredPose = m_trajectory.sample(m_timer.get()); - - // Get the reference chassis speeds from the Ramsete controller. - var refChassisSpeeds = m_ramseteController.calculate(m_drive.getPose(), desiredPose); - - // Set the linear and angular speeds. - m_drive.drive(refChassisSpeeds.vxMetersPerSecond, refChassisSpeeds.omegaRadiansPerSecond); - } else { - m_drive.drive(0, 0); - } - } - - @Override - public void teleopPeriodic() { - // Get the x speed. We are inverting this because Xbox controllers return - // negative values when we push forward. - final var xSpeed = -m_speedLimiter.calculate(m_controller.getLeftY()) * Drivetrain.kMaxSpeed; - - // Get the rate of angular rotation. We are inverting this because we want a - // positive value when we pull to the left (remember, CCW is positive in - // mathematics). Xbox controllers return positive values when you pull to - // the right by default. - final var rot = -m_rotLimiter.calculate(m_controller.getRightX()) * Drivetrain.kMaxAngularSpeed; - - m_drive.drive(xSpeed, rot); - } -} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/RapidReactCommandBot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/RapidReactCommandBot.java index 12d7f662c6a..88b1913aa09 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/RapidReactCommandBot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/RapidReactCommandBot.java @@ -46,11 +46,12 @@ public class RapidReactCommandBot { */ public void configureBindings() { // Automatically run the storage motor whenever the ball storage is not full, - // and turn it off whenever it fills. - new Trigger(m_storage::isFull).whileFalse(m_storage.runCommand()); + // and turn it off whenever it fills. Uses subsystem-hosted trigger to + // improve readability and make inter-subsystem communication easier. + m_storage.hasCargo.whileFalse(m_storage.runCommand()); // Automatically disable and retract the intake whenever the ball storage is full. - new Trigger(m_storage::isFull).onTrue(m_intake.retractCommand()); + m_storage.hasCargo.onTrue(m_intake.retractCommand()); // Control the drive with split-stick arcade controls m_drive.setDefaultCommand( diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Drive.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Drive.java index 736ff446da4..dd7854d15ff 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Drive.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Drive.java @@ -4,10 +4,10 @@ package edu.wpi.first.wpilibj.examples.rapidreactcommandbot.subsystems; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj.examples.rapidreactcommandbot.Constants.DriveConstants; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.SubsystemBase; @@ -15,19 +15,16 @@ public class Drive extends SubsystemBase { // The motors on the left side of the drive. - private final MotorControllerGroup m_leftMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kLeftMotor1Port), - new PWMSparkMax(DriveConstants.kLeftMotor2Port)); + private final PWMSparkMax m_leftLeader = new PWMSparkMax(DriveConstants.kLeftMotor1Port); + private final PWMSparkMax m_leftFollower = new PWMSparkMax(DriveConstants.kLeftMotor2Port); // The motors on the right side of the drive. - private final MotorControllerGroup m_rightMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kRightMotor1Port), - new PWMSparkMax(DriveConstants.kRightMotor2Port)); + private final PWMSparkMax m_rightLeader = new PWMSparkMax(DriveConstants.kRightMotor1Port); + private final PWMSparkMax m_rightFollower = new PWMSparkMax(DriveConstants.kRightMotor2Port); // The robot's drive - private final DifferentialDrive m_drive = new DifferentialDrive(m_leftMotors, m_rightMotors); + private final DifferentialDrive m_drive = + new DifferentialDrive(m_leftLeader::set, m_rightLeader::set); // The left-side drive encoder private final Encoder m_leftEncoder = @@ -45,10 +42,16 @@ public class Drive extends SubsystemBase { /** Creates a new Drive subsystem. */ public Drive() { + SendableRegistry.addChild(m_drive, m_leftLeader); + SendableRegistry.addChild(m_drive, m_rightLeader); + + m_leftLeader.addFollower(m_leftFollower); + m_rightLeader.addFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.setInverted(true); + m_rightLeader.setInverted(true); // Sets the distance per pulse for the encoders m_leftEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Pneumatics.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Pneumatics.java index 69ec0235430..b51562fca87 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Pneumatics.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Pneumatics.java @@ -50,16 +50,12 @@ private double getPressure() { */ public Command disableCompressorCommand() { return startEnd( - () -> { - // Disable closed-loop mode on the compressor. - m_compressor.disable(); - }, - () -> { - // Enable closed-loop mode based on the digital pressure switch connected to the - // PCM/PH. - // The switch is open when the pressure is over ~120 PSI. - m_compressor.enableDigital(); - }) + // Disable closed-loop mode on the compressor. + m_compressor::disable, + // Enable closed-loop mode based on the digital pressure switch connected to the + // PCM/PH. + // The switch is open when the pressure is over ~120 PSI. + m_compressor::enableDigital) .withName("Compressor Disabled"); } } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Shooter.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Shooter.java index 0e7f9b56cef..d282c2062cf 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Shooter.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Shooter.java @@ -10,7 +10,7 @@ import edu.wpi.first.math.controller.PIDController; import edu.wpi.first.math.controller.SimpleMotorFeedforward; import edu.wpi.first.wpilibj.Encoder; -import edu.wpi.first.wpilibj.examples.frisbeebot.Constants.ShooterConstants; +import edu.wpi.first.wpilibj.examples.rapidreactcommandbot.Constants.ShooterConstants; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.SubsystemBase; diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Storage.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Storage.java index dac61a43fce..f3812b1d894 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Storage.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/rapidreactcommandbot/subsystems/Storage.java @@ -4,28 +4,29 @@ package edu.wpi.first.wpilibj.examples.rapidreactcommandbot.subsystems; -import static edu.wpi.first.wpilibj.examples.rapidreactcommandbot.Constants.StorageConstants; - import edu.wpi.first.wpilibj.DigitalInput; +import edu.wpi.first.wpilibj.examples.rapidreactcommandbot.Constants.StorageConstants; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.SubsystemBase; +import edu.wpi.first.wpilibj2.command.button.Trigger; public class Storage extends SubsystemBase { private final PWMSparkMax m_motor = new PWMSparkMax(StorageConstants.kMotorPort); private final DigitalInput m_ballSensor = new DigitalInput(StorageConstants.kBallSensorPort); + // Expose trigger from subsystem to improve readability and ease + // inter-subsystem communications + /** Whether the ball storage is full. */ + @SuppressWarnings("checkstyle:MemberName") + public final Trigger hasCargo = new Trigger(m_ballSensor::get); + /** Create a new Storage subsystem. */ public Storage() { // Set default command to turn off the storage motor and then idle setDefaultCommand(runOnce(m_motor::disable).andThen(run(() -> {})).withName("Idle")); } - /** Whether the ball storage is full. */ - public boolean isFull() { - return m_ballSensor.get(); - } - /** Returns a command that runs the storage motor indefinitely. */ public Command runCommand() { return run(() -> m_motor.set(1)).withName("run"); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/romireference/subsystems/Drivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/romireference/subsystems/Drivetrain.java index d805590c068..42cf45eef8c 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/romireference/subsystems/Drivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/romireference/subsystems/Drivetrain.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj.examples.romireference.subsystems; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.BuiltInAccelerometer; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.drive.DifferentialDrive; @@ -26,7 +27,8 @@ public class Drivetrain extends SubsystemBase { private final Encoder m_rightEncoder = new Encoder(6, 7); // Set up the differential drive controller - private final DifferentialDrive m_diffDrive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_diffDrive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); // Set up the RomiGyro private final RomiGyro m_gyro = new RomiGyro(); @@ -36,6 +38,9 @@ public class Drivetrain extends SubsystemBase { /** Creates a new Drivetrain. */ public Drivetrain() { + SendableRegistry.addChild(m_diffDrive, m_leftMotor); + SendableRegistry.addChild(m_diffDrive, m_rightMotor); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/shuffleboard/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/shuffleboard/Robot.java index 47109e0f2fb..436d72685d4 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/shuffleboard/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/shuffleboard/Robot.java @@ -5,6 +5,7 @@ package edu.wpi.first.wpilibj.examples.shuffleboard; import edu.wpi.first.networktables.GenericEntry; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.AnalogPotentiometer; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.TimedRobot; @@ -16,8 +17,10 @@ import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; public class Robot extends TimedRobot { + private final PWMSparkMax m_leftDriveMotor = new PWMSparkMax(0); + private final PWMSparkMax m_rightDriveMotor = new PWMSparkMax(1); private final DifferentialDrive m_tankDrive = - new DifferentialDrive(new PWMSparkMax(0), new PWMSparkMax(1)); + new DifferentialDrive(m_leftDriveMotor::set, m_rightDriveMotor::set); private final Encoder m_leftEncoder = new Encoder(0, 1); private final Encoder m_rightEncoder = new Encoder(2, 3); @@ -27,6 +30,9 @@ public class Robot extends TimedRobot { @Override public void robotInit() { + SendableRegistry.addChild(m_tankDrive, m_leftDriveMotor); + SendableRegistry.addChild(m_tankDrive, m_rightDriveMotor); + // Add a 'max speed' widget to a tab named 'Configuration', using a number slider // The widget will be placed in the second column and row and will be TWO columns wide m_maxSpeed = diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/simpledifferentialdrivesimulation/Drivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/simpledifferentialdrivesimulation/Drivetrain.java index a9f53a9170d..a69839bc7e7 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/simpledifferentialdrivesimulation/Drivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/simpledifferentialdrivesimulation/Drivetrain.java @@ -18,7 +18,6 @@ import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.RobotController; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; import edu.wpi.first.wpilibj.simulation.AnalogGyroSim; import edu.wpi.first.wpilibj.simulation.DifferentialDrivetrainSim; @@ -41,11 +40,6 @@ public class Drivetrain { private final PWMSparkMax m_rightLeader = new PWMSparkMax(3); private final PWMSparkMax m_rightFollower = new PWMSparkMax(4); - private final MotorControllerGroup m_leftGroup = - new MotorControllerGroup(m_leftLeader, m_leftFollower); - private final MotorControllerGroup m_rightGroup = - new MotorControllerGroup(m_rightLeader, m_rightFollower); - private final Encoder m_leftEncoder = new Encoder(0, 1); private final Encoder m_rightEncoder = new Encoder(2, 3); @@ -77,10 +71,13 @@ public class Drivetrain { /** Subsystem constructor. */ public Drivetrain() { + m_leftLeader.addFollower(m_leftFollower); + m_rightLeader.addFollower(m_rightFollower); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. - m_rightGroup.setInverted(true); + m_rightLeader.setInverted(true); // Set the distance per pulse for the drive encoders. We can simply use the // distance traveled for one rotation of the wheel divided by the encoder @@ -91,7 +88,7 @@ public Drivetrain() { m_leftEncoder.reset(); m_rightEncoder.reset(); - m_rightGroup.setInverted(true); + m_rightLeader.setInverted(true); SmartDashboard.putData("Field", m_fieldSim); } @@ -104,8 +101,8 @@ public void setSpeeds(DifferentialDriveWheelSpeeds speeds) { double rightOutput = m_rightPIDController.calculate(m_rightEncoder.getRate(), speeds.rightMetersPerSecond); - m_leftGroup.setVoltage(leftOutput + leftFeedforward); - m_rightGroup.setVoltage(rightOutput + rightFeedforward); + m_leftLeader.setVoltage(leftOutput + leftFeedforward); + m_rightLeader.setVoltage(rightOutput + rightFeedforward); } /** @@ -126,8 +123,6 @@ public void updateOdometry() { /** Resets robot odometry. */ public void resetOdometry(Pose2d pose) { - m_leftEncoder.reset(); - m_rightEncoder.reset(); m_drivetrainSimulator.setPose(pose); m_odometry.resetPosition( m_gyro.getRotation2d(), m_leftEncoder.getDistance(), m_rightEncoder.getDistance(), pose); @@ -145,8 +140,8 @@ public void simulationPeriodic() { // simulated encoder and gyro. We negate the right side so that positive // voltages make the right side move forward. m_drivetrainSimulator.setInputs( - m_leftGroup.get() * RobotController.getInputVoltage(), - m_rightGroup.get() * RobotController.getInputVoltage()); + m_leftLeader.get() * RobotController.getInputVoltage(), + m_rightLeader.get() * RobotController.getInputVoltage()); m_drivetrainSimulator.update(0.02); m_leftEncoderSim.setDistance(m_drivetrainSimulator.getLeftPositionMeters()); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/simpledifferentialdrivesimulation/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/simpledifferentialdrivesimulation/Robot.java index 3ad50a4d602..0227c3bfc4a 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/simpledifferentialdrivesimulation/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/simpledifferentialdrivesimulation/Robot.java @@ -4,7 +4,7 @@ package edu.wpi.first.wpilibj.examples.simpledifferentialdrivesimulation; -import edu.wpi.first.math.controller.RamseteController; +import edu.wpi.first.math.controller.LTVUnicycleController; import edu.wpi.first.math.filter.SlewRateLimiter; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; @@ -26,7 +26,7 @@ public class Robot extends TimedRobot { private final SlewRateLimiter m_rotLimiter = new SlewRateLimiter(3); private final Drivetrain m_drive = new Drivetrain(); - private final RamseteController m_ramsete = new RamseteController(); + private final LTVUnicycleController m_feedback = new LTVUnicycleController(0.020); private final Timer m_timer = new Timer(); private Trajectory m_trajectory; @@ -34,9 +34,9 @@ public class Robot extends TimedRobot { public void robotInit() { m_trajectory = TrajectoryGenerator.generateTrajectory( - new Pose2d(2, 2, new Rotation2d()), + new Pose2d(2, 2, Rotation2d.kZero), List.of(), - new Pose2d(6, 4, new Rotation2d()), + new Pose2d(6, 4, Rotation2d.kZero), new TrajectoryConfig(2, 2)); } @@ -55,7 +55,7 @@ public void autonomousInit() { public void autonomousPeriodic() { double elapsed = m_timer.get(); Trajectory.State reference = m_trajectory.sample(elapsed); - ChassisSpeeds speeds = m_ramsete.calculate(m_drive.getPose(), reference); + ChassisSpeeds speeds = m_feedback.calculate(m_drive.getPose(), reference); m_drive.drive(speeds.vxMetersPerSecond, speeds.omegaRadiansPerSecond); } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/solenoid/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/solenoid/Robot.java index d6ae0487114..0b791c5120b 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/solenoid/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/solenoid/Robot.java @@ -53,33 +53,17 @@ public void robotInit() { tab.add("Compressor", m_compressor); // Also publish some raw data - tab.addDouble( - "PH Pressure [PSI]", - () -> { - // Get the pressure (in PSI) from the analog sensor connected to the PH. - // This function is supported only on the PH! - // On a PCM, this function will return 0. - return m_compressor.getPressure(); - }); - tab.addDouble( - "Compressor Current", - () -> { - // Get compressor current draw. - return m_compressor.getCurrent(); - }); - tab.addBoolean( - "Compressor Active", - () -> { - // Get whether the compressor is active. - return m_compressor.isEnabled(); - }); - tab.addBoolean( - "Pressure Switch", - () -> { - // Get the digital pressure switch connected to the PCM/PH. - // The switch is open when the pressure is over ~120 PSI. - return m_compressor.getPressureSwitchValue(); - }); + // Get the pressure (in PSI) from the analog sensor connected to the PH. + // This function is supported only on the PH! + // On a PCM, this function will return 0. + tab.addDouble("PH Pressure [PSI]", m_compressor::getPressure); + // Get compressor current draw. + tab.addDouble("Compressor Current", m_compressor::getCurrent); + // Get whether the compressor is active. + tab.addBoolean("Compressor Active", m_compressor::isEnabled); + // Get the digital pressure switch connected to the PCM/PH. + // The switch is open when the pressure is over ~120 PSI. + tab.addBoolean("Pressure Switch", m_compressor::getPressureSwitchValue); } @SuppressWarnings("PMD.UnconditionalIfStatement") diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacearm/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacearm/Robot.java index 1b24a612501..b0314305170 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacearm/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacearm/Robot.java @@ -19,7 +19,6 @@ import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.TimedRobot; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; /** @@ -53,15 +52,16 @@ public class Robot extends TimedRobot { // States: [position, velocity], in radians and radians per second. // Inputs (what we can "put in"): [voltage], in volts. // Outputs (what we can measure): [position], in radians. - private final LinearSystem m_armPlant = + private final LinearSystem m_armPlant = LinearSystemId.createSingleJointedArmSystem(DCMotor.getNEO(2), kArmMOI, kArmGearing); // The observer fuses our encoder data and voltage inputs to reject noise. + @SuppressWarnings("unchecked") private final KalmanFilter m_observer = new KalmanFilter<>( Nat.N2(), Nat.N1(), - m_armPlant, + (LinearSystem) m_armPlant.slice(0), VecBuilder.fill(0.015, 0.17), // How accurate we // think our model is, in radians and radians/sec VecBuilder.fill(0.01), // How accurate we think our encoder position @@ -69,9 +69,10 @@ public class Robot extends TimedRobot { 0.020); // A LQR uses feedback to create voltage commands. + @SuppressWarnings("unchecked") private final LinearQuadraticRegulator m_controller = new LinearQuadraticRegulator<>( - m_armPlant, + (LinearSystem) m_armPlant.slice(0), VecBuilder.fill(Units.degreesToRadians(1.0), Units.degreesToRadians(10.0)), // qelms. // Position and velocity error tolerances, in radians and radians per second. Decrease // this @@ -83,16 +84,19 @@ public class Robot extends TimedRobot { // heavily penalize control effort, or make the controller less aggressive. 12 is a good // starting point because that is the (approximate) maximum voltage of a battery. 0.020); // Nominal time between loops. 0.020 for TimedRobot, but can be + // lower if using notifiers. // The state-space loop combines a controller, observer, feedforward and plant for easy control. + @SuppressWarnings("unchecked") private final LinearSystemLoop m_loop = - new LinearSystemLoop<>(m_armPlant, m_controller, m_observer, 12.0, 0.020); + new LinearSystemLoop<>( + (LinearSystem) m_armPlant.slice(0), m_controller, m_observer, 12.0, 0.020); // An encoder set up to measure arm position in radians. private final Encoder m_encoder = new Encoder(kEncoderAChannel, kEncoderBChannel); - private final MotorController m_motor = new PWMSparkMax(kMotorPort); + private final PWMSparkMax m_motor = new PWMSparkMax(kMotorPort); // A joystick to read the trigger from. private final Joystick m_joystick = new Joystick(kJoystickPort); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/Constants.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/Constants.java deleted file mode 100644 index 2177bd71459..00000000000 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/Constants.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.examples.statespacedifferentialdrivesimulation; - -import edu.wpi.first.math.kinematics.DifferentialDriveKinematics; -import edu.wpi.first.math.numbers.N2; -import edu.wpi.first.math.system.LinearSystem; -import edu.wpi.first.math.system.plant.DCMotor; -import edu.wpi.first.math.system.plant.LinearSystemId; - -/** - * The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean - * constants. This class should not be used for any other purpose. All constants should be declared - * globally (i.e. public static). Do not put anything functional in this class. - * - *

    It is advised to statically import this class (or one of its inner classes) wherever the - * constants are needed, to reduce verbosity. - */ -public final class Constants { - public static final class DriveConstants { - public static final int kLeftMotor1Port = 0; - public static final int kLeftMotor2Port = 1; - public static final int kRightMotor1Port = 2; - public static final int kRightMotor2Port = 3; - - public static final int[] kLeftEncoderPorts = new int[] {0, 1}; - public static final int[] kRightEncoderPorts = new int[] {2, 3}; - public static final boolean kLeftEncoderReversed = false; - public static final boolean kRightEncoderReversed = true; - - public static final double kTrackwidthMeters = 0.69; - public static final DifferentialDriveKinematics kDriveKinematics = - new DifferentialDriveKinematics(kTrackwidthMeters); - - public static final int kEncoderCPR = 1024; - public static final double kWheelDiameterMeters = 0.15; - public static final double kEncoderDistancePerPulse = - // Assumes the encoders are directly mounted on the wheel shafts - (kWheelDiameterMeters * Math.PI) / (double) kEncoderCPR; - - public static final boolean kGyroReversed = true; - - // These are example values only - DO NOT USE THESE FOR YOUR OWN ROBOT! - // These characterization values MUST be determined either experimentally or theoretically - // for *your* robot's drive. - // The Robot Characterization Toolsuite provides a convenient tool for obtaining these - // values for your robot. - public static final double ksVolts = 0.22; - public static final double kvVoltSecondsPerMeter = 1.98; - public static final double kaVoltSecondsSquaredPerMeter = 0.2; - - // These are example values only - DO NOT USE THESE FOR YOUR OWN ROBOT! - // These characterization values MUST be determined either experimentally or theoretically - // for *your* robot's drive. - // These two values are "angular" kV and kA - public static final double kvVoltSecondsPerRadian = 1.5; - public static final double kaVoltSecondsSquaredPerRadian = 0.3; - - public static final LinearSystem kDrivetrainPlant = - LinearSystemId.identifyDrivetrainSystem( - kvVoltSecondsPerMeter, - kaVoltSecondsSquaredPerMeter, - kvVoltSecondsPerRadian, - kaVoltSecondsSquaredPerRadian); - - // Example values only -- use what's on your physical robot! - public static final DCMotor kDriveGearbox = DCMotor.getCIM(2); - public static final double kDriveGearing = 8; - - // Example value only - as above, this must be tuned for your drive! - public static final double kPDriveVel = 8.5; - } - - public static final class OIConstants { - public static final int kDriverControllerPort = 0; - } - - public static final class AutoConstants { - public static final double kMaxSpeedMetersPerSecond = 3; - public static final double kMaxAccelerationMetersPerSecondSquared = 3; - - // Reasonable baseline values for a RAMSETE follower in units of meters and seconds - public static final double kRamseteB = 2; - public static final double kRamseteZeta = 0.7; - } -} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/Main.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/Main.java deleted file mode 100644 index bccc25aa5c3..00000000000 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/Main.java +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.examples.statespacedifferentialdrivesimulation; - -import edu.wpi.first.wpilibj.RobotBase; - -/** - * Do NOT add any static variables to this class, or any initialization at all. Unless you know what - * you are doing, do not modify this file except to change the parameter class to the startRobot - * call. - */ -public final class Main { - private Main() {} - - /** - * Main initialization function. Do not perform any initialization here. - * - *

    If you change your main robot class, change the parameter type. - */ - public static void main(String... args) { - RobotBase.startRobot(Robot::new); - } -} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/Robot.java deleted file mode 100644 index 8eca311821b..00000000000 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/Robot.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.examples.statespacedifferentialdrivesimulation; - -import edu.wpi.first.wpilibj.TimedRobot; -import edu.wpi.first.wpilibj.simulation.BatterySim; -import edu.wpi.first.wpilibj.simulation.RoboRioSim; -import edu.wpi.first.wpilibj2.command.CommandScheduler; - -/** - * This is a sample program to demonstrate the use of state-space classes in robot simulation. This - * robot has a flywheel, elevator, arm and differential drivetrain, and interfaces with the sim - * GUI's {@link edu.wpi.first.wpilibj.simulation.Field2d} class. - */ -public class Robot extends TimedRobot { - private RobotContainer m_robotContainer; - - /** - * This function is run when the robot is first started up and should be used for any - * initialization code. - */ - @Override - public void robotInit() { - // Instantiate our RobotContainer. This will perform all our button bindings, and put our - // autonomous chooser on the dashboard. - m_robotContainer = new RobotContainer(); - } - - @Override - public void simulationPeriodic() { - // Here we calculate the battery voltage based on drawn current. - // As our robot draws more power from the battery its voltage drops. - // The estimated voltage is highly dependent on the battery's internal - // resistance. - double drawCurrent = m_robotContainer.getRobotDrive().getDrawnCurrentAmps(); - double loadedVoltage = BatterySim.calculateDefaultBatteryLoadedVoltage(drawCurrent); - RoboRioSim.setVInVoltage(loadedVoltage); - } - - @Override - public void robotPeriodic() { - CommandScheduler.getInstance().run(); - } - - @Override - public void autonomousInit() { - m_robotContainer.getAutonomousCommand().schedule(); - } - - @Override - public void disabledInit() { - CommandScheduler.getInstance().cancelAll(); - m_robotContainer.zeroAllOutputs(); - } -} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/RobotContainer.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/RobotContainer.java deleted file mode 100644 index 6cb6e0238e7..00000000000 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/RobotContainer.java +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.examples.statespacedifferentialdrivesimulation; - -import edu.wpi.first.math.controller.PIDController; -import edu.wpi.first.math.controller.RamseteController; -import edu.wpi.first.math.controller.SimpleMotorFeedforward; -import edu.wpi.first.math.geometry.Pose2d; -import edu.wpi.first.math.geometry.Rotation2d; -import edu.wpi.first.math.geometry.Translation2d; -import edu.wpi.first.math.trajectory.Trajectory; -import edu.wpi.first.math.trajectory.TrajectoryConfig; -import edu.wpi.first.math.trajectory.TrajectoryGenerator; -import edu.wpi.first.math.trajectory.constraint.DifferentialDriveVoltageConstraint; -import edu.wpi.first.wpilibj.XboxController; -import edu.wpi.first.wpilibj.XboxController.Button; -import edu.wpi.first.wpilibj.examples.statespacedifferentialdrivesimulation.subsystems.DriveSubsystem; -import edu.wpi.first.wpilibj2.command.Command; -import edu.wpi.first.wpilibj2.command.InstantCommand; -import edu.wpi.first.wpilibj2.command.RamseteCommand; -import edu.wpi.first.wpilibj2.command.RunCommand; -import edu.wpi.first.wpilibj2.command.button.JoystickButton; -import java.util.List; - -/** - * This class is where the bulk of the robot should be declared. Since Command-based is a - * "declarative" paradigm, very little robot logic should actually be handled in the Robot periodic - * methods (other than the scheduler calls). Instead, the structure of the robot (including - * subsystems, commands, and button mappings) should be declared here. - */ -public class RobotContainer { - // The robot's subsystems - private final DriveSubsystem m_robotDrive = new DriveSubsystem(); - - // The driver's controller - XboxController m_driverController = - new XboxController(Constants.OIConstants.kDriverControllerPort); - - /** The container for the robot. Contains subsystems, OI devices, and commands. */ - public RobotContainer() { - // Configure the button bindings - configureButtonBindings(); - - // Configure default commands - // Set the default drive command to split-stick arcade drive - m_robotDrive.setDefaultCommand( - // A split-stick arcade command, with forward/backward controlled by the left - // hand, and turning controlled by the right. - // If you are using the keyboard as a joystick, it is recommended that you go - // to the following link to read about editing the keyboard settings. - // https://docs.wpilib.org/en/stable/docs/software/wpilib-tools/robot-simulation/simulation-gui.html#using-the-keyboard-as-a-joystick - new RunCommand( - () -> - m_robotDrive.arcadeDrive( - -m_driverController.getLeftY(), -m_driverController.getRightX()), - m_robotDrive)); - } - - /** - * Use this method to define your button->command mappings. Buttons can be created by - * instantiating a {@link edu.wpi.first.wpilibj.GenericHID} or one of its subclasses ({@link - * edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then calling passing it to a - * {@link JoystickButton}. - */ - private void configureButtonBindings() { - // Drive at half speed when the right bumper is held - new JoystickButton(m_driverController, Button.kRightBumper.value) - .onTrue(new InstantCommand(() -> m_robotDrive.setMaxOutput(0.5))) - .onFalse(new InstantCommand(() -> m_robotDrive.setMaxOutput(1))); - } - - public DriveSubsystem getRobotDrive() { - return m_robotDrive; - } - - /** Zeros the outputs of all subsystems. */ - public void zeroAllOutputs() { - m_robotDrive.tankDriveVolts(0, 0); - } - - /** - * Use this to pass the autonomous command to the main {@link Robot} class. - * - * @return the command to run in autonomous - */ - public Command getAutonomousCommand() { - // Create a voltage constraint to ensure we don't accelerate too fast - var autoVoltageConstraint = - new DifferentialDriveVoltageConstraint( - new SimpleMotorFeedforward( - Constants.DriveConstants.ksVolts, - Constants.DriveConstants.kvVoltSecondsPerMeter, - Constants.DriveConstants.kaVoltSecondsSquaredPerMeter), - Constants.DriveConstants.kDriveKinematics, - 7); - - // Create config for trajectory - TrajectoryConfig config = - new TrajectoryConfig( - Constants.AutoConstants.kMaxSpeedMetersPerSecond, - Constants.AutoConstants.kMaxAccelerationMetersPerSecondSquared) - // Add kinematics to ensure max speed is actually obeyed - .setKinematics(Constants.DriveConstants.kDriveKinematics) - // Apply the voltage constraint - .addConstraint(autoVoltageConstraint); - - // An example trajectory to follow. All units in meters. - Trajectory exampleTrajectory = - TrajectoryGenerator.generateTrajectory( - // Start at (1, 2) facing the +X direction - new Pose2d(1, 2, new Rotation2d(0)), - // Pass through these two interior waypoints, making an 's' curve path - List.of(new Translation2d(2, 3), new Translation2d(3, 1)), - // End 3 meters straight ahead of where we started, facing forward - new Pose2d(4, 2, new Rotation2d(0)), - // Pass config - config); - - RamseteCommand ramseteCommand = - new RamseteCommand( - exampleTrajectory, - m_robotDrive::getPose, - new RamseteController( - Constants.AutoConstants.kRamseteB, Constants.AutoConstants.kRamseteZeta), - new SimpleMotorFeedforward( - Constants.DriveConstants.ksVolts, - Constants.DriveConstants.kvVoltSecondsPerMeter, - Constants.DriveConstants.kaVoltSecondsSquaredPerMeter), - Constants.DriveConstants.kDriveKinematics, - m_robotDrive::getWheelSpeeds, - new PIDController(Constants.DriveConstants.kPDriveVel, 0, 0), - new PIDController(Constants.DriveConstants.kPDriveVel, 0, 0), - // RamseteCommand passes volts to the callback - m_robotDrive::tankDriveVolts, - m_robotDrive); - - // Reset odometry to starting pose of trajectory. - m_robotDrive.resetOdometry(exampleTrajectory.getInitialPose()); - - // Run path following command, then stop at the end. - return ramseteCommand.andThen(() -> m_robotDrive.tankDriveVolts(0, 0)); - } -} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/subsystems/DriveSubsystem.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/subsystems/DriveSubsystem.java deleted file mode 100644 index 406178a8abd..00000000000 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespacedifferentialdrivesimulation/subsystems/DriveSubsystem.java +++ /dev/null @@ -1,265 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.wpilibj.examples.statespacedifferentialdrivesimulation.subsystems; - -import edu.wpi.first.math.VecBuilder; -import edu.wpi.first.math.geometry.Pose2d; -import edu.wpi.first.math.geometry.Rotation2d; -import edu.wpi.first.math.kinematics.DifferentialDriveOdometry; -import edu.wpi.first.math.kinematics.DifferentialDriveWheelSpeeds; -import edu.wpi.first.wpilibj.ADXRS450_Gyro; -import edu.wpi.first.wpilibj.Encoder; -import edu.wpi.first.wpilibj.RobotBase; -import edu.wpi.first.wpilibj.RobotController; -import edu.wpi.first.wpilibj.drive.DifferentialDrive; -import edu.wpi.first.wpilibj.examples.statespacedifferentialdrivesimulation.Constants.DriveConstants; -import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup; -import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; -import edu.wpi.first.wpilibj.simulation.ADXRS450_GyroSim; -import edu.wpi.first.wpilibj.simulation.DifferentialDrivetrainSim; -import edu.wpi.first.wpilibj.simulation.EncoderSim; -import edu.wpi.first.wpilibj.smartdashboard.Field2d; -import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; -import edu.wpi.first.wpilibj2.command.SubsystemBase; - -public class DriveSubsystem extends SubsystemBase { - // The motors on the left side of the drive. - private final MotorControllerGroup m_leftMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kLeftMotor1Port), - new PWMSparkMax(DriveConstants.kLeftMotor2Port)); - - // The motors on the right side of the drive. - private final MotorControllerGroup m_rightMotors = - new MotorControllerGroup( - new PWMSparkMax(DriveConstants.kRightMotor1Port), - new PWMSparkMax(DriveConstants.kRightMotor2Port)); - - // The robot's drive - private final DifferentialDrive m_drive = new DifferentialDrive(m_leftMotors, m_rightMotors); - - // The left-side drive encoder - private final Encoder m_leftEncoder = - new Encoder( - DriveConstants.kLeftEncoderPorts[0], - DriveConstants.kLeftEncoderPorts[1], - DriveConstants.kLeftEncoderReversed); - - // The right-side drive encoder - private final Encoder m_rightEncoder = - new Encoder( - DriveConstants.kRightEncoderPorts[0], - DriveConstants.kRightEncoderPorts[1], - DriveConstants.kRightEncoderReversed); - - // The gyro sensor - private final ADXRS450_Gyro m_gyro = new ADXRS450_Gyro(); - - // Odometry class for tracking robot pose - private final DifferentialDriveOdometry m_odometry; - - // These classes help us simulate our drivetrain - public DifferentialDrivetrainSim m_drivetrainSimulator; - private final EncoderSim m_leftEncoderSim; - private final EncoderSim m_rightEncoderSim; - // The Field2d class shows the field in the sim GUI - private final Field2d m_fieldSim; - private final ADXRS450_GyroSim m_gyroSim; - - /** Creates a new DriveSubsystem. */ - public DriveSubsystem() { - // We need to invert one side of the drivetrain so that positive voltages - // result in both sides moving forward. Depending on how your robot's - // gearbox is constructed, you might have to invert the left side instead. - m_rightMotors.setInverted(true); - - // Sets the distance per pulse for the encoders - m_leftEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); - m_rightEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); - - resetEncoders(); - m_odometry = - new DifferentialDriveOdometry( - Rotation2d.fromDegrees(getHeading()), - m_leftEncoder.getDistance(), - m_rightEncoder.getDistance()); - - if (RobotBase.isSimulation()) { // If our robot is simulated - // This class simulates our drivetrain's motion around the field. - m_drivetrainSimulator = - new DifferentialDrivetrainSim( - DriveConstants.kDrivetrainPlant, - DriveConstants.kDriveGearbox, - DriveConstants.kDriveGearing, - DriveConstants.kTrackwidthMeters, - DriveConstants.kWheelDiameterMeters / 2.0, - VecBuilder.fill(0, 0, 0.0001, 0.1, 0.1, 0.005, 0.005)); - - // The encoder and gyro angle sims let us set simulated sensor readings - m_leftEncoderSim = new EncoderSim(m_leftEncoder); - m_rightEncoderSim = new EncoderSim(m_rightEncoder); - m_gyroSim = new ADXRS450_GyroSim(m_gyro); - - // the Field2d class lets us visualize our robot in the simulation GUI. - m_fieldSim = new Field2d(); - SmartDashboard.putData("Field", m_fieldSim); - } else { - m_leftEncoderSim = null; - m_rightEncoderSim = null; - m_gyroSim = null; - - m_fieldSim = null; - } - } - - @Override - public void periodic() { - // Update the odometry in the periodic block - m_odometry.update( - Rotation2d.fromDegrees(getHeading()), - m_leftEncoder.getDistance(), - m_rightEncoder.getDistance()); - m_fieldSim.setRobotPose(getPose()); - } - - @Override - public void simulationPeriodic() { - // To update our simulation, we set motor voltage inputs, update the simulation, - // and write the simulated positions and velocities to our simulated encoder and gyro. - // We negate the right side so that positive voltages make the right side - // move forward. - m_drivetrainSimulator.setInputs( - m_leftMotors.get() * RobotController.getBatteryVoltage(), - m_rightMotors.get() * RobotController.getBatteryVoltage()); - m_drivetrainSimulator.update(0.020); - - m_leftEncoderSim.setDistance(m_drivetrainSimulator.getLeftPositionMeters()); - m_leftEncoderSim.setRate(m_drivetrainSimulator.getLeftVelocityMetersPerSecond()); - m_rightEncoderSim.setDistance(m_drivetrainSimulator.getRightPositionMeters()); - m_rightEncoderSim.setRate(m_drivetrainSimulator.getRightVelocityMetersPerSecond()); - m_gyroSim.setAngle(-m_drivetrainSimulator.getHeading().getDegrees()); - } - - /** - * Returns the current being drawn by the drivetrain. This works in SIMULATION ONLY! If you want - * it to work elsewhere, use the code in {@link DifferentialDrivetrainSim#getCurrentDrawAmps()} - * - * @return The drawn current in Amps. - */ - public double getDrawnCurrentAmps() { - return m_drivetrainSimulator.getCurrentDrawAmps(); - } - - /** - * Returns the currently-estimated pose of the robot. - * - * @return The pose. - */ - public Pose2d getPose() { - return m_odometry.getPoseMeters(); - } - - /** - * Returns the current wheel speeds of the robot. - * - * @return The current wheel speeds. - */ - public DifferentialDriveWheelSpeeds getWheelSpeeds() { - return new DifferentialDriveWheelSpeeds(m_leftEncoder.getRate(), m_rightEncoder.getRate()); - } - - /** - * Resets the odometry to the specified pose. - * - * @param pose The pose to which to set the odometry. - */ - public void resetOdometry(Pose2d pose) { - resetEncoders(); - m_drivetrainSimulator.setPose(pose); - m_odometry.resetPosition( - Rotation2d.fromDegrees(getHeading()), - m_leftEncoder.getDistance(), - m_rightEncoder.getDistance(), - pose); - } - - /** - * Drives the robot using arcade controls. - * - * @param fwd the commanded forward movement - * @param rot the commanded rotation - */ - public void arcadeDrive(double fwd, double rot) { - m_drive.arcadeDrive(fwd, rot); - } - - /** - * Controls the left and right sides of the drive directly with voltages. - * - * @param leftVolts the commanded left output - * @param rightVolts the commanded right output - */ - public void tankDriveVolts(double leftVolts, double rightVolts) { - m_leftMotors.setVoltage(leftVolts); - m_rightMotors.setVoltage(rightVolts); - m_drive.feed(); - } - - /** Resets the drive encoders to currently read a position of 0. */ - public void resetEncoders() { - m_leftEncoder.reset(); - m_rightEncoder.reset(); - } - - /** - * Gets the average distance of the two encoders. - * - * @return the average of the two encoder readings - */ - public double getAverageEncoderDistance() { - return (m_leftEncoder.getDistance() + m_rightEncoder.getDistance()) / 2.0; - } - - /** - * Gets the left drive encoder. - * - * @return the left drive encoder - */ - public Encoder getLeftEncoder() { - return m_leftEncoder; - } - - /** - * Gets the right drive encoder. - * - * @return the right drive encoder - */ - public Encoder getRightEncoder() { - return m_rightEncoder; - } - - /** - * Sets the max output of the drive. Useful for scaling the drive to drive more slowly. - * - * @param maxOutput the maximum output to which the drive will be constrained - */ - public void setMaxOutput(double maxOutput) { - m_drive.setMaxOutput(maxOutput); - } - - /** Zeroes the heading of the robot. */ - public void zeroHeading() { - m_gyro.reset(); - } - - /** - * Returns the heading of the robot. - * - * @return the robot's heading in degrees, from -180 to 180 - */ - public double getHeading() { - return Math.IEEEremainder(m_gyro.getAngle(), 360) * (DriveConstants.kGyroReversed ? -1.0 : 1.0); - } -} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespaceelevator/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespaceelevator/Robot.java index cb196c814cd..0e9c045c9ca 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespaceelevator/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespaceelevator/Robot.java @@ -19,7 +19,6 @@ import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.TimedRobot; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; /** @@ -58,16 +57,17 @@ public class Robot extends TimedRobot { This elevator is driven by two NEO motors. */ - private final LinearSystem m_elevatorPlant = + private final LinearSystem m_elevatorPlant = LinearSystemId.createElevatorSystem( DCMotor.getNEO(2), kCarriageMass, kDrumRadius, kElevatorGearing); // The observer fuses our encoder data and voltage inputs to reject noise. + @SuppressWarnings("unchecked") private final KalmanFilter m_observer = new KalmanFilter<>( Nat.N2(), Nat.N1(), - m_elevatorPlant, + (LinearSystem) m_elevatorPlant.slice(0), VecBuilder.fill(Units.inchesToMeters(2), Units.inchesToMeters(40)), // How accurate we // think our model is, in meters and meters/second. VecBuilder.fill(0.001), // How accurate we think our encoder position @@ -75,9 +75,10 @@ public class Robot extends TimedRobot { 0.020); // A LQR uses feedback to create voltage commands. + @SuppressWarnings("unchecked") private final LinearQuadraticRegulator m_controller = new LinearQuadraticRegulator<>( - m_elevatorPlant, + (LinearSystem) m_elevatorPlant.slice(0), VecBuilder.fill(Units.inchesToMeters(1.0), Units.inchesToMeters(10.0)), // qelms. Position // and velocity error tolerances, in meters and meters per second. Decrease this to more // heavily penalize state excursion, or make the controller behave more aggressively. In @@ -87,16 +88,23 @@ public class Robot extends TimedRobot { // heavily penalize control effort, or make the controller less aggressive. 12 is a good // starting point because that is the (approximate) maximum voltage of a battery. 0.020); // Nominal time between loops. 0.020 for TimedRobot, but can be + // lower if using notifiers. // The state-space loop combines a controller, observer, feedforward and plant for easy control. + @SuppressWarnings("unchecked") private final LinearSystemLoop m_loop = - new LinearSystemLoop<>(m_elevatorPlant, m_controller, m_observer, 12.0, 0.020); + new LinearSystemLoop<>( + (LinearSystem) m_elevatorPlant.slice(0), + m_controller, + m_observer, + 12.0, + 0.020); // An encoder set up to measure elevator height in meters. private final Encoder m_encoder = new Encoder(kEncoderAChannel, kEncoderBChannel); - private final MotorController m_motor = new PWMSparkMax(kMotorPort); + private final PWMSparkMax m_motor = new PWMSparkMax(kMotorPort); // A joystick to read the trigger from. private final Joystick m_joystick = new Joystick(kJoystickPort); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespaceflywheel/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespaceflywheel/Robot.java index 06e8d29bb66..94566eac348 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespaceflywheel/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespaceflywheel/Robot.java @@ -17,7 +17,6 @@ import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.TimedRobot; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; /** @@ -77,7 +76,7 @@ public class Robot extends TimedRobot { // An encoder set up to measure flywheel velocity in radians per second. private final Encoder m_encoder = new Encoder(kEncoderAChannel, kEncoderBChannel); - private final MotorController m_motor = new PWMSparkMax(kMotorPort); + private final PWMSparkMax m_motor = new PWMSparkMax(kMotorPort); // A joystick to read the trigger from. private final Joystick m_joystick = new Joystick(kJoystickPort); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespaceflywheelsysid/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespaceflywheelsysid/Robot.java index 26ee8f702ac..3a073fe9d5e 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespaceflywheelsysid/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/statespaceflywheelsysid/Robot.java @@ -16,7 +16,6 @@ import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.TimedRobot; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; /** @@ -72,7 +71,7 @@ public class Robot extends TimedRobot { // An encoder set up to measure flywheel velocity in radians per second. private final Encoder m_encoder = new Encoder(kEncoderAChannel, kEncoderBChannel); - private final MotorController m_motor = new PWMSparkMax(kMotorPort); + private final PWMSparkMax m_motor = new PWMSparkMax(kMotorPort); // A joystick to read the trigger from. private final Joystick m_joystick = new Joystick(kJoystickPort); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervebot/SwerveModule.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervebot/SwerveModule.java index 65089f973da..c168860c99b 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervebot/SwerveModule.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervebot/SwerveModule.java @@ -12,7 +12,6 @@ import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.math.trajectory.TrapezoidProfile; import edu.wpi.first.wpilibj.Encoder; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; public class SwerveModule { @@ -23,8 +22,8 @@ public class SwerveModule { private static final double kModuleMaxAngularAcceleration = 2 * Math.PI; // radians per second squared - private final MotorController m_driveMotor; - private final MotorController m_turningMotor; + private final PWMSparkMax m_driveMotor; + private final PWMSparkMax m_turningMotor; private final Encoder m_driveEncoder; private final Encoder m_turningEncoder; diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervecontrollercommand/RobotContainer.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervecontrollercommand/RobotContainer.java index cf0ff8c5efe..f2641890a6d 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervecontrollercommand/RobotContainer.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervecontrollercommand/RobotContainer.java @@ -19,6 +19,8 @@ import edu.wpi.first.wpilibj.examples.swervecontrollercommand.Constants.OIConstants; import edu.wpi.first.wpilibj.examples.swervecontrollercommand.subsystems.DriveSubsystem; import edu.wpi.first.wpilibj2.command.Command; +import edu.wpi.first.wpilibj2.command.Commands; +import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.RunCommand; import edu.wpi.first.wpilibj2.command.SwerveControllerCommand; import edu.wpi.first.wpilibj2.command.button.JoystickButton; @@ -82,15 +84,15 @@ public Command getAutonomousCommand() { // Add kinematics to ensure max speed is actually obeyed .setKinematics(DriveConstants.kDriveKinematics); - // An example trajectory to follow. All units in meters. + // An example trajectory to follow. All units in meters. Trajectory exampleTrajectory = TrajectoryGenerator.generateTrajectory( // Start at the origin facing the +X direction - new Pose2d(0, 0, new Rotation2d(0)), + Pose2d.kZero, // Pass through these two interior waypoints, making an 's' curve path List.of(new Translation2d(1, 1), new Translation2d(2, -1)), // End 3 meters straight ahead of where we started, facing forward - new Pose2d(3, 0, new Rotation2d(0)), + new Pose2d(3, 0, Rotation2d.kZero), config); var thetaController = @@ -111,10 +113,11 @@ public Command getAutonomousCommand() { m_robotDrive::setModuleStates, m_robotDrive); - // Reset odometry to the starting pose of the trajectory. - m_robotDrive.resetOdometry(exampleTrajectory.getInitialPose()); - - // Run path following command, then stop at the end. - return swerveControllerCommand.andThen(() -> m_robotDrive.drive(0, 0, 0, false)); + // Reset odometry to the initial pose of the trajectory, run path following + // command, then stop at the end. + return Commands.sequence( + new InstantCommand(() -> m_robotDrive.resetOdometry(exampleTrajectory.getInitialPose())), + swerveControllerCommand, + new InstantCommand(() -> m_robotDrive.drive(0, 0, 0, false))); } } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervedriveposeestimator/Drivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervedriveposeestimator/Drivetrain.java index 6eb80e0fe50..9d68c0e3c34 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervedriveposeestimator/Drivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervedriveposeestimator/Drivetrain.java @@ -48,7 +48,7 @@ public class Drivetrain { m_backLeft.getPosition(), m_backRight.getPosition() }, - new Pose2d(), + Pose2d.kZero, VecBuilder.fill(0.05, 0.05, Units.degreesToRadians(5)), VecBuilder.fill(0.5, 0.5, Units.degreesToRadians(30))); diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervedriveposeestimator/SwerveModule.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervedriveposeestimator/SwerveModule.java index 938b6c8f3c7..8ee8f4b07b8 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervedriveposeestimator/SwerveModule.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervedriveposeestimator/SwerveModule.java @@ -12,7 +12,6 @@ import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.math.trajectory.TrapezoidProfile; import edu.wpi.first.wpilibj.Encoder; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; public class SwerveModule { @@ -23,8 +22,8 @@ public class SwerveModule { private static final double kModuleMaxAngularAcceleration = 2 * Math.PI; // radians per second squared - private final MotorController m_driveMotor; - private final MotorController m_turningMotor; + private final PWMSparkMax m_driveMotor; + private final PWMSparkMax m_turningMotor; private final Encoder m_driveEncoder; private final Encoder m_turningEncoder; diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/Constants.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/Constants.java new file mode 100644 index 00000000000..f7731317dec --- /dev/null +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/Constants.java @@ -0,0 +1,84 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.wpilibj.examples.sysid; + +import edu.wpi.first.math.util.Units; + +/** + * The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean + * constants. This class should not be used for any other purpose. All constants should be declared + * globally (i.e. public static). Do not put anything functional in this class. + * + *

    It is advised to statically import this class (or one of its inner classes) wherever the + * constants are needed, to reduce verbosity. + */ +public final class Constants { + public static final class DriveConstants { + public static final int kLeftMotor1Port = 0; + public static final int kLeftMotor2Port = 1; + public static final int kRightMotor1Port = 2; + public static final int kRightMotor2Port = 3; + + public static final int[] kLeftEncoderPorts = {0, 1}; + public static final int[] kRightEncoderPorts = {2, 3}; + public static final boolean kLeftEncoderReversed = false; + public static final boolean kRightEncoderReversed = true; + + public static final int kEncoderCPR = 1024; + public static final double kWheelDiameterMeters = Units.inchesToMeters(6); + public static final double kEncoderDistancePerPulse = + // Assumes the encoders are directly mounted on the wheel shafts + (kWheelDiameterMeters * Math.PI) / (double) kEncoderCPR; + } + + public static final class ShooterConstants { + public static final int[] kEncoderPorts = {4, 5}; + public static final boolean kEncoderReversed = false; + public static final int kEncoderCPR = 1024; + public static final double kEncoderDistancePerPulse = + // Distance units will be rotations + 1.0 / (double) kEncoderCPR; + + public static final int kShooterMotorPort = 4; + public static final int kFeederMotorPort = 5; + + public static final double kShooterFreeRPS = 5300; + public static final double kShooterTargetRPS = 4000; + public static final double kShooterToleranceRPS = 50; + + // These are not real PID gains, and will have to be tuned for your specific robot. + public static final double kP = 1; + + // On a real robot the feedforward constants should be empirically determined; these are + // reasonable guesses. + public static final double kSVolts = 0.05; + public static final double kVVoltSecondsPerRotation = + // Should have value 12V at free speed... + 12.0 / kShooterFreeRPS; + public static final double kAVoltSecondsSquaredPerRotation = 0; + + public static final double kFeederSpeed = 0.5; + } + + public static final class IntakeConstants { + public static final int kMotorPort = 6; + public static final int[] kSolenoidPorts = {2, 3}; + } + + public static final class StorageConstants { + public static final int kMotorPort = 7; + public static final int kBallSensorPort = 6; + } + + public static final class AutoConstants { + public static final double kTimeoutSeconds = 3; + public static final double kDriveDistanceMeters = 2; + public static final double kDriveSpeed = 0.5; + } + + public static final class OIConstants { + public static final int kDriverControllerPort = 0; + } +} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/Main.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/Main.java similarity index 93% rename from wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/Main.java rename to wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/Main.java index 462edd450ed..1fdd4b7374c 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/Main.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/Main.java @@ -2,7 +2,7 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -package edu.wpi.first.wpilibj.examples.ramsetecommand; +package edu.wpi.first.wpilibj.examples.sysid; import edu.wpi.first.wpilibj.RobotBase; diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/Robot.java similarity index 73% rename from wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/Robot.java rename to wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/Robot.java index b072443cee3..0b0f1428913 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ramsetecommand/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/Robot.java @@ -2,7 +2,7 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -package edu.wpi.first.wpilibj.examples.ramsetecommand; +package edu.wpi.first.wpilibj.examples.sysid; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj2.command.Command; @@ -17,7 +17,7 @@ public class Robot extends TimedRobot { private Command m_autonomousCommand; - private RobotContainer m_robotContainer; + private final SysIdRoutineBot m_robot = new SysIdRoutineBot(); /** * This function is run when the robot is first started up and should be used for any @@ -25,14 +25,13 @@ public class Robot extends TimedRobot { */ @Override public void robotInit() { - // Instantiate our RobotContainer. This will perform all our button bindings, and put our - // autonomous chooser on the dashboard. - m_robotContainer = new RobotContainer(); + // Configure default commands and condition bindings on robot startup + m_robot.configureBindings(); } /** - * This function is called every 20 ms, no matter the mode. Use this for items like diagnostics - * that you want ran during disabled, autonomous, teleoperated and test. + * This function is called every robot packet, no matter the mode. Use this for items like + * diagnostics that you want ran during disabled, autonomous, teleoperated and test. * *

    This runs after the mode specific periodic functions, but before LiveWindow and * SmartDashboard integrated updating. @@ -53,19 +52,10 @@ public void disabledInit() {} @Override public void disabledPeriodic() {} - /** This autonomous runs the autonomous command selected by your {@link RobotContainer} class. */ @Override public void autonomousInit() { - m_autonomousCommand = m_robotContainer.getAutonomousCommand(); + m_autonomousCommand = m_robot.getAutonomousCommand(); - /* - * String autoSelected = SmartDashboard.getString("Auto Selector", - * "Default"); switch(autoSelected) { case "My Auto": autonomousCommand - * = new MyAutoCommand(); break; case "Default Auto": default: - * autonomousCommand = new ExampleCommand(); break; } - */ - - // schedule the autonomous command (example) if (m_autonomousCommand != null) { m_autonomousCommand.schedule(); } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/SysIdRoutineBot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/SysIdRoutineBot.java new file mode 100644 index 00000000000..93496fdcc37 --- /dev/null +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/SysIdRoutineBot.java @@ -0,0 +1,95 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.wpilibj.examples.sysid; + +import edu.wpi.first.wpilibj.examples.sysid.Constants.OIConstants; +import edu.wpi.first.wpilibj.examples.sysid.subsystems.Drive; +import edu.wpi.first.wpilibj.examples.sysid.subsystems.Shooter; +import edu.wpi.first.wpilibj2.command.Command; +import edu.wpi.first.wpilibj2.command.button.CommandXboxController; +import edu.wpi.first.wpilibj2.command.button.Trigger; +import edu.wpi.first.wpilibj2.command.sysid.SysIdRoutine; + +/** + * This class is where the bulk of the robot should be declared. Since Command-based is a + * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} + * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including + * subsystems, commands, and button mappings) should be declared here. + */ +public class SysIdRoutineBot { + // The robot's subsystems + private final Drive m_drive = new Drive(); + private final Shooter m_shooter = new Shooter(); + + // The driver's controller + CommandXboxController m_driverController = + new CommandXboxController(OIConstants.kDriverControllerPort); + + /** + * Use this method to define bindings between conditions and commands. These are useful for + * automating robot behaviors based on button and sensor input. + * + *

    Should be called during {@link Robot#robotInit()}. + * + *

    Event binding methods are available on the {@link Trigger} class. + */ + public void configureBindings() { + // Control the drive with split-stick arcade controls + m_drive.setDefaultCommand( + m_drive.arcadeDriveCommand( + () -> -m_driverController.getLeftY(), () -> -m_driverController.getRightX())); + + // Bind full set of SysId routine tests to buttons; a complete routine should run each of these + // once. + // Using bumpers as a modifier and combining it with the buttons so that we can have both sets + // of bindings at once + m_driverController + .a() + .and(m_driverController.rightBumper()) + .whileTrue(m_drive.sysIdQuasistatic(SysIdRoutine.Direction.kForward)); + m_driverController + .b() + .and(m_driverController.rightBumper()) + .whileTrue(m_drive.sysIdQuasistatic(SysIdRoutine.Direction.kReverse)); + m_driverController + .x() + .and(m_driverController.rightBumper()) + .whileTrue(m_drive.sysIdDynamic(SysIdRoutine.Direction.kForward)); + m_driverController + .y() + .and(m_driverController.rightBumper()) + .whileTrue(m_drive.sysIdDynamic(SysIdRoutine.Direction.kReverse)); + + // Control the shooter wheel with the left trigger + m_shooter.setDefaultCommand(m_shooter.runShooter(m_driverController::getLeftTriggerAxis)); + + m_driverController + .a() + .and(m_driverController.leftBumper()) + .whileTrue(m_drive.sysIdQuasistatic(SysIdRoutine.Direction.kForward)); + m_driverController + .b() + .and(m_driverController.leftBumper()) + .whileTrue(m_drive.sysIdQuasistatic(SysIdRoutine.Direction.kReverse)); + m_driverController + .x() + .and(m_driverController.leftBumper()) + .whileTrue(m_drive.sysIdDynamic(SysIdRoutine.Direction.kForward)); + m_driverController + .y() + .and(m_driverController.leftBumper()) + .whileTrue(m_drive.sysIdDynamic(SysIdRoutine.Direction.kReverse)); + } + + /** + * Use this to define the command that runs during autonomous. + * + *

    Scheduled during {@link Robot#autonomousInit()}. + */ + public Command getAutonomousCommand() { + // Do nothing + return m_drive.run(() -> {}); + } +} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/subsystems/Drive.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/subsystems/Drive.java new file mode 100644 index 00000000000..9cad2950c0d --- /dev/null +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/subsystems/Drive.java @@ -0,0 +1,142 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.wpilibj.examples.sysid.subsystems; + +import static edu.wpi.first.units.MutableMeasure.mutable; +import static edu.wpi.first.units.Units.Meters; +import static edu.wpi.first.units.Units.MetersPerSecond; +import static edu.wpi.first.units.Units.Volts; + +import edu.wpi.first.units.Distance; +import edu.wpi.first.units.Measure; +import edu.wpi.first.units.MutableMeasure; +import edu.wpi.first.units.Velocity; +import edu.wpi.first.units.Voltage; +import edu.wpi.first.wpilibj.Encoder; +import edu.wpi.first.wpilibj.RobotController; +import edu.wpi.first.wpilibj.drive.DifferentialDrive; +import edu.wpi.first.wpilibj.examples.rapidreactcommandbot.Constants.DriveConstants; +import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; +import edu.wpi.first.wpilibj2.command.Command; +import edu.wpi.first.wpilibj2.command.SubsystemBase; +import edu.wpi.first.wpilibj2.command.sysid.SysIdRoutine; +import java.util.function.DoubleSupplier; + +public class Drive extends SubsystemBase { + // The motors on the left side of the drive. + private final PWMSparkMax m_leftMotor = new PWMSparkMax(DriveConstants.kLeftMotor1Port); + + // The motors on the right side of the drive. + private final PWMSparkMax m_rightMotor = new PWMSparkMax(DriveConstants.kRightMotor1Port); + + // The robot's drive + private final DifferentialDrive m_drive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); + + // The left-side drive encoder + private final Encoder m_leftEncoder = + new Encoder( + DriveConstants.kLeftEncoderPorts[0], + DriveConstants.kLeftEncoderPorts[1], + DriveConstants.kLeftEncoderReversed); + + // The right-side drive encoder + private final Encoder m_rightEncoder = + new Encoder( + DriveConstants.kRightEncoderPorts[0], + DriveConstants.kRightEncoderPorts[1], + DriveConstants.kRightEncoderReversed); + + // Mutable holder for unit-safe voltage values, persisted to avoid reallocation. + private final MutableMeasure m_appliedVoltage = mutable(Volts.of(0)); + // Mutable holder for unit-safe linear distance values, persisted to avoid reallocation. + private final MutableMeasure m_distance = mutable(Meters.of(0)); + // Mutable holder for unit-safe linear velocity values, persisted to avoid reallocation. + private final MutableMeasure> m_velocity = mutable(MetersPerSecond.of(0)); + + // Create a new SysId routine for characterizing the drive. + private final SysIdRoutine m_sysIdRoutine = + new SysIdRoutine( + // Empty config defaults to 1 volt/second ramp rate and 7 volt step voltage. + new SysIdRoutine.Config(), + new SysIdRoutine.Mechanism( + // Tell SysId how to plumb the driving voltage to the motors. + (Measure volts) -> { + m_leftMotor.setVoltage(volts.in(Volts)); + m_rightMotor.setVoltage(volts.in(Volts)); + }, + // Tell SysId how to record a frame of data for each motor on the mechanism being + // characterized. + log -> { + // Record a frame for the left motors. Since these share an encoder, we consider + // the entire group to be one motor. + log.motor("drive-left") + .voltage( + m_appliedVoltage.mut_replace( + m_leftMotor.get() * RobotController.getBatteryVoltage(), Volts)) + .linearPosition(m_distance.mut_replace(m_leftEncoder.getDistance(), Meters)) + .linearVelocity( + m_velocity.mut_replace(m_leftEncoder.getRate(), MetersPerSecond)); + // Record a frame for the right motors. Since these share an encoder, we consider + // the entire group to be one motor. + log.motor("drive-right") + .voltage( + m_appliedVoltage.mut_replace( + m_rightMotor.get() * RobotController.getBatteryVoltage(), Volts)) + .linearPosition(m_distance.mut_replace(m_rightEncoder.getDistance(), Meters)) + .linearVelocity( + m_velocity.mut_replace(m_rightEncoder.getRate(), MetersPerSecond)); + }, + // Tell SysId to make generated commands require this subsystem, suffix test state in + // WPILog with this subsystem's name ("drive") + this)); + + /** Creates a new Drive subsystem. */ + public Drive() { + // Add the second motors on each side of the drivetrain + m_leftMotor.addFollower(new PWMSparkMax(DriveConstants.kLeftMotor2Port)); + m_rightMotor.addFollower(new PWMSparkMax(DriveConstants.kRightMotor2Port)); + + // We need to invert one side of the drivetrain so that positive voltages + // result in both sides moving forward. Depending on how your robot's + // gearbox is constructed, you might have to invert the left side instead. + m_rightMotor.setInverted(true); + + // Sets the distance per pulse for the encoders + m_leftEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); + m_rightEncoder.setDistancePerPulse(DriveConstants.kEncoderDistancePerPulse); + } + + /** + * Returns a command that drives the robot with arcade controls. + * + * @param fwd the commanded forward movement + * @param rot the commanded rotation + */ + public Command arcadeDriveCommand(DoubleSupplier fwd, DoubleSupplier rot) { + // A split-stick arcade command, with forward/backward controlled by the left + // hand, and turning controlled by the right. + return run(() -> m_drive.arcadeDrive(fwd.getAsDouble(), rot.getAsDouble())) + .withName("arcadeDrive"); + } + + /** + * Returns a command that will execute a quasistatic test in the given direction. + * + * @param direction The direction (forward or reverse) to run the test in + */ + public Command sysIdQuasistatic(SysIdRoutine.Direction direction) { + return m_sysIdRoutine.quasistatic(direction); + } + + /** + * Returns a command that will execute a dynamic test in the given direction. + * + * @param direction The direction (forward or reverse) to run the test in + */ + public Command sysIdDynamic(SysIdRoutine.Direction direction) { + return m_sysIdRoutine.dynamic(direction); + } +} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/subsystems/Shooter.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/subsystems/Shooter.java new file mode 100644 index 00000000000..322df8e1390 --- /dev/null +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/sysid/subsystems/Shooter.java @@ -0,0 +1,129 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.wpilibj.examples.sysid.subsystems; + +import static edu.wpi.first.units.MutableMeasure.mutable; +import static edu.wpi.first.units.Units.Rotations; +import static edu.wpi.first.units.Units.RotationsPerSecond; +import static edu.wpi.first.units.Units.Volts; + +import edu.wpi.first.math.controller.PIDController; +import edu.wpi.first.math.controller.SimpleMotorFeedforward; +import edu.wpi.first.units.Angle; +import edu.wpi.first.units.Measure; +import edu.wpi.first.units.MutableMeasure; +import edu.wpi.first.units.Velocity; +import edu.wpi.first.units.Voltage; +import edu.wpi.first.wpilibj.Encoder; +import edu.wpi.first.wpilibj.RobotController; +import edu.wpi.first.wpilibj.examples.sysid.Constants.ShooterConstants; +import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; +import edu.wpi.first.wpilibj2.command.Command; +import edu.wpi.first.wpilibj2.command.SubsystemBase; +import edu.wpi.first.wpilibj2.command.sysid.SysIdRoutine; +import java.util.function.DoubleSupplier; + +public class Shooter extends SubsystemBase { + // The motor on the shooter wheel . + private final PWMSparkMax m_shooterMotor = new PWMSparkMax(ShooterConstants.kShooterMotorPort); + + // The motor on the feeder wheels. + private final PWMSparkMax m_feederMotor = new PWMSparkMax(ShooterConstants.kFeederMotorPort); + + // The shooter wheel encoder + private final Encoder m_shooterEncoder = + new Encoder( + ShooterConstants.kEncoderPorts[0], + ShooterConstants.kEncoderPorts[1], + ShooterConstants.kEncoderReversed); + + // Mutable holder for unit-safe voltage values, persisted to avoid reallocation. + private final MutableMeasure m_appliedVoltage = mutable(Volts.of(0)); + // Mutable holder for unit-safe linear distance values, persisted to avoid reallocation. + private final MutableMeasure m_angle = mutable(Rotations.of(0)); + // Mutable holder for unit-safe linear velocity values, persisted to avoid reallocation. + private final MutableMeasure> m_velocity = mutable(RotationsPerSecond.of(0)); + + // Create a new SysId routine for characterizing the shooter. + private final SysIdRoutine m_sysIdRoutine = + new SysIdRoutine( + // Empty config defaults to 1 volt/second ramp rate and 7 volt step voltage. + new SysIdRoutine.Config(), + new SysIdRoutine.Mechanism( + // Tell SysId how to plumb the driving voltage to the motor(s). + (Measure volts) -> { + m_shooterMotor.setVoltage(volts.in(Volts)); + }, + // Tell SysId how to record a frame of data for each motor on the mechanism being + // characterized. + log -> { + // Record a frame for the shooter motor. + log.motor("shooter-wheel") + .voltage( + m_appliedVoltage.mut_replace( + m_shooterMotor.get() * RobotController.getBatteryVoltage(), Volts)) + .angularPosition(m_angle.mut_replace(m_shooterEncoder.getDistance(), Rotations)) + .angularVelocity( + m_velocity.mut_replace(m_shooterEncoder.getRate(), RotationsPerSecond)); + }, + // Tell SysId to make generated commands require this subsystem, suffix test state in + // WPILog with this subsystem's name ("shooter") + this)); + // PID controller to run the shooter wheel in closed-loop, set the constants equal to those + // calculated by SysId + private final PIDController m_shooterFeedback = new PIDController(ShooterConstants.kP, 0, 0); + // Feedforward controller to run the shooter wheel in closed-loop, set the constants equal to + // those calculated by SysId + private final SimpleMotorFeedforward m_shooterFeedforward = + new SimpleMotorFeedforward( + ShooterConstants.kSVolts, + ShooterConstants.kVVoltSecondsPerRotation, + ShooterConstants.kAVoltSecondsSquaredPerRotation); + + /** Creates a new Shooter subsystem. */ + public Shooter() { + // Sets the distance per pulse for the encoders + m_shooterEncoder.setDistancePerPulse(ShooterConstants.kEncoderDistancePerPulse); + } + + /** + * Returns a command that runs the shooter at a specifc velocity. + * + * @param shooterSpeed The commanded shooter wheel speed in rotations per second + */ + public Command runShooter(DoubleSupplier shooterSpeed) { + // Run shooter wheel at the desired speed using a PID controller and feedforward. + return run(() -> { + m_shooterMotor.setVoltage( + m_shooterFeedback.calculate(m_shooterEncoder.getRate(), shooterSpeed.getAsDouble()) + + m_shooterFeedforward.calculate(shooterSpeed.getAsDouble())); + m_feederMotor.set(ShooterConstants.kFeederSpeed); + }) + .finallyDo( + () -> { + m_shooterMotor.stopMotor(); + m_feederMotor.stopMotor(); + }) + .withName("runShooter"); + } + + /** + * Returns a command that will execute a quasistatic test in the given direction. + * + * @param direction The direction (forward or reverse) to run the test in + */ + public Command sysIdQuasistatic(SysIdRoutine.Direction direction) { + return m_sysIdRoutine.quasistatic(direction); + } + + /** + * Returns a command that will execute a dynamic test in the given direction. + * + * @param direction The direction (forward or reverse) to run the test in + */ + public Command sysIdDynamic(SysIdRoutine.Direction direction) { + return m_sysIdRoutine.dynamic(direction); + } +} diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/tankdrive/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/tankdrive/Robot.java index 3883d145866..a217f51b559 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/tankdrive/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/tankdrive/Robot.java @@ -4,10 +4,10 @@ package edu.wpi.first.wpilibj.examples.tankdrive; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.drive.DifferentialDrive; -import edu.wpi.first.wpilibj.motorcontrol.MotorController; import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax; /** @@ -15,27 +15,30 @@ * the code necessary to operate a robot with tank drive. */ public class Robot extends TimedRobot { - private DifferentialDrive m_myRobot; + private DifferentialDrive m_robotDrive; private Joystick m_leftStick; private Joystick m_rightStick; - private final MotorController m_leftMotor = new PWMSparkMax(0); - private final MotorController m_rightMotor = new PWMSparkMax(1); + private final PWMSparkMax m_leftMotor = new PWMSparkMax(0); + private final PWMSparkMax m_rightMotor = new PWMSparkMax(1); @Override public void robotInit() { + SendableRegistry.addChild(m_robotDrive, m_leftMotor); + SendableRegistry.addChild(m_robotDrive, m_rightMotor); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. m_rightMotor.setInverted(true); - m_myRobot = new DifferentialDrive(m_leftMotor, m_rightMotor); + m_robotDrive = new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); m_leftStick = new Joystick(0); m_rightStick = new Joystick(1); } @Override public void teleopPeriodic() { - m_myRobot.tankDrive(-m_leftStick.getY(), -m_rightStick.getY()); + m_robotDrive.tankDrive(-m_leftStick.getY(), -m_rightStick.getY()); } } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/tankdrivexboxcontroller/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/tankdrivexboxcontroller/Robot.java index c6a985af5c9..c1a850c5f70 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/tankdrivexboxcontroller/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/tankdrivexboxcontroller/Robot.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj.examples.tankdrivexboxcontroller; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj.drive.DifferentialDrive; @@ -16,11 +17,15 @@ public class Robot extends TimedRobot { private final PWMSparkMax m_leftMotor = new PWMSparkMax(0); private final PWMSparkMax m_rightMotor = new PWMSparkMax(1); - private final DifferentialDrive m_robotDrive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_robotDrive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); private final XboxController m_driverController = new XboxController(0); @Override public void robotInit() { + SendableRegistry.addChild(m_robotDrive, m_leftMotor); + SendableRegistry.addChild(m_robotDrive, m_rightMotor); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ultrasonicpid/Robot.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ultrasonicpid/Robot.java index 532e9ac4482..33681d00859 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ultrasonicpid/Robot.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/ultrasonicpid/Robot.java @@ -6,6 +6,7 @@ import edu.wpi.first.math.controller.PIDController; import edu.wpi.first.math.filter.MedianFilter; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.Ultrasonic; import edu.wpi.first.wpilibj.drive.DifferentialDrive; @@ -21,8 +22,7 @@ public class Robot extends TimedRobot { static final double kHoldDistanceMillimeters = 1.0e3; // proportional speed constant - // negative because applying positive voltage will bring us closer to the target - private static final double kP = -0.001; + private static final double kP = 0.001; // integral speed constant private static final double kI = 0.0; // derivative speed constant @@ -41,9 +41,15 @@ public class Robot extends TimedRobot { private final Ultrasonic m_ultrasonic = new Ultrasonic(kUltrasonicPingPort, kUltrasonicEchoPort); private final PWMSparkMax m_leftMotor = new PWMSparkMax(kLeftMotorPort); private final PWMSparkMax m_rightMotor = new PWMSparkMax(kRightMotorPort); - private final DifferentialDrive m_robotDrive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_robotDrive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); private final PIDController m_pidController = new PIDController(kP, kI, kD); + public Robot() { + SendableRegistry.addChild(m_robotDrive, m_leftMotor); + SendableRegistry.addChild(m_robotDrive, m_rightMotor); + } + @Override public void autonomousInit() { // Set setpoint of the pid controller diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/unittest/subsystems/Intake.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/unittest/subsystems/Intake.java index a51d505a988..e84a6079a6a 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/unittest/subsystems/Intake.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/unittest/subsystems/Intake.java @@ -44,7 +44,7 @@ public boolean isDeployed() { } @Override - public void close() throws Exception { + public void close() { m_piston.close(); m_motor.close(); } diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/xrpreference/subsystems/Drivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/xrpreference/subsystems/Drivetrain.java index f618add665d..87b985d6522 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/xrpreference/subsystems/Drivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/xrpreference/subsystems/Drivetrain.java @@ -4,6 +4,7 @@ package edu.wpi.first.wpilibj.examples.xrpreference.subsystems; +import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.BuiltInAccelerometer; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.drive.DifferentialDrive; @@ -29,7 +30,8 @@ public class Drivetrain extends SubsystemBase { private final Encoder m_rightEncoder = new Encoder(6, 7); // Set up the differential drive controller - private final DifferentialDrive m_diffDrive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_diffDrive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); // Set up the XRPGyro private final XRPGyro m_gyro = new XRPGyro(); @@ -39,6 +41,9 @@ public class Drivetrain extends SubsystemBase { /** Creates a new Drivetrain. */ public Drivetrain() { + SendableRegistry.addChild(m_diffDrive, m_leftMotor); + SendableRegistry.addChild(m_diffDrive, m_rightMotor); + // We need to invert one side of the drivetrain so that positive voltages // result in both sides moving forward. Depending on how your robot's // gearbox is constructed, you might have to invert the left side instead. diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/romicommandbased/subsystems/RomiDrivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/romicommandbased/subsystems/RomiDrivetrain.java index 276e5cee7d8..c1cfac1f325 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/romicommandbased/subsystems/RomiDrivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/romicommandbased/subsystems/RomiDrivetrain.java @@ -24,7 +24,8 @@ public class RomiDrivetrain extends SubsystemBase { private final Encoder m_rightEncoder = new Encoder(6, 7); // Set up the differential drive controller - private final DifferentialDrive m_diffDrive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_diffDrive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); /** Creates a new RomiDrivetrain. */ public RomiDrivetrain() { diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/romieducational/RomiDrivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/romieducational/RomiDrivetrain.java index 4b73a448a08..7d2a4381cb2 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/romieducational/RomiDrivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/romieducational/RomiDrivetrain.java @@ -23,7 +23,8 @@ public class RomiDrivetrain { private final Encoder m_rightEncoder = new Encoder(6, 7); // Set up the differential drive controller - private final DifferentialDrive m_diffDrive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_diffDrive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); /** Creates a new RomiDrivetrain. */ public RomiDrivetrain() { diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/romitimed/RomiDrivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/romitimed/RomiDrivetrain.java index e4f85599cea..a0f4f47b38b 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/romitimed/RomiDrivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/romitimed/RomiDrivetrain.java @@ -23,7 +23,8 @@ public class RomiDrivetrain { private final Encoder m_rightEncoder = new Encoder(6, 7); // Set up the differential drive controller - private final DifferentialDrive m_diffDrive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_diffDrive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); /** Creates a new RomiDrivetrain. */ public RomiDrivetrain() { diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/xrpcommandbased/subsystems/XRPDrivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/xrpcommandbased/subsystems/XRPDrivetrain.java index a3a1063a211..85febbed592 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/xrpcommandbased/subsystems/XRPDrivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/xrpcommandbased/subsystems/XRPDrivetrain.java @@ -27,7 +27,8 @@ public class XRPDrivetrain extends SubsystemBase { private final Encoder m_rightEncoder = new Encoder(6, 7); // Set up the differential drive controller - private final DifferentialDrive m_diffDrive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_diffDrive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); /** Creates a new XRPDrivetrain. */ public XRPDrivetrain() { diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/xrpeducational/XRPDrivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/xrpeducational/XRPDrivetrain.java index 8f73baec50d..a2459558056 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/xrpeducational/XRPDrivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/xrpeducational/XRPDrivetrain.java @@ -26,7 +26,8 @@ public class XRPDrivetrain { private final Encoder m_rightEncoder = new Encoder(6, 7); // Set up the differential drive controller - private final DifferentialDrive m_diffDrive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_diffDrive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); /** Creates a new XRPDrivetrain. */ public XRPDrivetrain() { diff --git a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/xrptimed/XRPDrivetrain.java b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/xrptimed/XRPDrivetrain.java index e66d750d092..790acc7801b 100644 --- a/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/xrptimed/XRPDrivetrain.java +++ b/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/templates/xrptimed/XRPDrivetrain.java @@ -26,7 +26,8 @@ public class XRPDrivetrain { private final Encoder m_rightEncoder = new Encoder(6, 7); // Set up the differential drive controller - private final DifferentialDrive m_diffDrive = new DifferentialDrive(m_leftMotor, m_rightMotor); + private final DifferentialDrive m_diffDrive = + new DifferentialDrive(m_leftMotor::set, m_rightMotor::set); /** Creates a new XRPDrivetrain. */ public XRPDrivetrain() { diff --git a/wpilibjExamples/src/test/java/edu/wpi/first/wpilibj/examples/potentiometerpid/PotentiometerPIDTest.java b/wpilibjExamples/src/test/java/edu/wpi/first/wpilibj/examples/potentiometerpid/PotentiometerPIDTest.java index 0da5e3d9309..8a3d92b8e66 100644 --- a/wpilibjExamples/src/test/java/edu/wpi/first/wpilibj/examples/potentiometerpid/PotentiometerPIDTest.java +++ b/wpilibjExamples/src/test/java/edu/wpi/first/wpilibj/examples/potentiometerpid/PotentiometerPIDTest.java @@ -55,8 +55,7 @@ void startThread() { 0.0, Robot.kFullHeightMeters, true, - 0, - null); + 0); m_analogSim = new AnalogInputSim(Robot.kPotChannel); m_motorSim = new PWMSim(Robot.kMotorChannel); m_joystickSim = new JoystickSim(Robot.kJoystickChannel); diff --git a/wpilibjExamples/src/test/java/edu/wpi/first/wpilibj/examples/ultrasonicpid/UltrasonicPIDTest.java b/wpilibjExamples/src/test/java/edu/wpi/first/wpilibj/examples/ultrasonicpid/UltrasonicPIDTest.java index 342daa29220..f0a27b8f9c0 100644 --- a/wpilibjExamples/src/test/java/edu/wpi/first/wpilibj/examples/ultrasonicpid/UltrasonicPIDTest.java +++ b/wpilibjExamples/src/test/java/edu/wpi/first/wpilibj/examples/ultrasonicpid/UltrasonicPIDTest.java @@ -80,7 +80,7 @@ private void startThread() { m_driveSim.update(0.02); double startingDistance = m_startToObject; - double range = startingDistance - m_driveSim.getLeftPositionMeters(); + double range = m_driveSim.getLeftPositionMeters() - startingDistance; m_ultrasonicSim.setRangeMeters(range); m_distanceMM = range * 1.0e3; @@ -126,10 +126,9 @@ void autoTest(double distance) { } { - // advance 100 timesteps - SimHooks.stepTiming(2.0); + SimHooks.stepTiming(5.0); - assertEquals(Robot.kHoldDistanceMillimeters, m_distanceMM, 10); + assertEquals(Robot.kHoldDistanceMillimeters, m_distanceMM, 10.0); } } } diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java index bdc467578f2..22267b13f82 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java @@ -4,11 +4,11 @@ package edu.wpi.first.wpilibj; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java index e6585e4f8ea..eaf975dce81 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java @@ -7,8 +7,8 @@ import static org.junit.Assert.assertEquals; import edu.wpi.first.wpilibj.test.AbstractComsSetup; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.logging.Logger; import org.junit.BeforeClass; import org.junit.Test; @@ -38,7 +38,7 @@ public static void waitASecond() { /** Test with all valid ranges to make sure unpacking is always done correctly. */ @Parameters public static Collection generateData() { - return Arrays.asList( + return List.of( new BuiltInAccelerometer.Range[][] { {BuiltInAccelerometer.Range.k2G}, {BuiltInAccelerometer.Range.k4G}, diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java index 72c2c55aade..078ef5aa693 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java @@ -14,8 +14,8 @@ import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.logging.Logger; import org.junit.After; import org.junit.AfterClass; @@ -56,7 +56,7 @@ public MotorEncoderTest(MotorEncoderFixture mef) { @Parameters(name = "{index}: {0}") public static Collection[]> generateData() { // logger.fine("Loading the MotorList"); - return Arrays.asList( + return List.of( new MotorEncoderFixture[][] { {TestBench.getTalonPair()}, {TestBench.getVictorPair()}, {TestBench.getJaguarPair()} }); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java index 769fa7fe98a..4ec5a722481 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java @@ -10,8 +10,8 @@ import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.logging.Logger; import org.junit.AfterClass; import org.junit.Before; @@ -44,7 +44,7 @@ public MotorInvertingTest(MotorEncoderFixture afixture) { @Parameters(name = "{index}: {0}") public static Collection[]> generateData() { // logger.fine("Loading the MotorList"); - return Arrays.asList( + return List.of( new MotorEncoderFixture[][] { {TestBench.getTalonPair()}, {TestBench.getVictorPair()}, {TestBench.getJaguarPair()} }); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java index f2bc522e388..d668d16d5a0 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java @@ -4,17 +4,17 @@ package edu.wpi.first.wpilibj; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; import edu.wpi.first.hal.can.CANMessageNotFoundException; import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.logging.Logger; import org.junit.After; import org.junit.AfterClass; @@ -65,7 +65,7 @@ public PDPTest(MotorEncoderFixture mef, Double expectedCurrentDraw) { @Parameters(name = "{index}: {0}, Expected Stopped Current Draw: {1}") public static Collection generateData() { // logger.fine("Loading the MotorList"); - return Arrays.asList(new Object[][] {{TestBench.getTalonPair(), 0.0}}); + return List.of(new Object[][] {{TestBench.getTalonPair(), 0.0}}); } @After diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java index b5e0fc8fd9b..f2cd12fd0ad 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java @@ -16,8 +16,8 @@ import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.logging.Logger; import org.junit.After; import org.junit.AfterClass; @@ -72,13 +72,13 @@ public PIDTest(Double p, Double i, Double d, MotorEncoderFixture mef) { @Parameters public static Collection generateData() { // logger.fine("Loading the MotorList"); - Collection data = new ArrayList(); + Collection data = new ArrayList<>(); double kp = 0.001; double ki = 0.0005; double kd = 0.0; for (int i = 0; i < 1; i++) { data.addAll( - Arrays.asList( + List.of( new Object[][] { {kp, ki, kd, TestBench.getTalonPair()}, {kp, ki, kd, TestBench.getVictorPair()}, diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java index ca93c4a2ac1..d6322913dc9 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java @@ -22,6 +22,7 @@ * fixture. This allows tests to be mailable so that you can easily reconfigure the physical testbed * without breaking the tests. */ +@SuppressWarnings("removal") public abstract class MotorEncoderFixture implements ITestFixture { private static final Logger logger = Logger.getLogger(MotorEncoderFixture.class.getName()); private boolean m_initialized = false; diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java index 056ff5ff1c7..4a912931bde 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java @@ -31,7 +31,7 @@ public abstract class AbstractComsSetup { // We have no way to stop the MockDS, so its thread is daemon. private static MockDS ds; - /** + /* * This sets up the network communications library to enable the driver station. After starting * network coms, it will loop until the driver station returns that the robot is enabled, to * ensure that tests will be able to run on the hardware. diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java index ff0542c7b2c..b8adb17b4e2 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java @@ -34,15 +34,11 @@ public abstract class AbstractTestSuite { */ protected List> getAnnotatedTestClasses() { SuiteClasses annotation = getClass().getAnnotation(SuiteClasses.class); - List> classes = new ArrayList<>(); if (annotation == null) { throw new RuntimeException( String.format("class '%s' must have a SuiteClasses annotation", getClass().getName())); } - for (Class c : annotation.value()) { - classes.add(c); - } - return classes; + return List.of(annotation.value()); } private boolean areAnySuperClassesOfTypeAbstractTestSuite(Class check) { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLauncher.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLauncher.java index 07d0af72f35..31da1036fad 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLauncher.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLauncher.java @@ -24,9 +24,8 @@ public class AntJunitLauncher { */ public static void main(String... args) { if (args.length == 0) { - String path = + String pathToReports = String.format("%s/%s", System.getProperty("user.dir"), "/testResults/AntReports"); - String pathToReports = path; Project project = new Project(); try { diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java index 258d640af99..cba5a357132 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java @@ -20,7 +20,6 @@ import edu.wpi.first.wpilibj.motorcontrol.Victor; import java.io.PrintStream; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -53,13 +52,14 @@ public final class TestBench { public static final int DIOCrossConnectA1 = 6; /** The Singleton instance of the Test Bench. */ + @SuppressWarnings("unused") private static TestBench instance = null; /** * The single constructor for the TestBench. This method is private in order to prevent multiple * TestBench objects from being allocated. */ - protected TestBench() {} + private TestBench() {} /** * Constructs a new set of objects representing a connected set of Talon controlled Motors and an @@ -68,7 +68,7 @@ protected TestBench() {} * @return a freshly allocated Talon, Encoder pair */ public static MotorEncoderFixture getTalonPair() { - return new MotorEncoderFixture() { + return new MotorEncoderFixture<>() { @Override protected Talon giveMotorController() { return new Talon(kTalonChannel); @@ -98,7 +98,7 @@ public int getPDPChannel() { * @return a freshly allocated Victor, Encoder pair */ public static MotorEncoderFixture getVictorPair() { - return new MotorEncoderFixture() { + return new MotorEncoderFixture<>() { @Override protected Victor giveMotorController() { return new Victor(kVictorChannel); @@ -128,7 +128,7 @@ public int getPDPChannel() { * @return a freshly allocated Jaguar, Encoder pair */ public static MotorEncoderFixture getJaguarPair() { - return new MotorEncoderFixture() { + return new MotorEncoderFixture<>() { @Override protected Jaguar giveMotorController() { return new Jaguar(kJaguarChannel); @@ -190,9 +190,9 @@ public static DIOCrossConnectFixture getDIOCrossConnectFixture(int inputPort, in /** Gets two lists of possible DIO pairs for the two pairs. */ private static List> getDIOCrossConnect() { - List> pairs = new ArrayList>(); + List> pairs = new ArrayList<>(); List setA = - Arrays.asList( + List.of( new Integer[][] { {DIOCrossConnectA1, DIOCrossConnectA2}, {DIOCrossConnectA2, DIOCrossConnectA1} @@ -200,7 +200,7 @@ private static List> getDIOCrossConnect() { pairs.add(setA); List setB = - Arrays.asList( + List.of( new Integer[][] { {DIOCrossConnectB1, DIOCrossConnectB2}, {DIOCrossConnectB2, DIOCrossConnectB1} @@ -252,7 +252,7 @@ protected DigitalInput giveInputOne() { * @return pairs of DIOCrossConnectFixtures */ public static Collection getDIOCrossConnectCollection() { - Collection pairs = new ArrayList(); + Collection pairs = new ArrayList<>(); for (Collection collection : getDIOCrossConnect()) { pairs.addAll(collection); } @@ -267,7 +267,7 @@ public static Collection getDIOCrossConnectCollection() { */ private static Collection getPairArray( List listA, List listB, boolean flip) { - Collection encoderPortPairs = new ArrayList(); + Collection encoderPortPairs = new ArrayList<>(); for (Integer[] portPairsA : listA) { Integer[] inputs = new Integer[5]; inputs[0] = portPairsA[0]; // InputA @@ -279,7 +279,7 @@ private static Collection getPairArray( inputs[4] = flip ? 0 : 1; // The flip bit } - ArrayList construtorInput = new ArrayList(); + ArrayList construtorInput = new ArrayList<>(); construtorInput.add(inputs); inputs = inputs.clone(); @@ -300,7 +300,7 @@ private static Collection getPairArray( * @return A collection of different input pairs to use for the encoder */ public static Collection getEncoderDIOCrossConnectCollection() { - Collection encoderPortPairs = new ArrayList(); + Collection encoderPortPairs = new ArrayList<>(); assert getDIOCrossConnect().size() == 2; encoderPortPairs.addAll( getPairArray(getDIOCrossConnect().get(0), getDIOCrossConnect().get(1), false)); diff --git a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java index 880a97c011e..232781013e8 100644 --- a/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java +++ b/wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java @@ -8,7 +8,6 @@ import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.LogManager; @@ -51,7 +50,10 @@ public class TestSuite extends AbstractTestSuite { TestBench.out().println("Starting Tests"); } + @SuppressWarnings("unused") private static final Logger WPILIBJ_ROOT_LOGGER = Logger.getLogger("edu.wpi.first.wpilibj"); + + @SuppressWarnings("unused") private static final Logger WPILIBJ_COMMAND_ROOT_LOGGER = Logger.getLogger("edu.wpi.first.wpilibj.command"); @@ -77,40 +79,36 @@ public TestSuite() {} /** Displays a help message for the user when they use the --help flag at runtime. */ protected static void displayHelp() { - StringBuilder helpMessage = new StringBuilder("Test Parameters help: \n"); - helpMessage.append( - "\t" + String helpMessage = + "Test Parameters help: \n" + + "\t" + QUICK_TEST_FLAG + " will cause the quick test to be run. Ignores other flags except for " + METHOD_REPEAT_FILTER - + "\n"); - helpMessage.append( - "\t" + + "\n" + + "\t" + CLASS_NAME_FILTER + " will use the supplied regex text to search for suite/test class names " - + "matching the regex and run them.\n"); - helpMessage.append( - "\t" + + "matching the regex and run them.\n" + + "\t" + METHOD_NAME_FILTER + " will use the supplied regex text to search for test methods (excluding methods " + "with the @Ignore annotation) and run only those methods. Can be paired with " + METHOD_REPEAT_FILTER + " to " - + "repeat the selected tests multiple times.\n"); - helpMessage.append( - "\t" + + "repeat the selected tests multiple times.\n" + + "\t" + METHOD_REPEAT_FILTER + " will repeat the tests selected with either " + QUICK_TEST_FLAG + " or " + CLASS_NAME_FILTER - + " and run them the given number of times.\n"); - helpMessage.append( - "[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This " + + " and run them the given number of times.\n" + + "[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This " + "documentation can be found at " - + "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\n"); - helpMessage.append("\n"); - helpMessage.append("\n"); + + "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\n" + + "\n" + + "\n"; TestBench.out().println(helpMessage); } @@ -123,7 +121,7 @@ protected static void displayInvalidUsage(String message, String... args) { StringBuilder invalidMessage = new StringBuilder("Invalid Usage: " + message + "\n"); invalidMessage.append("Params received: "); for (String a : args) { - invalidMessage.append(a + " "); + invalidMessage.append(a).append(" "); } invalidMessage.append("\n"); invalidMessage.append( @@ -145,9 +143,9 @@ protected static void printLoadedTests(final Class... classes) { for (Class c : classes) { if (c.getPackage().equals(packagE)) { packagE = c.getPackage(); - loadedTestsMessage.append(packagE.getName() + "\n"); + loadedTestsMessage.append(packagE.getName()).append("\n"); } - loadedTestsMessage.append("\t" + c.getSimpleName() + "\n"); + loadedTestsMessage.append("\t").append(c.getSimpleName()).append("\n"); } TestBench.out().println(loadedTestsMessage); } @@ -193,7 +191,7 @@ protected static Result parseArgsRunAndGetResult(final String[] args) { } } - ArrayList argsParsed = new ArrayList(Arrays.asList(args)); + ArrayList argsParsed = new ArrayList<>(List.of(args)); if (argsParsed.contains(HELP_FLAG)) { // If the user inputs the help flag then return the help message and exit // without running any tests @@ -257,7 +255,7 @@ void addResult(Result result) { // If a specific method has been requested if (methodFilter) { List pairs = (new TestSuite()).getMethodMatching(methodRegex); - if (pairs.size() == 0) { + if (pairs.isEmpty()) { displayInvalidUsage( "None of the arguments passed to the method name filter matched.", args); return null; @@ -292,7 +290,7 @@ void addResult(Result result) { // If a specific class has been requested if (classFilter) { List> testClasses = (new TestSuite()).getSuiteOrTestMatchingRegex(classRegex); - if (testClasses.size() == 0) { + if (testClasses.isEmpty()) { displayInvalidUsage("None of the arguments passed to the filter matched.", args); return null; } diff --git a/wpimath/.styleguide b/wpimath/.styleguide index 257b50bcaec..00437ce869e 100644 --- a/wpimath/.styleguide +++ b/wpimath/.styleguide @@ -21,6 +21,7 @@ generatedFileExclude { src/test/native/cpp/UnitsTest\.cpp$ src/test/native/cpp/drake/ src/test/native/include/drake/ + src/generated/main/java/edu/wpi/first/math/proto } repoRootNameOverride { diff --git a/wpimath/CMakeLists.txt b/wpimath/CMakeLists.txt index bb3f99c37e5..ca49610175b 100644 --- a/wpimath/CMakeLists.txt +++ b/wpimath/CMakeLists.txt @@ -8,167 +8,153 @@ include(DownloadAndCheck) # workaround for makefiles - for some reason parent directories aren't created. file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/protobuf") file(GLOB wpimath_proto_src src/main/proto/*.proto) -protobuf_generate_cpp(WPIMATH_PROTO_SRCS WPIMATH_PROTO_HDRS PROTOC_OUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/protobuf" PROTOS ${wpimath_proto_src}) - -function(quickbuf_generate SRCS JAVA_PACKAGE) - if(NOT ARGN) - message(SEND_ERROR "Error: PROTOBUF_GENERATE_QUICKBUF() called without any proto files") - return() - endif() - - set(_generated_srcs_all) - foreach(_proto ${ARGN}) - get_filename_component(_abs_file ${_proto} ABSOLUTE) - get_filename_component(_abs_dir ${_abs_file} DIRECTORY) - get_filename_component(_basename ${_proto} NAME_WLE) - file(RELATIVE_PATH _rel_dir ${CMAKE_CURRENT_SOURCE_DIR} ${_abs_dir}) - - # convert to QuickBuffers Java case (geometry2d -> Geometry2D) - string(REGEX MATCHALL "[A-Za-z_]+|[0-9]+" _name_components ${_basename}) - set(_name_components_out) - foreach(_part ${_name_components}) - string(SUBSTRING ${_part} 0 1 _first_letter) - string(TOUPPER ${_first_letter} _first_letter) - string(REGEX REPLACE "^.(.*)" "${_first_letter}\\1" _part_out "${_part}") - list(APPEND _name_components_out ${_part_out}) - endforeach() - list(JOIN _name_components_out "" _basename_title) - - set(_generated_src "${CMAKE_CURRENT_BINARY_DIR}/quickbuf/${JAVA_PACKAGE}/${_basename_title}.java") - - list(APPEND _generated_srcs_all ${_generated_src}) - - add_custom_command( - OUTPUT ${_generated_src} - COMMAND protobuf::protoc - ARGS --plugin=protoc-gen-quickbuf=${Quickbuf_EXECUTABLE} --quickbuf_out=gen_descriptors=true:${CMAKE_CURRENT_BINARY_DIR}/quickbuf -I${_abs_dir} ${_abs_file} - DEPENDS ${_abs_file} protobuf::protoc - COMMENT "Running quickbuf protocol buffer compiler on ${_proto}" - VERBATIM ) - endforeach() - - set(${SRCS} ${_generated_srcs_all} PARENT_SCOPE) -endfunction() - -file(GLOB wpimath_jni_src src/main/native/cpp/jni/WPIMathJNI_DARE.cpp - src/main/native/cpp/jni/WPIMathJNI_Eigen.cpp - src/main/native/cpp/jni/WPIMathJNI_Exceptions.cpp - src/main/native/cpp/jni/WPIMathJNI_Pose3d.cpp - src/main/native/cpp/jni/WPIMathJNI_StateSpaceUtil.cpp - src/main/native/cpp/jni/WPIMathJNI_Trajectory.cpp) +protobuf_generate_cpp( + WPIMATH_PROTO_SRCS + WPIMATH_PROTO_HDRS + PROTOC_OUT_DIR + "${CMAKE_CURRENT_BINARY_DIR}/protobuf" + PROTOS + ${wpimath_proto_src} +) + +file( + GLOB wpimath_jni_src + src/main/native/cpp/jni/WPIMathJNI_ArmFeedforward.cpp + src/main/native/cpp/jni/WPIMathJNI_DARE.cpp + src/main/native/cpp/jni/WPIMathJNI_Eigen.cpp + src/main/native/cpp/jni/WPIMathJNI_Exceptions.cpp + src/main/native/cpp/jni/WPIMathJNI_Pose3d.cpp + src/main/native/cpp/jni/WPIMathJNI_StateSpaceUtil.cpp + src/main/native/cpp/jni/WPIMathJNI_Trajectory.cpp +) # Java bindings -if (WITH_JAVA) - find_package(Java REQUIRED) - find_package(JNI REQUIRED) - include(UseJava) - set(CMAKE_JAVA_COMPILE_FLAGS "-encoding" "UTF8" "-Xlint:unchecked") - - quickbuf_generate(WPIMATH_QUICKBUF_SRCS "edu/wpi/first/math/proto" ${wpimath_proto_src}) - - if(NOT EXISTS "${WPILIB_BINARY_DIR}/wpimath/thirdparty/ejml/ejml-simple-0.43.1.jar") - set(BASE_URL "https://search.maven.org/remotecontent?filepath=") - set(JAR_ROOT "${WPILIB_BINARY_DIR}/wpimath/thirdparty/ejml") - - message(STATUS "Downloading EJML jarfiles...") - - download_and_check("${BASE_URL}org/ejml/ejml-cdense/0.43.1/ejml-cdense-0.43.1.jar" - "${JAR_ROOT}/ejml-cdense-0.43.1.jar") - download_and_check("${BASE_URL}org/ejml/ejml-core/0.43.1/ejml-core-0.43.1.jar" - "${JAR_ROOT}/ejml-core-0.43.1.jar") - download_and_check("${BASE_URL}org/ejml/ejml-ddense/0.43.1/ejml-ddense-0.43.1.jar" - "${JAR_ROOT}/ejml-ddense-0.43.1.jar") - download_and_check("${BASE_URL}org/ejml/ejml-dsparse/0.43.1/ejml-dsparse-0.43.1.jar" - "${JAR_ROOT}/ejml-dsparse-0.43.1.jar") - download_and_check("${BASE_URL}org/ejml/ejml-fdense/0.43.1/ejml-fdense-0.43.1.jar" - "${JAR_ROOT}/ejml-fdense-0.43.1.jar") - download_and_check("${BASE_URL}org/ejml/ejml-simple/0.43.1/ejml-simple-0.43.1.jar" - "${JAR_ROOT}/ejml-simple-0.43.1.jar") - download_and_check("${BASE_URL}org/ejml/ejml-zdense/0.43.1/ejml-zdense-0.43.1.jar" - "${JAR_ROOT}/ejml-zdense-0.43.1.jar") - - message(STATUS "All files downloaded.") - endif() - - file(GLOB EJML_JARS "${WPILIB_BINARY_DIR}/wpimath/thirdparty/ejml/*.jar") - file(GLOB JACKSON_JARS "${WPILIB_BINARY_DIR}/wpiutil/thirdparty/jackson/*.jar") - file(GLOB QUICKBUF_JAR - ${WPILIB_BINARY_DIR}/wpiutil/thirdparty/quickbuf/*.jar) - - set(CMAKE_JAVA_INCLUDE_PATH wpimath.jar ${EJML_JARS} ${JACKSON_JARS} ${QUICKBUF_JAR}) - - execute_process(COMMAND python3 ${CMAKE_CURRENT_SOURCE_DIR}/generate_numbers.py ${WPILIB_BINARY_DIR}/wpimath RESULT_VARIABLE generateResult) - if(NOT (generateResult EQUAL "0")) - # Try python - execute_process(COMMAND python ${CMAKE_CURRENT_SOURCE_DIR}/generate_numbers.py ${WPILIB_BINARY_DIR}/wpimath RESULT_VARIABLE generateResult) - if(NOT (generateResult EQUAL "0")) - message(FATAL_ERROR "python and python3 generate_numbers.py failed") +if(WITH_JAVA) + find_package(Java REQUIRED) + find_package(JNI REQUIRED) + include(UseJava) + set(CMAKE_JAVA_COMPILE_FLAGS "-encoding" "UTF8" "-Xlint:unchecked") + + if(NOT EXISTS "${WPILIB_BINARY_DIR}/wpimath/thirdparty/ejml/ejml-simple-0.43.1.jar") + set(BASE_URL "https://search.maven.org/remotecontent?filepath=") + set(JAR_ROOT "${WPILIB_BINARY_DIR}/wpimath/thirdparty/ejml") + + message(STATUS "Downloading EJML jarfiles...") + + download_and_check("${BASE_URL}org/ejml/ejml-cdense/0.43.1/ejml-cdense-0.43.1.jar" + "${JAR_ROOT}/ejml-cdense-0.43.1.jar" + ) + download_and_check("${BASE_URL}org/ejml/ejml-core/0.43.1/ejml-core-0.43.1.jar" + "${JAR_ROOT}/ejml-core-0.43.1.jar" + ) + download_and_check("${BASE_URL}org/ejml/ejml-ddense/0.43.1/ejml-ddense-0.43.1.jar" + "${JAR_ROOT}/ejml-ddense-0.43.1.jar" + ) + download_and_check("${BASE_URL}org/ejml/ejml-dsparse/0.43.1/ejml-dsparse-0.43.1.jar" + "${JAR_ROOT}/ejml-dsparse-0.43.1.jar" + ) + download_and_check("${BASE_URL}org/ejml/ejml-fdense/0.43.1/ejml-fdense-0.43.1.jar" + "${JAR_ROOT}/ejml-fdense-0.43.1.jar" + ) + download_and_check("${BASE_URL}org/ejml/ejml-simple/0.43.1/ejml-simple-0.43.1.jar" + "${JAR_ROOT}/ejml-simple-0.43.1.jar" + ) + download_and_check("${BASE_URL}org/ejml/ejml-zdense/0.43.1/ejml-zdense-0.43.1.jar" + "${JAR_ROOT}/ejml-zdense-0.43.1.jar" + ) + + message(STATUS "All files downloaded.") endif() - endif() - set(CMAKE_JNI_TARGET true) + file(GLOB EJML_JARS "${WPILIB_BINARY_DIR}/wpimath/thirdparty/ejml/*.jar") + file(GLOB JACKSON_JARS "${WPILIB_BINARY_DIR}/wpiutil/thirdparty/jackson/*.jar") + file(GLOB QUICKBUF_JAR ${WPILIB_BINARY_DIR}/wpiutil/thirdparty/quickbuf/*.jar) - file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java ${WPILIB_BINARY_DIR}/wpimath/generated/*.java) + set(CMAKE_JAVA_INCLUDE_PATH wpimath.jar ${EJML_JARS} ${JACKSON_JARS} ${QUICKBUF_JAR}) - add_jar(wpimath_jar ${JAVA_SOURCES} ${WPIMATH_QUICKBUF_SRCS} INCLUDE_JARS ${EJML_JARS} wpiutil_jar wpiunits_jar OUTPUT_NAME wpimath GENERATE_NATIVE_HEADERS wpimath_jni_headers) + set(CMAKE_JNI_TARGET true) - get_property(WPIMATH_JAR_FILE TARGET wpimath_jar PROPERTY JAR_FILE) - install(FILES ${WPIMATH_JAR_FILE} DESTINATION "${java_lib_dest}") + file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java src/generated/main/java/*.java) - set_property(TARGET wpimath_jar PROPERTY FOLDER "java") + add_jar( + wpimath_jar + ${JAVA_SOURCES} + INCLUDE_JARS ${EJML_JARS} wpiutil_jar wpiunits_jar + OUTPUT_NAME wpimath + GENERATE_NATIVE_HEADERS wpimath_jni_headers + ) - add_library(wpimathjni ${wpimath_jni_src}) - wpilib_target_warnings(wpimathjni) - target_link_libraries(wpimathjni PUBLIC wpimath) + install_jar(wpimath_jar DESTINATION ${java_lib_dest}) + install_jar_exports(TARGETS wpimath_jar FILE wpimath_jar.cmake DESTINATION share/wpimath) - set_property(TARGET wpimathjni PROPERTY FOLDER "libraries") + add_library(wpimathjni ${wpimath_jni_src}) + wpilib_target_warnings(wpimathjni) + target_link_libraries(wpimathjni PUBLIC wpimath) - target_link_libraries(wpimathjni PRIVATE wpimath_jni_headers) - add_dependencies(wpimathjni wpimath_jar) + set_property(TARGET wpimathjni PROPERTY FOLDER "libraries") - install(TARGETS wpimathjni EXPORT wpimathjni) + target_link_libraries(wpimathjni PRIVATE wpimath_jni_headers) + add_dependencies(wpimathjni wpimath_jar) + install(TARGETS wpimathjni EXPORT wpimathjni) + export(TARGETS wpimathjni FILE wpimathjni.cmake NAMESPACE wpimathjni::) endif() -if (WITH_JAVA_SOURCE) - find_package(Java REQUIRED) - include(UseJava) - file(GLOB WPIMATH_SOURCES src/main/java/edu/wpi/first/math/*.java ${WPILIB_BINARY_DIR}/wpimath/generated/main/java/edu/wpi/first/math/Nat.java) - file(GLOB WPIMATH_CONTROLLER_SOURCES src/main/java/edu/wpi/first/math/controller/*.java) - file(GLOB WPIMATH_ESTIMATOR_SOURCES src/main/java/edu/wpi/first/math/estimator/*.java) - file(GLOB WPIMATH_FILTER_SOURCES src/main/java/edu/wpi/first/math/filter/*.java) - file(GLOB WPIMATH_GEOMETRY_SOURCES src/main/java/edu/wpi/first/math/geometry/*.java) - file(GLOB WPIMATH_INTERPOLATION_SOURCES src/main/java/edu/wpi/first/math/interpolation/*.java) - file(GLOB WPIMATH_KINEMATICS_SOURCES src/main/java/edu/wpi/first/math/kinematics/*.java) - file(GLOB WPIMATH_NUMBERS_SOURCES ${WPILIB_BINARY_DIR}/wpimath/generated/main/java/edu/wpi/first/math/numbers/*.java) - file(GLOB WPIMATH_SPLINE_SOURCES src/main/java/edu/wpi/first/math/spline/*.java) - file(GLOB WPIMATH_SYSTEM_SOURCES src/main/java/edu/wpi/first/math/system/*.java) - file(GLOB WPIMATH_SYSTEM_PLANT_SOURCES src/main/java/edu/wpi/first/math/system/plant/*.java) - file(GLOB WPIMATH_TRAJECTORY_SOURCES src/main/java/edu/wpi/first/math/trajectory/*.java) - file(GLOB WPIMATH_TRAJECTORY_CONSTRAINT_SOURCES src/main/java/edu/wpi/first/math/trajectory/constraint/*.java) - add_jar(wpimath_src_jar - RESOURCES NAMESPACE "edu/wpi/first/math" ${WPIMATH_SOURCES} - NAMESPACE "edu/wpi/first/math/controller" ${WPIMATH_CONTROLLER_SOURCES} - NAMESPACE "edu/wpi/first/math/estimator" ${WPIMATH_ESTIMATOR_SOURCES} - NAMESPACE "edu/wpi/first/math/filter" ${WPIMATH_FILTER_SOURCES} - NAMESPACE "edu/wpi/first/math/geometry" ${WPIMATH_GEOMETRY_SOURCES} - NAMESPACE "edu/wpi/first/math/interpolation" ${WPIMATH_INTERPOLATION_SOURCES} - NAMESPACE "edu/wpi/first/math/kinematics" ${WPIMATH_KINEMATICS_SOURCES} - NAMESPACE "edu/wpi/first/math/spline" ${WPIMATH_SPLINE_SOURCES} - NAMESPACE "edu/wpi/first/math/system" ${WPIMATH_SYSTEM_SOURCES} - NAMESPACE "edu/wpi/first/math/system/plant" ${WPIMATH_SYSTEM_PLANT_SOURCES} - NAMESPACE "edu/wpi/first/math/trajectory" ${WPIMATH_TRAJECTORY_SOURCES} - NAMESPACE "edu/wpi/first/math/trajectory/constraint" ${WPIMATH_TRAJECTORY_CONSTRAINT_SOURCES} - NAMESPACE "edu/wpi/first/math/util" src/main/java/edu/wpi/first/math/util/Units.java - OUTPUT_NAME wpimath-sources) - - get_property(WPIMATH_SRC_JAR_FILE TARGET wpimath_src_jar PROPERTY JAR_FILE) - install(FILES ${WPIMATH_SRC_JAR_FILE} DESTINATION "${java_lib_dest}") - - set_property(TARGET wpimath_src_jar PROPERTY FOLDER "java") +if(WITH_JAVA_SOURCE) + find_package(Java REQUIRED) + include(UseJava) + file( + GLOB WPIMATH_SOURCES + src/main/java/edu/wpi/first/math/*.java + src/generated/main/java/edu/wpi/first/math/Nat.java + ) + file(GLOB WPIMATH_CONTROLLER_SOURCES src/main/java/edu/wpi/first/math/controller/*.java) + file(GLOB WPIMATH_ESTIMATOR_SOURCES src/main/java/edu/wpi/first/math/estimator/*.java) + file(GLOB WPIMATH_FILTER_SOURCES src/main/java/edu/wpi/first/math/filter/*.java) + file(GLOB WPIMATH_GEOMETRY_SOURCES src/main/java/edu/wpi/first/math/geometry/*.java) + file(GLOB WPIMATH_INTERPOLATION_SOURCES src/main/java/edu/wpi/first/math/interpolation/*.java) + file(GLOB WPIMATH_KINEMATICS_SOURCES src/main/java/edu/wpi/first/math/kinematics/*.java) + file(GLOB WPIMATH_NUMBERS_SOURCES src/generated/main/java/edu/wpi/first/math/numbers/*.java) + file(GLOB WPIMATH_SPLINE_SOURCES src/main/java/edu/wpi/first/math/spline/*.java) + file(GLOB WPIMATH_SYSTEM_SOURCES src/main/java/edu/wpi/first/math/system/*.java) + file(GLOB WPIMATH_SYSTEM_PLANT_SOURCES src/main/java/edu/wpi/first/math/system/plant/*.java) + file(GLOB WPIMATH_TRAJECTORY_SOURCES src/main/java/edu/wpi/first/math/trajectory/*.java) + file( + GLOB WPIMATH_TRAJECTORY_CONSTRAINT_SOURCES + src/main/java/edu/wpi/first/math/trajectory/constraint/*.java + ) + add_jar( + wpimath_src_jar + RESOURCES + NAMESPACE "edu/wpi/first/math" ${WPIMATH_SOURCES} + NAMESPACE "edu/wpi/first/math/controller" ${WPIMATH_CONTROLLER_SOURCES} + NAMESPACE "edu/wpi/first/math/estimator" ${WPIMATH_ESTIMATOR_SOURCES} + NAMESPACE "edu/wpi/first/math/filter" ${WPIMATH_FILTER_SOURCES} + NAMESPACE "edu/wpi/first/math/geometry" ${WPIMATH_GEOMETRY_SOURCES} + NAMESPACE "edu/wpi/first/math/interpolation" ${WPIMATH_INTERPOLATION_SOURCES} + NAMESPACE "edu/wpi/first/math/kinematics" ${WPIMATH_KINEMATICS_SOURCES} + NAMESPACE "edu/wpi/first/math/spline" ${WPIMATH_SPLINE_SOURCES} + NAMESPACE "edu/wpi/first/math/system" ${WPIMATH_SYSTEM_SOURCES} + NAMESPACE "edu/wpi/first/math/system/plant" ${WPIMATH_SYSTEM_PLANT_SOURCES} + NAMESPACE "edu/wpi/first/math/trajectory" ${WPIMATH_TRAJECTORY_SOURCES} + NAMESPACE + "edu/wpi/first/math/trajectory/constraint" + ${WPIMATH_TRAJECTORY_CONSTRAINT_SOURCES} + NAMESPACE "edu/wpi/first/math/util" src/main/java/edu/wpi/first/math/util/Units.java + OUTPUT_NAME wpimath-sources + ) + + get_property(WPIMATH_SRC_JAR_FILE TARGET wpimath_src_jar PROPERTY JAR_FILE) + install(FILES ${WPIMATH_SRC_JAR_FILE} DESTINATION "${java_lib_dest}") + + set_property(TARGET wpimath_src_jar PROPERTY FOLDER "java") endif() -file(GLOB_RECURSE wpimath_native_src src/main/native/cpp/*.cpp) +file( + GLOB_RECURSE wpimath_native_src + src/main/native/cpp/*.cpp + src/main/native/thirdparty/sleipnir/src/*.cpp +) list(REMOVE_ITEM wpimath_native_src ${wpimath_jni_src}) set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS FALSE) @@ -177,48 +163,68 @@ set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE) set_target_properties(wpimath PROPERTIES DEBUG_POSTFIX "d") set_property(TARGET wpimath PROPERTY FOLDER "libraries") -target_compile_definitions(wpimath PRIVATE WPILIB_EXPORTS) +target_compile_definitions(wpimath PRIVATE WPILIB_EXPORTS SLEIPNIR_EXPORTS) target_compile_features(wpimath PUBLIC cxx_std_20) -if (MSVC) - target_compile_options(wpimath PUBLIC /bigobj) +if(MSVC) + target_compile_options(wpimath PUBLIC /utf-8 /bigobj) endif() wpilib_target_warnings(wpimath) target_link_libraries(wpimath wpiutil) -if (NOT USE_SYSTEM_EIGEN) - install(DIRECTORY src/main/native/thirdparty/eigen/include/ DESTINATION "${include_dest}/wpimath") - target_include_directories(wpimath SYSTEM PUBLIC - $ - $) +if(NOT USE_SYSTEM_EIGEN) + install( + DIRECTORY src/main/native/thirdparty/eigen/include/ + DESTINATION "${include_dest}/wpimath" + ) + target_include_directories( + wpimath + SYSTEM + PUBLIC + $ + $ + ) else() find_package(Eigen3 CONFIG REQUIRED) - target_link_libraries (wpimath Eigen3::Eigen) + target_link_libraries(wpimath Eigen3::Eigen) endif() +install( + DIRECTORY src/main/native/thirdparty/sleipnir/include/ + DESTINATION "${include_dest}/wpimath" +) +target_include_directories( + wpimath + SYSTEM + PUBLIC + $ + $ +) + install(DIRECTORY src/main/native/thirdparty/gcem/include/ DESTINATION "${include_dest}/wpimath") -target_include_directories(wpimath SYSTEM PUBLIC - $) +target_include_directories( + wpimath + SYSTEM + PUBLIC $ +) install(DIRECTORY src/main/native/include/ DESTINATION "${include_dest}/wpimath") -target_include_directories(wpimath PUBLIC - $ - $ - $) +target_include_directories( + wpimath + PUBLIC + $ + $ + $ +) install(TARGETS wpimath EXPORT wpimath) +export(TARGETS wpimath FILE wpimath.cmake NAMESPACE wpimath::) -if (WITH_FLAT_INSTALL) - set (wpimath_config_dir ${wpilib_dest}) -else() - set (wpimath_config_dir share/wpimath) -endif() - -configure_file(wpimath-config.cmake.in ${WPILIB_BINARY_DIR}/wpimath-config.cmake ) -install(FILES ${WPILIB_BINARY_DIR}/wpimath-config.cmake DESTINATION ${wpimath_config_dir}) -install(EXPORT wpimath DESTINATION ${wpimath_config_dir}) +configure_file(wpimath-config.cmake.in ${WPILIB_BINARY_DIR}/wpimath-config.cmake) +install(FILES ${WPILIB_BINARY_DIR}/wpimath-config.cmake DESTINATION share/wpimath) +install(EXPORT wpimath DESTINATION share/wpimath) -if (WITH_TESTS) +if(WITH_TESTS) wpilib_add_test(wpimath src/test/native/cpp) target_include_directories(wpimath_test PRIVATE src/test/native/include) target_link_libraries(wpimath_test wpimath gmock_main) diff --git a/wpimath/build.gradle b/wpimath/build.gradle index 32ea0a1b569..06d4e4668de 100644 --- a/wpimath/build.gradle +++ b/wpimath/build.gradle @@ -9,6 +9,23 @@ ext { nativeName = 'wpimath' devMain = 'edu.wpi.first.math.DevMain' + + splitSetup = { + it.sources { + sleipnirCpp(CppSourceSet) { + source { + srcDirs 'src/main/native/thirdparty/sleipnir/src' + include '**/*.cpp' + } + exportedHeaders { + srcDirs 'src/main/native/thirdparty/eigen/include', + 'src/main/native/thirdparty/fmt/include', + 'src/main/native/thirdparty/sleipnir/include', + 'src/main/native/thirdparty/sleipnir/src' + } + } + } + } } apply from: "${rootDir}/shared/jni/setupBuild.gradle" @@ -24,6 +41,9 @@ cppHeadersZip { into '/wpimath/protobuf' include '*.h' } + from('src/main/native/thirdparty/sleipnir/include') { + into '/' + } } cppHeadersZip.dependsOn generateProto @@ -35,11 +55,38 @@ model { it.exportedHeaders { srcDirs 'src/main/native/include', 'src/main/native/thirdparty/eigen/include', - 'src/main/native/thirdparty/gcem/include' + 'src/main/native/thirdparty/gcem/include', + 'src/main/native/thirdparty/sleipnir/include' } } } } + binaries { + all { + it.cppCompiler.define 'SLEIPNIR_EXPORTS' + } + } +} + +nativeUtils.exportsConfigs { + wpimath { + x64ExcludeSymbols = [ + '_CT??_R0?AV_System_error', + '_CT??_R0?AVexception', + '_CT??_R0?AVfailure', + '_CT??_R0?AVruntime_error', + '_CT??_R0?AVsystem_error', + '_CTA5?AVfailure', + '_TI5?AVfailure', + '_CT??_R0?AVout_of_range', + '_CTA3?AVout_of_range', + '_TI3?AVout_of_range', + '_CT??_R0?AVbad_cast' + ] + objectFilterClosure = { file -> + return file.name.endsWith('.pb.obj') + } + } } dependencies { @@ -48,71 +95,10 @@ dependencies { api "com.fasterxml.jackson.core:jackson-annotations:2.15.2" api "com.fasterxml.jackson.core:jackson-core:2.15.2" api "com.fasterxml.jackson.core:jackson-databind:2.15.2" - api "us.hebi.quickbuf:quickbuf-runtime:1.3.2" -} - -def wpilibNumberFileInput = file("src/generate/GenericNumber.java.jinja") -def natFileInput = file("src/generate/Nat.java.jinja") -def wpilibNumberFileOutputDir = file("$buildDir/generated/java/edu/wpi/first/math/numbers") -def wpilibNatFileOutput = file("$buildDir/generated/java/edu/wpi/first/math/Nat.java") -def maxNum = 20 - -task generateNumbers() { - description = "Generates generic number classes from template" - group = "WPILib" - - inputs.file wpilibNumberFileInput - outputs.dir wpilibNumberFileOutputDir - - doLast { - if(wpilibNumberFileOutputDir.exists()) { - wpilibNumberFileOutputDir.delete() - } - wpilibNumberFileOutputDir.mkdirs() - - def config = new JinjavaConfig() - def jinjava = new Jinjava(config) - - def template = wpilibNumberFileInput.text - - for(i in 0..maxNum) { - def outputFile = new File(wpilibNumberFileOutputDir, "N${i}.java") - def replacements = new HashMap() - replacements.put("num", i) - def output = jinjava.render(template, replacements) - outputFile.write(output) - } - } -} - -task generateNat() { - description = "Generates Nat.java" - group = "WPILib" - inputs.file natFileInput - outputs.file wpilibNatFileOutput - dependsOn generateNumbers - - doLast { - if(wpilibNatFileOutput.exists()) { - wpilibNatFileOutput.delete() - } - - def config = new JinjavaConfig() - def jinjava = new Jinjava(config) - - def template = natFileInput.text - - def replacements = new HashMap() - replacements.put("nums", 0..maxNum) - - def output = jinjava.render(template, replacements) - wpilibNatFileOutput.write(output) - } + api "us.hebi.quickbuf:quickbuf-runtime:1.3.3" } -sourceSets.main.java.srcDir "${buildDir}/generated/java" -compileJava.dependsOn generateNumbers -compileJava.dependsOn generateNat +sourceSets.main.java.srcDir "${projectDir}/src/generated/main/java" task unitsHeaders(type: Zip) { destinationDirectory = file("$buildDir/outputs") diff --git a/wpimath/generate_numbers.py b/wpimath/generate_numbers.py old mode 100644 new mode 100755 index c9da1a4cd82..2aeb45a56d8 --- a/wpimath/generate_numbers.py +++ b/wpimath/generate_numbers.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python3 + # Copyright (c) FIRST and other WPILib contributors. # Open Source Software; you can modify and/or share it under the terms of # the WPILib BSD license file in the root directory of this project. @@ -19,7 +21,7 @@ def output(outPath, outfn, contents): return # File either doesn't exist or has different contents - with open(outpathname, "w") as f: + with open(outpathname, "w", newline="\n") as f: f.write(contents) @@ -27,23 +29,22 @@ def main(): MAX_NUM = 20 dirname, _ = os.path.split(os.path.abspath(__file__)) - cmake_binary_dir = sys.argv[1] env = Environment( - loader=FileSystemLoader(f"{dirname}/src/generate"), + loader=FileSystemLoader(f"{dirname}/src/generate/main/java"), autoescape=False, keep_trailing_newline=True, ) template = env.get_template("GenericNumber.java.jinja") - rootPath = f"{cmake_binary_dir}/generated/main/java/edu/wpi/first/math/numbers" + rootPath = f"{dirname}/src/generated/main/java/edu/wpi/first/math/numbers" for i in range(MAX_NUM + 1): contents = template.render(num=i) output(rootPath, f"N{i}.java", contents) template = env.get_template("Nat.java.jinja") - rootPath = f"{cmake_binary_dir}/generated/main/java/edu/wpi/first/math" + rootPath = f"{dirname}/src/generated/main/java/edu/wpi/first/math" contents = template.render(nums=range(MAX_NUM + 1)) output(rootPath, "Nat.java", contents) diff --git a/wpimath/generate_quickbuf.py b/wpimath/generate_quickbuf.py new file mode 100755 index 00000000000..506c5bc92d2 --- /dev/null +++ b/wpimath/generate_quickbuf.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 + +# Copyright (c) FIRST and other WPILib contributors. +# Open Source Software; you can modify and/or share it under the terms of +# the WPILib BSD license file in the root directory of this project. +import os.path +import subprocess +import sys +from glob import glob + +if __name__ == "__main__": + proto_files = glob("wpimath/src/main/proto/*.proto") + for path in proto_files: + absolute_filename = os.path.abspath(path) + absolute_dir, filename = os.path.split(absolute_filename) + subprocess.run( + [ + sys.argv[1], + f"--plugin=protoc-gen-quickbuf={sys.argv[2]}", + f"--quickbuf_out=gen_descriptors=true:{os.path.abspath('./wpimath/src/generated/main/java')}", + f"-I{absolute_dir}", + absolute_filename, + ] + ) + java_files = glob("wpimath/src/generated/main/java/edu/wpi/first/math/proto/*.java") + for java_file in java_files: + with open(java_file) as file: + content = file.read() + with open(java_file, "tw") as file: + file.write( + "// Copyright (c) FIRST and other WPILib contributors.\n// Open Source Software; you can modify and/or share it under the terms of\n// the WPILib BSD license file in the root directory of this project.\n" + + content + ) diff --git a/wpimath/src/dev/native/cpp/main.cpp b/wpimath/src/dev/native/cpp/main.cpp index 447d3f2bce9..ca3ecc348da 100644 --- a/wpimath/src/dev/native/cpp/main.cpp +++ b/wpimath/src/dev/native/cpp/main.cpp @@ -4,8 +4,8 @@ #include -#include +#include int main() { - fmt::print("{}\n", std::numbers::pi); + wpi::print("{}\n", std::numbers::pi); } diff --git a/wpimath/src/generate/GenericNumber.java.jinja b/wpimath/src/generate/main/java/GenericNumber.java.jinja similarity index 73% rename from wpimath/src/generate/GenericNumber.java.jinja rename to wpimath/src/generate/main/java/GenericNumber.java.jinja index 5e4be85aeb5..2bd940b628e 100644 --- a/wpimath/src/generate/GenericNumber.java.jinja +++ b/wpimath/src/generate/main/java/GenericNumber.java.jinja @@ -2,30 +2,27 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + package edu.wpi.first.math.numbers; import edu.wpi.first.math.Nat; import edu.wpi.first.math.Num; -/** - * A class representing the number {{ num }}. -*/ +/** A class representing the number {{ num }}. */ public final class N{{ num }} extends Num implements Nat { - private N{{ num }}() { - } + private N{{ num }}() {} /** * The integer this class represents. * * @return The literal number {{ num }}. - */ + */ @Override public int getNum() { return {{ num }}; } - /** - * The singleton instance of this class. - */ + /** The singleton instance of this class. */ public static final N{{ num }} instance = new N{{ num }}(); } diff --git a/wpimath/src/generate/Nat.java.jinja b/wpimath/src/generate/main/java/Nat.java.jinja similarity index 75% rename from wpimath/src/generate/Nat.java.jinja rename to wpimath/src/generate/main/java/Nat.java.jinja index cbc0ddb24e5..66f06390c22 100644 --- a/wpimath/src/generate/Nat.java.jinja +++ b/wpimath/src/generate/main/java/Nat.java.jinja @@ -2,13 +2,15 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + package edu.wpi.first.math; -//CHECKSTYLE.OFF: ImportOrder +// CHECKSTYLE.OFF: ImportOrder {% for num in nums %} import edu.wpi.first.math.numbers.N{{ num }}; {%- endfor %} -//CHECKSTYLE.ON +// CHECKSTYLE.ON /** * A natural number expressed as a java class. @@ -24,8 +26,13 @@ public interface Nat { */ int getNum(); {% for num in nums %} + /** + * Returns the Nat instance for {{ num }}. + * + * @return The Nat instance for {{ num }}. + */ static Nat N{{ num }}() { return N{{ num }}.instance; } -{% endfor %} +{% endfor -%} } diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/Nat.java b/wpimath/src/generated/main/java/edu/wpi/first/math/Nat.java new file mode 100644 index 00000000000..f6b0b81250b --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/Nat.java @@ -0,0 +1,236 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math; + +// CHECKSTYLE.OFF: ImportOrder + +import edu.wpi.first.math.numbers.N0; +import edu.wpi.first.math.numbers.N1; +import edu.wpi.first.math.numbers.N2; +import edu.wpi.first.math.numbers.N3; +import edu.wpi.first.math.numbers.N4; +import edu.wpi.first.math.numbers.N5; +import edu.wpi.first.math.numbers.N6; +import edu.wpi.first.math.numbers.N7; +import edu.wpi.first.math.numbers.N8; +import edu.wpi.first.math.numbers.N9; +import edu.wpi.first.math.numbers.N10; +import edu.wpi.first.math.numbers.N11; +import edu.wpi.first.math.numbers.N12; +import edu.wpi.first.math.numbers.N13; +import edu.wpi.first.math.numbers.N14; +import edu.wpi.first.math.numbers.N15; +import edu.wpi.first.math.numbers.N16; +import edu.wpi.first.math.numbers.N17; +import edu.wpi.first.math.numbers.N18; +import edu.wpi.first.math.numbers.N19; +import edu.wpi.first.math.numbers.N20; +// CHECKSTYLE.ON + +/** + * A natural number expressed as a java class. + * The counterpart to {@link Num} that should be used as a concrete value. + * + * @param The {@link Num} this represents. + */ +public interface Nat { + /** + * The number this interface represents. + * + * @return The number backing this value. + */ + int getNum(); + + /** + * Returns the Nat instance for 0. + * + * @return The Nat instance for 0. + */ + static Nat N0() { + return N0.instance; + } + + /** + * Returns the Nat instance for 1. + * + * @return The Nat instance for 1. + */ + static Nat N1() { + return N1.instance; + } + + /** + * Returns the Nat instance for 2. + * + * @return The Nat instance for 2. + */ + static Nat N2() { + return N2.instance; + } + + /** + * Returns the Nat instance for 3. + * + * @return The Nat instance for 3. + */ + static Nat N3() { + return N3.instance; + } + + /** + * Returns the Nat instance for 4. + * + * @return The Nat instance for 4. + */ + static Nat N4() { + return N4.instance; + } + + /** + * Returns the Nat instance for 5. + * + * @return The Nat instance for 5. + */ + static Nat N5() { + return N5.instance; + } + + /** + * Returns the Nat instance for 6. + * + * @return The Nat instance for 6. + */ + static Nat N6() { + return N6.instance; + } + + /** + * Returns the Nat instance for 7. + * + * @return The Nat instance for 7. + */ + static Nat N7() { + return N7.instance; + } + + /** + * Returns the Nat instance for 8. + * + * @return The Nat instance for 8. + */ + static Nat N8() { + return N8.instance; + } + + /** + * Returns the Nat instance for 9. + * + * @return The Nat instance for 9. + */ + static Nat N9() { + return N9.instance; + } + + /** + * Returns the Nat instance for 10. + * + * @return The Nat instance for 10. + */ + static Nat N10() { + return N10.instance; + } + + /** + * Returns the Nat instance for 11. + * + * @return The Nat instance for 11. + */ + static Nat N11() { + return N11.instance; + } + + /** + * Returns the Nat instance for 12. + * + * @return The Nat instance for 12. + */ + static Nat N12() { + return N12.instance; + } + + /** + * Returns the Nat instance for 13. + * + * @return The Nat instance for 13. + */ + static Nat N13() { + return N13.instance; + } + + /** + * Returns the Nat instance for 14. + * + * @return The Nat instance for 14. + */ + static Nat N14() { + return N14.instance; + } + + /** + * Returns the Nat instance for 15. + * + * @return The Nat instance for 15. + */ + static Nat N15() { + return N15.instance; + } + + /** + * Returns the Nat instance for 16. + * + * @return The Nat instance for 16. + */ + static Nat N16() { + return N16.instance; + } + + /** + * Returns the Nat instance for 17. + * + * @return The Nat instance for 17. + */ + static Nat N17() { + return N17.instance; + } + + /** + * Returns the Nat instance for 18. + * + * @return The Nat instance for 18. + */ + static Nat N18() { + return N18.instance; + } + + /** + * Returns the Nat instance for 19. + * + * @return The Nat instance for 19. + */ + static Nat N19() { + return N19.instance; + } + + /** + * Returns the Nat instance for 20. + * + * @return The Nat instance for 20. + */ + static Nat N20() { + return N20.instance; + } +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N0.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N0.java new file mode 100644 index 00000000000..85065f75f20 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N0.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 0. */ +public final class N0 extends Num implements Nat { + private N0() {} + + /** + * The integer this class represents. + * + * @return The literal number 0. + */ + @Override + public int getNum() { + return 0; + } + + /** The singleton instance of this class. */ + public static final N0 instance = new N0(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N1.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N1.java new file mode 100644 index 00000000000..8977a7ae803 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N1.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 1. */ +public final class N1 extends Num implements Nat { + private N1() {} + + /** + * The integer this class represents. + * + * @return The literal number 1. + */ + @Override + public int getNum() { + return 1; + } + + /** The singleton instance of this class. */ + public static final N1 instance = new N1(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N10.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N10.java new file mode 100644 index 00000000000..540f1d3653a --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N10.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 10. */ +public final class N10 extends Num implements Nat { + private N10() {} + + /** + * The integer this class represents. + * + * @return The literal number 10. + */ + @Override + public int getNum() { + return 10; + } + + /** The singleton instance of this class. */ + public static final N10 instance = new N10(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N11.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N11.java new file mode 100644 index 00000000000..45113c9b4fd --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N11.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 11. */ +public final class N11 extends Num implements Nat { + private N11() {} + + /** + * The integer this class represents. + * + * @return The literal number 11. + */ + @Override + public int getNum() { + return 11; + } + + /** The singleton instance of this class. */ + public static final N11 instance = new N11(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N12.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N12.java new file mode 100644 index 00000000000..6a86c80ac60 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N12.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 12. */ +public final class N12 extends Num implements Nat { + private N12() {} + + /** + * The integer this class represents. + * + * @return The literal number 12. + */ + @Override + public int getNum() { + return 12; + } + + /** The singleton instance of this class. */ + public static final N12 instance = new N12(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N13.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N13.java new file mode 100644 index 00000000000..7ae2ca14903 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N13.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 13. */ +public final class N13 extends Num implements Nat { + private N13() {} + + /** + * The integer this class represents. + * + * @return The literal number 13. + */ + @Override + public int getNum() { + return 13; + } + + /** The singleton instance of this class. */ + public static final N13 instance = new N13(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N14.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N14.java new file mode 100644 index 00000000000..58a4192679a --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N14.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 14. */ +public final class N14 extends Num implements Nat { + private N14() {} + + /** + * The integer this class represents. + * + * @return The literal number 14. + */ + @Override + public int getNum() { + return 14; + } + + /** The singleton instance of this class. */ + public static final N14 instance = new N14(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N15.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N15.java new file mode 100644 index 00000000000..5794daca03f --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N15.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 15. */ +public final class N15 extends Num implements Nat { + private N15() {} + + /** + * The integer this class represents. + * + * @return The literal number 15. + */ + @Override + public int getNum() { + return 15; + } + + /** The singleton instance of this class. */ + public static final N15 instance = new N15(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N16.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N16.java new file mode 100644 index 00000000000..37274638681 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N16.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 16. */ +public final class N16 extends Num implements Nat { + private N16() {} + + /** + * The integer this class represents. + * + * @return The literal number 16. + */ + @Override + public int getNum() { + return 16; + } + + /** The singleton instance of this class. */ + public static final N16 instance = new N16(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N17.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N17.java new file mode 100644 index 00000000000..e2968d7672b --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N17.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 17. */ +public final class N17 extends Num implements Nat { + private N17() {} + + /** + * The integer this class represents. + * + * @return The literal number 17. + */ + @Override + public int getNum() { + return 17; + } + + /** The singleton instance of this class. */ + public static final N17 instance = new N17(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N18.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N18.java new file mode 100644 index 00000000000..031089395ee --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N18.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 18. */ +public final class N18 extends Num implements Nat { + private N18() {} + + /** + * The integer this class represents. + * + * @return The literal number 18. + */ + @Override + public int getNum() { + return 18; + } + + /** The singleton instance of this class. */ + public static final N18 instance = new N18(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N19.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N19.java new file mode 100644 index 00000000000..8c5d48d0265 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N19.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 19. */ +public final class N19 extends Num implements Nat { + private N19() {} + + /** + * The integer this class represents. + * + * @return The literal number 19. + */ + @Override + public int getNum() { + return 19; + } + + /** The singleton instance of this class. */ + public static final N19 instance = new N19(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N2.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N2.java new file mode 100644 index 00000000000..27f32571355 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N2.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 2. */ +public final class N2 extends Num implements Nat { + private N2() {} + + /** + * The integer this class represents. + * + * @return The literal number 2. + */ + @Override + public int getNum() { + return 2; + } + + /** The singleton instance of this class. */ + public static final N2 instance = new N2(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N20.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N20.java new file mode 100644 index 00000000000..fefbfe6810b --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N20.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 20. */ +public final class N20 extends Num implements Nat { + private N20() {} + + /** + * The integer this class represents. + * + * @return The literal number 20. + */ + @Override + public int getNum() { + return 20; + } + + /** The singleton instance of this class. */ + public static final N20 instance = new N20(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N3.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N3.java new file mode 100644 index 00000000000..1e10c907b7b --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N3.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 3. */ +public final class N3 extends Num implements Nat { + private N3() {} + + /** + * The integer this class represents. + * + * @return The literal number 3. + */ + @Override + public int getNum() { + return 3; + } + + /** The singleton instance of this class. */ + public static final N3 instance = new N3(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N4.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N4.java new file mode 100644 index 00000000000..f7fe57e2757 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N4.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 4. */ +public final class N4 extends Num implements Nat { + private N4() {} + + /** + * The integer this class represents. + * + * @return The literal number 4. + */ + @Override + public int getNum() { + return 4; + } + + /** The singleton instance of this class. */ + public static final N4 instance = new N4(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N5.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N5.java new file mode 100644 index 00000000000..ec5deb504b8 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N5.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 5. */ +public final class N5 extends Num implements Nat { + private N5() {} + + /** + * The integer this class represents. + * + * @return The literal number 5. + */ + @Override + public int getNum() { + return 5; + } + + /** The singleton instance of this class. */ + public static final N5 instance = new N5(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N6.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N6.java new file mode 100644 index 00000000000..fe94f08c60a --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N6.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 6. */ +public final class N6 extends Num implements Nat { + private N6() {} + + /** + * The integer this class represents. + * + * @return The literal number 6. + */ + @Override + public int getNum() { + return 6; + } + + /** The singleton instance of this class. */ + public static final N6 instance = new N6(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N7.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N7.java new file mode 100644 index 00000000000..241c9925489 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N7.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 7. */ +public final class N7 extends Num implements Nat { + private N7() {} + + /** + * The integer this class represents. + * + * @return The literal number 7. + */ + @Override + public int getNum() { + return 7; + } + + /** The singleton instance of this class. */ + public static final N7 instance = new N7(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N8.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N8.java new file mode 100644 index 00000000000..4930b009753 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N8.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 8. */ +public final class N8 extends Num implements Nat { + private N8() {} + + /** + * The integer this class represents. + * + * @return The literal number 8. + */ + @Override + public int getNum() { + return 8; + } + + /** The singleton instance of this class. */ + public static final N8 instance = new N8(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N9.java b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N9.java new file mode 100644 index 00000000000..2c6e4eed952 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/numbers/N9.java @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +// THIS FILE WAS AUTO-GENERATED BY ./wpimath/generate_numbers.py. DO NOT MODIFY + +package edu.wpi.first.math.numbers; + +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; + +/** A class representing the number 9. */ +public final class N9 extends Num implements Nat { + private N9() {} + + /** + * The integer this class represents. + * + * @return The literal number 9. + */ + @Override + public int getNum() { + return 9; + } + + /** The singleton instance of this class. */ + public static final N9 instance = new N9(); +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Controller.java b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Controller.java new file mode 100644 index 00000000000..ed423da5831 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Controller.java @@ -0,0 +1,2309 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. +// Code generated by protocol buffer compiler. Do not edit! +package edu.wpi.first.math.proto; + +import java.io.IOException; +import us.hebi.quickbuf.Descriptors; +import us.hebi.quickbuf.FieldName; +import us.hebi.quickbuf.InvalidProtocolBufferException; +import us.hebi.quickbuf.JsonSink; +import us.hebi.quickbuf.JsonSource; +import us.hebi.quickbuf.MessageFactory; +import us.hebi.quickbuf.ProtoMessage; +import us.hebi.quickbuf.ProtoSink; +import us.hebi.quickbuf.ProtoSource; +import us.hebi.quickbuf.ProtoUtil; +import us.hebi.quickbuf.RepeatedByte; + +public final class Controller { + private static final RepeatedByte descriptorData = ProtoUtil.decodeBase64(1684, + "ChBjb250cm9sbGVyLnByb3RvEgl3cGkucHJvdG8iWAoWUHJvdG9idWZBcm1GZWVkZm9yd2FyZBIOCgJr" + + "cxgBIAEoAVICa3MSDgoCa2cYAiABKAFSAmtnEg4KAmt2GAMgASgBUgJrdhIOCgJrYRgEIAEoAVICa2Ei" + + "ngEKJFByb3RvYnVmRGlmZmVyZW50aWFsRHJpdmVGZWVkZm9yd2FyZBIbCglrdl9saW5lYXIYASABKAFS" + + "CGt2TGluZWFyEhsKCWthX2xpbmVhchgCIAEoAVIIa2FMaW5lYXISHQoKa3ZfYW5ndWxhchgDIAEoAVIJ" + + "a3ZBbmd1bGFyEh0KCmthX2FuZ3VsYXIYBCABKAFSCWthQW5ndWxhciJdChtQcm90b2J1ZkVsZXZhdG9y" + + "RmVlZGZvcndhcmQSDgoCa3MYASABKAFSAmtzEg4KAmtnGAIgASgBUgJrZxIOCgJrdhgDIAEoAVICa3YS" + + "DgoCa2EYBCABKAFSAmthIlAKHlByb3RvYnVmU2ltcGxlTW90b3JGZWVkZm9yd2FyZBIOCgJrcxgBIAEo" + + "AVICa3MSDgoCa3YYAiABKAFSAmt2Eg4KAmthGAMgASgBUgJrYSJSCiZQcm90b2J1ZkRpZmZlcmVudGlh" + + "bERyaXZlV2hlZWxWb2x0YWdlcxISCgRsZWZ0GAEgASgBUgRsZWZ0EhQKBXJpZ2h0GAIgASgBUgVyaWdo" + + "dEIaChhlZHUud3BpLmZpcnN0Lm1hdGgucHJvdG9K0AgKBhIEAAAkAQoICgEMEgMAABIKCAoBAhIDAgAS" + + "CggKAQgSAwQAMQoJCgIIARIDBAAxCgoKAgQAEgQGAAsBCgoKAwQAARIDBggeCgsKBAQAAgASAwcCEAoM" + + "CgUEAAIABRIDBwIICgwKBQQAAgABEgMHCQsKDAoFBAACAAMSAwcODwoLCgQEAAIBEgMIAhAKDAoFBAAC" + + "AQUSAwgCCAoMCgUEAAIBARIDCAkLCgwKBQQAAgEDEgMIDg8KCwoEBAACAhIDCQIQCgwKBQQAAgIFEgMJ" + + "AggKDAoFBAACAgESAwkJCwoMCgUEAAICAxIDCQ4PCgsKBAQAAgMSAwoCEAoMCgUEAAIDBRIDCgIICgwK" + + "BQQAAgMBEgMKCQsKDAoFBAACAwMSAwoODwoKCgIEARIEDQASAQoKCgMEAQESAw0ILAoLCgQEAQIAEgMO" + + "AhcKDAoFBAECAAUSAw4CCAoMCgUEAQIAARIDDgkSCgwKBQQBAgADEgMOFRYKCwoEBAECARIDDwIXCgwK" + + "BQQBAgEFEgMPAggKDAoFBAECAQESAw8JEgoMCgUEAQIBAxIDDxUWCgsKBAQBAgISAxACGAoMCgUEAQIC" + + "BRIDEAIICgwKBQQBAgIBEgMQCRMKDAoFBAECAgMSAxAWFwoLCgQEAQIDEgMRAhgKDAoFBAECAwUSAxEC" + + "CAoMCgUEAQIDARIDEQkTCgwKBQQBAgMDEgMRFhcKCgoCBAISBBQAGQEKCgoDBAIBEgMUCCMKCwoEBAIC" + + "ABIDFQIQCgwKBQQCAgAFEgMVAggKDAoFBAICAAESAxUJCwoMCgUEAgIAAxIDFQ4PCgsKBAQCAgESAxYC", + "EAoMCgUEAgIBBRIDFgIICgwKBQQCAgEBEgMWCQsKDAoFBAICAQMSAxYODwoLCgQEAgICEgMXAhAKDAoF" + + "BAICAgUSAxcCCAoMCgUEAgICARIDFwkLCgwKBQQCAgIDEgMXDg8KCwoEBAICAxIDGAIQCgwKBQQCAgMF" + + "EgMYAggKDAoFBAICAwESAxgJCwoMCgUEAgIDAxIDGA4PCgoKAgQDEgQbAB8BCgoKAwQDARIDGwgmCgsK" + + "BAQDAgASAxwCEAoMCgUEAwIABRIDHAIICgwKBQQDAgABEgMcCQsKDAoFBAMCAAMSAxwODwoLCgQEAwIB" + + "EgMdAhAKDAoFBAMCAQUSAx0CCAoMCgUEAwIBARIDHQkLCgwKBQQDAgEDEgMdDg8KCwoEBAMCAhIDHgIQ" + + "CgwKBQQDAgIFEgMeAggKDAoFBAMCAgESAx4JCwoMCgUEAwICAxIDHg4PCgoKAgQEEgQhACQBCgoKAwQE" + + "ARIDIQguCgsKBAQEAgASAyICEgoMCgUEBAIABRIDIgIICgwKBQQEAgABEgMiCQ0KDAoFBAQCAAMSAyIQ" + + "EQoLCgQEBAIBEgMjAhMKDAoFBAQCAQUSAyMCCAoMCgUEBAIBARIDIwkOCgwKBQQEAgEDEgMjERJiBnBy" + + "b3RvMw=="); + + static final Descriptors.FileDescriptor descriptor = Descriptors.FileDescriptor.internalBuildGeneratedFileFrom("controller.proto", "wpi.proto", descriptorData); + + static final Descriptors.Descriptor wpi_proto_ProtobufArmFeedforward_descriptor = descriptor.internalContainedType(31, 88, "ProtobufArmFeedforward", "wpi.proto.ProtobufArmFeedforward"); + + static final Descriptors.Descriptor wpi_proto_ProtobufDifferentialDriveFeedforward_descriptor = descriptor.internalContainedType(122, 158, "ProtobufDifferentialDriveFeedforward", "wpi.proto.ProtobufDifferentialDriveFeedforward"); + + static final Descriptors.Descriptor wpi_proto_ProtobufElevatorFeedforward_descriptor = descriptor.internalContainedType(282, 93, "ProtobufElevatorFeedforward", "wpi.proto.ProtobufElevatorFeedforward"); + + static final Descriptors.Descriptor wpi_proto_ProtobufSimpleMotorFeedforward_descriptor = descriptor.internalContainedType(377, 80, "ProtobufSimpleMotorFeedforward", "wpi.proto.ProtobufSimpleMotorFeedforward"); + + static final Descriptors.Descriptor wpi_proto_ProtobufDifferentialDriveWheelVoltages_descriptor = descriptor.internalContainedType(459, 82, "ProtobufDifferentialDriveWheelVoltages", "wpi.proto.ProtobufDifferentialDriveWheelVoltages"); + + /** + * @return this proto file's descriptor. + */ + public static Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + /** + * Protobuf type {@code ProtobufArmFeedforward} + */ + public static final class ProtobufArmFeedforward extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double ks = 1; + */ + private double ks; + + /** + * optional double kg = 2; + */ + private double kg; + + /** + * optional double kv = 3; + */ + private double kv; + + /** + * optional double ka = 4; + */ + private double ka; + + private ProtobufArmFeedforward() { + } + + /** + * @return a new empty instance of {@code ProtobufArmFeedforward} + */ + public static ProtobufArmFeedforward newInstance() { + return new ProtobufArmFeedforward(); + } + + /** + * optional double ks = 1; + * @return whether the ks field is set + */ + public boolean hasKs() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double ks = 1; + * @return this + */ + public ProtobufArmFeedforward clearKs() { + bitField0_ &= ~0x00000001; + ks = 0D; + return this; + } + + /** + * optional double ks = 1; + * @return the ks + */ + public double getKs() { + return ks; + } + + /** + * optional double ks = 1; + * @param value the ks to set + * @return this + */ + public ProtobufArmFeedforward setKs(final double value) { + bitField0_ |= 0x00000001; + ks = value; + return this; + } + + /** + * optional double kg = 2; + * @return whether the kg field is set + */ + public boolean hasKg() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double kg = 2; + * @return this + */ + public ProtobufArmFeedforward clearKg() { + bitField0_ &= ~0x00000002; + kg = 0D; + return this; + } + + /** + * optional double kg = 2; + * @return the kg + */ + public double getKg() { + return kg; + } + + /** + * optional double kg = 2; + * @param value the kg to set + * @return this + */ + public ProtobufArmFeedforward setKg(final double value) { + bitField0_ |= 0x00000002; + kg = value; + return this; + } + + /** + * optional double kv = 3; + * @return whether the kv field is set + */ + public boolean hasKv() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double kv = 3; + * @return this + */ + public ProtobufArmFeedforward clearKv() { + bitField0_ &= ~0x00000004; + kv = 0D; + return this; + } + + /** + * optional double kv = 3; + * @return the kv + */ + public double getKv() { + return kv; + } + + /** + * optional double kv = 3; + * @param value the kv to set + * @return this + */ + public ProtobufArmFeedforward setKv(final double value) { + bitField0_ |= 0x00000004; + kv = value; + return this; + } + + /** + * optional double ka = 4; + * @return whether the ka field is set + */ + public boolean hasKa() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * optional double ka = 4; + * @return this + */ + public ProtobufArmFeedforward clearKa() { + bitField0_ &= ~0x00000008; + ka = 0D; + return this; + } + + /** + * optional double ka = 4; + * @return the ka + */ + public double getKa() { + return ka; + } + + /** + * optional double ka = 4; + * @param value the ka to set + * @return this + */ + public ProtobufArmFeedforward setKa(final double value) { + bitField0_ |= 0x00000008; + ka = value; + return this; + } + + @Override + public ProtobufArmFeedforward copyFrom(final ProtobufArmFeedforward other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + ks = other.ks; + kg = other.kg; + kv = other.kv; + ka = other.ka; + } + return this; + } + + @Override + public ProtobufArmFeedforward mergeFrom(final ProtobufArmFeedforward other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasKs()) { + setKs(other.ks); + } + if (other.hasKg()) { + setKg(other.kg); + } + if (other.hasKv()) { + setKv(other.kv); + } + if (other.hasKa()) { + setKa(other.ka); + } + return this; + } + + @Override + public ProtobufArmFeedforward clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + ks = 0D; + kg = 0D; + kv = 0D; + ka = 0D; + return this; + } + + @Override + public ProtobufArmFeedforward clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufArmFeedforward)) { + return false; + } + ProtobufArmFeedforward other = (ProtobufArmFeedforward) o; + return bitField0_ == other.bitField0_ + && (!hasKs() || ProtoUtil.isEqual(ks, other.ks)) + && (!hasKg() || ProtoUtil.isEqual(kg, other.kg)) + && (!hasKv() || ProtoUtil.isEqual(kv, other.kv)) + && (!hasKa() || ProtoUtil.isEqual(ka, other.ka)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(ks); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(kg); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(kv); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRawByte((byte) 33); + output.writeDoubleNoTag(ka); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000008) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufArmFeedforward mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // ks + ks = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // kg + kg = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // kv + kv = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 33) { + break; + } + } + case 33: { + // ka + ka = input.readDouble(); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.ks, ks); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.kg, kg); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.kv, kv); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeDouble(FieldNames.ka, ka); + } + output.endObject(); + } + + @Override + public ProtobufArmFeedforward mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 3432: { + if (input.isAtField(FieldNames.ks)) { + if (!input.trySkipNullValue()) { + ks = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3420: { + if (input.isAtField(FieldNames.kg)) { + if (!input.trySkipNullValue()) { + kg = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3435: { + if (input.isAtField(FieldNames.kv)) { + if (!input.trySkipNullValue()) { + kv = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3414: { + if (input.isAtField(FieldNames.ka)) { + if (!input.trySkipNullValue()) { + ka = input.readDouble(); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufArmFeedforward clone() { + return new ProtobufArmFeedforward().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufArmFeedforward parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufArmFeedforward(), data).checkInitialized(); + } + + public static ProtobufArmFeedforward parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufArmFeedforward(), input).checkInitialized(); + } + + public static ProtobufArmFeedforward parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufArmFeedforward(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufArmFeedforward messages + */ + public static MessageFactory getFactory() { + return ProtobufArmFeedforwardFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Controller.wpi_proto_ProtobufArmFeedforward_descriptor; + } + + private enum ProtobufArmFeedforwardFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufArmFeedforward create() { + return ProtobufArmFeedforward.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName ks = FieldName.forField("ks"); + + static final FieldName kg = FieldName.forField("kg"); + + static final FieldName kv = FieldName.forField("kv"); + + static final FieldName ka = FieldName.forField("ka"); + } + } + + /** + * Protobuf type {@code ProtobufDifferentialDriveFeedforward} + */ + public static final class ProtobufDifferentialDriveFeedforward extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double kv_linear = 1; + */ + private double kvLinear; + + /** + * optional double ka_linear = 2; + */ + private double kaLinear; + + /** + * optional double kv_angular = 3; + */ + private double kvAngular; + + /** + * optional double ka_angular = 4; + */ + private double kaAngular; + + private ProtobufDifferentialDriveFeedforward() { + } + + /** + * @return a new empty instance of {@code ProtobufDifferentialDriveFeedforward} + */ + public static ProtobufDifferentialDriveFeedforward newInstance() { + return new ProtobufDifferentialDriveFeedforward(); + } + + /** + * optional double kv_linear = 1; + * @return whether the kvLinear field is set + */ + public boolean hasKvLinear() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double kv_linear = 1; + * @return this + */ + public ProtobufDifferentialDriveFeedforward clearKvLinear() { + bitField0_ &= ~0x00000001; + kvLinear = 0D; + return this; + } + + /** + * optional double kv_linear = 1; + * @return the kvLinear + */ + public double getKvLinear() { + return kvLinear; + } + + /** + * optional double kv_linear = 1; + * @param value the kvLinear to set + * @return this + */ + public ProtobufDifferentialDriveFeedforward setKvLinear(final double value) { + bitField0_ |= 0x00000001; + kvLinear = value; + return this; + } + + /** + * optional double ka_linear = 2; + * @return whether the kaLinear field is set + */ + public boolean hasKaLinear() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double ka_linear = 2; + * @return this + */ + public ProtobufDifferentialDriveFeedforward clearKaLinear() { + bitField0_ &= ~0x00000002; + kaLinear = 0D; + return this; + } + + /** + * optional double ka_linear = 2; + * @return the kaLinear + */ + public double getKaLinear() { + return kaLinear; + } + + /** + * optional double ka_linear = 2; + * @param value the kaLinear to set + * @return this + */ + public ProtobufDifferentialDriveFeedforward setKaLinear(final double value) { + bitField0_ |= 0x00000002; + kaLinear = value; + return this; + } + + /** + * optional double kv_angular = 3; + * @return whether the kvAngular field is set + */ + public boolean hasKvAngular() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double kv_angular = 3; + * @return this + */ + public ProtobufDifferentialDriveFeedforward clearKvAngular() { + bitField0_ &= ~0x00000004; + kvAngular = 0D; + return this; + } + + /** + * optional double kv_angular = 3; + * @return the kvAngular + */ + public double getKvAngular() { + return kvAngular; + } + + /** + * optional double kv_angular = 3; + * @param value the kvAngular to set + * @return this + */ + public ProtobufDifferentialDriveFeedforward setKvAngular(final double value) { + bitField0_ |= 0x00000004; + kvAngular = value; + return this; + } + + /** + * optional double ka_angular = 4; + * @return whether the kaAngular field is set + */ + public boolean hasKaAngular() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * optional double ka_angular = 4; + * @return this + */ + public ProtobufDifferentialDriveFeedforward clearKaAngular() { + bitField0_ &= ~0x00000008; + kaAngular = 0D; + return this; + } + + /** + * optional double ka_angular = 4; + * @return the kaAngular + */ + public double getKaAngular() { + return kaAngular; + } + + /** + * optional double ka_angular = 4; + * @param value the kaAngular to set + * @return this + */ + public ProtobufDifferentialDriveFeedforward setKaAngular(final double value) { + bitField0_ |= 0x00000008; + kaAngular = value; + return this; + } + + @Override + public ProtobufDifferentialDriveFeedforward copyFrom( + final ProtobufDifferentialDriveFeedforward other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + kvLinear = other.kvLinear; + kaLinear = other.kaLinear; + kvAngular = other.kvAngular; + kaAngular = other.kaAngular; + } + return this; + } + + @Override + public ProtobufDifferentialDriveFeedforward mergeFrom( + final ProtobufDifferentialDriveFeedforward other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasKvLinear()) { + setKvLinear(other.kvLinear); + } + if (other.hasKaLinear()) { + setKaLinear(other.kaLinear); + } + if (other.hasKvAngular()) { + setKvAngular(other.kvAngular); + } + if (other.hasKaAngular()) { + setKaAngular(other.kaAngular); + } + return this; + } + + @Override + public ProtobufDifferentialDriveFeedforward clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + kvLinear = 0D; + kaLinear = 0D; + kvAngular = 0D; + kaAngular = 0D; + return this; + } + + @Override + public ProtobufDifferentialDriveFeedforward clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufDifferentialDriveFeedforward)) { + return false; + } + ProtobufDifferentialDriveFeedforward other = (ProtobufDifferentialDriveFeedforward) o; + return bitField0_ == other.bitField0_ + && (!hasKvLinear() || ProtoUtil.isEqual(kvLinear, other.kvLinear)) + && (!hasKaLinear() || ProtoUtil.isEqual(kaLinear, other.kaLinear)) + && (!hasKvAngular() || ProtoUtil.isEqual(kvAngular, other.kvAngular)) + && (!hasKaAngular() || ProtoUtil.isEqual(kaAngular, other.kaAngular)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(kvLinear); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(kaLinear); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(kvAngular); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRawByte((byte) 33); + output.writeDoubleNoTag(kaAngular); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000008) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufDifferentialDriveFeedforward mergeFrom(final ProtoSource input) throws + IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // kvLinear + kvLinear = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // kaLinear + kaLinear = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // kvAngular + kvAngular = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 33) { + break; + } + } + case 33: { + // kaAngular + kaAngular = input.readDouble(); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.kvLinear, kvLinear); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.kaLinear, kaLinear); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.kvAngular, kvAngular); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeDouble(FieldNames.kaAngular, kaAngular); + } + output.endObject(); + } + + @Override + public ProtobufDifferentialDriveFeedforward mergeFrom(final JsonSource input) throws + IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 1424526448: + case 974889081: { + if (input.isAtField(FieldNames.kvLinear)) { + if (!input.trySkipNullValue()) { + kvLinear = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case -33181669: + case -1264389586: { + if (input.isAtField(FieldNames.kaLinear)) { + if (!input.trySkipNullValue()) { + kaLinear = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case 175208951: + case -878647538: { + if (input.isAtField(FieldNames.kvAngular)) { + if (!input.trySkipNullValue()) { + kvAngular = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case -2064069716: + case -1576809479: { + if (input.isAtField(FieldNames.kaAngular)) { + if (!input.trySkipNullValue()) { + kaAngular = input.readDouble(); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufDifferentialDriveFeedforward clone() { + return new ProtobufDifferentialDriveFeedforward().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufDifferentialDriveFeedforward parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveFeedforward(), data).checkInitialized(); + } + + public static ProtobufDifferentialDriveFeedforward parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveFeedforward(), input).checkInitialized(); + } + + public static ProtobufDifferentialDriveFeedforward parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveFeedforward(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufDifferentialDriveFeedforward messages + */ + public static MessageFactory getFactory() { + return ProtobufDifferentialDriveFeedforwardFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Controller.wpi_proto_ProtobufDifferentialDriveFeedforward_descriptor; + } + + private enum ProtobufDifferentialDriveFeedforwardFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufDifferentialDriveFeedforward create() { + return ProtobufDifferentialDriveFeedforward.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName kvLinear = FieldName.forField("kvLinear", "kv_linear"); + + static final FieldName kaLinear = FieldName.forField("kaLinear", "ka_linear"); + + static final FieldName kvAngular = FieldName.forField("kvAngular", "kv_angular"); + + static final FieldName kaAngular = FieldName.forField("kaAngular", "ka_angular"); + } + } + + /** + * Protobuf type {@code ProtobufElevatorFeedforward} + */ + public static final class ProtobufElevatorFeedforward extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double ks = 1; + */ + private double ks; + + /** + * optional double kg = 2; + */ + private double kg; + + /** + * optional double kv = 3; + */ + private double kv; + + /** + * optional double ka = 4; + */ + private double ka; + + private ProtobufElevatorFeedforward() { + } + + /** + * @return a new empty instance of {@code ProtobufElevatorFeedforward} + */ + public static ProtobufElevatorFeedforward newInstance() { + return new ProtobufElevatorFeedforward(); + } + + /** + * optional double ks = 1; + * @return whether the ks field is set + */ + public boolean hasKs() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double ks = 1; + * @return this + */ + public ProtobufElevatorFeedforward clearKs() { + bitField0_ &= ~0x00000001; + ks = 0D; + return this; + } + + /** + * optional double ks = 1; + * @return the ks + */ + public double getKs() { + return ks; + } + + /** + * optional double ks = 1; + * @param value the ks to set + * @return this + */ + public ProtobufElevatorFeedforward setKs(final double value) { + bitField0_ |= 0x00000001; + ks = value; + return this; + } + + /** + * optional double kg = 2; + * @return whether the kg field is set + */ + public boolean hasKg() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double kg = 2; + * @return this + */ + public ProtobufElevatorFeedforward clearKg() { + bitField0_ &= ~0x00000002; + kg = 0D; + return this; + } + + /** + * optional double kg = 2; + * @return the kg + */ + public double getKg() { + return kg; + } + + /** + * optional double kg = 2; + * @param value the kg to set + * @return this + */ + public ProtobufElevatorFeedforward setKg(final double value) { + bitField0_ |= 0x00000002; + kg = value; + return this; + } + + /** + * optional double kv = 3; + * @return whether the kv field is set + */ + public boolean hasKv() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double kv = 3; + * @return this + */ + public ProtobufElevatorFeedforward clearKv() { + bitField0_ &= ~0x00000004; + kv = 0D; + return this; + } + + /** + * optional double kv = 3; + * @return the kv + */ + public double getKv() { + return kv; + } + + /** + * optional double kv = 3; + * @param value the kv to set + * @return this + */ + public ProtobufElevatorFeedforward setKv(final double value) { + bitField0_ |= 0x00000004; + kv = value; + return this; + } + + /** + * optional double ka = 4; + * @return whether the ka field is set + */ + public boolean hasKa() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * optional double ka = 4; + * @return this + */ + public ProtobufElevatorFeedforward clearKa() { + bitField0_ &= ~0x00000008; + ka = 0D; + return this; + } + + /** + * optional double ka = 4; + * @return the ka + */ + public double getKa() { + return ka; + } + + /** + * optional double ka = 4; + * @param value the ka to set + * @return this + */ + public ProtobufElevatorFeedforward setKa(final double value) { + bitField0_ |= 0x00000008; + ka = value; + return this; + } + + @Override + public ProtobufElevatorFeedforward copyFrom(final ProtobufElevatorFeedforward other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + ks = other.ks; + kg = other.kg; + kv = other.kv; + ka = other.ka; + } + return this; + } + + @Override + public ProtobufElevatorFeedforward mergeFrom(final ProtobufElevatorFeedforward other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasKs()) { + setKs(other.ks); + } + if (other.hasKg()) { + setKg(other.kg); + } + if (other.hasKv()) { + setKv(other.kv); + } + if (other.hasKa()) { + setKa(other.ka); + } + return this; + } + + @Override + public ProtobufElevatorFeedforward clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + ks = 0D; + kg = 0D; + kv = 0D; + ka = 0D; + return this; + } + + @Override + public ProtobufElevatorFeedforward clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufElevatorFeedforward)) { + return false; + } + ProtobufElevatorFeedforward other = (ProtobufElevatorFeedforward) o; + return bitField0_ == other.bitField0_ + && (!hasKs() || ProtoUtil.isEqual(ks, other.ks)) + && (!hasKg() || ProtoUtil.isEqual(kg, other.kg)) + && (!hasKv() || ProtoUtil.isEqual(kv, other.kv)) + && (!hasKa() || ProtoUtil.isEqual(ka, other.ka)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(ks); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(kg); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(kv); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRawByte((byte) 33); + output.writeDoubleNoTag(ka); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000008) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufElevatorFeedforward mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // ks + ks = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // kg + kg = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // kv + kv = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 33) { + break; + } + } + case 33: { + // ka + ka = input.readDouble(); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.ks, ks); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.kg, kg); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.kv, kv); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeDouble(FieldNames.ka, ka); + } + output.endObject(); + } + + @Override + public ProtobufElevatorFeedforward mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 3432: { + if (input.isAtField(FieldNames.ks)) { + if (!input.trySkipNullValue()) { + ks = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3420: { + if (input.isAtField(FieldNames.kg)) { + if (!input.trySkipNullValue()) { + kg = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3435: { + if (input.isAtField(FieldNames.kv)) { + if (!input.trySkipNullValue()) { + kv = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3414: { + if (input.isAtField(FieldNames.ka)) { + if (!input.trySkipNullValue()) { + ka = input.readDouble(); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufElevatorFeedforward clone() { + return new ProtobufElevatorFeedforward().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufElevatorFeedforward parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufElevatorFeedforward(), data).checkInitialized(); + } + + public static ProtobufElevatorFeedforward parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufElevatorFeedforward(), input).checkInitialized(); + } + + public static ProtobufElevatorFeedforward parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufElevatorFeedforward(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufElevatorFeedforward messages + */ + public static MessageFactory getFactory() { + return ProtobufElevatorFeedforwardFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Controller.wpi_proto_ProtobufElevatorFeedforward_descriptor; + } + + private enum ProtobufElevatorFeedforwardFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufElevatorFeedforward create() { + return ProtobufElevatorFeedforward.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName ks = FieldName.forField("ks"); + + static final FieldName kg = FieldName.forField("kg"); + + static final FieldName kv = FieldName.forField("kv"); + + static final FieldName ka = FieldName.forField("ka"); + } + } + + /** + * Protobuf type {@code ProtobufSimpleMotorFeedforward} + */ + public static final class ProtobufSimpleMotorFeedforward extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double ks = 1; + */ + private double ks; + + /** + * optional double kv = 2; + */ + private double kv; + + /** + * optional double ka = 3; + */ + private double ka; + + private ProtobufSimpleMotorFeedforward() { + } + + /** + * @return a new empty instance of {@code ProtobufSimpleMotorFeedforward} + */ + public static ProtobufSimpleMotorFeedforward newInstance() { + return new ProtobufSimpleMotorFeedforward(); + } + + /** + * optional double ks = 1; + * @return whether the ks field is set + */ + public boolean hasKs() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double ks = 1; + * @return this + */ + public ProtobufSimpleMotorFeedforward clearKs() { + bitField0_ &= ~0x00000001; + ks = 0D; + return this; + } + + /** + * optional double ks = 1; + * @return the ks + */ + public double getKs() { + return ks; + } + + /** + * optional double ks = 1; + * @param value the ks to set + * @return this + */ + public ProtobufSimpleMotorFeedforward setKs(final double value) { + bitField0_ |= 0x00000001; + ks = value; + return this; + } + + /** + * optional double kv = 2; + * @return whether the kv field is set + */ + public boolean hasKv() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double kv = 2; + * @return this + */ + public ProtobufSimpleMotorFeedforward clearKv() { + bitField0_ &= ~0x00000002; + kv = 0D; + return this; + } + + /** + * optional double kv = 2; + * @return the kv + */ + public double getKv() { + return kv; + } + + /** + * optional double kv = 2; + * @param value the kv to set + * @return this + */ + public ProtobufSimpleMotorFeedforward setKv(final double value) { + bitField0_ |= 0x00000002; + kv = value; + return this; + } + + /** + * optional double ka = 3; + * @return whether the ka field is set + */ + public boolean hasKa() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double ka = 3; + * @return this + */ + public ProtobufSimpleMotorFeedforward clearKa() { + bitField0_ &= ~0x00000004; + ka = 0D; + return this; + } + + /** + * optional double ka = 3; + * @return the ka + */ + public double getKa() { + return ka; + } + + /** + * optional double ka = 3; + * @param value the ka to set + * @return this + */ + public ProtobufSimpleMotorFeedforward setKa(final double value) { + bitField0_ |= 0x00000004; + ka = value; + return this; + } + + @Override + public ProtobufSimpleMotorFeedforward copyFrom(final ProtobufSimpleMotorFeedforward other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + ks = other.ks; + kv = other.kv; + ka = other.ka; + } + return this; + } + + @Override + public ProtobufSimpleMotorFeedforward mergeFrom(final ProtobufSimpleMotorFeedforward other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasKs()) { + setKs(other.ks); + } + if (other.hasKv()) { + setKv(other.kv); + } + if (other.hasKa()) { + setKa(other.ka); + } + return this; + } + + @Override + public ProtobufSimpleMotorFeedforward clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + ks = 0D; + kv = 0D; + ka = 0D; + return this; + } + + @Override + public ProtobufSimpleMotorFeedforward clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufSimpleMotorFeedforward)) { + return false; + } + ProtobufSimpleMotorFeedforward other = (ProtobufSimpleMotorFeedforward) o; + return bitField0_ == other.bitField0_ + && (!hasKs() || ProtoUtil.isEqual(ks, other.ks)) + && (!hasKv() || ProtoUtil.isEqual(kv, other.kv)) + && (!hasKa() || ProtoUtil.isEqual(ka, other.ka)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(ks); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(kv); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(ka); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufSimpleMotorFeedforward mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // ks + ks = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // kv + kv = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // ka + ka = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.ks, ks); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.kv, kv); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.ka, ka); + } + output.endObject(); + } + + @Override + public ProtobufSimpleMotorFeedforward mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 3432: { + if (input.isAtField(FieldNames.ks)) { + if (!input.trySkipNullValue()) { + ks = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3435: { + if (input.isAtField(FieldNames.kv)) { + if (!input.trySkipNullValue()) { + kv = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3414: { + if (input.isAtField(FieldNames.ka)) { + if (!input.trySkipNullValue()) { + ka = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufSimpleMotorFeedforward clone() { + return new ProtobufSimpleMotorFeedforward().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufSimpleMotorFeedforward parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufSimpleMotorFeedforward(), data).checkInitialized(); + } + + public static ProtobufSimpleMotorFeedforward parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufSimpleMotorFeedforward(), input).checkInitialized(); + } + + public static ProtobufSimpleMotorFeedforward parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufSimpleMotorFeedforward(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufSimpleMotorFeedforward messages + */ + public static MessageFactory getFactory() { + return ProtobufSimpleMotorFeedforwardFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Controller.wpi_proto_ProtobufSimpleMotorFeedforward_descriptor; + } + + private enum ProtobufSimpleMotorFeedforwardFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufSimpleMotorFeedforward create() { + return ProtobufSimpleMotorFeedforward.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName ks = FieldName.forField("ks"); + + static final FieldName kv = FieldName.forField("kv"); + + static final FieldName ka = FieldName.forField("ka"); + } + } + + /** + * Protobuf type {@code ProtobufDifferentialDriveWheelVoltages} + */ + public static final class ProtobufDifferentialDriveWheelVoltages extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double left = 1; + */ + private double left; + + /** + * optional double right = 2; + */ + private double right; + + private ProtobufDifferentialDriveWheelVoltages() { + } + + /** + * @return a new empty instance of {@code ProtobufDifferentialDriveWheelVoltages} + */ + public static ProtobufDifferentialDriveWheelVoltages newInstance() { + return new ProtobufDifferentialDriveWheelVoltages(); + } + + /** + * optional double left = 1; + * @return whether the left field is set + */ + public boolean hasLeft() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double left = 1; + * @return this + */ + public ProtobufDifferentialDriveWheelVoltages clearLeft() { + bitField0_ &= ~0x00000001; + left = 0D; + return this; + } + + /** + * optional double left = 1; + * @return the left + */ + public double getLeft() { + return left; + } + + /** + * optional double left = 1; + * @param value the left to set + * @return this + */ + public ProtobufDifferentialDriveWheelVoltages setLeft(final double value) { + bitField0_ |= 0x00000001; + left = value; + return this; + } + + /** + * optional double right = 2; + * @return whether the right field is set + */ + public boolean hasRight() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double right = 2; + * @return this + */ + public ProtobufDifferentialDriveWheelVoltages clearRight() { + bitField0_ &= ~0x00000002; + right = 0D; + return this; + } + + /** + * optional double right = 2; + * @return the right + */ + public double getRight() { + return right; + } + + /** + * optional double right = 2; + * @param value the right to set + * @return this + */ + public ProtobufDifferentialDriveWheelVoltages setRight(final double value) { + bitField0_ |= 0x00000002; + right = value; + return this; + } + + @Override + public ProtobufDifferentialDriveWheelVoltages copyFrom( + final ProtobufDifferentialDriveWheelVoltages other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + left = other.left; + right = other.right; + } + return this; + } + + @Override + public ProtobufDifferentialDriveWheelVoltages mergeFrom( + final ProtobufDifferentialDriveWheelVoltages other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasLeft()) { + setLeft(other.left); + } + if (other.hasRight()) { + setRight(other.right); + } + return this; + } + + @Override + public ProtobufDifferentialDriveWheelVoltages clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + left = 0D; + right = 0D; + return this; + } + + @Override + public ProtobufDifferentialDriveWheelVoltages clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufDifferentialDriveWheelVoltages)) { + return false; + } + ProtobufDifferentialDriveWheelVoltages other = (ProtobufDifferentialDriveWheelVoltages) o; + return bitField0_ == other.bitField0_ + && (!hasLeft() || ProtoUtil.isEqual(left, other.left)) + && (!hasRight() || ProtoUtil.isEqual(right, other.right)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(left); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(right); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufDifferentialDriveWheelVoltages mergeFrom(final ProtoSource input) throws + IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // left + left = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // right + right = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.left, left); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.right, right); + } + output.endObject(); + } + + @Override + public ProtobufDifferentialDriveWheelVoltages mergeFrom(final JsonSource input) throws + IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 3317767: { + if (input.isAtField(FieldNames.left)) { + if (!input.trySkipNullValue()) { + left = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 108511772: { + if (input.isAtField(FieldNames.right)) { + if (!input.trySkipNullValue()) { + right = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufDifferentialDriveWheelVoltages clone() { + return new ProtobufDifferentialDriveWheelVoltages().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufDifferentialDriveWheelVoltages parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveWheelVoltages(), data).checkInitialized(); + } + + public static ProtobufDifferentialDriveWheelVoltages parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveWheelVoltages(), input).checkInitialized(); + } + + public static ProtobufDifferentialDriveWheelVoltages parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveWheelVoltages(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufDifferentialDriveWheelVoltages messages + */ + public static MessageFactory getFactory() { + return ProtobufDifferentialDriveWheelVoltagesFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Controller.wpi_proto_ProtobufDifferentialDriveWheelVoltages_descriptor; + } + + private enum ProtobufDifferentialDriveWheelVoltagesFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufDifferentialDriveWheelVoltages create() { + return ProtobufDifferentialDriveWheelVoltages.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName left = FieldName.forField("left"); + + static final FieldName right = FieldName.forField("right"); + } + } +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Geometry2D.java b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Geometry2D.java new file mode 100644 index 00000000000..331ccd1c8ad --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Geometry2D.java @@ -0,0 +1,1806 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. +// Code generated by protocol buffer compiler. Do not edit! +package edu.wpi.first.math.proto; + +import java.io.IOException; +import us.hebi.quickbuf.Descriptors; +import us.hebi.quickbuf.FieldName; +import us.hebi.quickbuf.InvalidProtocolBufferException; +import us.hebi.quickbuf.JsonSink; +import us.hebi.quickbuf.JsonSource; +import us.hebi.quickbuf.MessageFactory; +import us.hebi.quickbuf.ProtoMessage; +import us.hebi.quickbuf.ProtoSink; +import us.hebi.quickbuf.ProtoSource; +import us.hebi.quickbuf.ProtoUtil; +import us.hebi.quickbuf.RepeatedByte; + +public final class Geometry2D { + private static final RepeatedByte descriptorData = ProtoUtil.decodeBase64(1256, + "ChBnZW9tZXRyeTJkLnByb3RvEgl3cGkucHJvdG8iMwoVUHJvdG9idWZUcmFuc2xhdGlvbjJkEgwKAXgY" + + "ASABKAFSAXgSDAoBeRgCIAEoAVIBeSIqChJQcm90b2J1ZlJvdGF0aW9uMmQSFAoFdmFsdWUYASABKAFS" + + "BXZhbHVlIo8BCg5Qcm90b2J1ZlBvc2UyZBJCCgt0cmFuc2xhdGlvbhgBIAEoCzIgLndwaS5wcm90by5Q" + + "cm90b2J1ZlRyYW5zbGF0aW9uMmRSC3RyYW5zbGF0aW9uEjkKCHJvdGF0aW9uGAIgASgLMh0ud3BpLnBy" + + "b3RvLlByb3RvYnVmUm90YXRpb24yZFIIcm90YXRpb24ilAEKE1Byb3RvYnVmVHJhbnNmb3JtMmQSQgoL" + + "dHJhbnNsYXRpb24YASABKAsyIC53cGkucHJvdG8uUHJvdG9idWZUcmFuc2xhdGlvbjJkUgt0cmFuc2xh" + + "dGlvbhI5Cghyb3RhdGlvbhgCIAEoCzIdLndwaS5wcm90by5Qcm90b2J1ZlJvdGF0aW9uMmRSCHJvdGF0" + + "aW9uIkkKD1Byb3RvYnVmVHdpc3QyZBIOCgJkeBgBIAEoAVICZHgSDgoCZHkYAiABKAFSAmR5EhYKBmR0" + + "aGV0YRgDIAEoAVIGZHRoZXRhQhoKGGVkdS53cGkuZmlyc3QubWF0aC5wcm90b0rPBQoGEgQAAB0BCggK" + + "AQwSAwAAEgoICgECEgMCABIKCAoBCBIDBAAxCgkKAggBEgMEADEKCgoCBAASBAYACQEKCgoDBAABEgMG" + + "CB0KCwoEBAACABIDBwIPCgwKBQQAAgAFEgMHAggKDAoFBAACAAESAwcJCgoMCgUEAAIAAxIDBw0OCgsK" + + "BAQAAgESAwgCDwoMCgUEAAIBBRIDCAIICgwKBQQAAgEBEgMICQoKDAoFBAACAQMSAwgNDgoKCgIEARIE" + + "CwANAQoKCgMEAQESAwsIGgoLCgQEAQIAEgMMAhMKDAoFBAECAAUSAwwCCAoMCgUEAQIAARIDDAkOCgwK" + + "BQQBAgADEgMMERIKCgoCBAISBA8AEgEKCgoDBAIBEgMPCBYKCwoEBAICABIDEAIoCgwKBQQCAgAGEgMQ" + + "AhcKDAoFBAICAAESAxAYIwoMCgUEAgIAAxIDECYnCgsKBAQCAgESAxECIgoMCgUEAgIBBhIDEQIUCgwK" + + "BQQCAgEBEgMRFR0KDAoFBAICAQMSAxEgIQoKCgIEAxIEFAAXAQoKCgMEAwESAxQIGwoLCgQEAwIAEgMV" + + "AigKDAoFBAMCAAYSAxUCFwoMCgUEAwIAARIDFRgjCgwKBQQDAgADEgMVJicKCwoEBAMCARIDFgIiCgwK" + + "BQQDAgEGEgMWAhQKDAoFBAMCAQESAxYVHQoMCgUEAwIBAxIDFiAhCgoKAgQEEgQZAB0BCgoKAwQEARID" + + "GQgXCgsKBAQEAgASAxoCEAoMCgUEBAIABRIDGgIICgwKBQQEAgABEgMaCQsKDAoFBAQCAAMSAxoODwoL" + + "CgQEBAIBEgMbAhAKDAoFBAQCAQUSAxsCCAoMCgUEBAIBARIDGwkLCgwKBQQEAgEDEgMbDg8KCwoEBAQC", + "AhIDHAIUCgwKBQQEAgIFEgMcAggKDAoFBAQCAgESAxwJDwoMCgUEBAICAxIDHBITYgZwcm90bzM="); + + static final Descriptors.FileDescriptor descriptor = Descriptors.FileDescriptor.internalBuildGeneratedFileFrom("geometry2d.proto", "wpi.proto", descriptorData); + + static final Descriptors.Descriptor wpi_proto_ProtobufTranslation2d_descriptor = descriptor.internalContainedType(31, 51, "ProtobufTranslation2d", "wpi.proto.ProtobufTranslation2d"); + + static final Descriptors.Descriptor wpi_proto_ProtobufRotation2d_descriptor = descriptor.internalContainedType(84, 42, "ProtobufRotation2d", "wpi.proto.ProtobufRotation2d"); + + static final Descriptors.Descriptor wpi_proto_ProtobufPose2d_descriptor = descriptor.internalContainedType(129, 143, "ProtobufPose2d", "wpi.proto.ProtobufPose2d"); + + static final Descriptors.Descriptor wpi_proto_ProtobufTransform2d_descriptor = descriptor.internalContainedType(275, 148, "ProtobufTransform2d", "wpi.proto.ProtobufTransform2d"); + + static final Descriptors.Descriptor wpi_proto_ProtobufTwist2d_descriptor = descriptor.internalContainedType(425, 73, "ProtobufTwist2d", "wpi.proto.ProtobufTwist2d"); + + /** + * @return this proto file's descriptor. + */ + public static Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + /** + * Protobuf type {@code ProtobufTranslation2d} + */ + public static final class ProtobufTranslation2d extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double x = 1; + */ + private double x; + + /** + * optional double y = 2; + */ + private double y; + + private ProtobufTranslation2d() { + } + + /** + * @return a new empty instance of {@code ProtobufTranslation2d} + */ + public static ProtobufTranslation2d newInstance() { + return new ProtobufTranslation2d(); + } + + /** + * optional double x = 1; + * @return whether the x field is set + */ + public boolean hasX() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double x = 1; + * @return this + */ + public ProtobufTranslation2d clearX() { + bitField0_ &= ~0x00000001; + x = 0D; + return this; + } + + /** + * optional double x = 1; + * @return the x + */ + public double getX() { + return x; + } + + /** + * optional double x = 1; + * @param value the x to set + * @return this + */ + public ProtobufTranslation2d setX(final double value) { + bitField0_ |= 0x00000001; + x = value; + return this; + } + + /** + * optional double y = 2; + * @return whether the y field is set + */ + public boolean hasY() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double y = 2; + * @return this + */ + public ProtobufTranslation2d clearY() { + bitField0_ &= ~0x00000002; + y = 0D; + return this; + } + + /** + * optional double y = 2; + * @return the y + */ + public double getY() { + return y; + } + + /** + * optional double y = 2; + * @param value the y to set + * @return this + */ + public ProtobufTranslation2d setY(final double value) { + bitField0_ |= 0x00000002; + y = value; + return this; + } + + @Override + public ProtobufTranslation2d copyFrom(final ProtobufTranslation2d other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + x = other.x; + y = other.y; + } + return this; + } + + @Override + public ProtobufTranslation2d mergeFrom(final ProtobufTranslation2d other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasX()) { + setX(other.x); + } + if (other.hasY()) { + setY(other.y); + } + return this; + } + + @Override + public ProtobufTranslation2d clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + x = 0D; + y = 0D; + return this; + } + + @Override + public ProtobufTranslation2d clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufTranslation2d)) { + return false; + } + ProtobufTranslation2d other = (ProtobufTranslation2d) o; + return bitField0_ == other.bitField0_ + && (!hasX() || ProtoUtil.isEqual(x, other.x)) + && (!hasY() || ProtoUtil.isEqual(y, other.y)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(x); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(y); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufTranslation2d mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // x + x = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // y + y = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.x, x); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.y, y); + } + output.endObject(); + } + + @Override + public ProtobufTranslation2d mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 120: { + if (input.isAtField(FieldNames.x)) { + if (!input.trySkipNullValue()) { + x = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 121: { + if (input.isAtField(FieldNames.y)) { + if (!input.trySkipNullValue()) { + y = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufTranslation2d clone() { + return new ProtobufTranslation2d().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufTranslation2d parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufTranslation2d(), data).checkInitialized(); + } + + public static ProtobufTranslation2d parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTranslation2d(), input).checkInitialized(); + } + + public static ProtobufTranslation2d parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTranslation2d(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufTranslation2d messages + */ + public static MessageFactory getFactory() { + return ProtobufTranslation2dFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Geometry2D.wpi_proto_ProtobufTranslation2d_descriptor; + } + + private enum ProtobufTranslation2dFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufTranslation2d create() { + return ProtobufTranslation2d.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName x = FieldName.forField("x"); + + static final FieldName y = FieldName.forField("y"); + } + } + + /** + * Protobuf type {@code ProtobufRotation2d} + */ + public static final class ProtobufRotation2d extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double value = 1; + */ + private double value_; + + private ProtobufRotation2d() { + } + + /** + * @return a new empty instance of {@code ProtobufRotation2d} + */ + public static ProtobufRotation2d newInstance() { + return new ProtobufRotation2d(); + } + + /** + * optional double value = 1; + * @return whether the value_ field is set + */ + public boolean hasValue() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double value = 1; + * @return this + */ + public ProtobufRotation2d clearValue() { + bitField0_ &= ~0x00000001; + value_ = 0D; + return this; + } + + /** + * optional double value = 1; + * @return the value_ + */ + public double getValue() { + return value_; + } + + /** + * optional double value = 1; + * @param value the value_ to set + * @return this + */ + public ProtobufRotation2d setValue(final double value) { + bitField0_ |= 0x00000001; + value_ = value; + return this; + } + + @Override + public ProtobufRotation2d copyFrom(final ProtobufRotation2d other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + value_ = other.value_; + } + return this; + } + + @Override + public ProtobufRotation2d mergeFrom(final ProtobufRotation2d other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasValue()) { + setValue(other.value_); + } + return this; + } + + @Override + public ProtobufRotation2d clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + value_ = 0D; + return this; + } + + @Override + public ProtobufRotation2d clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufRotation2d)) { + return false; + } + ProtobufRotation2d other = (ProtobufRotation2d) o; + return bitField0_ == other.bitField0_ + && (!hasValue() || ProtoUtil.isEqual(value_, other.value_)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(value_); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufRotation2d mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // value_ + value_ = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.value_, value_); + } + output.endObject(); + } + + @Override + public ProtobufRotation2d mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 111972721: { + if (input.isAtField(FieldNames.value_)) { + if (!input.trySkipNullValue()) { + value_ = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufRotation2d clone() { + return new ProtobufRotation2d().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufRotation2d parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufRotation2d(), data).checkInitialized(); + } + + public static ProtobufRotation2d parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufRotation2d(), input).checkInitialized(); + } + + public static ProtobufRotation2d parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufRotation2d(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufRotation2d messages + */ + public static MessageFactory getFactory() { + return ProtobufRotation2dFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Geometry2D.wpi_proto_ProtobufRotation2d_descriptor; + } + + private enum ProtobufRotation2dFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufRotation2d create() { + return ProtobufRotation2d.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName value_ = FieldName.forField("value"); + } + } + + /** + * Protobuf type {@code ProtobufPose2d} + */ + public static final class ProtobufPose2d extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional .wpi.proto.ProtobufTranslation2d translation = 1; + */ + private final ProtobufTranslation2d translation = ProtobufTranslation2d.newInstance(); + + /** + * optional .wpi.proto.ProtobufRotation2d rotation = 2; + */ + private final ProtobufRotation2d rotation = ProtobufRotation2d.newInstance(); + + private ProtobufPose2d() { + } + + /** + * @return a new empty instance of {@code ProtobufPose2d} + */ + public static ProtobufPose2d newInstance() { + return new ProtobufPose2d(); + } + + /** + * optional .wpi.proto.ProtobufTranslation2d translation = 1; + * @return whether the translation field is set + */ + public boolean hasTranslation() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d translation = 1; + * @return this + */ + public ProtobufPose2d clearTranslation() { + bitField0_ &= ~0x00000001; + translation.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d translation = 1; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableTranslation()} if you want to modify it. + * + * @return internal storage object for reading + */ + public ProtobufTranslation2d getTranslation() { + return translation; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d translation = 1; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public ProtobufTranslation2d getMutableTranslation() { + bitField0_ |= 0x00000001; + return translation; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d translation = 1; + * @param value the translation to set + * @return this + */ + public ProtobufPose2d setTranslation(final ProtobufTranslation2d value) { + bitField0_ |= 0x00000001; + translation.copyFrom(value); + return this; + } + + /** + * optional .wpi.proto.ProtobufRotation2d rotation = 2; + * @return whether the rotation field is set + */ + public boolean hasRotation() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional .wpi.proto.ProtobufRotation2d rotation = 2; + * @return this + */ + public ProtobufPose2d clearRotation() { + bitField0_ &= ~0x00000002; + rotation.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufRotation2d rotation = 2; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableRotation()} if you want to modify it. + * + * @return internal storage object for reading + */ + public ProtobufRotation2d getRotation() { + return rotation; + } + + /** + * optional .wpi.proto.ProtobufRotation2d rotation = 2; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public ProtobufRotation2d getMutableRotation() { + bitField0_ |= 0x00000002; + return rotation; + } + + /** + * optional .wpi.proto.ProtobufRotation2d rotation = 2; + * @param value the rotation to set + * @return this + */ + public ProtobufPose2d setRotation(final ProtobufRotation2d value) { + bitField0_ |= 0x00000002; + rotation.copyFrom(value); + return this; + } + + @Override + public ProtobufPose2d copyFrom(final ProtobufPose2d other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + translation.copyFrom(other.translation); + rotation.copyFrom(other.rotation); + } + return this; + } + + @Override + public ProtobufPose2d mergeFrom(final ProtobufPose2d other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasTranslation()) { + getMutableTranslation().mergeFrom(other.translation); + } + if (other.hasRotation()) { + getMutableRotation().mergeFrom(other.rotation); + } + return this; + } + + @Override + public ProtobufPose2d clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + translation.clear(); + rotation.clear(); + return this; + } + + @Override + public ProtobufPose2d clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + translation.clearQuick(); + rotation.clearQuick(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufPose2d)) { + return false; + } + ProtobufPose2d other = (ProtobufPose2d) o; + return bitField0_ == other.bitField0_ + && (!hasTranslation() || translation.equals(other.translation)) + && (!hasRotation() || rotation.equals(other.rotation)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 10); + output.writeMessageNoTag(translation); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 18); + output.writeMessageNoTag(rotation); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(translation); + } + if ((bitField0_ & 0x00000002) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(rotation); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufPose2d mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 10: { + // translation + input.readMessage(translation); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 18) { + break; + } + } + case 18: { + // rotation + input.readMessage(rotation); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeMessage(FieldNames.translation, translation); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeMessage(FieldNames.rotation, rotation); + } + output.endObject(); + } + + @Override + public ProtobufPose2d mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case -1840647503: { + if (input.isAtField(FieldNames.translation)) { + if (!input.trySkipNullValue()) { + input.readMessage(translation); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case -40300674: { + if (input.isAtField(FieldNames.rotation)) { + if (!input.trySkipNullValue()) { + input.readMessage(rotation); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufPose2d clone() { + return new ProtobufPose2d().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufPose2d parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufPose2d(), data).checkInitialized(); + } + + public static ProtobufPose2d parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufPose2d(), input).checkInitialized(); + } + + public static ProtobufPose2d parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufPose2d(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufPose2d messages + */ + public static MessageFactory getFactory() { + return ProtobufPose2dFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Geometry2D.wpi_proto_ProtobufPose2d_descriptor; + } + + private enum ProtobufPose2dFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufPose2d create() { + return ProtobufPose2d.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName translation = FieldName.forField("translation"); + + static final FieldName rotation = FieldName.forField("rotation"); + } + } + + /** + * Protobuf type {@code ProtobufTransform2d} + */ + public static final class ProtobufTransform2d extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional .wpi.proto.ProtobufTranslation2d translation = 1; + */ + private final ProtobufTranslation2d translation = ProtobufTranslation2d.newInstance(); + + /** + * optional .wpi.proto.ProtobufRotation2d rotation = 2; + */ + private final ProtobufRotation2d rotation = ProtobufRotation2d.newInstance(); + + private ProtobufTransform2d() { + } + + /** + * @return a new empty instance of {@code ProtobufTransform2d} + */ + public static ProtobufTransform2d newInstance() { + return new ProtobufTransform2d(); + } + + /** + * optional .wpi.proto.ProtobufTranslation2d translation = 1; + * @return whether the translation field is set + */ + public boolean hasTranslation() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d translation = 1; + * @return this + */ + public ProtobufTransform2d clearTranslation() { + bitField0_ &= ~0x00000001; + translation.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d translation = 1; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableTranslation()} if you want to modify it. + * + * @return internal storage object for reading + */ + public ProtobufTranslation2d getTranslation() { + return translation; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d translation = 1; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public ProtobufTranslation2d getMutableTranslation() { + bitField0_ |= 0x00000001; + return translation; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d translation = 1; + * @param value the translation to set + * @return this + */ + public ProtobufTransform2d setTranslation(final ProtobufTranslation2d value) { + bitField0_ |= 0x00000001; + translation.copyFrom(value); + return this; + } + + /** + * optional .wpi.proto.ProtobufRotation2d rotation = 2; + * @return whether the rotation field is set + */ + public boolean hasRotation() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional .wpi.proto.ProtobufRotation2d rotation = 2; + * @return this + */ + public ProtobufTransform2d clearRotation() { + bitField0_ &= ~0x00000002; + rotation.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufRotation2d rotation = 2; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableRotation()} if you want to modify it. + * + * @return internal storage object for reading + */ + public ProtobufRotation2d getRotation() { + return rotation; + } + + /** + * optional .wpi.proto.ProtobufRotation2d rotation = 2; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public ProtobufRotation2d getMutableRotation() { + bitField0_ |= 0x00000002; + return rotation; + } + + /** + * optional .wpi.proto.ProtobufRotation2d rotation = 2; + * @param value the rotation to set + * @return this + */ + public ProtobufTransform2d setRotation(final ProtobufRotation2d value) { + bitField0_ |= 0x00000002; + rotation.copyFrom(value); + return this; + } + + @Override + public ProtobufTransform2d copyFrom(final ProtobufTransform2d other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + translation.copyFrom(other.translation); + rotation.copyFrom(other.rotation); + } + return this; + } + + @Override + public ProtobufTransform2d mergeFrom(final ProtobufTransform2d other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasTranslation()) { + getMutableTranslation().mergeFrom(other.translation); + } + if (other.hasRotation()) { + getMutableRotation().mergeFrom(other.rotation); + } + return this; + } + + @Override + public ProtobufTransform2d clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + translation.clear(); + rotation.clear(); + return this; + } + + @Override + public ProtobufTransform2d clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + translation.clearQuick(); + rotation.clearQuick(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufTransform2d)) { + return false; + } + ProtobufTransform2d other = (ProtobufTransform2d) o; + return bitField0_ == other.bitField0_ + && (!hasTranslation() || translation.equals(other.translation)) + && (!hasRotation() || rotation.equals(other.rotation)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 10); + output.writeMessageNoTag(translation); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 18); + output.writeMessageNoTag(rotation); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(translation); + } + if ((bitField0_ & 0x00000002) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(rotation); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufTransform2d mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 10: { + // translation + input.readMessage(translation); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 18) { + break; + } + } + case 18: { + // rotation + input.readMessage(rotation); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeMessage(FieldNames.translation, translation); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeMessage(FieldNames.rotation, rotation); + } + output.endObject(); + } + + @Override + public ProtobufTransform2d mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case -1840647503: { + if (input.isAtField(FieldNames.translation)) { + if (!input.trySkipNullValue()) { + input.readMessage(translation); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case -40300674: { + if (input.isAtField(FieldNames.rotation)) { + if (!input.trySkipNullValue()) { + input.readMessage(rotation); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufTransform2d clone() { + return new ProtobufTransform2d().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufTransform2d parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufTransform2d(), data).checkInitialized(); + } + + public static ProtobufTransform2d parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTransform2d(), input).checkInitialized(); + } + + public static ProtobufTransform2d parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTransform2d(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufTransform2d messages + */ + public static MessageFactory getFactory() { + return ProtobufTransform2dFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Geometry2D.wpi_proto_ProtobufTransform2d_descriptor; + } + + private enum ProtobufTransform2dFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufTransform2d create() { + return ProtobufTransform2d.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName translation = FieldName.forField("translation"); + + static final FieldName rotation = FieldName.forField("rotation"); + } + } + + /** + * Protobuf type {@code ProtobufTwist2d} + */ + public static final class ProtobufTwist2d extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double dx = 1; + */ + private double dx; + + /** + * optional double dy = 2; + */ + private double dy; + + /** + * optional double dtheta = 3; + */ + private double dtheta; + + private ProtobufTwist2d() { + } + + /** + * @return a new empty instance of {@code ProtobufTwist2d} + */ + public static ProtobufTwist2d newInstance() { + return new ProtobufTwist2d(); + } + + /** + * optional double dx = 1; + * @return whether the dx field is set + */ + public boolean hasDx() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double dx = 1; + * @return this + */ + public ProtobufTwist2d clearDx() { + bitField0_ &= ~0x00000001; + dx = 0D; + return this; + } + + /** + * optional double dx = 1; + * @return the dx + */ + public double getDx() { + return dx; + } + + /** + * optional double dx = 1; + * @param value the dx to set + * @return this + */ + public ProtobufTwist2d setDx(final double value) { + bitField0_ |= 0x00000001; + dx = value; + return this; + } + + /** + * optional double dy = 2; + * @return whether the dy field is set + */ + public boolean hasDy() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double dy = 2; + * @return this + */ + public ProtobufTwist2d clearDy() { + bitField0_ &= ~0x00000002; + dy = 0D; + return this; + } + + /** + * optional double dy = 2; + * @return the dy + */ + public double getDy() { + return dy; + } + + /** + * optional double dy = 2; + * @param value the dy to set + * @return this + */ + public ProtobufTwist2d setDy(final double value) { + bitField0_ |= 0x00000002; + dy = value; + return this; + } + + /** + * optional double dtheta = 3; + * @return whether the dtheta field is set + */ + public boolean hasDtheta() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double dtheta = 3; + * @return this + */ + public ProtobufTwist2d clearDtheta() { + bitField0_ &= ~0x00000004; + dtheta = 0D; + return this; + } + + /** + * optional double dtheta = 3; + * @return the dtheta + */ + public double getDtheta() { + return dtheta; + } + + /** + * optional double dtheta = 3; + * @param value the dtheta to set + * @return this + */ + public ProtobufTwist2d setDtheta(final double value) { + bitField0_ |= 0x00000004; + dtheta = value; + return this; + } + + @Override + public ProtobufTwist2d copyFrom(final ProtobufTwist2d other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + dx = other.dx; + dy = other.dy; + dtheta = other.dtheta; + } + return this; + } + + @Override + public ProtobufTwist2d mergeFrom(final ProtobufTwist2d other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasDx()) { + setDx(other.dx); + } + if (other.hasDy()) { + setDy(other.dy); + } + if (other.hasDtheta()) { + setDtheta(other.dtheta); + } + return this; + } + + @Override + public ProtobufTwist2d clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + dx = 0D; + dy = 0D; + dtheta = 0D; + return this; + } + + @Override + public ProtobufTwist2d clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufTwist2d)) { + return false; + } + ProtobufTwist2d other = (ProtobufTwist2d) o; + return bitField0_ == other.bitField0_ + && (!hasDx() || ProtoUtil.isEqual(dx, other.dx)) + && (!hasDy() || ProtoUtil.isEqual(dy, other.dy)) + && (!hasDtheta() || ProtoUtil.isEqual(dtheta, other.dtheta)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(dx); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(dy); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(dtheta); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufTwist2d mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // dx + dx = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // dy + dy = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // dtheta + dtheta = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.dx, dx); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.dy, dy); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.dtheta, dtheta); + } + output.endObject(); + } + + @Override + public ProtobufTwist2d mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 3220: { + if (input.isAtField(FieldNames.dx)) { + if (!input.trySkipNullValue()) { + dx = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3221: { + if (input.isAtField(FieldNames.dy)) { + if (!input.trySkipNullValue()) { + dy = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case -1321724742: { + if (input.isAtField(FieldNames.dtheta)) { + if (!input.trySkipNullValue()) { + dtheta = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufTwist2d clone() { + return new ProtobufTwist2d().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufTwist2d parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufTwist2d(), data).checkInitialized(); + } + + public static ProtobufTwist2d parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTwist2d(), input).checkInitialized(); + } + + public static ProtobufTwist2d parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTwist2d(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufTwist2d messages + */ + public static MessageFactory getFactory() { + return ProtobufTwist2dFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Geometry2D.wpi_proto_ProtobufTwist2d_descriptor; + } + + private enum ProtobufTwist2dFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufTwist2d create() { + return ProtobufTwist2d.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName dx = FieldName.forField("dx"); + + static final FieldName dy = FieldName.forField("dy"); + + static final FieldName dtheta = FieldName.forField("dtheta"); + } + } +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Geometry3D.java b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Geometry3D.java new file mode 100644 index 00000000000..404d7b0719e --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Geometry3D.java @@ -0,0 +1,2652 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. +// Code generated by protocol buffer compiler. Do not edit! +package edu.wpi.first.math.proto; + +import java.io.IOException; +import us.hebi.quickbuf.Descriptors; +import us.hebi.quickbuf.FieldName; +import us.hebi.quickbuf.InvalidProtocolBufferException; +import us.hebi.quickbuf.JsonSink; +import us.hebi.quickbuf.JsonSource; +import us.hebi.quickbuf.MessageFactory; +import us.hebi.quickbuf.ProtoMessage; +import us.hebi.quickbuf.ProtoSink; +import us.hebi.quickbuf.ProtoSource; +import us.hebi.quickbuf.ProtoUtil; +import us.hebi.quickbuf.RepeatedByte; + +public final class Geometry3D { + private static final RepeatedByte descriptorData = ProtoUtil.decodeBase64(1875, + "ChBnZW9tZXRyeTNkLnByb3RvEgl3cGkucHJvdG8iQQoVUHJvdG9idWZUcmFuc2xhdGlvbjNkEgwKAXgY" + + "ASABKAFSAXgSDAoBeRgCIAEoAVIBeRIMCgF6GAMgASgBUgF6IkwKElByb3RvYnVmUXVhdGVybmlvbhIM" + + "CgF3GAEgASgBUgF3EgwKAXgYAiABKAFSAXgSDAoBeRgDIAEoAVIBeRIMCgF6GAQgASgBUgF6IkEKElBy" + + "b3RvYnVmUm90YXRpb24zZBIrCgFxGAEgASgLMh0ud3BpLnByb3RvLlByb3RvYnVmUXVhdGVybmlvblIB" + + "cSKPAQoOUHJvdG9idWZQb3NlM2QSQgoLdHJhbnNsYXRpb24YASABKAsyIC53cGkucHJvdG8uUHJvdG9i" + + "dWZUcmFuc2xhdGlvbjNkUgt0cmFuc2xhdGlvbhI5Cghyb3RhdGlvbhgCIAEoCzIdLndwaS5wcm90by5Q" + + "cm90b2J1ZlJvdGF0aW9uM2RSCHJvdGF0aW9uIpQBChNQcm90b2J1ZlRyYW5zZm9ybTNkEkIKC3RyYW5z" + + "bGF0aW9uGAEgASgLMiAud3BpLnByb3RvLlByb3RvYnVmVHJhbnNsYXRpb24zZFILdHJhbnNsYXRpb24S" + + "OQoIcm90YXRpb24YAiABKAsyHS53cGkucHJvdG8uUHJvdG9idWZSb3RhdGlvbjNkUghyb3RhdGlvbiJx" + + "Cg9Qcm90b2J1ZlR3aXN0M2QSDgoCZHgYASABKAFSAmR4Eg4KAmR5GAIgASgBUgJkeRIOCgJkehgDIAEo" + + "AVICZHoSDgoCcngYBCABKAFSAnJ4Eg4KAnJ5GAUgASgBUgJyeRIOCgJyehgGIAEoAVICcnpCGgoYZWR1" + + "LndwaS5maXJzdC5tYXRoLnByb3RvSp8JCgYSBAAAKAEKCAoBDBIDAAASCggKAQISAwIAEgoICgEIEgME" + + "ADEKCQoCCAESAwQAMQoKCgIEABIEBgAKAQoKCgMEAAESAwYIHQoLCgQEAAIAEgMHAg8KDAoFBAACAAUS" + + "AwcCCAoMCgUEAAIAARIDBwkKCgwKBQQAAgADEgMHDQ4KCwoEBAACARIDCAIPCgwKBQQAAgEFEgMIAggK" + + "DAoFBAACAQESAwgJCgoMCgUEAAIBAxIDCA0OCgsKBAQAAgISAwkCDwoMCgUEAAICBRIDCQIICgwKBQQA" + + "AgIBEgMJCQoKDAoFBAACAgMSAwkNDgoKCgIEARIEDAARAQoKCgMEAQESAwwIGgoLCgQEAQIAEgMNAg8K" + + "DAoFBAECAAUSAw0CCAoMCgUEAQIAARIDDQkKCgwKBQQBAgADEgMNDQ4KCwoEBAECARIDDgIPCgwKBQQB" + + "AgEFEgMOAggKDAoFBAECAQESAw4JCgoMCgUEAQIBAxIDDg0OCgsKBAQBAgISAw8CDwoMCgUEAQICBRID" + + "DwIICgwKBQQBAgIBEgMPCQoKDAoFBAECAgMSAw8NDgoLCgQEAQIDEgMQAg8KDAoFBAECAwUSAxACCAoM" + + "CgUEAQIDARIDEAkKCgwKBQQBAgMDEgMQDQ4KCgoCBAISBBMAFQEKCgoDBAIBEgMTCBoKCwoEBAICABID", + "FAIbCgwKBQQCAgAGEgMUAhQKDAoFBAICAAESAxQVFgoMCgUEAgIAAxIDFBkaCgoKAgQDEgQXABoBCgoK" + + "AwQDARIDFwgWCgsKBAQDAgASAxgCKAoMCgUEAwIABhIDGAIXCgwKBQQDAgABEgMYGCMKDAoFBAMCAAMS" + + "AxgmJwoLCgQEAwIBEgMZAiIKDAoFBAMCAQYSAxkCFAoMCgUEAwIBARIDGRUdCgwKBQQDAgEDEgMZICEK" + + "CgoCBAQSBBwAHwEKCgoDBAQBEgMcCBsKCwoEBAQCABIDHQIoCgwKBQQEAgAGEgMdAhcKDAoFBAQCAAES" + + "Ax0YIwoMCgUEBAIAAxIDHSYnCgsKBAQEAgESAx4CIgoMCgUEBAIBBhIDHgIUCgwKBQQEAgEBEgMeFR0K" + + "DAoFBAQCAQMSAx4gIQoKCgIEBRIEIQAoAQoKCgMEBQESAyEIFwoLCgQEBQIAEgMiAhAKDAoFBAUCAAUS" + + "AyICCAoMCgUEBQIAARIDIgkLCgwKBQQFAgADEgMiDg8KCwoEBAUCARIDIwIQCgwKBQQFAgEFEgMjAggK" + + "DAoFBAUCAQESAyMJCwoMCgUEBQIBAxIDIw4PCgsKBAQFAgISAyQCEAoMCgUEBQICBRIDJAIICgwKBQQF" + + "AgIBEgMkCQsKDAoFBAUCAgMSAyQODwoLCgQEBQIDEgMlAhAKDAoFBAUCAwUSAyUCCAoMCgUEBQIDARID" + + "JQkLCgwKBQQFAgMDEgMlDg8KCwoEBAUCBBIDJgIQCgwKBQQFAgQFEgMmAggKDAoFBAUCBAESAyYJCwoM" + + "CgUEBQIEAxIDJg4PCgsKBAQFAgUSAycCEAoMCgUEBQIFBRIDJwIICgwKBQQFAgUBEgMnCQsKDAoFBAUC" + + "BQMSAycOD2IGcHJvdG8z"); + + static final Descriptors.FileDescriptor descriptor = Descriptors.FileDescriptor.internalBuildGeneratedFileFrom("geometry3d.proto", "wpi.proto", descriptorData); + + static final Descriptors.Descriptor wpi_proto_ProtobufTranslation3d_descriptor = descriptor.internalContainedType(31, 65, "ProtobufTranslation3d", "wpi.proto.ProtobufTranslation3d"); + + static final Descriptors.Descriptor wpi_proto_ProtobufQuaternion_descriptor = descriptor.internalContainedType(98, 76, "ProtobufQuaternion", "wpi.proto.ProtobufQuaternion"); + + static final Descriptors.Descriptor wpi_proto_ProtobufRotation3d_descriptor = descriptor.internalContainedType(176, 65, "ProtobufRotation3d", "wpi.proto.ProtobufRotation3d"); + + static final Descriptors.Descriptor wpi_proto_ProtobufPose3d_descriptor = descriptor.internalContainedType(244, 143, "ProtobufPose3d", "wpi.proto.ProtobufPose3d"); + + static final Descriptors.Descriptor wpi_proto_ProtobufTransform3d_descriptor = descriptor.internalContainedType(390, 148, "ProtobufTransform3d", "wpi.proto.ProtobufTransform3d"); + + static final Descriptors.Descriptor wpi_proto_ProtobufTwist3d_descriptor = descriptor.internalContainedType(540, 113, "ProtobufTwist3d", "wpi.proto.ProtobufTwist3d"); + + /** + * @return this proto file's descriptor. + */ + public static Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + /** + * Protobuf type {@code ProtobufTranslation3d} + */ + public static final class ProtobufTranslation3d extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double x = 1; + */ + private double x; + + /** + * optional double y = 2; + */ + private double y; + + /** + * optional double z = 3; + */ + private double z; + + private ProtobufTranslation3d() { + } + + /** + * @return a new empty instance of {@code ProtobufTranslation3d} + */ + public static ProtobufTranslation3d newInstance() { + return new ProtobufTranslation3d(); + } + + /** + * optional double x = 1; + * @return whether the x field is set + */ + public boolean hasX() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double x = 1; + * @return this + */ + public ProtobufTranslation3d clearX() { + bitField0_ &= ~0x00000001; + x = 0D; + return this; + } + + /** + * optional double x = 1; + * @return the x + */ + public double getX() { + return x; + } + + /** + * optional double x = 1; + * @param value the x to set + * @return this + */ + public ProtobufTranslation3d setX(final double value) { + bitField0_ |= 0x00000001; + x = value; + return this; + } + + /** + * optional double y = 2; + * @return whether the y field is set + */ + public boolean hasY() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double y = 2; + * @return this + */ + public ProtobufTranslation3d clearY() { + bitField0_ &= ~0x00000002; + y = 0D; + return this; + } + + /** + * optional double y = 2; + * @return the y + */ + public double getY() { + return y; + } + + /** + * optional double y = 2; + * @param value the y to set + * @return this + */ + public ProtobufTranslation3d setY(final double value) { + bitField0_ |= 0x00000002; + y = value; + return this; + } + + /** + * optional double z = 3; + * @return whether the z field is set + */ + public boolean hasZ() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double z = 3; + * @return this + */ + public ProtobufTranslation3d clearZ() { + bitField0_ &= ~0x00000004; + z = 0D; + return this; + } + + /** + * optional double z = 3; + * @return the z + */ + public double getZ() { + return z; + } + + /** + * optional double z = 3; + * @param value the z to set + * @return this + */ + public ProtobufTranslation3d setZ(final double value) { + bitField0_ |= 0x00000004; + z = value; + return this; + } + + @Override + public ProtobufTranslation3d copyFrom(final ProtobufTranslation3d other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + x = other.x; + y = other.y; + z = other.z; + } + return this; + } + + @Override + public ProtobufTranslation3d mergeFrom(final ProtobufTranslation3d other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasX()) { + setX(other.x); + } + if (other.hasY()) { + setY(other.y); + } + if (other.hasZ()) { + setZ(other.z); + } + return this; + } + + @Override + public ProtobufTranslation3d clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + x = 0D; + y = 0D; + z = 0D; + return this; + } + + @Override + public ProtobufTranslation3d clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufTranslation3d)) { + return false; + } + ProtobufTranslation3d other = (ProtobufTranslation3d) o; + return bitField0_ == other.bitField0_ + && (!hasX() || ProtoUtil.isEqual(x, other.x)) + && (!hasY() || ProtoUtil.isEqual(y, other.y)) + && (!hasZ() || ProtoUtil.isEqual(z, other.z)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(x); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(y); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(z); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufTranslation3d mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // x + x = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // y + y = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // z + z = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.x, x); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.y, y); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.z, z); + } + output.endObject(); + } + + @Override + public ProtobufTranslation3d mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 120: { + if (input.isAtField(FieldNames.x)) { + if (!input.trySkipNullValue()) { + x = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 121: { + if (input.isAtField(FieldNames.y)) { + if (!input.trySkipNullValue()) { + y = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case 122: { + if (input.isAtField(FieldNames.z)) { + if (!input.trySkipNullValue()) { + z = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufTranslation3d clone() { + return new ProtobufTranslation3d().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufTranslation3d parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufTranslation3d(), data).checkInitialized(); + } + + public static ProtobufTranslation3d parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTranslation3d(), input).checkInitialized(); + } + + public static ProtobufTranslation3d parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTranslation3d(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufTranslation3d messages + */ + public static MessageFactory getFactory() { + return ProtobufTranslation3dFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Geometry3D.wpi_proto_ProtobufTranslation3d_descriptor; + } + + private enum ProtobufTranslation3dFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufTranslation3d create() { + return ProtobufTranslation3d.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName x = FieldName.forField("x"); + + static final FieldName y = FieldName.forField("y"); + + static final FieldName z = FieldName.forField("z"); + } + } + + /** + * Protobuf type {@code ProtobufQuaternion} + */ + public static final class ProtobufQuaternion extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double w = 1; + */ + private double w; + + /** + * optional double x = 2; + */ + private double x; + + /** + * optional double y = 3; + */ + private double y; + + /** + * optional double z = 4; + */ + private double z; + + private ProtobufQuaternion() { + } + + /** + * @return a new empty instance of {@code ProtobufQuaternion} + */ + public static ProtobufQuaternion newInstance() { + return new ProtobufQuaternion(); + } + + /** + * optional double w = 1; + * @return whether the w field is set + */ + public boolean hasW() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double w = 1; + * @return this + */ + public ProtobufQuaternion clearW() { + bitField0_ &= ~0x00000001; + w = 0D; + return this; + } + + /** + * optional double w = 1; + * @return the w + */ + public double getW() { + return w; + } + + /** + * optional double w = 1; + * @param value the w to set + * @return this + */ + public ProtobufQuaternion setW(final double value) { + bitField0_ |= 0x00000001; + w = value; + return this; + } + + /** + * optional double x = 2; + * @return whether the x field is set + */ + public boolean hasX() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double x = 2; + * @return this + */ + public ProtobufQuaternion clearX() { + bitField0_ &= ~0x00000002; + x = 0D; + return this; + } + + /** + * optional double x = 2; + * @return the x + */ + public double getX() { + return x; + } + + /** + * optional double x = 2; + * @param value the x to set + * @return this + */ + public ProtobufQuaternion setX(final double value) { + bitField0_ |= 0x00000002; + x = value; + return this; + } + + /** + * optional double y = 3; + * @return whether the y field is set + */ + public boolean hasY() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double y = 3; + * @return this + */ + public ProtobufQuaternion clearY() { + bitField0_ &= ~0x00000004; + y = 0D; + return this; + } + + /** + * optional double y = 3; + * @return the y + */ + public double getY() { + return y; + } + + /** + * optional double y = 3; + * @param value the y to set + * @return this + */ + public ProtobufQuaternion setY(final double value) { + bitField0_ |= 0x00000004; + y = value; + return this; + } + + /** + * optional double z = 4; + * @return whether the z field is set + */ + public boolean hasZ() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * optional double z = 4; + * @return this + */ + public ProtobufQuaternion clearZ() { + bitField0_ &= ~0x00000008; + z = 0D; + return this; + } + + /** + * optional double z = 4; + * @return the z + */ + public double getZ() { + return z; + } + + /** + * optional double z = 4; + * @param value the z to set + * @return this + */ + public ProtobufQuaternion setZ(final double value) { + bitField0_ |= 0x00000008; + z = value; + return this; + } + + @Override + public ProtobufQuaternion copyFrom(final ProtobufQuaternion other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + w = other.w; + x = other.x; + y = other.y; + z = other.z; + } + return this; + } + + @Override + public ProtobufQuaternion mergeFrom(final ProtobufQuaternion other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasW()) { + setW(other.w); + } + if (other.hasX()) { + setX(other.x); + } + if (other.hasY()) { + setY(other.y); + } + if (other.hasZ()) { + setZ(other.z); + } + return this; + } + + @Override + public ProtobufQuaternion clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + w = 0D; + x = 0D; + y = 0D; + z = 0D; + return this; + } + + @Override + public ProtobufQuaternion clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufQuaternion)) { + return false; + } + ProtobufQuaternion other = (ProtobufQuaternion) o; + return bitField0_ == other.bitField0_ + && (!hasW() || ProtoUtil.isEqual(w, other.w)) + && (!hasX() || ProtoUtil.isEqual(x, other.x)) + && (!hasY() || ProtoUtil.isEqual(y, other.y)) + && (!hasZ() || ProtoUtil.isEqual(z, other.z)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(w); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(x); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(y); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRawByte((byte) 33); + output.writeDoubleNoTag(z); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000008) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufQuaternion mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // w + w = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // x + x = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // y + y = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 33) { + break; + } + } + case 33: { + // z + z = input.readDouble(); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.w, w); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.x, x); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.y, y); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeDouble(FieldNames.z, z); + } + output.endObject(); + } + + @Override + public ProtobufQuaternion mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 119: { + if (input.isAtField(FieldNames.w)) { + if (!input.trySkipNullValue()) { + w = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 120: { + if (input.isAtField(FieldNames.x)) { + if (!input.trySkipNullValue()) { + x = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case 121: { + if (input.isAtField(FieldNames.y)) { + if (!input.trySkipNullValue()) { + y = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case 122: { + if (input.isAtField(FieldNames.z)) { + if (!input.trySkipNullValue()) { + z = input.readDouble(); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufQuaternion clone() { + return new ProtobufQuaternion().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufQuaternion parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufQuaternion(), data).checkInitialized(); + } + + public static ProtobufQuaternion parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufQuaternion(), input).checkInitialized(); + } + + public static ProtobufQuaternion parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufQuaternion(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufQuaternion messages + */ + public static MessageFactory getFactory() { + return ProtobufQuaternionFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Geometry3D.wpi_proto_ProtobufQuaternion_descriptor; + } + + private enum ProtobufQuaternionFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufQuaternion create() { + return ProtobufQuaternion.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName w = FieldName.forField("w"); + + static final FieldName x = FieldName.forField("x"); + + static final FieldName y = FieldName.forField("y"); + + static final FieldName z = FieldName.forField("z"); + } + } + + /** + * Protobuf type {@code ProtobufRotation3d} + */ + public static final class ProtobufRotation3d extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional .wpi.proto.ProtobufQuaternion q = 1; + */ + private final ProtobufQuaternion q = ProtobufQuaternion.newInstance(); + + private ProtobufRotation3d() { + } + + /** + * @return a new empty instance of {@code ProtobufRotation3d} + */ + public static ProtobufRotation3d newInstance() { + return new ProtobufRotation3d(); + } + + /** + * optional .wpi.proto.ProtobufQuaternion q = 1; + * @return whether the q field is set + */ + public boolean hasQ() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional .wpi.proto.ProtobufQuaternion q = 1; + * @return this + */ + public ProtobufRotation3d clearQ() { + bitField0_ &= ~0x00000001; + q.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufQuaternion q = 1; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableQ()} if you want to modify it. + * + * @return internal storage object for reading + */ + public ProtobufQuaternion getQ() { + return q; + } + + /** + * optional .wpi.proto.ProtobufQuaternion q = 1; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public ProtobufQuaternion getMutableQ() { + bitField0_ |= 0x00000001; + return q; + } + + /** + * optional .wpi.proto.ProtobufQuaternion q = 1; + * @param value the q to set + * @return this + */ + public ProtobufRotation3d setQ(final ProtobufQuaternion value) { + bitField0_ |= 0x00000001; + q.copyFrom(value); + return this; + } + + @Override + public ProtobufRotation3d copyFrom(final ProtobufRotation3d other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + q.copyFrom(other.q); + } + return this; + } + + @Override + public ProtobufRotation3d mergeFrom(final ProtobufRotation3d other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasQ()) { + getMutableQ().mergeFrom(other.q); + } + return this; + } + + @Override + public ProtobufRotation3d clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + q.clear(); + return this; + } + + @Override + public ProtobufRotation3d clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + q.clearQuick(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufRotation3d)) { + return false; + } + ProtobufRotation3d other = (ProtobufRotation3d) o; + return bitField0_ == other.bitField0_ + && (!hasQ() || q.equals(other.q)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 10); + output.writeMessageNoTag(q); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(q); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufRotation3d mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 10: { + // q + input.readMessage(q); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeMessage(FieldNames.q, q); + } + output.endObject(); + } + + @Override + public ProtobufRotation3d mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 113: { + if (input.isAtField(FieldNames.q)) { + if (!input.trySkipNullValue()) { + input.readMessage(q); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufRotation3d clone() { + return new ProtobufRotation3d().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufRotation3d parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufRotation3d(), data).checkInitialized(); + } + + public static ProtobufRotation3d parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufRotation3d(), input).checkInitialized(); + } + + public static ProtobufRotation3d parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufRotation3d(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufRotation3d messages + */ + public static MessageFactory getFactory() { + return ProtobufRotation3dFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Geometry3D.wpi_proto_ProtobufRotation3d_descriptor; + } + + private enum ProtobufRotation3dFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufRotation3d create() { + return ProtobufRotation3d.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName q = FieldName.forField("q"); + } + } + + /** + * Protobuf type {@code ProtobufPose3d} + */ + public static final class ProtobufPose3d extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional .wpi.proto.ProtobufTranslation3d translation = 1; + */ + private final ProtobufTranslation3d translation = ProtobufTranslation3d.newInstance(); + + /** + * optional .wpi.proto.ProtobufRotation3d rotation = 2; + */ + private final ProtobufRotation3d rotation = ProtobufRotation3d.newInstance(); + + private ProtobufPose3d() { + } + + /** + * @return a new empty instance of {@code ProtobufPose3d} + */ + public static ProtobufPose3d newInstance() { + return new ProtobufPose3d(); + } + + /** + * optional .wpi.proto.ProtobufTranslation3d translation = 1; + * @return whether the translation field is set + */ + public boolean hasTranslation() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional .wpi.proto.ProtobufTranslation3d translation = 1; + * @return this + */ + public ProtobufPose3d clearTranslation() { + bitField0_ &= ~0x00000001; + translation.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufTranslation3d translation = 1; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableTranslation()} if you want to modify it. + * + * @return internal storage object for reading + */ + public ProtobufTranslation3d getTranslation() { + return translation; + } + + /** + * optional .wpi.proto.ProtobufTranslation3d translation = 1; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public ProtobufTranslation3d getMutableTranslation() { + bitField0_ |= 0x00000001; + return translation; + } + + /** + * optional .wpi.proto.ProtobufTranslation3d translation = 1; + * @param value the translation to set + * @return this + */ + public ProtobufPose3d setTranslation(final ProtobufTranslation3d value) { + bitField0_ |= 0x00000001; + translation.copyFrom(value); + return this; + } + + /** + * optional .wpi.proto.ProtobufRotation3d rotation = 2; + * @return whether the rotation field is set + */ + public boolean hasRotation() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional .wpi.proto.ProtobufRotation3d rotation = 2; + * @return this + */ + public ProtobufPose3d clearRotation() { + bitField0_ &= ~0x00000002; + rotation.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufRotation3d rotation = 2; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableRotation()} if you want to modify it. + * + * @return internal storage object for reading + */ + public ProtobufRotation3d getRotation() { + return rotation; + } + + /** + * optional .wpi.proto.ProtobufRotation3d rotation = 2; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public ProtobufRotation3d getMutableRotation() { + bitField0_ |= 0x00000002; + return rotation; + } + + /** + * optional .wpi.proto.ProtobufRotation3d rotation = 2; + * @param value the rotation to set + * @return this + */ + public ProtobufPose3d setRotation(final ProtobufRotation3d value) { + bitField0_ |= 0x00000002; + rotation.copyFrom(value); + return this; + } + + @Override + public ProtobufPose3d copyFrom(final ProtobufPose3d other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + translation.copyFrom(other.translation); + rotation.copyFrom(other.rotation); + } + return this; + } + + @Override + public ProtobufPose3d mergeFrom(final ProtobufPose3d other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasTranslation()) { + getMutableTranslation().mergeFrom(other.translation); + } + if (other.hasRotation()) { + getMutableRotation().mergeFrom(other.rotation); + } + return this; + } + + @Override + public ProtobufPose3d clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + translation.clear(); + rotation.clear(); + return this; + } + + @Override + public ProtobufPose3d clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + translation.clearQuick(); + rotation.clearQuick(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufPose3d)) { + return false; + } + ProtobufPose3d other = (ProtobufPose3d) o; + return bitField0_ == other.bitField0_ + && (!hasTranslation() || translation.equals(other.translation)) + && (!hasRotation() || rotation.equals(other.rotation)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 10); + output.writeMessageNoTag(translation); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 18); + output.writeMessageNoTag(rotation); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(translation); + } + if ((bitField0_ & 0x00000002) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(rotation); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufPose3d mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 10: { + // translation + input.readMessage(translation); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 18) { + break; + } + } + case 18: { + // rotation + input.readMessage(rotation); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeMessage(FieldNames.translation, translation); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeMessage(FieldNames.rotation, rotation); + } + output.endObject(); + } + + @Override + public ProtobufPose3d mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case -1840647503: { + if (input.isAtField(FieldNames.translation)) { + if (!input.trySkipNullValue()) { + input.readMessage(translation); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case -40300674: { + if (input.isAtField(FieldNames.rotation)) { + if (!input.trySkipNullValue()) { + input.readMessage(rotation); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufPose3d clone() { + return new ProtobufPose3d().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufPose3d parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufPose3d(), data).checkInitialized(); + } + + public static ProtobufPose3d parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufPose3d(), input).checkInitialized(); + } + + public static ProtobufPose3d parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufPose3d(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufPose3d messages + */ + public static MessageFactory getFactory() { + return ProtobufPose3dFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Geometry3D.wpi_proto_ProtobufPose3d_descriptor; + } + + private enum ProtobufPose3dFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufPose3d create() { + return ProtobufPose3d.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName translation = FieldName.forField("translation"); + + static final FieldName rotation = FieldName.forField("rotation"); + } + } + + /** + * Protobuf type {@code ProtobufTransform3d} + */ + public static final class ProtobufTransform3d extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional .wpi.proto.ProtobufTranslation3d translation = 1; + */ + private final ProtobufTranslation3d translation = ProtobufTranslation3d.newInstance(); + + /** + * optional .wpi.proto.ProtobufRotation3d rotation = 2; + */ + private final ProtobufRotation3d rotation = ProtobufRotation3d.newInstance(); + + private ProtobufTransform3d() { + } + + /** + * @return a new empty instance of {@code ProtobufTransform3d} + */ + public static ProtobufTransform3d newInstance() { + return new ProtobufTransform3d(); + } + + /** + * optional .wpi.proto.ProtobufTranslation3d translation = 1; + * @return whether the translation field is set + */ + public boolean hasTranslation() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional .wpi.proto.ProtobufTranslation3d translation = 1; + * @return this + */ + public ProtobufTransform3d clearTranslation() { + bitField0_ &= ~0x00000001; + translation.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufTranslation3d translation = 1; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableTranslation()} if you want to modify it. + * + * @return internal storage object for reading + */ + public ProtobufTranslation3d getTranslation() { + return translation; + } + + /** + * optional .wpi.proto.ProtobufTranslation3d translation = 1; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public ProtobufTranslation3d getMutableTranslation() { + bitField0_ |= 0x00000001; + return translation; + } + + /** + * optional .wpi.proto.ProtobufTranslation3d translation = 1; + * @param value the translation to set + * @return this + */ + public ProtobufTransform3d setTranslation(final ProtobufTranslation3d value) { + bitField0_ |= 0x00000001; + translation.copyFrom(value); + return this; + } + + /** + * optional .wpi.proto.ProtobufRotation3d rotation = 2; + * @return whether the rotation field is set + */ + public boolean hasRotation() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional .wpi.proto.ProtobufRotation3d rotation = 2; + * @return this + */ + public ProtobufTransform3d clearRotation() { + bitField0_ &= ~0x00000002; + rotation.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufRotation3d rotation = 2; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableRotation()} if you want to modify it. + * + * @return internal storage object for reading + */ + public ProtobufRotation3d getRotation() { + return rotation; + } + + /** + * optional .wpi.proto.ProtobufRotation3d rotation = 2; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public ProtobufRotation3d getMutableRotation() { + bitField0_ |= 0x00000002; + return rotation; + } + + /** + * optional .wpi.proto.ProtobufRotation3d rotation = 2; + * @param value the rotation to set + * @return this + */ + public ProtobufTransform3d setRotation(final ProtobufRotation3d value) { + bitField0_ |= 0x00000002; + rotation.copyFrom(value); + return this; + } + + @Override + public ProtobufTransform3d copyFrom(final ProtobufTransform3d other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + translation.copyFrom(other.translation); + rotation.copyFrom(other.rotation); + } + return this; + } + + @Override + public ProtobufTransform3d mergeFrom(final ProtobufTransform3d other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasTranslation()) { + getMutableTranslation().mergeFrom(other.translation); + } + if (other.hasRotation()) { + getMutableRotation().mergeFrom(other.rotation); + } + return this; + } + + @Override + public ProtobufTransform3d clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + translation.clear(); + rotation.clear(); + return this; + } + + @Override + public ProtobufTransform3d clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + translation.clearQuick(); + rotation.clearQuick(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufTransform3d)) { + return false; + } + ProtobufTransform3d other = (ProtobufTransform3d) o; + return bitField0_ == other.bitField0_ + && (!hasTranslation() || translation.equals(other.translation)) + && (!hasRotation() || rotation.equals(other.rotation)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 10); + output.writeMessageNoTag(translation); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 18); + output.writeMessageNoTag(rotation); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(translation); + } + if ((bitField0_ & 0x00000002) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(rotation); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufTransform3d mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 10: { + // translation + input.readMessage(translation); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 18) { + break; + } + } + case 18: { + // rotation + input.readMessage(rotation); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeMessage(FieldNames.translation, translation); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeMessage(FieldNames.rotation, rotation); + } + output.endObject(); + } + + @Override + public ProtobufTransform3d mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case -1840647503: { + if (input.isAtField(FieldNames.translation)) { + if (!input.trySkipNullValue()) { + input.readMessage(translation); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case -40300674: { + if (input.isAtField(FieldNames.rotation)) { + if (!input.trySkipNullValue()) { + input.readMessage(rotation); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufTransform3d clone() { + return new ProtobufTransform3d().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufTransform3d parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufTransform3d(), data).checkInitialized(); + } + + public static ProtobufTransform3d parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTransform3d(), input).checkInitialized(); + } + + public static ProtobufTransform3d parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTransform3d(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufTransform3d messages + */ + public static MessageFactory getFactory() { + return ProtobufTransform3dFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Geometry3D.wpi_proto_ProtobufTransform3d_descriptor; + } + + private enum ProtobufTransform3dFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufTransform3d create() { + return ProtobufTransform3d.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName translation = FieldName.forField("translation"); + + static final FieldName rotation = FieldName.forField("rotation"); + } + } + + /** + * Protobuf type {@code ProtobufTwist3d} + */ + public static final class ProtobufTwist3d extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double dx = 1; + */ + private double dx; + + /** + * optional double dy = 2; + */ + private double dy; + + /** + * optional double dz = 3; + */ + private double dz; + + /** + * optional double rx = 4; + */ + private double rx; + + /** + * optional double ry = 5; + */ + private double ry; + + /** + * optional double rz = 6; + */ + private double rz; + + private ProtobufTwist3d() { + } + + /** + * @return a new empty instance of {@code ProtobufTwist3d} + */ + public static ProtobufTwist3d newInstance() { + return new ProtobufTwist3d(); + } + + /** + * optional double dx = 1; + * @return whether the dx field is set + */ + public boolean hasDx() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double dx = 1; + * @return this + */ + public ProtobufTwist3d clearDx() { + bitField0_ &= ~0x00000001; + dx = 0D; + return this; + } + + /** + * optional double dx = 1; + * @return the dx + */ + public double getDx() { + return dx; + } + + /** + * optional double dx = 1; + * @param value the dx to set + * @return this + */ + public ProtobufTwist3d setDx(final double value) { + bitField0_ |= 0x00000001; + dx = value; + return this; + } + + /** + * optional double dy = 2; + * @return whether the dy field is set + */ + public boolean hasDy() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double dy = 2; + * @return this + */ + public ProtobufTwist3d clearDy() { + bitField0_ &= ~0x00000002; + dy = 0D; + return this; + } + + /** + * optional double dy = 2; + * @return the dy + */ + public double getDy() { + return dy; + } + + /** + * optional double dy = 2; + * @param value the dy to set + * @return this + */ + public ProtobufTwist3d setDy(final double value) { + bitField0_ |= 0x00000002; + dy = value; + return this; + } + + /** + * optional double dz = 3; + * @return whether the dz field is set + */ + public boolean hasDz() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double dz = 3; + * @return this + */ + public ProtobufTwist3d clearDz() { + bitField0_ &= ~0x00000004; + dz = 0D; + return this; + } + + /** + * optional double dz = 3; + * @return the dz + */ + public double getDz() { + return dz; + } + + /** + * optional double dz = 3; + * @param value the dz to set + * @return this + */ + public ProtobufTwist3d setDz(final double value) { + bitField0_ |= 0x00000004; + dz = value; + return this; + } + + /** + * optional double rx = 4; + * @return whether the rx field is set + */ + public boolean hasRx() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * optional double rx = 4; + * @return this + */ + public ProtobufTwist3d clearRx() { + bitField0_ &= ~0x00000008; + rx = 0D; + return this; + } + + /** + * optional double rx = 4; + * @return the rx + */ + public double getRx() { + return rx; + } + + /** + * optional double rx = 4; + * @param value the rx to set + * @return this + */ + public ProtobufTwist3d setRx(final double value) { + bitField0_ |= 0x00000008; + rx = value; + return this; + } + + /** + * optional double ry = 5; + * @return whether the ry field is set + */ + public boolean hasRy() { + return (bitField0_ & 0x00000010) != 0; + } + + /** + * optional double ry = 5; + * @return this + */ + public ProtobufTwist3d clearRy() { + bitField0_ &= ~0x00000010; + ry = 0D; + return this; + } + + /** + * optional double ry = 5; + * @return the ry + */ + public double getRy() { + return ry; + } + + /** + * optional double ry = 5; + * @param value the ry to set + * @return this + */ + public ProtobufTwist3d setRy(final double value) { + bitField0_ |= 0x00000010; + ry = value; + return this; + } + + /** + * optional double rz = 6; + * @return whether the rz field is set + */ + public boolean hasRz() { + return (bitField0_ & 0x00000020) != 0; + } + + /** + * optional double rz = 6; + * @return this + */ + public ProtobufTwist3d clearRz() { + bitField0_ &= ~0x00000020; + rz = 0D; + return this; + } + + /** + * optional double rz = 6; + * @return the rz + */ + public double getRz() { + return rz; + } + + /** + * optional double rz = 6; + * @param value the rz to set + * @return this + */ + public ProtobufTwist3d setRz(final double value) { + bitField0_ |= 0x00000020; + rz = value; + return this; + } + + @Override + public ProtobufTwist3d copyFrom(final ProtobufTwist3d other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + dx = other.dx; + dy = other.dy; + dz = other.dz; + rx = other.rx; + ry = other.ry; + rz = other.rz; + } + return this; + } + + @Override + public ProtobufTwist3d mergeFrom(final ProtobufTwist3d other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasDx()) { + setDx(other.dx); + } + if (other.hasDy()) { + setDy(other.dy); + } + if (other.hasDz()) { + setDz(other.dz); + } + if (other.hasRx()) { + setRx(other.rx); + } + if (other.hasRy()) { + setRy(other.ry); + } + if (other.hasRz()) { + setRz(other.rz); + } + return this; + } + + @Override + public ProtobufTwist3d clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + dx = 0D; + dy = 0D; + dz = 0D; + rx = 0D; + ry = 0D; + rz = 0D; + return this; + } + + @Override + public ProtobufTwist3d clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufTwist3d)) { + return false; + } + ProtobufTwist3d other = (ProtobufTwist3d) o; + return bitField0_ == other.bitField0_ + && (!hasDx() || ProtoUtil.isEqual(dx, other.dx)) + && (!hasDy() || ProtoUtil.isEqual(dy, other.dy)) + && (!hasDz() || ProtoUtil.isEqual(dz, other.dz)) + && (!hasRx() || ProtoUtil.isEqual(rx, other.rx)) + && (!hasRy() || ProtoUtil.isEqual(ry, other.ry)) + && (!hasRz() || ProtoUtil.isEqual(rz, other.rz)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(dx); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(dy); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(dz); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRawByte((byte) 33); + output.writeDoubleNoTag(rx); + } + if ((bitField0_ & 0x00000010) != 0) { + output.writeRawByte((byte) 41); + output.writeDoubleNoTag(ry); + } + if ((bitField0_ & 0x00000020) != 0) { + output.writeRawByte((byte) 49); + output.writeDoubleNoTag(rz); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000008) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000010) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000020) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufTwist3d mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // dx + dx = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // dy + dy = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // dz + dz = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 33) { + break; + } + } + case 33: { + // rx + rx = input.readDouble(); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 41) { + break; + } + } + case 41: { + // ry + ry = input.readDouble(); + bitField0_ |= 0x00000010; + tag = input.readTag(); + if (tag != 49) { + break; + } + } + case 49: { + // rz + rz = input.readDouble(); + bitField0_ |= 0x00000020; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.dx, dx); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.dy, dy); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.dz, dz); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeDouble(FieldNames.rx, rx); + } + if ((bitField0_ & 0x00000010) != 0) { + output.writeDouble(FieldNames.ry, ry); + } + if ((bitField0_ & 0x00000020) != 0) { + output.writeDouble(FieldNames.rz, rz); + } + output.endObject(); + } + + @Override + public ProtobufTwist3d mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 3220: { + if (input.isAtField(FieldNames.dx)) { + if (!input.trySkipNullValue()) { + dx = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3221: { + if (input.isAtField(FieldNames.dy)) { + if (!input.trySkipNullValue()) { + dy = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3222: { + if (input.isAtField(FieldNames.dz)) { + if (!input.trySkipNullValue()) { + dz = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3654: { + if (input.isAtField(FieldNames.rx)) { + if (!input.trySkipNullValue()) { + rx = input.readDouble(); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3655: { + if (input.isAtField(FieldNames.ry)) { + if (!input.trySkipNullValue()) { + ry = input.readDouble(); + bitField0_ |= 0x00000010; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3656: { + if (input.isAtField(FieldNames.rz)) { + if (!input.trySkipNullValue()) { + rz = input.readDouble(); + bitField0_ |= 0x00000020; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufTwist3d clone() { + return new ProtobufTwist3d().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufTwist3d parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufTwist3d(), data).checkInitialized(); + } + + public static ProtobufTwist3d parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTwist3d(), input).checkInitialized(); + } + + public static ProtobufTwist3d parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTwist3d(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufTwist3d messages + */ + public static MessageFactory getFactory() { + return ProtobufTwist3dFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Geometry3D.wpi_proto_ProtobufTwist3d_descriptor; + } + + private enum ProtobufTwist3dFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufTwist3d create() { + return ProtobufTwist3d.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName dx = FieldName.forField("dx"); + + static final FieldName dy = FieldName.forField("dy"); + + static final FieldName dz = FieldName.forField("dz"); + + static final FieldName rx = FieldName.forField("rx"); + + static final FieldName ry = FieldName.forField("ry"); + + static final FieldName rz = FieldName.forField("rz"); + } + } +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Kinematics.java b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Kinematics.java new file mode 100644 index 00000000000..5494f0b6752 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Kinematics.java @@ -0,0 +1,4540 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. +// Code generated by protocol buffer compiler. Do not edit! +package edu.wpi.first.math.proto; + +import java.io.IOException; +import us.hebi.quickbuf.Descriptors; +import us.hebi.quickbuf.FieldName; +import us.hebi.quickbuf.InvalidProtocolBufferException; +import us.hebi.quickbuf.JsonSink; +import us.hebi.quickbuf.JsonSource; +import us.hebi.quickbuf.MessageFactory; +import us.hebi.quickbuf.ProtoMessage; +import us.hebi.quickbuf.ProtoSink; +import us.hebi.quickbuf.ProtoSource; +import us.hebi.quickbuf.ProtoUtil; +import us.hebi.quickbuf.RepeatedByte; +import us.hebi.quickbuf.RepeatedMessage; + +public final class Kinematics { + private static final RepeatedByte descriptorData = ProtoUtil.decodeBase64(3427, + "ChBraW5lbWF0aWNzLnByb3RvEgl3cGkucHJvdG8aEGdlb21ldHJ5MmQucHJvdG8iTQoVUHJvdG9idWZD" + + "aGFzc2lzU3BlZWRzEg4KAnZ4GAEgASgBUgJ2eBIOCgJ2eRgCIAEoAVICdnkSFAoFb21lZ2EYAyABKAFS" + + "BW9tZWdhIkYKI1Byb3RvYnVmRGlmZmVyZW50aWFsRHJpdmVLaW5lbWF0aWNzEh8KC3RyYWNrX3dpZHRo" + + "GAEgASgBUgp0cmFja1dpZHRoIlAKJFByb3RvYnVmRGlmZmVyZW50aWFsRHJpdmVXaGVlbFNwZWVkcxIS" + + "CgRsZWZ0GAEgASgBUgRsZWZ0EhQKBXJpZ2h0GAIgASgBUgVyaWdodCJTCidQcm90b2J1ZkRpZmZlcmVu" + + "dGlhbERyaXZlV2hlZWxQb3NpdGlvbnMSEgoEbGVmdBgBIAEoAVIEbGVmdBIUCgVyaWdodBgCIAEoAVIF" + + "cmlnaHQipAIKHlByb3RvYnVmTWVjYW51bURyaXZlS2luZW1hdGljcxI/Cgpmcm9udF9sZWZ0GAEgASgL" + + "MiAud3BpLnByb3RvLlByb3RvYnVmVHJhbnNsYXRpb24yZFIJZnJvbnRMZWZ0EkEKC2Zyb250X3JpZ2h0" + + "GAIgASgLMiAud3BpLnByb3RvLlByb3RvYnVmVHJhbnNsYXRpb24yZFIKZnJvbnRSaWdodBI9CglyZWFy" + + "X2xlZnQYAyABKAsyIC53cGkucHJvdG8uUHJvdG9idWZUcmFuc2xhdGlvbjJkUghyZWFyTGVmdBI/Cgpy" + + "ZWFyX3JpZ2h0GAQgASgLMiAud3BpLnByb3RvLlByb3RvYnVmVHJhbnNsYXRpb24yZFIJcmVhclJpZ2h0" + + "Ip8BCiFQcm90b2J1Zk1lY2FudW1Ecml2ZU1vdG9yVm9sdGFnZXMSHQoKZnJvbnRfbGVmdBgBIAEoAVIJ" + + "ZnJvbnRMZWZ0Eh8KC2Zyb250X3JpZ2h0GAIgASgBUgpmcm9udFJpZ2h0EhsKCXJlYXJfbGVmdBgDIAEo" + + "AVIIcmVhckxlZnQSHQoKcmVhcl9yaWdodBgEIAEoAVIJcmVhclJpZ2h0IqABCiJQcm90b2J1Zk1lY2Fu" + + "dW1Ecml2ZVdoZWVsUG9zaXRpb25zEh0KCmZyb250X2xlZnQYASABKAFSCWZyb250TGVmdBIfCgtmcm9u" + + "dF9yaWdodBgCIAEoAVIKZnJvbnRSaWdodBIbCglyZWFyX2xlZnQYAyABKAFSCHJlYXJMZWZ0Eh0KCnJl" + + "YXJfcmlnaHQYBCABKAFSCXJlYXJSaWdodCKdAQofUHJvdG9idWZNZWNhbnVtRHJpdmVXaGVlbFNwZWVk" + + "cxIdCgpmcm9udF9sZWZ0GAEgASgBUglmcm9udExlZnQSHwoLZnJvbnRfcmlnaHQYAiABKAFSCmZyb250" + + "UmlnaHQSGwoJcmVhcl9sZWZ0GAMgASgBUghyZWFyTGVmdBIdCgpyZWFyX3JpZ2h0GAQgASgBUglyZWFy" + + "UmlnaHQiWwodUHJvdG9idWZTd2VydmVEcml2ZUtpbmVtYXRpY3MSOgoHbW9kdWxlcxgBIAMoCzIgLndw", + "aS5wcm90by5Qcm90b2J1ZlRyYW5zbGF0aW9uMmRSB21vZHVsZXMibwocUHJvdG9idWZTd2VydmVNb2R1" + + "bGVQb3NpdGlvbhIaCghkaXN0YW5jZRgBIAEoAVIIZGlzdGFuY2USMwoFYW5nbGUYAiABKAsyHS53cGku" + + "cHJvdG8uUHJvdG9idWZSb3RhdGlvbjJkUgVhbmdsZSJmChlQcm90b2J1ZlN3ZXJ2ZU1vZHVsZVN0YXRl" + + "EhQKBXNwZWVkGAEgASgBUgVzcGVlZBIzCgVhbmdsZRgCIAEoCzIdLndwaS5wcm90by5Qcm90b2J1ZlJv" + + "dGF0aW9uMmRSBWFuZ2xlQhoKGGVkdS53cGkuZmlyc3QubWF0aC5wcm90b0qNDwoGEgQAAEQBCggKAQwS" + + "AwAAEgoICgECEgMCABIKCQoCAwASAwQAGgoICgEIEgMGADEKCQoCCAESAwYAMQoKCgIEABIECAAMAQoK" + + "CgMEAAESAwgIHQoLCgQEAAIAEgMJAhAKDAoFBAACAAUSAwkCCAoMCgUEAAIAARIDCQkLCgwKBQQAAgAD" + + "EgMJDg8KCwoEBAACARIDCgIQCgwKBQQAAgEFEgMKAggKDAoFBAACAQESAwoJCwoMCgUEAAIBAxIDCg4P" + + "CgsKBAQAAgISAwsCEwoMCgUEAAICBRIDCwIICgwKBQQAAgIBEgMLCQ4KDAoFBAACAgMSAwsREgoKCgIE" + + "ARIEDgAQAQoKCgMEAQESAw4IKwoLCgQEAQIAEgMPAhkKDAoFBAECAAUSAw8CCAoMCgUEAQIAARIDDwkU" + + "CgwKBQQBAgADEgMPFxgKCgoCBAISBBIAFQEKCgoDBAIBEgMSCCwKCwoEBAICABIDEwISCgwKBQQCAgAF" + + "EgMTAggKDAoFBAICAAESAxMJDQoMCgUEAgIAAxIDExARCgsKBAQCAgESAxQCEwoMCgUEAgIBBRIDFAII" + + "CgwKBQQCAgEBEgMUCQ4KDAoFBAICAQMSAxQREgoKCgIEAxIEFwAaAQoKCgMEAwESAxcILwoLCgQEAwIA" + + "EgMYAhIKDAoFBAMCAAUSAxgCCAoMCgUEAwIAARIDGAkNCgwKBQQDAgADEgMYEBEKCwoEBAMCARIDGQIT" + + "CgwKBQQDAgEFEgMZAggKDAoFBAMCAQESAxkJDgoMCgUEAwIBAxIDGRESCgoKAgQEEgQcACEBCgoKAwQE" + + "ARIDHAgmCgsKBAQEAgASAx0CJwoMCgUEBAIABhIDHQIXCgwKBQQEAgABEgMdGCIKDAoFBAQCAAMSAx0l" + + "JgoLCgQEBAIBEgMeAigKDAoFBAQCAQYSAx4CFwoMCgUEBAIBARIDHhgjCgwKBQQEAgEDEgMeJicKCwoE" + + "BAQCAhIDHwImCgwKBQQEAgIGEgMfAhcKDAoFBAQCAgESAx8YIQoMCgUEBAICAxIDHyQlCgsKBAQEAgMS" + + "AyACJwoMCgUEBAIDBhIDIAIXCgwKBQQEAgMBEgMgGCIKDAoFBAQCAwMSAyAlJgoKCgIEBRIEIwAoAQoK" + + "CgMEBQESAyMIKQoLCgQEBQIAEgMkAhgKDAoFBAUCAAUSAyQCCAoMCgUEBQIAARIDJAkTCgwKBQQFAgAD", + "EgMkFhcKCwoEBAUCARIDJQIZCgwKBQQFAgEFEgMlAggKDAoFBAUCAQESAyUJFAoMCgUEBQIBAxIDJRcY" + + "CgsKBAQFAgISAyYCFwoMCgUEBQICBRIDJgIICgwKBQQFAgIBEgMmCRIKDAoFBAUCAgMSAyYVFgoLCgQE" + + "BQIDEgMnAhgKDAoFBAUCAwUSAycCCAoMCgUEBQIDARIDJwkTCgwKBQQFAgMDEgMnFhcKCgoCBAYSBCoA" + + "LwEKCgoDBAYBEgMqCCoKCwoEBAYCABIDKwIYCgwKBQQGAgAFEgMrAggKDAoFBAYCAAESAysJEwoMCgUE" + + "BgIAAxIDKxYXCgsKBAQGAgESAywCGQoMCgUEBgIBBRIDLAIICgwKBQQGAgEBEgMsCRQKDAoFBAYCAQMS" + + "AywXGAoLCgQEBgICEgMtAhcKDAoFBAYCAgUSAy0CCAoMCgUEBgICARIDLQkSCgwKBQQGAgIDEgMtFRYK" + + "CwoEBAYCAxIDLgIYCgwKBQQGAgMFEgMuAggKDAoFBAYCAwESAy4JEwoMCgUEBgIDAxIDLhYXCgoKAgQH" + + "EgQxADYBCgoKAwQHARIDMQgnCgsKBAQHAgASAzICGAoMCgUEBwIABRIDMgIICgwKBQQHAgABEgMyCRMK" + + "DAoFBAcCAAMSAzIWFwoLCgQEBwIBEgMzAhkKDAoFBAcCAQUSAzMCCAoMCgUEBwIBARIDMwkUCgwKBQQH" + + "AgEDEgMzFxgKCwoEBAcCAhIDNAIXCgwKBQQHAgIFEgM0AggKDAoFBAcCAgESAzQJEgoMCgUEBwICAxID" + + "NBUWCgsKBAQHAgMSAzUCGAoMCgUEBwIDBRIDNQIICgwKBQQHAgMBEgM1CRMKDAoFBAcCAwMSAzUWFwoK" + + "CgIECBIEOAA6AQoKCgMECAESAzgIJQoLCgQECAIAEgM5Ai0KDAoFBAgCAAQSAzkCCgoMCgUECAIABhID" + + "OQsgCgwKBQQIAgABEgM5ISgKDAoFBAgCAAMSAzkrLAoKCgIECRIEPAA/AQoKCgMECQESAzwIJAoLCgQE" + + "CQIAEgM9AhYKDAoFBAkCAAUSAz0CCAoMCgUECQIAARIDPQkRCgwKBQQJAgADEgM9FBUKCwoEBAkCARID" + + "PgIfCgwKBQQJAgEGEgM+AhQKDAoFBAkCAQESAz4VGgoMCgUECQIBAxIDPh0eCgoKAgQKEgRBAEQBCgoK" + + "AwQKARIDQQghCgsKBAQKAgASA0ICEwoMCgUECgIABRIDQgIICgwKBQQKAgABEgNCCQ4KDAoFBAoCAAMS" + + "A0IREgoLCgQECgIBEgNDAh8KDAoFBAoCAQYSA0MCFAoMCgUECgIBARIDQxUaCgwKBQQKAgEDEgNDHR5i" + + "BnByb3RvMw=="); + + static final Descriptors.FileDescriptor descriptor = Descriptors.FileDescriptor.internalBuildGeneratedFileFrom("kinematics.proto", "wpi.proto", descriptorData, Geometry2D.getDescriptor()); + + static final Descriptors.Descriptor wpi_proto_ProtobufChassisSpeeds_descriptor = descriptor.internalContainedType(49, 77, "ProtobufChassisSpeeds", "wpi.proto.ProtobufChassisSpeeds"); + + static final Descriptors.Descriptor wpi_proto_ProtobufDifferentialDriveKinematics_descriptor = descriptor.internalContainedType(128, 70, "ProtobufDifferentialDriveKinematics", "wpi.proto.ProtobufDifferentialDriveKinematics"); + + static final Descriptors.Descriptor wpi_proto_ProtobufDifferentialDriveWheelSpeeds_descriptor = descriptor.internalContainedType(200, 80, "ProtobufDifferentialDriveWheelSpeeds", "wpi.proto.ProtobufDifferentialDriveWheelSpeeds"); + + static final Descriptors.Descriptor wpi_proto_ProtobufDifferentialDriveWheelPositions_descriptor = descriptor.internalContainedType(282, 83, "ProtobufDifferentialDriveWheelPositions", "wpi.proto.ProtobufDifferentialDriveWheelPositions"); + + static final Descriptors.Descriptor wpi_proto_ProtobufMecanumDriveKinematics_descriptor = descriptor.internalContainedType(368, 292, "ProtobufMecanumDriveKinematics", "wpi.proto.ProtobufMecanumDriveKinematics"); + + static final Descriptors.Descriptor wpi_proto_ProtobufMecanumDriveMotorVoltages_descriptor = descriptor.internalContainedType(663, 159, "ProtobufMecanumDriveMotorVoltages", "wpi.proto.ProtobufMecanumDriveMotorVoltages"); + + static final Descriptors.Descriptor wpi_proto_ProtobufMecanumDriveWheelPositions_descriptor = descriptor.internalContainedType(825, 160, "ProtobufMecanumDriveWheelPositions", "wpi.proto.ProtobufMecanumDriveWheelPositions"); + + static final Descriptors.Descriptor wpi_proto_ProtobufMecanumDriveWheelSpeeds_descriptor = descriptor.internalContainedType(988, 157, "ProtobufMecanumDriveWheelSpeeds", "wpi.proto.ProtobufMecanumDriveWheelSpeeds"); + + static final Descriptors.Descriptor wpi_proto_ProtobufSwerveDriveKinematics_descriptor = descriptor.internalContainedType(1147, 91, "ProtobufSwerveDriveKinematics", "wpi.proto.ProtobufSwerveDriveKinematics"); + + static final Descriptors.Descriptor wpi_proto_ProtobufSwerveModulePosition_descriptor = descriptor.internalContainedType(1240, 111, "ProtobufSwerveModulePosition", "wpi.proto.ProtobufSwerveModulePosition"); + + static final Descriptors.Descriptor wpi_proto_ProtobufSwerveModuleState_descriptor = descriptor.internalContainedType(1353, 102, "ProtobufSwerveModuleState", "wpi.proto.ProtobufSwerveModuleState"); + + /** + * @return this proto file's descriptor. + */ + public static Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + /** + * Protobuf type {@code ProtobufChassisSpeeds} + */ + public static final class ProtobufChassisSpeeds extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double vx = 1; + */ + private double vx; + + /** + * optional double vy = 2; + */ + private double vy; + + /** + * optional double omega = 3; + */ + private double omega; + + private ProtobufChassisSpeeds() { + } + + /** + * @return a new empty instance of {@code ProtobufChassisSpeeds} + */ + public static ProtobufChassisSpeeds newInstance() { + return new ProtobufChassisSpeeds(); + } + + /** + * optional double vx = 1; + * @return whether the vx field is set + */ + public boolean hasVx() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double vx = 1; + * @return this + */ + public ProtobufChassisSpeeds clearVx() { + bitField0_ &= ~0x00000001; + vx = 0D; + return this; + } + + /** + * optional double vx = 1; + * @return the vx + */ + public double getVx() { + return vx; + } + + /** + * optional double vx = 1; + * @param value the vx to set + * @return this + */ + public ProtobufChassisSpeeds setVx(final double value) { + bitField0_ |= 0x00000001; + vx = value; + return this; + } + + /** + * optional double vy = 2; + * @return whether the vy field is set + */ + public boolean hasVy() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double vy = 2; + * @return this + */ + public ProtobufChassisSpeeds clearVy() { + bitField0_ &= ~0x00000002; + vy = 0D; + return this; + } + + /** + * optional double vy = 2; + * @return the vy + */ + public double getVy() { + return vy; + } + + /** + * optional double vy = 2; + * @param value the vy to set + * @return this + */ + public ProtobufChassisSpeeds setVy(final double value) { + bitField0_ |= 0x00000002; + vy = value; + return this; + } + + /** + * optional double omega = 3; + * @return whether the omega field is set + */ + public boolean hasOmega() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double omega = 3; + * @return this + */ + public ProtobufChassisSpeeds clearOmega() { + bitField0_ &= ~0x00000004; + omega = 0D; + return this; + } + + /** + * optional double omega = 3; + * @return the omega + */ + public double getOmega() { + return omega; + } + + /** + * optional double omega = 3; + * @param value the omega to set + * @return this + */ + public ProtobufChassisSpeeds setOmega(final double value) { + bitField0_ |= 0x00000004; + omega = value; + return this; + } + + @Override + public ProtobufChassisSpeeds copyFrom(final ProtobufChassisSpeeds other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + vx = other.vx; + vy = other.vy; + omega = other.omega; + } + return this; + } + + @Override + public ProtobufChassisSpeeds mergeFrom(final ProtobufChassisSpeeds other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasVx()) { + setVx(other.vx); + } + if (other.hasVy()) { + setVy(other.vy); + } + if (other.hasOmega()) { + setOmega(other.omega); + } + return this; + } + + @Override + public ProtobufChassisSpeeds clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + vx = 0D; + vy = 0D; + omega = 0D; + return this; + } + + @Override + public ProtobufChassisSpeeds clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufChassisSpeeds)) { + return false; + } + ProtobufChassisSpeeds other = (ProtobufChassisSpeeds) o; + return bitField0_ == other.bitField0_ + && (!hasVx() || ProtoUtil.isEqual(vx, other.vx)) + && (!hasVy() || ProtoUtil.isEqual(vy, other.vy)) + && (!hasOmega() || ProtoUtil.isEqual(omega, other.omega)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(vx); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(vy); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(omega); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufChassisSpeeds mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // vx + vx = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // vy + vy = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // omega + omega = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.vx, vx); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.vy, vy); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.omega, omega); + } + output.endObject(); + } + + @Override + public ProtobufChassisSpeeds mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 3778: { + if (input.isAtField(FieldNames.vx)) { + if (!input.trySkipNullValue()) { + vx = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3779: { + if (input.isAtField(FieldNames.vy)) { + if (!input.trySkipNullValue()) { + vy = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case 105858401: { + if (input.isAtField(FieldNames.omega)) { + if (!input.trySkipNullValue()) { + omega = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufChassisSpeeds clone() { + return new ProtobufChassisSpeeds().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufChassisSpeeds parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufChassisSpeeds(), data).checkInitialized(); + } + + public static ProtobufChassisSpeeds parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufChassisSpeeds(), input).checkInitialized(); + } + + public static ProtobufChassisSpeeds parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufChassisSpeeds(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufChassisSpeeds messages + */ + public static MessageFactory getFactory() { + return ProtobufChassisSpeedsFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Kinematics.wpi_proto_ProtobufChassisSpeeds_descriptor; + } + + private enum ProtobufChassisSpeedsFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufChassisSpeeds create() { + return ProtobufChassisSpeeds.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName vx = FieldName.forField("vx"); + + static final FieldName vy = FieldName.forField("vy"); + + static final FieldName omega = FieldName.forField("omega"); + } + } + + /** + * Protobuf type {@code ProtobufDifferentialDriveKinematics} + */ + public static final class ProtobufDifferentialDriveKinematics extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double track_width = 1; + */ + private double trackWidth; + + private ProtobufDifferentialDriveKinematics() { + } + + /** + * @return a new empty instance of {@code ProtobufDifferentialDriveKinematics} + */ + public static ProtobufDifferentialDriveKinematics newInstance() { + return new ProtobufDifferentialDriveKinematics(); + } + + /** + * optional double track_width = 1; + * @return whether the trackWidth field is set + */ + public boolean hasTrackWidth() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double track_width = 1; + * @return this + */ + public ProtobufDifferentialDriveKinematics clearTrackWidth() { + bitField0_ &= ~0x00000001; + trackWidth = 0D; + return this; + } + + /** + * optional double track_width = 1; + * @return the trackWidth + */ + public double getTrackWidth() { + return trackWidth; + } + + /** + * optional double track_width = 1; + * @param value the trackWidth to set + * @return this + */ + public ProtobufDifferentialDriveKinematics setTrackWidth(final double value) { + bitField0_ |= 0x00000001; + trackWidth = value; + return this; + } + + @Override + public ProtobufDifferentialDriveKinematics copyFrom( + final ProtobufDifferentialDriveKinematics other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + trackWidth = other.trackWidth; + } + return this; + } + + @Override + public ProtobufDifferentialDriveKinematics mergeFrom( + final ProtobufDifferentialDriveKinematics other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasTrackWidth()) { + setTrackWidth(other.trackWidth); + } + return this; + } + + @Override + public ProtobufDifferentialDriveKinematics clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + trackWidth = 0D; + return this; + } + + @Override + public ProtobufDifferentialDriveKinematics clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufDifferentialDriveKinematics)) { + return false; + } + ProtobufDifferentialDriveKinematics other = (ProtobufDifferentialDriveKinematics) o; + return bitField0_ == other.bitField0_ + && (!hasTrackWidth() || ProtoUtil.isEqual(trackWidth, other.trackWidth)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(trackWidth); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufDifferentialDriveKinematics mergeFrom(final ProtoSource input) throws + IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // trackWidth + trackWidth = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.trackWidth, trackWidth); + } + output.endObject(); + } + + @Override + public ProtobufDifferentialDriveKinematics mergeFrom(final JsonSource input) throws + IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 1152213819: + case 1600986578: { + if (input.isAtField(FieldNames.trackWidth)) { + if (!input.trySkipNullValue()) { + trackWidth = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufDifferentialDriveKinematics clone() { + return new ProtobufDifferentialDriveKinematics().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufDifferentialDriveKinematics parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveKinematics(), data).checkInitialized(); + } + + public static ProtobufDifferentialDriveKinematics parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveKinematics(), input).checkInitialized(); + } + + public static ProtobufDifferentialDriveKinematics parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveKinematics(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufDifferentialDriveKinematics messages + */ + public static MessageFactory getFactory() { + return ProtobufDifferentialDriveKinematicsFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Kinematics.wpi_proto_ProtobufDifferentialDriveKinematics_descriptor; + } + + private enum ProtobufDifferentialDriveKinematicsFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufDifferentialDriveKinematics create() { + return ProtobufDifferentialDriveKinematics.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName trackWidth = FieldName.forField("trackWidth", "track_width"); + } + } + + /** + * Protobuf type {@code ProtobufDifferentialDriveWheelSpeeds} + */ + public static final class ProtobufDifferentialDriveWheelSpeeds extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double left = 1; + */ + private double left; + + /** + * optional double right = 2; + */ + private double right; + + private ProtobufDifferentialDriveWheelSpeeds() { + } + + /** + * @return a new empty instance of {@code ProtobufDifferentialDriveWheelSpeeds} + */ + public static ProtobufDifferentialDriveWheelSpeeds newInstance() { + return new ProtobufDifferentialDriveWheelSpeeds(); + } + + /** + * optional double left = 1; + * @return whether the left field is set + */ + public boolean hasLeft() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double left = 1; + * @return this + */ + public ProtobufDifferentialDriveWheelSpeeds clearLeft() { + bitField0_ &= ~0x00000001; + left = 0D; + return this; + } + + /** + * optional double left = 1; + * @return the left + */ + public double getLeft() { + return left; + } + + /** + * optional double left = 1; + * @param value the left to set + * @return this + */ + public ProtobufDifferentialDriveWheelSpeeds setLeft(final double value) { + bitField0_ |= 0x00000001; + left = value; + return this; + } + + /** + * optional double right = 2; + * @return whether the right field is set + */ + public boolean hasRight() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double right = 2; + * @return this + */ + public ProtobufDifferentialDriveWheelSpeeds clearRight() { + bitField0_ &= ~0x00000002; + right = 0D; + return this; + } + + /** + * optional double right = 2; + * @return the right + */ + public double getRight() { + return right; + } + + /** + * optional double right = 2; + * @param value the right to set + * @return this + */ + public ProtobufDifferentialDriveWheelSpeeds setRight(final double value) { + bitField0_ |= 0x00000002; + right = value; + return this; + } + + @Override + public ProtobufDifferentialDriveWheelSpeeds copyFrom( + final ProtobufDifferentialDriveWheelSpeeds other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + left = other.left; + right = other.right; + } + return this; + } + + @Override + public ProtobufDifferentialDriveWheelSpeeds mergeFrom( + final ProtobufDifferentialDriveWheelSpeeds other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasLeft()) { + setLeft(other.left); + } + if (other.hasRight()) { + setRight(other.right); + } + return this; + } + + @Override + public ProtobufDifferentialDriveWheelSpeeds clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + left = 0D; + right = 0D; + return this; + } + + @Override + public ProtobufDifferentialDriveWheelSpeeds clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufDifferentialDriveWheelSpeeds)) { + return false; + } + ProtobufDifferentialDriveWheelSpeeds other = (ProtobufDifferentialDriveWheelSpeeds) o; + return bitField0_ == other.bitField0_ + && (!hasLeft() || ProtoUtil.isEqual(left, other.left)) + && (!hasRight() || ProtoUtil.isEqual(right, other.right)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(left); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(right); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufDifferentialDriveWheelSpeeds mergeFrom(final ProtoSource input) throws + IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // left + left = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // right + right = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.left, left); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.right, right); + } + output.endObject(); + } + + @Override + public ProtobufDifferentialDriveWheelSpeeds mergeFrom(final JsonSource input) throws + IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 3317767: { + if (input.isAtField(FieldNames.left)) { + if (!input.trySkipNullValue()) { + left = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 108511772: { + if (input.isAtField(FieldNames.right)) { + if (!input.trySkipNullValue()) { + right = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufDifferentialDriveWheelSpeeds clone() { + return new ProtobufDifferentialDriveWheelSpeeds().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufDifferentialDriveWheelSpeeds parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveWheelSpeeds(), data).checkInitialized(); + } + + public static ProtobufDifferentialDriveWheelSpeeds parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveWheelSpeeds(), input).checkInitialized(); + } + + public static ProtobufDifferentialDriveWheelSpeeds parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveWheelSpeeds(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufDifferentialDriveWheelSpeeds messages + */ + public static MessageFactory getFactory() { + return ProtobufDifferentialDriveWheelSpeedsFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Kinematics.wpi_proto_ProtobufDifferentialDriveWheelSpeeds_descriptor; + } + + private enum ProtobufDifferentialDriveWheelSpeedsFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufDifferentialDriveWheelSpeeds create() { + return ProtobufDifferentialDriveWheelSpeeds.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName left = FieldName.forField("left"); + + static final FieldName right = FieldName.forField("right"); + } + } + + /** + * Protobuf type {@code ProtobufDifferentialDriveWheelPositions} + */ + public static final class ProtobufDifferentialDriveWheelPositions extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double left = 1; + */ + private double left; + + /** + * optional double right = 2; + */ + private double right; + + private ProtobufDifferentialDriveWheelPositions() { + } + + /** + * @return a new empty instance of {@code ProtobufDifferentialDriveWheelPositions} + */ + public static ProtobufDifferentialDriveWheelPositions newInstance() { + return new ProtobufDifferentialDriveWheelPositions(); + } + + /** + * optional double left = 1; + * @return whether the left field is set + */ + public boolean hasLeft() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double left = 1; + * @return this + */ + public ProtobufDifferentialDriveWheelPositions clearLeft() { + bitField0_ &= ~0x00000001; + left = 0D; + return this; + } + + /** + * optional double left = 1; + * @return the left + */ + public double getLeft() { + return left; + } + + /** + * optional double left = 1; + * @param value the left to set + * @return this + */ + public ProtobufDifferentialDriveWheelPositions setLeft(final double value) { + bitField0_ |= 0x00000001; + left = value; + return this; + } + + /** + * optional double right = 2; + * @return whether the right field is set + */ + public boolean hasRight() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double right = 2; + * @return this + */ + public ProtobufDifferentialDriveWheelPositions clearRight() { + bitField0_ &= ~0x00000002; + right = 0D; + return this; + } + + /** + * optional double right = 2; + * @return the right + */ + public double getRight() { + return right; + } + + /** + * optional double right = 2; + * @param value the right to set + * @return this + */ + public ProtobufDifferentialDriveWheelPositions setRight(final double value) { + bitField0_ |= 0x00000002; + right = value; + return this; + } + + @Override + public ProtobufDifferentialDriveWheelPositions copyFrom( + final ProtobufDifferentialDriveWheelPositions other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + left = other.left; + right = other.right; + } + return this; + } + + @Override + public ProtobufDifferentialDriveWheelPositions mergeFrom( + final ProtobufDifferentialDriveWheelPositions other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasLeft()) { + setLeft(other.left); + } + if (other.hasRight()) { + setRight(other.right); + } + return this; + } + + @Override + public ProtobufDifferentialDriveWheelPositions clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + left = 0D; + right = 0D; + return this; + } + + @Override + public ProtobufDifferentialDriveWheelPositions clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufDifferentialDriveWheelPositions)) { + return false; + } + ProtobufDifferentialDriveWheelPositions other = (ProtobufDifferentialDriveWheelPositions) o; + return bitField0_ == other.bitField0_ + && (!hasLeft() || ProtoUtil.isEqual(left, other.left)) + && (!hasRight() || ProtoUtil.isEqual(right, other.right)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(left); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(right); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufDifferentialDriveWheelPositions mergeFrom(final ProtoSource input) throws + IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // left + left = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // right + right = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.left, left); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.right, right); + } + output.endObject(); + } + + @Override + public ProtobufDifferentialDriveWheelPositions mergeFrom(final JsonSource input) throws + IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 3317767: { + if (input.isAtField(FieldNames.left)) { + if (!input.trySkipNullValue()) { + left = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 108511772: { + if (input.isAtField(FieldNames.right)) { + if (!input.trySkipNullValue()) { + right = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufDifferentialDriveWheelPositions clone() { + return new ProtobufDifferentialDriveWheelPositions().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufDifferentialDriveWheelPositions parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveWheelPositions(), data).checkInitialized(); + } + + public static ProtobufDifferentialDriveWheelPositions parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveWheelPositions(), input).checkInitialized(); + } + + public static ProtobufDifferentialDriveWheelPositions parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufDifferentialDriveWheelPositions(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufDifferentialDriveWheelPositions messages + */ + public static MessageFactory getFactory() { + return ProtobufDifferentialDriveWheelPositionsFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Kinematics.wpi_proto_ProtobufDifferentialDriveWheelPositions_descriptor; + } + + private enum ProtobufDifferentialDriveWheelPositionsFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufDifferentialDriveWheelPositions create() { + return ProtobufDifferentialDriveWheelPositions.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName left = FieldName.forField("left"); + + static final FieldName right = FieldName.forField("right"); + } + } + + /** + * Protobuf type {@code ProtobufMecanumDriveKinematics} + */ + public static final class ProtobufMecanumDriveKinematics extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional .wpi.proto.ProtobufTranslation2d front_left = 1; + */ + private final Geometry2D.ProtobufTranslation2d frontLeft = Geometry2D.ProtobufTranslation2d.newInstance(); + + /** + * optional .wpi.proto.ProtobufTranslation2d front_right = 2; + */ + private final Geometry2D.ProtobufTranslation2d frontRight = Geometry2D.ProtobufTranslation2d.newInstance(); + + /** + * optional .wpi.proto.ProtobufTranslation2d rear_left = 3; + */ + private final Geometry2D.ProtobufTranslation2d rearLeft = Geometry2D.ProtobufTranslation2d.newInstance(); + + /** + * optional .wpi.proto.ProtobufTranslation2d rear_right = 4; + */ + private final Geometry2D.ProtobufTranslation2d rearRight = Geometry2D.ProtobufTranslation2d.newInstance(); + + private ProtobufMecanumDriveKinematics() { + } + + /** + * @return a new empty instance of {@code ProtobufMecanumDriveKinematics} + */ + public static ProtobufMecanumDriveKinematics newInstance() { + return new ProtobufMecanumDriveKinematics(); + } + + /** + * optional .wpi.proto.ProtobufTranslation2d front_left = 1; + * @return whether the frontLeft field is set + */ + public boolean hasFrontLeft() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d front_left = 1; + * @return this + */ + public ProtobufMecanumDriveKinematics clearFrontLeft() { + bitField0_ &= ~0x00000001; + frontLeft.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d front_left = 1; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableFrontLeft()} if you want to modify it. + * + * @return internal storage object for reading + */ + public Geometry2D.ProtobufTranslation2d getFrontLeft() { + return frontLeft; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d front_left = 1; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public Geometry2D.ProtobufTranslation2d getMutableFrontLeft() { + bitField0_ |= 0x00000001; + return frontLeft; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d front_left = 1; + * @param value the frontLeft to set + * @return this + */ + public ProtobufMecanumDriveKinematics setFrontLeft( + final Geometry2D.ProtobufTranslation2d value) { + bitField0_ |= 0x00000001; + frontLeft.copyFrom(value); + return this; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d front_right = 2; + * @return whether the frontRight field is set + */ + public boolean hasFrontRight() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d front_right = 2; + * @return this + */ + public ProtobufMecanumDriveKinematics clearFrontRight() { + bitField0_ &= ~0x00000002; + frontRight.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d front_right = 2; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableFrontRight()} if you want to modify it. + * + * @return internal storage object for reading + */ + public Geometry2D.ProtobufTranslation2d getFrontRight() { + return frontRight; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d front_right = 2; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public Geometry2D.ProtobufTranslation2d getMutableFrontRight() { + bitField0_ |= 0x00000002; + return frontRight; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d front_right = 2; + * @param value the frontRight to set + * @return this + */ + public ProtobufMecanumDriveKinematics setFrontRight( + final Geometry2D.ProtobufTranslation2d value) { + bitField0_ |= 0x00000002; + frontRight.copyFrom(value); + return this; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d rear_left = 3; + * @return whether the rearLeft field is set + */ + public boolean hasRearLeft() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d rear_left = 3; + * @return this + */ + public ProtobufMecanumDriveKinematics clearRearLeft() { + bitField0_ &= ~0x00000004; + rearLeft.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d rear_left = 3; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableRearLeft()} if you want to modify it. + * + * @return internal storage object for reading + */ + public Geometry2D.ProtobufTranslation2d getRearLeft() { + return rearLeft; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d rear_left = 3; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public Geometry2D.ProtobufTranslation2d getMutableRearLeft() { + bitField0_ |= 0x00000004; + return rearLeft; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d rear_left = 3; + * @param value the rearLeft to set + * @return this + */ + public ProtobufMecanumDriveKinematics setRearLeft( + final Geometry2D.ProtobufTranslation2d value) { + bitField0_ |= 0x00000004; + rearLeft.copyFrom(value); + return this; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d rear_right = 4; + * @return whether the rearRight field is set + */ + public boolean hasRearRight() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d rear_right = 4; + * @return this + */ + public ProtobufMecanumDriveKinematics clearRearRight() { + bitField0_ &= ~0x00000008; + rearRight.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d rear_right = 4; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableRearRight()} if you want to modify it. + * + * @return internal storage object for reading + */ + public Geometry2D.ProtobufTranslation2d getRearRight() { + return rearRight; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d rear_right = 4; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public Geometry2D.ProtobufTranslation2d getMutableRearRight() { + bitField0_ |= 0x00000008; + return rearRight; + } + + /** + * optional .wpi.proto.ProtobufTranslation2d rear_right = 4; + * @param value the rearRight to set + * @return this + */ + public ProtobufMecanumDriveKinematics setRearRight( + final Geometry2D.ProtobufTranslation2d value) { + bitField0_ |= 0x00000008; + rearRight.copyFrom(value); + return this; + } + + @Override + public ProtobufMecanumDriveKinematics copyFrom(final ProtobufMecanumDriveKinematics other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + frontLeft.copyFrom(other.frontLeft); + frontRight.copyFrom(other.frontRight); + rearLeft.copyFrom(other.rearLeft); + rearRight.copyFrom(other.rearRight); + } + return this; + } + + @Override + public ProtobufMecanumDriveKinematics mergeFrom(final ProtobufMecanumDriveKinematics other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasFrontLeft()) { + getMutableFrontLeft().mergeFrom(other.frontLeft); + } + if (other.hasFrontRight()) { + getMutableFrontRight().mergeFrom(other.frontRight); + } + if (other.hasRearLeft()) { + getMutableRearLeft().mergeFrom(other.rearLeft); + } + if (other.hasRearRight()) { + getMutableRearRight().mergeFrom(other.rearRight); + } + return this; + } + + @Override + public ProtobufMecanumDriveKinematics clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + frontLeft.clear(); + frontRight.clear(); + rearLeft.clear(); + rearRight.clear(); + return this; + } + + @Override + public ProtobufMecanumDriveKinematics clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + frontLeft.clearQuick(); + frontRight.clearQuick(); + rearLeft.clearQuick(); + rearRight.clearQuick(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufMecanumDriveKinematics)) { + return false; + } + ProtobufMecanumDriveKinematics other = (ProtobufMecanumDriveKinematics) o; + return bitField0_ == other.bitField0_ + && (!hasFrontLeft() || frontLeft.equals(other.frontLeft)) + && (!hasFrontRight() || frontRight.equals(other.frontRight)) + && (!hasRearLeft() || rearLeft.equals(other.rearLeft)) + && (!hasRearRight() || rearRight.equals(other.rearRight)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 10); + output.writeMessageNoTag(frontLeft); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 18); + output.writeMessageNoTag(frontRight); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 26); + output.writeMessageNoTag(rearLeft); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRawByte((byte) 34); + output.writeMessageNoTag(rearRight); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(frontLeft); + } + if ((bitField0_ & 0x00000002) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(frontRight); + } + if ((bitField0_ & 0x00000004) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(rearLeft); + } + if ((bitField0_ & 0x00000008) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(rearRight); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufMecanumDriveKinematics mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 10: { + // frontLeft + input.readMessage(frontLeft); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 18) { + break; + } + } + case 18: { + // frontRight + input.readMessage(frontRight); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 26) { + break; + } + } + case 26: { + // rearLeft + input.readMessage(rearLeft); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 34) { + break; + } + } + case 34: { + // rearRight + input.readMessage(rearRight); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeMessage(FieldNames.frontLeft, frontLeft); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeMessage(FieldNames.frontRight, frontRight); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeMessage(FieldNames.rearLeft, rearLeft); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeMessage(FieldNames.rearRight, rearRight); + } + output.endObject(); + } + + @Override + public ProtobufMecanumDriveKinematics mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 127514064: + case -324277155: { + if (input.isAtField(FieldNames.frontLeft)) { + if (!input.trySkipNullValue()) { + input.readMessage(frontLeft); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case -336370317: + case -1456996218: { + if (input.isAtField(FieldNames.frontRight)) { + if (!input.trySkipNullValue()) { + input.readMessage(frontRight); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case -854852661: + case -712874558: { + if (input.isAtField(FieldNames.rearLeft)) { + if (!input.trySkipNullValue()) { + input.readMessage(rearLeft); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case -724967720: + case -618613823: { + if (input.isAtField(FieldNames.rearRight)) { + if (!input.trySkipNullValue()) { + input.readMessage(rearRight); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufMecanumDriveKinematics clone() { + return new ProtobufMecanumDriveKinematics().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufMecanumDriveKinematics parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufMecanumDriveKinematics(), data).checkInitialized(); + } + + public static ProtobufMecanumDriveKinematics parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufMecanumDriveKinematics(), input).checkInitialized(); + } + + public static ProtobufMecanumDriveKinematics parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufMecanumDriveKinematics(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufMecanumDriveKinematics messages + */ + public static MessageFactory getFactory() { + return ProtobufMecanumDriveKinematicsFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Kinematics.wpi_proto_ProtobufMecanumDriveKinematics_descriptor; + } + + private enum ProtobufMecanumDriveKinematicsFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufMecanumDriveKinematics create() { + return ProtobufMecanumDriveKinematics.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName frontLeft = FieldName.forField("frontLeft", "front_left"); + + static final FieldName frontRight = FieldName.forField("frontRight", "front_right"); + + static final FieldName rearLeft = FieldName.forField("rearLeft", "rear_left"); + + static final FieldName rearRight = FieldName.forField("rearRight", "rear_right"); + } + } + + /** + * Protobuf type {@code ProtobufMecanumDriveMotorVoltages} + */ + public static final class ProtobufMecanumDriveMotorVoltages extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double front_left = 1; + */ + private double frontLeft; + + /** + * optional double front_right = 2; + */ + private double frontRight; + + /** + * optional double rear_left = 3; + */ + private double rearLeft; + + /** + * optional double rear_right = 4; + */ + private double rearRight; + + private ProtobufMecanumDriveMotorVoltages() { + } + + /** + * @return a new empty instance of {@code ProtobufMecanumDriveMotorVoltages} + */ + public static ProtobufMecanumDriveMotorVoltages newInstance() { + return new ProtobufMecanumDriveMotorVoltages(); + } + + /** + * optional double front_left = 1; + * @return whether the frontLeft field is set + */ + public boolean hasFrontLeft() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double front_left = 1; + * @return this + */ + public ProtobufMecanumDriveMotorVoltages clearFrontLeft() { + bitField0_ &= ~0x00000001; + frontLeft = 0D; + return this; + } + + /** + * optional double front_left = 1; + * @return the frontLeft + */ + public double getFrontLeft() { + return frontLeft; + } + + /** + * optional double front_left = 1; + * @param value the frontLeft to set + * @return this + */ + public ProtobufMecanumDriveMotorVoltages setFrontLeft(final double value) { + bitField0_ |= 0x00000001; + frontLeft = value; + return this; + } + + /** + * optional double front_right = 2; + * @return whether the frontRight field is set + */ + public boolean hasFrontRight() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double front_right = 2; + * @return this + */ + public ProtobufMecanumDriveMotorVoltages clearFrontRight() { + bitField0_ &= ~0x00000002; + frontRight = 0D; + return this; + } + + /** + * optional double front_right = 2; + * @return the frontRight + */ + public double getFrontRight() { + return frontRight; + } + + /** + * optional double front_right = 2; + * @param value the frontRight to set + * @return this + */ + public ProtobufMecanumDriveMotorVoltages setFrontRight(final double value) { + bitField0_ |= 0x00000002; + frontRight = value; + return this; + } + + /** + * optional double rear_left = 3; + * @return whether the rearLeft field is set + */ + public boolean hasRearLeft() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double rear_left = 3; + * @return this + */ + public ProtobufMecanumDriveMotorVoltages clearRearLeft() { + bitField0_ &= ~0x00000004; + rearLeft = 0D; + return this; + } + + /** + * optional double rear_left = 3; + * @return the rearLeft + */ + public double getRearLeft() { + return rearLeft; + } + + /** + * optional double rear_left = 3; + * @param value the rearLeft to set + * @return this + */ + public ProtobufMecanumDriveMotorVoltages setRearLeft(final double value) { + bitField0_ |= 0x00000004; + rearLeft = value; + return this; + } + + /** + * optional double rear_right = 4; + * @return whether the rearRight field is set + */ + public boolean hasRearRight() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * optional double rear_right = 4; + * @return this + */ + public ProtobufMecanumDriveMotorVoltages clearRearRight() { + bitField0_ &= ~0x00000008; + rearRight = 0D; + return this; + } + + /** + * optional double rear_right = 4; + * @return the rearRight + */ + public double getRearRight() { + return rearRight; + } + + /** + * optional double rear_right = 4; + * @param value the rearRight to set + * @return this + */ + public ProtobufMecanumDriveMotorVoltages setRearRight(final double value) { + bitField0_ |= 0x00000008; + rearRight = value; + return this; + } + + @Override + public ProtobufMecanumDriveMotorVoltages copyFrom( + final ProtobufMecanumDriveMotorVoltages other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + frontLeft = other.frontLeft; + frontRight = other.frontRight; + rearLeft = other.rearLeft; + rearRight = other.rearRight; + } + return this; + } + + @Override + public ProtobufMecanumDriveMotorVoltages mergeFrom( + final ProtobufMecanumDriveMotorVoltages other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasFrontLeft()) { + setFrontLeft(other.frontLeft); + } + if (other.hasFrontRight()) { + setFrontRight(other.frontRight); + } + if (other.hasRearLeft()) { + setRearLeft(other.rearLeft); + } + if (other.hasRearRight()) { + setRearRight(other.rearRight); + } + return this; + } + + @Override + public ProtobufMecanumDriveMotorVoltages clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + frontLeft = 0D; + frontRight = 0D; + rearLeft = 0D; + rearRight = 0D; + return this; + } + + @Override + public ProtobufMecanumDriveMotorVoltages clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufMecanumDriveMotorVoltages)) { + return false; + } + ProtobufMecanumDriveMotorVoltages other = (ProtobufMecanumDriveMotorVoltages) o; + return bitField0_ == other.bitField0_ + && (!hasFrontLeft() || ProtoUtil.isEqual(frontLeft, other.frontLeft)) + && (!hasFrontRight() || ProtoUtil.isEqual(frontRight, other.frontRight)) + && (!hasRearLeft() || ProtoUtil.isEqual(rearLeft, other.rearLeft)) + && (!hasRearRight() || ProtoUtil.isEqual(rearRight, other.rearRight)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(frontLeft); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(frontRight); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(rearLeft); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRawByte((byte) 33); + output.writeDoubleNoTag(rearRight); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000008) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufMecanumDriveMotorVoltages mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // frontLeft + frontLeft = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // frontRight + frontRight = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // rearLeft + rearLeft = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 33) { + break; + } + } + case 33: { + // rearRight + rearRight = input.readDouble(); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.frontLeft, frontLeft); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.frontRight, frontRight); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.rearLeft, rearLeft); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeDouble(FieldNames.rearRight, rearRight); + } + output.endObject(); + } + + @Override + public ProtobufMecanumDriveMotorVoltages mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 127514064: + case -324277155: { + if (input.isAtField(FieldNames.frontLeft)) { + if (!input.trySkipNullValue()) { + frontLeft = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case -336370317: + case -1456996218: { + if (input.isAtField(FieldNames.frontRight)) { + if (!input.trySkipNullValue()) { + frontRight = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case -854852661: + case -712874558: { + if (input.isAtField(FieldNames.rearLeft)) { + if (!input.trySkipNullValue()) { + rearLeft = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case -724967720: + case -618613823: { + if (input.isAtField(FieldNames.rearRight)) { + if (!input.trySkipNullValue()) { + rearRight = input.readDouble(); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufMecanumDriveMotorVoltages clone() { + return new ProtobufMecanumDriveMotorVoltages().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufMecanumDriveMotorVoltages parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufMecanumDriveMotorVoltages(), data).checkInitialized(); + } + + public static ProtobufMecanumDriveMotorVoltages parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufMecanumDriveMotorVoltages(), input).checkInitialized(); + } + + public static ProtobufMecanumDriveMotorVoltages parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufMecanumDriveMotorVoltages(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufMecanumDriveMotorVoltages messages + */ + public static MessageFactory getFactory() { + return ProtobufMecanumDriveMotorVoltagesFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Kinematics.wpi_proto_ProtobufMecanumDriveMotorVoltages_descriptor; + } + + private enum ProtobufMecanumDriveMotorVoltagesFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufMecanumDriveMotorVoltages create() { + return ProtobufMecanumDriveMotorVoltages.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName frontLeft = FieldName.forField("frontLeft", "front_left"); + + static final FieldName frontRight = FieldName.forField("frontRight", "front_right"); + + static final FieldName rearLeft = FieldName.forField("rearLeft", "rear_left"); + + static final FieldName rearRight = FieldName.forField("rearRight", "rear_right"); + } + } + + /** + * Protobuf type {@code ProtobufMecanumDriveWheelPositions} + */ + public static final class ProtobufMecanumDriveWheelPositions extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double front_left = 1; + */ + private double frontLeft; + + /** + * optional double front_right = 2; + */ + private double frontRight; + + /** + * optional double rear_left = 3; + */ + private double rearLeft; + + /** + * optional double rear_right = 4; + */ + private double rearRight; + + private ProtobufMecanumDriveWheelPositions() { + } + + /** + * @return a new empty instance of {@code ProtobufMecanumDriveWheelPositions} + */ + public static ProtobufMecanumDriveWheelPositions newInstance() { + return new ProtobufMecanumDriveWheelPositions(); + } + + /** + * optional double front_left = 1; + * @return whether the frontLeft field is set + */ + public boolean hasFrontLeft() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double front_left = 1; + * @return this + */ + public ProtobufMecanumDriveWheelPositions clearFrontLeft() { + bitField0_ &= ~0x00000001; + frontLeft = 0D; + return this; + } + + /** + * optional double front_left = 1; + * @return the frontLeft + */ + public double getFrontLeft() { + return frontLeft; + } + + /** + * optional double front_left = 1; + * @param value the frontLeft to set + * @return this + */ + public ProtobufMecanumDriveWheelPositions setFrontLeft(final double value) { + bitField0_ |= 0x00000001; + frontLeft = value; + return this; + } + + /** + * optional double front_right = 2; + * @return whether the frontRight field is set + */ + public boolean hasFrontRight() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double front_right = 2; + * @return this + */ + public ProtobufMecanumDriveWheelPositions clearFrontRight() { + bitField0_ &= ~0x00000002; + frontRight = 0D; + return this; + } + + /** + * optional double front_right = 2; + * @return the frontRight + */ + public double getFrontRight() { + return frontRight; + } + + /** + * optional double front_right = 2; + * @param value the frontRight to set + * @return this + */ + public ProtobufMecanumDriveWheelPositions setFrontRight(final double value) { + bitField0_ |= 0x00000002; + frontRight = value; + return this; + } + + /** + * optional double rear_left = 3; + * @return whether the rearLeft field is set + */ + public boolean hasRearLeft() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double rear_left = 3; + * @return this + */ + public ProtobufMecanumDriveWheelPositions clearRearLeft() { + bitField0_ &= ~0x00000004; + rearLeft = 0D; + return this; + } + + /** + * optional double rear_left = 3; + * @return the rearLeft + */ + public double getRearLeft() { + return rearLeft; + } + + /** + * optional double rear_left = 3; + * @param value the rearLeft to set + * @return this + */ + public ProtobufMecanumDriveWheelPositions setRearLeft(final double value) { + bitField0_ |= 0x00000004; + rearLeft = value; + return this; + } + + /** + * optional double rear_right = 4; + * @return whether the rearRight field is set + */ + public boolean hasRearRight() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * optional double rear_right = 4; + * @return this + */ + public ProtobufMecanumDriveWheelPositions clearRearRight() { + bitField0_ &= ~0x00000008; + rearRight = 0D; + return this; + } + + /** + * optional double rear_right = 4; + * @return the rearRight + */ + public double getRearRight() { + return rearRight; + } + + /** + * optional double rear_right = 4; + * @param value the rearRight to set + * @return this + */ + public ProtobufMecanumDriveWheelPositions setRearRight(final double value) { + bitField0_ |= 0x00000008; + rearRight = value; + return this; + } + + @Override + public ProtobufMecanumDriveWheelPositions copyFrom( + final ProtobufMecanumDriveWheelPositions other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + frontLeft = other.frontLeft; + frontRight = other.frontRight; + rearLeft = other.rearLeft; + rearRight = other.rearRight; + } + return this; + } + + @Override + public ProtobufMecanumDriveWheelPositions mergeFrom( + final ProtobufMecanumDriveWheelPositions other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasFrontLeft()) { + setFrontLeft(other.frontLeft); + } + if (other.hasFrontRight()) { + setFrontRight(other.frontRight); + } + if (other.hasRearLeft()) { + setRearLeft(other.rearLeft); + } + if (other.hasRearRight()) { + setRearRight(other.rearRight); + } + return this; + } + + @Override + public ProtobufMecanumDriveWheelPositions clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + frontLeft = 0D; + frontRight = 0D; + rearLeft = 0D; + rearRight = 0D; + return this; + } + + @Override + public ProtobufMecanumDriveWheelPositions clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufMecanumDriveWheelPositions)) { + return false; + } + ProtobufMecanumDriveWheelPositions other = (ProtobufMecanumDriveWheelPositions) o; + return bitField0_ == other.bitField0_ + && (!hasFrontLeft() || ProtoUtil.isEqual(frontLeft, other.frontLeft)) + && (!hasFrontRight() || ProtoUtil.isEqual(frontRight, other.frontRight)) + && (!hasRearLeft() || ProtoUtil.isEqual(rearLeft, other.rearLeft)) + && (!hasRearRight() || ProtoUtil.isEqual(rearRight, other.rearRight)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(frontLeft); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(frontRight); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(rearLeft); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRawByte((byte) 33); + output.writeDoubleNoTag(rearRight); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000008) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufMecanumDriveWheelPositions mergeFrom(final ProtoSource input) throws + IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // frontLeft + frontLeft = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // frontRight + frontRight = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // rearLeft + rearLeft = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 33) { + break; + } + } + case 33: { + // rearRight + rearRight = input.readDouble(); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.frontLeft, frontLeft); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.frontRight, frontRight); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.rearLeft, rearLeft); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeDouble(FieldNames.rearRight, rearRight); + } + output.endObject(); + } + + @Override + public ProtobufMecanumDriveWheelPositions mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 127514064: + case -324277155: { + if (input.isAtField(FieldNames.frontLeft)) { + if (!input.trySkipNullValue()) { + frontLeft = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case -336370317: + case -1456996218: { + if (input.isAtField(FieldNames.frontRight)) { + if (!input.trySkipNullValue()) { + frontRight = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case -854852661: + case -712874558: { + if (input.isAtField(FieldNames.rearLeft)) { + if (!input.trySkipNullValue()) { + rearLeft = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case -724967720: + case -618613823: { + if (input.isAtField(FieldNames.rearRight)) { + if (!input.trySkipNullValue()) { + rearRight = input.readDouble(); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufMecanumDriveWheelPositions clone() { + return new ProtobufMecanumDriveWheelPositions().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufMecanumDriveWheelPositions parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufMecanumDriveWheelPositions(), data).checkInitialized(); + } + + public static ProtobufMecanumDriveWheelPositions parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufMecanumDriveWheelPositions(), input).checkInitialized(); + } + + public static ProtobufMecanumDriveWheelPositions parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufMecanumDriveWheelPositions(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufMecanumDriveWheelPositions messages + */ + public static MessageFactory getFactory() { + return ProtobufMecanumDriveWheelPositionsFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Kinematics.wpi_proto_ProtobufMecanumDriveWheelPositions_descriptor; + } + + private enum ProtobufMecanumDriveWheelPositionsFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufMecanumDriveWheelPositions create() { + return ProtobufMecanumDriveWheelPositions.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName frontLeft = FieldName.forField("frontLeft", "front_left"); + + static final FieldName frontRight = FieldName.forField("frontRight", "front_right"); + + static final FieldName rearLeft = FieldName.forField("rearLeft", "rear_left"); + + static final FieldName rearRight = FieldName.forField("rearRight", "rear_right"); + } + } + + /** + * Protobuf type {@code ProtobufMecanumDriveWheelSpeeds} + */ + public static final class ProtobufMecanumDriveWheelSpeeds extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double front_left = 1; + */ + private double frontLeft; + + /** + * optional double front_right = 2; + */ + private double frontRight; + + /** + * optional double rear_left = 3; + */ + private double rearLeft; + + /** + * optional double rear_right = 4; + */ + private double rearRight; + + private ProtobufMecanumDriveWheelSpeeds() { + } + + /** + * @return a new empty instance of {@code ProtobufMecanumDriveWheelSpeeds} + */ + public static ProtobufMecanumDriveWheelSpeeds newInstance() { + return new ProtobufMecanumDriveWheelSpeeds(); + } + + /** + * optional double front_left = 1; + * @return whether the frontLeft field is set + */ + public boolean hasFrontLeft() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double front_left = 1; + * @return this + */ + public ProtobufMecanumDriveWheelSpeeds clearFrontLeft() { + bitField0_ &= ~0x00000001; + frontLeft = 0D; + return this; + } + + /** + * optional double front_left = 1; + * @return the frontLeft + */ + public double getFrontLeft() { + return frontLeft; + } + + /** + * optional double front_left = 1; + * @param value the frontLeft to set + * @return this + */ + public ProtobufMecanumDriveWheelSpeeds setFrontLeft(final double value) { + bitField0_ |= 0x00000001; + frontLeft = value; + return this; + } + + /** + * optional double front_right = 2; + * @return whether the frontRight field is set + */ + public boolean hasFrontRight() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double front_right = 2; + * @return this + */ + public ProtobufMecanumDriveWheelSpeeds clearFrontRight() { + bitField0_ &= ~0x00000002; + frontRight = 0D; + return this; + } + + /** + * optional double front_right = 2; + * @return the frontRight + */ + public double getFrontRight() { + return frontRight; + } + + /** + * optional double front_right = 2; + * @param value the frontRight to set + * @return this + */ + public ProtobufMecanumDriveWheelSpeeds setFrontRight(final double value) { + bitField0_ |= 0x00000002; + frontRight = value; + return this; + } + + /** + * optional double rear_left = 3; + * @return whether the rearLeft field is set + */ + public boolean hasRearLeft() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double rear_left = 3; + * @return this + */ + public ProtobufMecanumDriveWheelSpeeds clearRearLeft() { + bitField0_ &= ~0x00000004; + rearLeft = 0D; + return this; + } + + /** + * optional double rear_left = 3; + * @return the rearLeft + */ + public double getRearLeft() { + return rearLeft; + } + + /** + * optional double rear_left = 3; + * @param value the rearLeft to set + * @return this + */ + public ProtobufMecanumDriveWheelSpeeds setRearLeft(final double value) { + bitField0_ |= 0x00000004; + rearLeft = value; + return this; + } + + /** + * optional double rear_right = 4; + * @return whether the rearRight field is set + */ + public boolean hasRearRight() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * optional double rear_right = 4; + * @return this + */ + public ProtobufMecanumDriveWheelSpeeds clearRearRight() { + bitField0_ &= ~0x00000008; + rearRight = 0D; + return this; + } + + /** + * optional double rear_right = 4; + * @return the rearRight + */ + public double getRearRight() { + return rearRight; + } + + /** + * optional double rear_right = 4; + * @param value the rearRight to set + * @return this + */ + public ProtobufMecanumDriveWheelSpeeds setRearRight(final double value) { + bitField0_ |= 0x00000008; + rearRight = value; + return this; + } + + @Override + public ProtobufMecanumDriveWheelSpeeds copyFrom(final ProtobufMecanumDriveWheelSpeeds other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + frontLeft = other.frontLeft; + frontRight = other.frontRight; + rearLeft = other.rearLeft; + rearRight = other.rearRight; + } + return this; + } + + @Override + public ProtobufMecanumDriveWheelSpeeds mergeFrom(final ProtobufMecanumDriveWheelSpeeds other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasFrontLeft()) { + setFrontLeft(other.frontLeft); + } + if (other.hasFrontRight()) { + setFrontRight(other.frontRight); + } + if (other.hasRearLeft()) { + setRearLeft(other.rearLeft); + } + if (other.hasRearRight()) { + setRearRight(other.rearRight); + } + return this; + } + + @Override + public ProtobufMecanumDriveWheelSpeeds clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + frontLeft = 0D; + frontRight = 0D; + rearLeft = 0D; + rearRight = 0D; + return this; + } + + @Override + public ProtobufMecanumDriveWheelSpeeds clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufMecanumDriveWheelSpeeds)) { + return false; + } + ProtobufMecanumDriveWheelSpeeds other = (ProtobufMecanumDriveWheelSpeeds) o; + return bitField0_ == other.bitField0_ + && (!hasFrontLeft() || ProtoUtil.isEqual(frontLeft, other.frontLeft)) + && (!hasFrontRight() || ProtoUtil.isEqual(frontRight, other.frontRight)) + && (!hasRearLeft() || ProtoUtil.isEqual(rearLeft, other.rearLeft)) + && (!hasRearRight() || ProtoUtil.isEqual(rearRight, other.rearRight)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(frontLeft); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(frontRight); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(rearLeft); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRawByte((byte) 33); + output.writeDoubleNoTag(rearRight); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000008) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufMecanumDriveWheelSpeeds mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // frontLeft + frontLeft = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // frontRight + frontRight = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // rearLeft + rearLeft = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 33) { + break; + } + } + case 33: { + // rearRight + rearRight = input.readDouble(); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.frontLeft, frontLeft); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.frontRight, frontRight); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.rearLeft, rearLeft); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeDouble(FieldNames.rearRight, rearRight); + } + output.endObject(); + } + + @Override + public ProtobufMecanumDriveWheelSpeeds mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 127514064: + case -324277155: { + if (input.isAtField(FieldNames.frontLeft)) { + if (!input.trySkipNullValue()) { + frontLeft = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case -336370317: + case -1456996218: { + if (input.isAtField(FieldNames.frontRight)) { + if (!input.trySkipNullValue()) { + frontRight = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case -854852661: + case -712874558: { + if (input.isAtField(FieldNames.rearLeft)) { + if (!input.trySkipNullValue()) { + rearLeft = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case -724967720: + case -618613823: { + if (input.isAtField(FieldNames.rearRight)) { + if (!input.trySkipNullValue()) { + rearRight = input.readDouble(); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufMecanumDriveWheelSpeeds clone() { + return new ProtobufMecanumDriveWheelSpeeds().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufMecanumDriveWheelSpeeds parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufMecanumDriveWheelSpeeds(), data).checkInitialized(); + } + + public static ProtobufMecanumDriveWheelSpeeds parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufMecanumDriveWheelSpeeds(), input).checkInitialized(); + } + + public static ProtobufMecanumDriveWheelSpeeds parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufMecanumDriveWheelSpeeds(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufMecanumDriveWheelSpeeds messages + */ + public static MessageFactory getFactory() { + return ProtobufMecanumDriveWheelSpeedsFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Kinematics.wpi_proto_ProtobufMecanumDriveWheelSpeeds_descriptor; + } + + private enum ProtobufMecanumDriveWheelSpeedsFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufMecanumDriveWheelSpeeds create() { + return ProtobufMecanumDriveWheelSpeeds.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName frontLeft = FieldName.forField("frontLeft", "front_left"); + + static final FieldName frontRight = FieldName.forField("frontRight", "front_right"); + + static final FieldName rearLeft = FieldName.forField("rearLeft", "rear_left"); + + static final FieldName rearRight = FieldName.forField("rearRight", "rear_right"); + } + } + + /** + * Protobuf type {@code ProtobufSwerveDriveKinematics} + */ + public static final class ProtobufSwerveDriveKinematics extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * repeated .wpi.proto.ProtobufTranslation2d modules = 1; + */ + private final RepeatedMessage modules = RepeatedMessage.newEmptyInstance(Geometry2D.ProtobufTranslation2d.getFactory()); + + private ProtobufSwerveDriveKinematics() { + } + + /** + * @return a new empty instance of {@code ProtobufSwerveDriveKinematics} + */ + public static ProtobufSwerveDriveKinematics newInstance() { + return new ProtobufSwerveDriveKinematics(); + } + + /** + * repeated .wpi.proto.ProtobufTranslation2d modules = 1; + * @return whether the modules field is set + */ + public boolean hasModules() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * repeated .wpi.proto.ProtobufTranslation2d modules = 1; + * @return this + */ + public ProtobufSwerveDriveKinematics clearModules() { + bitField0_ &= ~0x00000001; + modules.clear(); + return this; + } + + /** + * repeated .wpi.proto.ProtobufTranslation2d modules = 1; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableModules()} if you want to modify it. + * + * @return internal storage object for reading + */ + public RepeatedMessage getModules() { + return modules; + } + + /** + * repeated .wpi.proto.ProtobufTranslation2d modules = 1; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public RepeatedMessage getMutableModules() { + bitField0_ |= 0x00000001; + return modules; + } + + /** + * repeated .wpi.proto.ProtobufTranslation2d modules = 1; + * @param value the modules to add + * @return this + */ + public ProtobufSwerveDriveKinematics addModules(final Geometry2D.ProtobufTranslation2d value) { + bitField0_ |= 0x00000001; + modules.add(value); + return this; + } + + /** + * repeated .wpi.proto.ProtobufTranslation2d modules = 1; + * @param values the modules to add + * @return this + */ + public ProtobufSwerveDriveKinematics addAllModules( + final Geometry2D.ProtobufTranslation2d... values) { + bitField0_ |= 0x00000001; + modules.addAll(values); + return this; + } + + @Override + public ProtobufSwerveDriveKinematics copyFrom(final ProtobufSwerveDriveKinematics other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + modules.copyFrom(other.modules); + } + return this; + } + + @Override + public ProtobufSwerveDriveKinematics mergeFrom(final ProtobufSwerveDriveKinematics other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasModules()) { + getMutableModules().addAll(other.modules); + } + return this; + } + + @Override + public ProtobufSwerveDriveKinematics clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + modules.clear(); + return this; + } + + @Override + public ProtobufSwerveDriveKinematics clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + modules.clearQuick(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufSwerveDriveKinematics)) { + return false; + } + ProtobufSwerveDriveKinematics other = (ProtobufSwerveDriveKinematics) o; + return bitField0_ == other.bitField0_ + && (!hasModules() || modules.equals(other.modules)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + for (int i = 0; i < modules.length(); i++) { + output.writeRawByte((byte) 10); + output.writeMessageNoTag(modules.get(i)); + } + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += (1 * modules.length()) + ProtoSink.computeRepeatedMessageSizeNoTag(modules); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufSwerveDriveKinematics mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 10: { + // modules + tag = input.readRepeatedMessage(modules, tag); + bitField0_ |= 0x00000001; + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeRepeatedMessage(FieldNames.modules, modules); + } + output.endObject(); + } + + @Override + public ProtobufSwerveDriveKinematics mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 1227433863: { + if (input.isAtField(FieldNames.modules)) { + if (!input.trySkipNullValue()) { + input.readRepeatedMessage(modules); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufSwerveDriveKinematics clone() { + return new ProtobufSwerveDriveKinematics().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufSwerveDriveKinematics parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufSwerveDriveKinematics(), data).checkInitialized(); + } + + public static ProtobufSwerveDriveKinematics parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufSwerveDriveKinematics(), input).checkInitialized(); + } + + public static ProtobufSwerveDriveKinematics parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufSwerveDriveKinematics(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufSwerveDriveKinematics messages + */ + public static MessageFactory getFactory() { + return ProtobufSwerveDriveKinematicsFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Kinematics.wpi_proto_ProtobufSwerveDriveKinematics_descriptor; + } + + private enum ProtobufSwerveDriveKinematicsFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufSwerveDriveKinematics create() { + return ProtobufSwerveDriveKinematics.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName modules = FieldName.forField("modules"); + } + } + + /** + * Protobuf type {@code ProtobufSwerveModulePosition} + */ + public static final class ProtobufSwerveModulePosition extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double distance = 1; + */ + private double distance; + + /** + * optional .wpi.proto.ProtobufRotation2d angle = 2; + */ + private final Geometry2D.ProtobufRotation2d angle = Geometry2D.ProtobufRotation2d.newInstance(); + + private ProtobufSwerveModulePosition() { + } + + /** + * @return a new empty instance of {@code ProtobufSwerveModulePosition} + */ + public static ProtobufSwerveModulePosition newInstance() { + return new ProtobufSwerveModulePosition(); + } + + /** + * optional double distance = 1; + * @return whether the distance field is set + */ + public boolean hasDistance() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double distance = 1; + * @return this + */ + public ProtobufSwerveModulePosition clearDistance() { + bitField0_ &= ~0x00000001; + distance = 0D; + return this; + } + + /** + * optional double distance = 1; + * @return the distance + */ + public double getDistance() { + return distance; + } + + /** + * optional double distance = 1; + * @param value the distance to set + * @return this + */ + public ProtobufSwerveModulePosition setDistance(final double value) { + bitField0_ |= 0x00000001; + distance = value; + return this; + } + + /** + * optional .wpi.proto.ProtobufRotation2d angle = 2; + * @return whether the angle field is set + */ + public boolean hasAngle() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional .wpi.proto.ProtobufRotation2d angle = 2; + * @return this + */ + public ProtobufSwerveModulePosition clearAngle() { + bitField0_ &= ~0x00000002; + angle.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufRotation2d angle = 2; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableAngle()} if you want to modify it. + * + * @return internal storage object for reading + */ + public Geometry2D.ProtobufRotation2d getAngle() { + return angle; + } + + /** + * optional .wpi.proto.ProtobufRotation2d angle = 2; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public Geometry2D.ProtobufRotation2d getMutableAngle() { + bitField0_ |= 0x00000002; + return angle; + } + + /** + * optional .wpi.proto.ProtobufRotation2d angle = 2; + * @param value the angle to set + * @return this + */ + public ProtobufSwerveModulePosition setAngle(final Geometry2D.ProtobufRotation2d value) { + bitField0_ |= 0x00000002; + angle.copyFrom(value); + return this; + } + + @Override + public ProtobufSwerveModulePosition copyFrom(final ProtobufSwerveModulePosition other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + distance = other.distance; + angle.copyFrom(other.angle); + } + return this; + } + + @Override + public ProtobufSwerveModulePosition mergeFrom(final ProtobufSwerveModulePosition other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasDistance()) { + setDistance(other.distance); + } + if (other.hasAngle()) { + getMutableAngle().mergeFrom(other.angle); + } + return this; + } + + @Override + public ProtobufSwerveModulePosition clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + distance = 0D; + angle.clear(); + return this; + } + + @Override + public ProtobufSwerveModulePosition clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + angle.clearQuick(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufSwerveModulePosition)) { + return false; + } + ProtobufSwerveModulePosition other = (ProtobufSwerveModulePosition) o; + return bitField0_ == other.bitField0_ + && (!hasDistance() || ProtoUtil.isEqual(distance, other.distance)) + && (!hasAngle() || angle.equals(other.angle)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(distance); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 18); + output.writeMessageNoTag(angle); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(angle); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufSwerveModulePosition mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // distance + distance = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 18) { + break; + } + } + case 18: { + // angle + input.readMessage(angle); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.distance, distance); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeMessage(FieldNames.angle, angle); + } + output.endObject(); + } + + @Override + public ProtobufSwerveModulePosition mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 288459765: { + if (input.isAtField(FieldNames.distance)) { + if (!input.trySkipNullValue()) { + distance = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 92960979: { + if (input.isAtField(FieldNames.angle)) { + if (!input.trySkipNullValue()) { + input.readMessage(angle); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufSwerveModulePosition clone() { + return new ProtobufSwerveModulePosition().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufSwerveModulePosition parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufSwerveModulePosition(), data).checkInitialized(); + } + + public static ProtobufSwerveModulePosition parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufSwerveModulePosition(), input).checkInitialized(); + } + + public static ProtobufSwerveModulePosition parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufSwerveModulePosition(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufSwerveModulePosition messages + */ + public static MessageFactory getFactory() { + return ProtobufSwerveModulePositionFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Kinematics.wpi_proto_ProtobufSwerveModulePosition_descriptor; + } + + private enum ProtobufSwerveModulePositionFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufSwerveModulePosition create() { + return ProtobufSwerveModulePosition.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName distance = FieldName.forField("distance"); + + static final FieldName angle = FieldName.forField("angle"); + } + } + + /** + * Protobuf type {@code ProtobufSwerveModuleState} + */ + public static final class ProtobufSwerveModuleState extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double speed = 1; + */ + private double speed; + + /** + * optional .wpi.proto.ProtobufRotation2d angle = 2; + */ + private final Geometry2D.ProtobufRotation2d angle = Geometry2D.ProtobufRotation2d.newInstance(); + + private ProtobufSwerveModuleState() { + } + + /** + * @return a new empty instance of {@code ProtobufSwerveModuleState} + */ + public static ProtobufSwerveModuleState newInstance() { + return new ProtobufSwerveModuleState(); + } + + /** + * optional double speed = 1; + * @return whether the speed field is set + */ + public boolean hasSpeed() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double speed = 1; + * @return this + */ + public ProtobufSwerveModuleState clearSpeed() { + bitField0_ &= ~0x00000001; + speed = 0D; + return this; + } + + /** + * optional double speed = 1; + * @return the speed + */ + public double getSpeed() { + return speed; + } + + /** + * optional double speed = 1; + * @param value the speed to set + * @return this + */ + public ProtobufSwerveModuleState setSpeed(final double value) { + bitField0_ |= 0x00000001; + speed = value; + return this; + } + + /** + * optional .wpi.proto.ProtobufRotation2d angle = 2; + * @return whether the angle field is set + */ + public boolean hasAngle() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional .wpi.proto.ProtobufRotation2d angle = 2; + * @return this + */ + public ProtobufSwerveModuleState clearAngle() { + bitField0_ &= ~0x00000002; + angle.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufRotation2d angle = 2; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableAngle()} if you want to modify it. + * + * @return internal storage object for reading + */ + public Geometry2D.ProtobufRotation2d getAngle() { + return angle; + } + + /** + * optional .wpi.proto.ProtobufRotation2d angle = 2; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public Geometry2D.ProtobufRotation2d getMutableAngle() { + bitField0_ |= 0x00000002; + return angle; + } + + /** + * optional .wpi.proto.ProtobufRotation2d angle = 2; + * @param value the angle to set + * @return this + */ + public ProtobufSwerveModuleState setAngle(final Geometry2D.ProtobufRotation2d value) { + bitField0_ |= 0x00000002; + angle.copyFrom(value); + return this; + } + + @Override + public ProtobufSwerveModuleState copyFrom(final ProtobufSwerveModuleState other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + speed = other.speed; + angle.copyFrom(other.angle); + } + return this; + } + + @Override + public ProtobufSwerveModuleState mergeFrom(final ProtobufSwerveModuleState other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasSpeed()) { + setSpeed(other.speed); + } + if (other.hasAngle()) { + getMutableAngle().mergeFrom(other.angle); + } + return this; + } + + @Override + public ProtobufSwerveModuleState clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + speed = 0D; + angle.clear(); + return this; + } + + @Override + public ProtobufSwerveModuleState clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + angle.clearQuick(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufSwerveModuleState)) { + return false; + } + ProtobufSwerveModuleState other = (ProtobufSwerveModuleState) o; + return bitField0_ == other.bitField0_ + && (!hasSpeed() || ProtoUtil.isEqual(speed, other.speed)) + && (!hasAngle() || angle.equals(other.angle)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(speed); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 18); + output.writeMessageNoTag(angle); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(angle); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufSwerveModuleState mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // speed + speed = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 18) { + break; + } + } + case 18: { + // angle + input.readMessage(angle); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.speed, speed); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeMessage(FieldNames.angle, angle); + } + output.endObject(); + } + + @Override + public ProtobufSwerveModuleState mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 109641799: { + if (input.isAtField(FieldNames.speed)) { + if (!input.trySkipNullValue()) { + speed = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 92960979: { + if (input.isAtField(FieldNames.angle)) { + if (!input.trySkipNullValue()) { + input.readMessage(angle); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufSwerveModuleState clone() { + return new ProtobufSwerveModuleState().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufSwerveModuleState parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufSwerveModuleState(), data).checkInitialized(); + } + + public static ProtobufSwerveModuleState parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufSwerveModuleState(), input).checkInitialized(); + } + + public static ProtobufSwerveModuleState parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufSwerveModuleState(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufSwerveModuleState messages + */ + public static MessageFactory getFactory() { + return ProtobufSwerveModuleStateFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Kinematics.wpi_proto_ProtobufSwerveModuleState_descriptor; + } + + private enum ProtobufSwerveModuleStateFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufSwerveModuleState create() { + return ProtobufSwerveModuleState.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName speed = FieldName.forField("speed"); + + static final FieldName angle = FieldName.forField("angle"); + } + } +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Plant.java b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Plant.java new file mode 100644 index 00000000000..61b758fd12f --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Plant.java @@ -0,0 +1,621 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. +// Code generated by protocol buffer compiler. Do not edit! +package edu.wpi.first.math.proto; + +import java.io.IOException; +import us.hebi.quickbuf.Descriptors; +import us.hebi.quickbuf.FieldName; +import us.hebi.quickbuf.InvalidProtocolBufferException; +import us.hebi.quickbuf.JsonSink; +import us.hebi.quickbuf.JsonSource; +import us.hebi.quickbuf.MessageFactory; +import us.hebi.quickbuf.ProtoMessage; +import us.hebi.quickbuf.ProtoSink; +import us.hebi.quickbuf.ProtoSource; +import us.hebi.quickbuf.ProtoUtil; +import us.hebi.quickbuf.RepeatedByte; + +public final class Plant { + private static final RepeatedByte descriptorData = ProtoUtil.decodeBase64(610, + "CgtwbGFudC5wcm90bxIJd3BpLnByb3RvIsQBCg9Qcm90b2J1ZkRDTW90b3ISJwoPbm9taW5hbF92b2x0" + + "YWdlGAEgASgBUg5ub21pbmFsVm9sdGFnZRIhCgxzdGFsbF90b3JxdWUYAiABKAFSC3N0YWxsVG9ycXVl" + + "EiMKDXN0YWxsX2N1cnJlbnQYAyABKAFSDHN0YWxsQ3VycmVudBIhCgxmcmVlX2N1cnJlbnQYBCABKAFS" + + "C2ZyZWVDdXJyZW50Eh0KCmZyZWVfc3BlZWQYBSABKAFSCWZyZWVTcGVlZEIaChhlZHUud3BpLmZpcnN0" + + "Lm1hdGgucHJvdG9K3AIKBhIEAAAMAQoICgEMEgMAABIKCAoBAhIDAgASCggKAQgSAwQAMQoJCgIIARID" + + "BAAxCgoKAgQAEgQGAAwBCgoKAwQAARIDBggXCgsKBAQAAgASAwcCHQoMCgUEAAIABRIDBwIICgwKBQQA" + + "AgABEgMHCRgKDAoFBAACAAMSAwcbHAoLCgQEAAIBEgMIAhoKDAoFBAACAQUSAwgCCAoMCgUEAAIBARID" + + "CAkVCgwKBQQAAgEDEgMIGBkKCwoEBAACAhIDCQIbCgwKBQQAAgIFEgMJAggKDAoFBAACAgESAwkJFgoM" + + "CgUEAAICAxIDCRkaCgsKBAQAAgMSAwoCGgoMCgUEAAIDBRIDCgIICgwKBQQAAgMBEgMKCRUKDAoFBAAC" + + "AwMSAwoYGQoLCgQEAAIEEgMLAhgKDAoFBAACBAUSAwsCCAoMCgUEAAIEARIDCwkTCgwKBQQAAgQDEgML" + + "FhdiBnByb3RvMw=="); + + static final Descriptors.FileDescriptor descriptor = Descriptors.FileDescriptor.internalBuildGeneratedFileFrom("plant.proto", "wpi.proto", descriptorData); + + static final Descriptors.Descriptor wpi_proto_ProtobufDCMotor_descriptor = descriptor.internalContainedType(27, 196, "ProtobufDCMotor", "wpi.proto.ProtobufDCMotor"); + + /** + * @return this proto file's descriptor. + */ + public static Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + /** + * Protobuf type {@code ProtobufDCMotor} + */ + public static final class ProtobufDCMotor extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double nominal_voltage = 1; + */ + private double nominalVoltage; + + /** + * optional double stall_torque = 2; + */ + private double stallTorque; + + /** + * optional double stall_current = 3; + */ + private double stallCurrent; + + /** + * optional double free_current = 4; + */ + private double freeCurrent; + + /** + * optional double free_speed = 5; + */ + private double freeSpeed; + + private ProtobufDCMotor() { + } + + /** + * @return a new empty instance of {@code ProtobufDCMotor} + */ + public static ProtobufDCMotor newInstance() { + return new ProtobufDCMotor(); + } + + /** + * optional double nominal_voltage = 1; + * @return whether the nominalVoltage field is set + */ + public boolean hasNominalVoltage() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double nominal_voltage = 1; + * @return this + */ + public ProtobufDCMotor clearNominalVoltage() { + bitField0_ &= ~0x00000001; + nominalVoltage = 0D; + return this; + } + + /** + * optional double nominal_voltage = 1; + * @return the nominalVoltage + */ + public double getNominalVoltage() { + return nominalVoltage; + } + + /** + * optional double nominal_voltage = 1; + * @param value the nominalVoltage to set + * @return this + */ + public ProtobufDCMotor setNominalVoltage(final double value) { + bitField0_ |= 0x00000001; + nominalVoltage = value; + return this; + } + + /** + * optional double stall_torque = 2; + * @return whether the stallTorque field is set + */ + public boolean hasStallTorque() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double stall_torque = 2; + * @return this + */ + public ProtobufDCMotor clearStallTorque() { + bitField0_ &= ~0x00000002; + stallTorque = 0D; + return this; + } + + /** + * optional double stall_torque = 2; + * @return the stallTorque + */ + public double getStallTorque() { + return stallTorque; + } + + /** + * optional double stall_torque = 2; + * @param value the stallTorque to set + * @return this + */ + public ProtobufDCMotor setStallTorque(final double value) { + bitField0_ |= 0x00000002; + stallTorque = value; + return this; + } + + /** + * optional double stall_current = 3; + * @return whether the stallCurrent field is set + */ + public boolean hasStallCurrent() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double stall_current = 3; + * @return this + */ + public ProtobufDCMotor clearStallCurrent() { + bitField0_ &= ~0x00000004; + stallCurrent = 0D; + return this; + } + + /** + * optional double stall_current = 3; + * @return the stallCurrent + */ + public double getStallCurrent() { + return stallCurrent; + } + + /** + * optional double stall_current = 3; + * @param value the stallCurrent to set + * @return this + */ + public ProtobufDCMotor setStallCurrent(final double value) { + bitField0_ |= 0x00000004; + stallCurrent = value; + return this; + } + + /** + * optional double free_current = 4; + * @return whether the freeCurrent field is set + */ + public boolean hasFreeCurrent() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * optional double free_current = 4; + * @return this + */ + public ProtobufDCMotor clearFreeCurrent() { + bitField0_ &= ~0x00000008; + freeCurrent = 0D; + return this; + } + + /** + * optional double free_current = 4; + * @return the freeCurrent + */ + public double getFreeCurrent() { + return freeCurrent; + } + + /** + * optional double free_current = 4; + * @param value the freeCurrent to set + * @return this + */ + public ProtobufDCMotor setFreeCurrent(final double value) { + bitField0_ |= 0x00000008; + freeCurrent = value; + return this; + } + + /** + * optional double free_speed = 5; + * @return whether the freeSpeed field is set + */ + public boolean hasFreeSpeed() { + return (bitField0_ & 0x00000010) != 0; + } + + /** + * optional double free_speed = 5; + * @return this + */ + public ProtobufDCMotor clearFreeSpeed() { + bitField0_ &= ~0x00000010; + freeSpeed = 0D; + return this; + } + + /** + * optional double free_speed = 5; + * @return the freeSpeed + */ + public double getFreeSpeed() { + return freeSpeed; + } + + /** + * optional double free_speed = 5; + * @param value the freeSpeed to set + * @return this + */ + public ProtobufDCMotor setFreeSpeed(final double value) { + bitField0_ |= 0x00000010; + freeSpeed = value; + return this; + } + + @Override + public ProtobufDCMotor copyFrom(final ProtobufDCMotor other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + nominalVoltage = other.nominalVoltage; + stallTorque = other.stallTorque; + stallCurrent = other.stallCurrent; + freeCurrent = other.freeCurrent; + freeSpeed = other.freeSpeed; + } + return this; + } + + @Override + public ProtobufDCMotor mergeFrom(final ProtobufDCMotor other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasNominalVoltage()) { + setNominalVoltage(other.nominalVoltage); + } + if (other.hasStallTorque()) { + setStallTorque(other.stallTorque); + } + if (other.hasStallCurrent()) { + setStallCurrent(other.stallCurrent); + } + if (other.hasFreeCurrent()) { + setFreeCurrent(other.freeCurrent); + } + if (other.hasFreeSpeed()) { + setFreeSpeed(other.freeSpeed); + } + return this; + } + + @Override + public ProtobufDCMotor clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + nominalVoltage = 0D; + stallTorque = 0D; + stallCurrent = 0D; + freeCurrent = 0D; + freeSpeed = 0D; + return this; + } + + @Override + public ProtobufDCMotor clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufDCMotor)) { + return false; + } + ProtobufDCMotor other = (ProtobufDCMotor) o; + return bitField0_ == other.bitField0_ + && (!hasNominalVoltage() || ProtoUtil.isEqual(nominalVoltage, other.nominalVoltage)) + && (!hasStallTorque() || ProtoUtil.isEqual(stallTorque, other.stallTorque)) + && (!hasStallCurrent() || ProtoUtil.isEqual(stallCurrent, other.stallCurrent)) + && (!hasFreeCurrent() || ProtoUtil.isEqual(freeCurrent, other.freeCurrent)) + && (!hasFreeSpeed() || ProtoUtil.isEqual(freeSpeed, other.freeSpeed)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(nominalVoltage); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(stallTorque); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(stallCurrent); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRawByte((byte) 33); + output.writeDoubleNoTag(freeCurrent); + } + if ((bitField0_ & 0x00000010) != 0) { + output.writeRawByte((byte) 41); + output.writeDoubleNoTag(freeSpeed); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000008) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000010) != 0) { + size += 9; + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufDCMotor mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // nominalVoltage + nominalVoltage = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // stallTorque + stallTorque = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // stallCurrent + stallCurrent = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 33) { + break; + } + } + case 33: { + // freeCurrent + freeCurrent = input.readDouble(); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 41) { + break; + } + } + case 41: { + // freeSpeed + freeSpeed = input.readDouble(); + bitField0_ |= 0x00000010; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.nominalVoltage, nominalVoltage); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.stallTorque, stallTorque); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.stallCurrent, stallCurrent); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeDouble(FieldNames.freeCurrent, freeCurrent); + } + if ((bitField0_ & 0x00000010) != 0) { + output.writeDouble(FieldNames.freeSpeed, freeSpeed); + } + output.endObject(); + } + + @Override + public ProtobufDCMotor mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 1374862050: + case 173092603: { + if (input.isAtField(FieldNames.nominalVoltage)) { + if (!input.trySkipNullValue()) { + nominalVoltage = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 2075810250: + case 1238615945: { + if (input.isAtField(FieldNames.stallTorque)) { + if (!input.trySkipNullValue()) { + stallTorque = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case -2105262663: + case 2006484954: { + if (input.isAtField(FieldNames.stallCurrent)) { + if (!input.trySkipNullValue()) { + stallCurrent = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case 1024355693: + case 240406182: { + if (input.isAtField(FieldNames.freeCurrent)) { + if (!input.trySkipNullValue()) { + freeCurrent = input.readDouble(); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + case -444654277: + case -552732492: { + if (input.isAtField(FieldNames.freeSpeed)) { + if (!input.trySkipNullValue()) { + freeSpeed = input.readDouble(); + bitField0_ |= 0x00000010; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufDCMotor clone() { + return new ProtobufDCMotor().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufDCMotor parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufDCMotor(), data).checkInitialized(); + } + + public static ProtobufDCMotor parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufDCMotor(), input).checkInitialized(); + } + + public static ProtobufDCMotor parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufDCMotor(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufDCMotor messages + */ + public static MessageFactory getFactory() { + return ProtobufDCMotorFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Plant.wpi_proto_ProtobufDCMotor_descriptor; + } + + private enum ProtobufDCMotorFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufDCMotor create() { + return ProtobufDCMotor.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName nominalVoltage = FieldName.forField("nominalVoltage", "nominal_voltage"); + + static final FieldName stallTorque = FieldName.forField("stallTorque", "stall_torque"); + + static final FieldName stallCurrent = FieldName.forField("stallCurrent", "stall_current"); + + static final FieldName freeCurrent = FieldName.forField("freeCurrent", "free_current"); + + static final FieldName freeSpeed = FieldName.forField("freeSpeed", "free_speed"); + } + } +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Spline.java b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Spline.java new file mode 100644 index 00000000000..accdecb07a7 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Spline.java @@ -0,0 +1,1367 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. +// Code generated by protocol buffer compiler. Do not edit! +package edu.wpi.first.math.proto; + +import java.io.IOException; +import us.hebi.quickbuf.Descriptors; +import us.hebi.quickbuf.FieldName; +import us.hebi.quickbuf.InvalidProtocolBufferException; +import us.hebi.quickbuf.JsonSink; +import us.hebi.quickbuf.JsonSource; +import us.hebi.quickbuf.MessageFactory; +import us.hebi.quickbuf.ProtoMessage; +import us.hebi.quickbuf.ProtoSink; +import us.hebi.quickbuf.ProtoSource; +import us.hebi.quickbuf.ProtoUtil; +import us.hebi.quickbuf.RepeatedByte; +import us.hebi.quickbuf.RepeatedDouble; + +public final class Spline { + private static final RepeatedByte descriptorData = ProtoUtil.decodeBase64(993, + "CgxzcGxpbmUucHJvdG8SCXdwaS5wcm90byKIAQoaUHJvdG9idWZDdWJpY0hlcm1pdGVTcGxpbmUSGwoJ" + + "eF9pbml0aWFsGAEgAygBUgh4SW5pdGlhbBIXCgd4X2ZpbmFsGAIgAygBUgZ4RmluYWwSGwoJeV9pbml0" + + "aWFsGAMgAygBUgh5SW5pdGlhbBIXCgd5X2ZpbmFsGAQgAygBUgZ5RmluYWwiigEKHFByb3RvYnVmUXVp" + + "bnRpY0hlcm1pdGVTcGxpbmUSGwoJeF9pbml0aWFsGAEgAygBUgh4SW5pdGlhbBIXCgd4X2ZpbmFsGAIg" + + "AygBUgZ4RmluYWwSGwoJeV9pbml0aWFsGAMgAygBUgh5SW5pdGlhbBIXCgd5X2ZpbmFsGAQgAygBUgZ5" + + "RmluYWxCGgoYZWR1LndwaS5maXJzdC5tYXRoLnByb3RvSokFCgYSBAAAEgEKCAoBDBIDAAASCggKAQIS" + + "AwIAEgoICgEIEgMEADEKCQoCCAESAwQAMQoKCgIEABIEBgALAQoKCgMEAAESAwYIIgoLCgQEAAIAEgMH" + + "AiAKDAoFBAACAAQSAwcCCgoMCgUEAAIABRIDBwsRCgwKBQQAAgABEgMHEhsKDAoFBAACAAMSAwceHwoL" + + "CgQEAAIBEgMIAh4KDAoFBAACAQQSAwgCCgoMCgUEAAIBBRIDCAsRCgwKBQQAAgEBEgMIEhkKDAoFBAAC" + + "AQMSAwgcHQoLCgQEAAICEgMJAiAKDAoFBAACAgQSAwkCCgoMCgUEAAICBRIDCQsRCgwKBQQAAgIBEgMJ" + + "EhsKDAoFBAACAgMSAwkeHwoLCgQEAAIDEgMKAh4KDAoFBAACAwQSAwoCCgoMCgUEAAIDBRIDCgsRCgwK" + + "BQQAAgMBEgMKEhkKDAoFBAACAwMSAwocHQoKCgIEARIEDQASAQoKCgMEAQESAw0IJAoLCgQEAQIAEgMO" + + "AiAKDAoFBAECAAQSAw4CCgoMCgUEAQIABRIDDgsRCgwKBQQBAgABEgMOEhsKDAoFBAECAAMSAw4eHwoL" + + "CgQEAQIBEgMPAh4KDAoFBAECAQQSAw8CCgoMCgUEAQIBBRIDDwsRCgwKBQQBAgEBEgMPEhkKDAoFBAEC" + + "AQMSAw8cHQoLCgQEAQICEgMQAiAKDAoFBAECAgQSAxACCgoMCgUEAQICBRIDEAsRCgwKBQQBAgIBEgMQ" + + "EhsKDAoFBAECAgMSAxAeHwoLCgQEAQIDEgMRAh4KDAoFBAECAwQSAxECCgoMCgUEAQIDBRIDEQsRCgwK" + + "BQQBAgMBEgMREhkKDAoFBAECAwMSAxEcHWIGcHJvdG8z"); + + static final Descriptors.FileDescriptor descriptor = Descriptors.FileDescriptor.internalBuildGeneratedFileFrom("spline.proto", "wpi.proto", descriptorData); + + static final Descriptors.Descriptor wpi_proto_ProtobufCubicHermiteSpline_descriptor = descriptor.internalContainedType(28, 136, "ProtobufCubicHermiteSpline", "wpi.proto.ProtobufCubicHermiteSpline"); + + static final Descriptors.Descriptor wpi_proto_ProtobufQuinticHermiteSpline_descriptor = descriptor.internalContainedType(167, 138, "ProtobufQuinticHermiteSpline", "wpi.proto.ProtobufQuinticHermiteSpline"); + + /** + * @return this proto file's descriptor. + */ + public static Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + /** + * Protobuf type {@code ProtobufCubicHermiteSpline} + */ + public static final class ProtobufCubicHermiteSpline extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * repeated double x_initial = 1; + */ + private final RepeatedDouble xInitial = RepeatedDouble.newEmptyInstance(); + + /** + * repeated double x_final = 2; + */ + private final RepeatedDouble xFinal = RepeatedDouble.newEmptyInstance(); + + /** + * repeated double y_initial = 3; + */ + private final RepeatedDouble yInitial = RepeatedDouble.newEmptyInstance(); + + /** + * repeated double y_final = 4; + */ + private final RepeatedDouble yFinal = RepeatedDouble.newEmptyInstance(); + + private ProtobufCubicHermiteSpline() { + } + + /** + * @return a new empty instance of {@code ProtobufCubicHermiteSpline} + */ + public static ProtobufCubicHermiteSpline newInstance() { + return new ProtobufCubicHermiteSpline(); + } + + /** + * repeated double x_initial = 1; + * @return whether the xInitial field is set + */ + public boolean hasXInitial() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * repeated double x_initial = 1; + * @return this + */ + public ProtobufCubicHermiteSpline clearXInitial() { + bitField0_ &= ~0x00000001; + xInitial.clear(); + return this; + } + + /** + * repeated double x_initial = 1; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableXInitial()} if you want to modify it. + * + * @return internal storage object for reading + */ + public RepeatedDouble getXInitial() { + return xInitial; + } + + /** + * repeated double x_initial = 1; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public RepeatedDouble getMutableXInitial() { + bitField0_ |= 0x00000001; + return xInitial; + } + + /** + * repeated double x_initial = 1; + * @param value the xInitial to add + * @return this + */ + public ProtobufCubicHermiteSpline addXInitial(final double value) { + bitField0_ |= 0x00000001; + xInitial.add(value); + return this; + } + + /** + * repeated double x_initial = 1; + * @param values the xInitial to add + * @return this + */ + public ProtobufCubicHermiteSpline addAllXInitial(final double... values) { + bitField0_ |= 0x00000001; + xInitial.addAll(values); + return this; + } + + /** + * repeated double x_final = 2; + * @return whether the xFinal field is set + */ + public boolean hasXFinal() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * repeated double x_final = 2; + * @return this + */ + public ProtobufCubicHermiteSpline clearXFinal() { + bitField0_ &= ~0x00000002; + xFinal.clear(); + return this; + } + + /** + * repeated double x_final = 2; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableXFinal()} if you want to modify it. + * + * @return internal storage object for reading + */ + public RepeatedDouble getXFinal() { + return xFinal; + } + + /** + * repeated double x_final = 2; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public RepeatedDouble getMutableXFinal() { + bitField0_ |= 0x00000002; + return xFinal; + } + + /** + * repeated double x_final = 2; + * @param value the xFinal to add + * @return this + */ + public ProtobufCubicHermiteSpline addXFinal(final double value) { + bitField0_ |= 0x00000002; + xFinal.add(value); + return this; + } + + /** + * repeated double x_final = 2; + * @param values the xFinal to add + * @return this + */ + public ProtobufCubicHermiteSpline addAllXFinal(final double... values) { + bitField0_ |= 0x00000002; + xFinal.addAll(values); + return this; + } + + /** + * repeated double y_initial = 3; + * @return whether the yInitial field is set + */ + public boolean hasYInitial() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * repeated double y_initial = 3; + * @return this + */ + public ProtobufCubicHermiteSpline clearYInitial() { + bitField0_ &= ~0x00000004; + yInitial.clear(); + return this; + } + + /** + * repeated double y_initial = 3; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableYInitial()} if you want to modify it. + * + * @return internal storage object for reading + */ + public RepeatedDouble getYInitial() { + return yInitial; + } + + /** + * repeated double y_initial = 3; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public RepeatedDouble getMutableYInitial() { + bitField0_ |= 0x00000004; + return yInitial; + } + + /** + * repeated double y_initial = 3; + * @param value the yInitial to add + * @return this + */ + public ProtobufCubicHermiteSpline addYInitial(final double value) { + bitField0_ |= 0x00000004; + yInitial.add(value); + return this; + } + + /** + * repeated double y_initial = 3; + * @param values the yInitial to add + * @return this + */ + public ProtobufCubicHermiteSpline addAllYInitial(final double... values) { + bitField0_ |= 0x00000004; + yInitial.addAll(values); + return this; + } + + /** + * repeated double y_final = 4; + * @return whether the yFinal field is set + */ + public boolean hasYFinal() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * repeated double y_final = 4; + * @return this + */ + public ProtobufCubicHermiteSpline clearYFinal() { + bitField0_ &= ~0x00000008; + yFinal.clear(); + return this; + } + + /** + * repeated double y_final = 4; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableYFinal()} if you want to modify it. + * + * @return internal storage object for reading + */ + public RepeatedDouble getYFinal() { + return yFinal; + } + + /** + * repeated double y_final = 4; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public RepeatedDouble getMutableYFinal() { + bitField0_ |= 0x00000008; + return yFinal; + } + + /** + * repeated double y_final = 4; + * @param value the yFinal to add + * @return this + */ + public ProtobufCubicHermiteSpline addYFinal(final double value) { + bitField0_ |= 0x00000008; + yFinal.add(value); + return this; + } + + /** + * repeated double y_final = 4; + * @param values the yFinal to add + * @return this + */ + public ProtobufCubicHermiteSpline addAllYFinal(final double... values) { + bitField0_ |= 0x00000008; + yFinal.addAll(values); + return this; + } + + @Override + public ProtobufCubicHermiteSpline copyFrom(final ProtobufCubicHermiteSpline other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + xInitial.copyFrom(other.xInitial); + xFinal.copyFrom(other.xFinal); + yInitial.copyFrom(other.yInitial); + yFinal.copyFrom(other.yFinal); + } + return this; + } + + @Override + public ProtobufCubicHermiteSpline mergeFrom(final ProtobufCubicHermiteSpline other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasXInitial()) { + getMutableXInitial().addAll(other.xInitial); + } + if (other.hasXFinal()) { + getMutableXFinal().addAll(other.xFinal); + } + if (other.hasYInitial()) { + getMutableYInitial().addAll(other.yInitial); + } + if (other.hasYFinal()) { + getMutableYFinal().addAll(other.yFinal); + } + return this; + } + + @Override + public ProtobufCubicHermiteSpline clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + xInitial.clear(); + xFinal.clear(); + yInitial.clear(); + yFinal.clear(); + return this; + } + + @Override + public ProtobufCubicHermiteSpline clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + xInitial.clear(); + xFinal.clear(); + yInitial.clear(); + yFinal.clear(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufCubicHermiteSpline)) { + return false; + } + ProtobufCubicHermiteSpline other = (ProtobufCubicHermiteSpline) o; + return bitField0_ == other.bitField0_ + && (!hasXInitial() || xInitial.equals(other.xInitial)) + && (!hasXFinal() || xFinal.equals(other.xFinal)) + && (!hasYInitial() || yInitial.equals(other.yInitial)) + && (!hasYFinal() || yFinal.equals(other.yFinal)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + for (int i = 0; i < xInitial.length(); i++) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(xInitial.array()[i]); + } + } + if ((bitField0_ & 0x00000002) != 0) { + for (int i = 0; i < xFinal.length(); i++) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(xFinal.array()[i]); + } + } + if ((bitField0_ & 0x00000004) != 0) { + for (int i = 0; i < yInitial.length(); i++) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(yInitial.array()[i]); + } + } + if ((bitField0_ & 0x00000008) != 0) { + for (int i = 0; i < yFinal.length(); i++) { + output.writeRawByte((byte) 33); + output.writeDoubleNoTag(yFinal.array()[i]); + } + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += (1 + 8) * xInitial.length(); + } + if ((bitField0_ & 0x00000002) != 0) { + size += (1 + 8) * xFinal.length(); + } + if ((bitField0_ & 0x00000004) != 0) { + size += (1 + 8) * yInitial.length(); + } + if ((bitField0_ & 0x00000008) != 0) { + size += (1 + 8) * yFinal.length(); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufCubicHermiteSpline mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 10: { + // xInitial [packed=true] + input.readPackedDouble(xInitial); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 18) { + break; + } + } + case 18: { + // xFinal [packed=true] + input.readPackedDouble(xFinal); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 26) { + break; + } + } + case 26: { + // yInitial [packed=true] + input.readPackedDouble(yInitial); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 34) { + break; + } + } + case 34: { + // yFinal [packed=true] + input.readPackedDouble(yFinal); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + case 9: { + // xInitial [packed=false] + tag = input.readRepeatedDouble(xInitial, tag); + bitField0_ |= 0x00000001; + break; + } + case 17: { + // xFinal [packed=false] + tag = input.readRepeatedDouble(xFinal, tag); + bitField0_ |= 0x00000002; + break; + } + case 25: { + // yInitial [packed=false] + tag = input.readRepeatedDouble(yInitial, tag); + bitField0_ |= 0x00000004; + break; + } + case 33: { + // yFinal [packed=false] + tag = input.readRepeatedDouble(yFinal, tag); + bitField0_ |= 0x00000008; + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeRepeatedDouble(FieldNames.xInitial, xInitial); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRepeatedDouble(FieldNames.xFinal, xFinal); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRepeatedDouble(FieldNames.yInitial, yInitial); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRepeatedDouble(FieldNames.yFinal, yFinal); + } + output.endObject(); + } + + @Override + public ProtobufCubicHermiteSpline mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case -1998129236: + case -2134571395: { + if (input.isAtField(FieldNames.xInitial)) { + if (!input.trySkipNullValue()) { + input.readRepeatedDouble(xInitial); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case -791585826: + case 1943464687: { + if (input.isAtField(FieldNames.xFinal)) { + if (!input.trySkipNullValue()) { + input.readRepeatedDouble(xFinal); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case -255318901: + case 352941438: { + if (input.isAtField(FieldNames.yInitial)) { + if (!input.trySkipNullValue()) { + input.readRepeatedDouble(yInitial); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case -762956675: + case -1463998928: { + if (input.isAtField(FieldNames.yFinal)) { + if (!input.trySkipNullValue()) { + input.readRepeatedDouble(yFinal); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufCubicHermiteSpline clone() { + return new ProtobufCubicHermiteSpline().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufCubicHermiteSpline parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufCubicHermiteSpline(), data).checkInitialized(); + } + + public static ProtobufCubicHermiteSpline parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufCubicHermiteSpline(), input).checkInitialized(); + } + + public static ProtobufCubicHermiteSpline parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufCubicHermiteSpline(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufCubicHermiteSpline messages + */ + public static MessageFactory getFactory() { + return ProtobufCubicHermiteSplineFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Spline.wpi_proto_ProtobufCubicHermiteSpline_descriptor; + } + + private enum ProtobufCubicHermiteSplineFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufCubicHermiteSpline create() { + return ProtobufCubicHermiteSpline.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName xInitial = FieldName.forField("xInitial", "x_initial"); + + static final FieldName xFinal = FieldName.forField("xFinal", "x_final"); + + static final FieldName yInitial = FieldName.forField("yInitial", "y_initial"); + + static final FieldName yFinal = FieldName.forField("yFinal", "y_final"); + } + } + + /** + * Protobuf type {@code ProtobufQuinticHermiteSpline} + */ + public static final class ProtobufQuinticHermiteSpline extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * repeated double x_initial = 1; + */ + private final RepeatedDouble xInitial = RepeatedDouble.newEmptyInstance(); + + /** + * repeated double x_final = 2; + */ + private final RepeatedDouble xFinal = RepeatedDouble.newEmptyInstance(); + + /** + * repeated double y_initial = 3; + */ + private final RepeatedDouble yInitial = RepeatedDouble.newEmptyInstance(); + + /** + * repeated double y_final = 4; + */ + private final RepeatedDouble yFinal = RepeatedDouble.newEmptyInstance(); + + private ProtobufQuinticHermiteSpline() { + } + + /** + * @return a new empty instance of {@code ProtobufQuinticHermiteSpline} + */ + public static ProtobufQuinticHermiteSpline newInstance() { + return new ProtobufQuinticHermiteSpline(); + } + + /** + * repeated double x_initial = 1; + * @return whether the xInitial field is set + */ + public boolean hasXInitial() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * repeated double x_initial = 1; + * @return this + */ + public ProtobufQuinticHermiteSpline clearXInitial() { + bitField0_ &= ~0x00000001; + xInitial.clear(); + return this; + } + + /** + * repeated double x_initial = 1; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableXInitial()} if you want to modify it. + * + * @return internal storage object for reading + */ + public RepeatedDouble getXInitial() { + return xInitial; + } + + /** + * repeated double x_initial = 1; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public RepeatedDouble getMutableXInitial() { + bitField0_ |= 0x00000001; + return xInitial; + } + + /** + * repeated double x_initial = 1; + * @param value the xInitial to add + * @return this + */ + public ProtobufQuinticHermiteSpline addXInitial(final double value) { + bitField0_ |= 0x00000001; + xInitial.add(value); + return this; + } + + /** + * repeated double x_initial = 1; + * @param values the xInitial to add + * @return this + */ + public ProtobufQuinticHermiteSpline addAllXInitial(final double... values) { + bitField0_ |= 0x00000001; + xInitial.addAll(values); + return this; + } + + /** + * repeated double x_final = 2; + * @return whether the xFinal field is set + */ + public boolean hasXFinal() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * repeated double x_final = 2; + * @return this + */ + public ProtobufQuinticHermiteSpline clearXFinal() { + bitField0_ &= ~0x00000002; + xFinal.clear(); + return this; + } + + /** + * repeated double x_final = 2; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableXFinal()} if you want to modify it. + * + * @return internal storage object for reading + */ + public RepeatedDouble getXFinal() { + return xFinal; + } + + /** + * repeated double x_final = 2; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public RepeatedDouble getMutableXFinal() { + bitField0_ |= 0x00000002; + return xFinal; + } + + /** + * repeated double x_final = 2; + * @param value the xFinal to add + * @return this + */ + public ProtobufQuinticHermiteSpline addXFinal(final double value) { + bitField0_ |= 0x00000002; + xFinal.add(value); + return this; + } + + /** + * repeated double x_final = 2; + * @param values the xFinal to add + * @return this + */ + public ProtobufQuinticHermiteSpline addAllXFinal(final double... values) { + bitField0_ |= 0x00000002; + xFinal.addAll(values); + return this; + } + + /** + * repeated double y_initial = 3; + * @return whether the yInitial field is set + */ + public boolean hasYInitial() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * repeated double y_initial = 3; + * @return this + */ + public ProtobufQuinticHermiteSpline clearYInitial() { + bitField0_ &= ~0x00000004; + yInitial.clear(); + return this; + } + + /** + * repeated double y_initial = 3; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableYInitial()} if you want to modify it. + * + * @return internal storage object for reading + */ + public RepeatedDouble getYInitial() { + return yInitial; + } + + /** + * repeated double y_initial = 3; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public RepeatedDouble getMutableYInitial() { + bitField0_ |= 0x00000004; + return yInitial; + } + + /** + * repeated double y_initial = 3; + * @param value the yInitial to add + * @return this + */ + public ProtobufQuinticHermiteSpline addYInitial(final double value) { + bitField0_ |= 0x00000004; + yInitial.add(value); + return this; + } + + /** + * repeated double y_initial = 3; + * @param values the yInitial to add + * @return this + */ + public ProtobufQuinticHermiteSpline addAllYInitial(final double... values) { + bitField0_ |= 0x00000004; + yInitial.addAll(values); + return this; + } + + /** + * repeated double y_final = 4; + * @return whether the yFinal field is set + */ + public boolean hasYFinal() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * repeated double y_final = 4; + * @return this + */ + public ProtobufQuinticHermiteSpline clearYFinal() { + bitField0_ &= ~0x00000008; + yFinal.clear(); + return this; + } + + /** + * repeated double y_final = 4; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableYFinal()} if you want to modify it. + * + * @return internal storage object for reading + */ + public RepeatedDouble getYFinal() { + return yFinal; + } + + /** + * repeated double y_final = 4; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public RepeatedDouble getMutableYFinal() { + bitField0_ |= 0x00000008; + return yFinal; + } + + /** + * repeated double y_final = 4; + * @param value the yFinal to add + * @return this + */ + public ProtobufQuinticHermiteSpline addYFinal(final double value) { + bitField0_ |= 0x00000008; + yFinal.add(value); + return this; + } + + /** + * repeated double y_final = 4; + * @param values the yFinal to add + * @return this + */ + public ProtobufQuinticHermiteSpline addAllYFinal(final double... values) { + bitField0_ |= 0x00000008; + yFinal.addAll(values); + return this; + } + + @Override + public ProtobufQuinticHermiteSpline copyFrom(final ProtobufQuinticHermiteSpline other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + xInitial.copyFrom(other.xInitial); + xFinal.copyFrom(other.xFinal); + yInitial.copyFrom(other.yInitial); + yFinal.copyFrom(other.yFinal); + } + return this; + } + + @Override + public ProtobufQuinticHermiteSpline mergeFrom(final ProtobufQuinticHermiteSpline other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasXInitial()) { + getMutableXInitial().addAll(other.xInitial); + } + if (other.hasXFinal()) { + getMutableXFinal().addAll(other.xFinal); + } + if (other.hasYInitial()) { + getMutableYInitial().addAll(other.yInitial); + } + if (other.hasYFinal()) { + getMutableYFinal().addAll(other.yFinal); + } + return this; + } + + @Override + public ProtobufQuinticHermiteSpline clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + xInitial.clear(); + xFinal.clear(); + yInitial.clear(); + yFinal.clear(); + return this; + } + + @Override + public ProtobufQuinticHermiteSpline clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + xInitial.clear(); + xFinal.clear(); + yInitial.clear(); + yFinal.clear(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufQuinticHermiteSpline)) { + return false; + } + ProtobufQuinticHermiteSpline other = (ProtobufQuinticHermiteSpline) o; + return bitField0_ == other.bitField0_ + && (!hasXInitial() || xInitial.equals(other.xInitial)) + && (!hasXFinal() || xFinal.equals(other.xFinal)) + && (!hasYInitial() || yInitial.equals(other.yInitial)) + && (!hasYFinal() || yFinal.equals(other.yFinal)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + for (int i = 0; i < xInitial.length(); i++) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(xInitial.array()[i]); + } + } + if ((bitField0_ & 0x00000002) != 0) { + for (int i = 0; i < xFinal.length(); i++) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(xFinal.array()[i]); + } + } + if ((bitField0_ & 0x00000004) != 0) { + for (int i = 0; i < yInitial.length(); i++) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(yInitial.array()[i]); + } + } + if ((bitField0_ & 0x00000008) != 0) { + for (int i = 0; i < yFinal.length(); i++) { + output.writeRawByte((byte) 33); + output.writeDoubleNoTag(yFinal.array()[i]); + } + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += (1 + 8) * xInitial.length(); + } + if ((bitField0_ & 0x00000002) != 0) { + size += (1 + 8) * xFinal.length(); + } + if ((bitField0_ & 0x00000004) != 0) { + size += (1 + 8) * yInitial.length(); + } + if ((bitField0_ & 0x00000008) != 0) { + size += (1 + 8) * yFinal.length(); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufQuinticHermiteSpline mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 10: { + // xInitial [packed=true] + input.readPackedDouble(xInitial); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 18) { + break; + } + } + case 18: { + // xFinal [packed=true] + input.readPackedDouble(xFinal); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 26) { + break; + } + } + case 26: { + // yInitial [packed=true] + input.readPackedDouble(yInitial); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 34) { + break; + } + } + case 34: { + // yFinal [packed=true] + input.readPackedDouble(yFinal); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + case 9: { + // xInitial [packed=false] + tag = input.readRepeatedDouble(xInitial, tag); + bitField0_ |= 0x00000001; + break; + } + case 17: { + // xFinal [packed=false] + tag = input.readRepeatedDouble(xFinal, tag); + bitField0_ |= 0x00000002; + break; + } + case 25: { + // yInitial [packed=false] + tag = input.readRepeatedDouble(yInitial, tag); + bitField0_ |= 0x00000004; + break; + } + case 33: { + // yFinal [packed=false] + tag = input.readRepeatedDouble(yFinal, tag); + bitField0_ |= 0x00000008; + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeRepeatedDouble(FieldNames.xInitial, xInitial); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRepeatedDouble(FieldNames.xFinal, xFinal); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRepeatedDouble(FieldNames.yInitial, yInitial); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRepeatedDouble(FieldNames.yFinal, yFinal); + } + output.endObject(); + } + + @Override + public ProtobufQuinticHermiteSpline mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case -1998129236: + case -2134571395: { + if (input.isAtField(FieldNames.xInitial)) { + if (!input.trySkipNullValue()) { + input.readRepeatedDouble(xInitial); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case -791585826: + case 1943464687: { + if (input.isAtField(FieldNames.xFinal)) { + if (!input.trySkipNullValue()) { + input.readRepeatedDouble(xFinal); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case -255318901: + case 352941438: { + if (input.isAtField(FieldNames.yInitial)) { + if (!input.trySkipNullValue()) { + input.readRepeatedDouble(yInitial); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case -762956675: + case -1463998928: { + if (input.isAtField(FieldNames.yFinal)) { + if (!input.trySkipNullValue()) { + input.readRepeatedDouble(yFinal); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufQuinticHermiteSpline clone() { + return new ProtobufQuinticHermiteSpline().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufQuinticHermiteSpline parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufQuinticHermiteSpline(), data).checkInitialized(); + } + + public static ProtobufQuinticHermiteSpline parseFrom(final ProtoSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufQuinticHermiteSpline(), input).checkInitialized(); + } + + public static ProtobufQuinticHermiteSpline parseFrom(final JsonSource input) throws + IOException { + return ProtoMessage.mergeFrom(new ProtobufQuinticHermiteSpline(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufQuinticHermiteSpline messages + */ + public static MessageFactory getFactory() { + return ProtobufQuinticHermiteSplineFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Spline.wpi_proto_ProtobufQuinticHermiteSpline_descriptor; + } + + private enum ProtobufQuinticHermiteSplineFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufQuinticHermiteSpline create() { + return ProtobufQuinticHermiteSpline.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName xInitial = FieldName.forField("xInitial", "x_initial"); + + static final FieldName xFinal = FieldName.forField("xFinal", "x_final"); + + static final FieldName yInitial = FieldName.forField("yInitial", "y_initial"); + + static final FieldName yFinal = FieldName.forField("yFinal", "y_final"); + } + } +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/proto/System.java b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/System.java new file mode 100644 index 00000000000..09ea3b529d9 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/System.java @@ -0,0 +1,866 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. +// Code generated by protocol buffer compiler. Do not edit! +package edu.wpi.first.math.proto; + +import java.io.IOException; +import us.hebi.quickbuf.Descriptors; +import us.hebi.quickbuf.FieldName; +import us.hebi.quickbuf.InvalidProtocolBufferException; +import us.hebi.quickbuf.JsonSink; +import us.hebi.quickbuf.JsonSource; +import us.hebi.quickbuf.MessageFactory; +import us.hebi.quickbuf.ProtoMessage; +import us.hebi.quickbuf.ProtoSink; +import us.hebi.quickbuf.ProtoSource; +import us.hebi.quickbuf.ProtoUtil; +import us.hebi.quickbuf.RepeatedByte; + +public final class System { + private static final RepeatedByte descriptorData = ProtoUtil.decodeBase64(832, + "CgxzeXN0ZW0ucHJvdG8SCXdwaS5wcm90bxoNd3BpbWF0aC5wcm90byKZAgoUUHJvdG9idWZMaW5lYXJT" + + "eXN0ZW0SHQoKbnVtX3N0YXRlcxgBIAEoDVIJbnVtU3RhdGVzEh0KCm51bV9pbnB1dHMYAiABKA1SCW51" + + "bUlucHV0cxIfCgtudW1fb3V0cHV0cxgDIAEoDVIKbnVtT3V0cHV0cxInCgFhGAQgASgLMhkud3BpLnBy" + + "b3RvLlByb3RvYnVmTWF0cml4UgFhEicKAWIYBSABKAsyGS53cGkucHJvdG8uUHJvdG9idWZNYXRyaXhS" + + "AWISJwoBYxgGIAEoCzIZLndwaS5wcm90by5Qcm90b2J1Zk1hdHJpeFIBYxInCgFkGAcgASgLMhkud3Bp" + + "LnByb3RvLlByb3RvYnVmTWF0cml4UgFkQhoKGGVkdS53cGkuZmlyc3QubWF0aC5wcm90b0rVAwoGEgQA" + + "ABABCggKAQwSAwAAEgoICgECEgMCABIKCQoCAwASAwQAFwoICgEIEgMGADEKCQoCCAESAwYAMQoKCgIE" + + "ABIECAAQAQoKCgMEAAESAwgIHAoLCgQEAAIAEgMJAhgKDAoFBAACAAUSAwkCCAoMCgUEAAIAARIDCQkT" + + "CgwKBQQAAgADEgMJFhcKCwoEBAACARIDCgIYCgwKBQQAAgEFEgMKAggKDAoFBAACAQESAwoJEwoMCgUE" + + "AAIBAxIDChYXCgsKBAQAAgISAwsCGQoMCgUEAAICBRIDCwIICgwKBQQAAgIBEgMLCRQKDAoFBAACAgMS" + + "AwsXGAoLCgQEAAIDEgMMAhcKDAoFBAACAwYSAwwCEAoMCgUEAAIDARIDDBESCgwKBQQAAgMDEgMMFRYK" + + "CwoEBAACBBIDDQIXCgwKBQQAAgQGEgMNAhAKDAoFBAACBAESAw0REgoMCgUEAAIEAxIDDRUWCgsKBAQA" + + "AgUSAw4CFwoMCgUEAAIFBhIDDgIQCgwKBQQAAgUBEgMOERIKDAoFBAACBQMSAw4VFgoLCgQEAAIGEgMP" + + "AhcKDAoFBAACBgYSAw8CEAoMCgUEAAIGARIDDxESCgwKBQQAAgYDEgMPFRZiBnByb3RvMw=="); + + static final Descriptors.FileDescriptor descriptor = Descriptors.FileDescriptor.internalBuildGeneratedFileFrom("system.proto", "wpi.proto", descriptorData, Wpimath.getDescriptor()); + + static final Descriptors.Descriptor wpi_proto_ProtobufLinearSystem_descriptor = descriptor.internalContainedType(43, 281, "ProtobufLinearSystem", "wpi.proto.ProtobufLinearSystem"); + + /** + * @return this proto file's descriptor. + */ + public static Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + /** + * Protobuf type {@code ProtobufLinearSystem} + */ + public static final class ProtobufLinearSystem extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional uint32 num_states = 1; + */ + private int numStates; + + /** + * optional uint32 num_inputs = 2; + */ + private int numInputs; + + /** + * optional uint32 num_outputs = 3; + */ + private int numOutputs; + + /** + * optional .wpi.proto.ProtobufMatrix a = 4; + */ + private final Wpimath.ProtobufMatrix a = Wpimath.ProtobufMatrix.newInstance(); + + /** + * optional .wpi.proto.ProtobufMatrix b = 5; + */ + private final Wpimath.ProtobufMatrix b = Wpimath.ProtobufMatrix.newInstance(); + + /** + * optional .wpi.proto.ProtobufMatrix c = 6; + */ + private final Wpimath.ProtobufMatrix c = Wpimath.ProtobufMatrix.newInstance(); + + /** + * optional .wpi.proto.ProtobufMatrix d = 7; + */ + private final Wpimath.ProtobufMatrix d = Wpimath.ProtobufMatrix.newInstance(); + + private ProtobufLinearSystem() { + } + + /** + * @return a new empty instance of {@code ProtobufLinearSystem} + */ + public static ProtobufLinearSystem newInstance() { + return new ProtobufLinearSystem(); + } + + /** + * optional uint32 num_states = 1; + * @return whether the numStates field is set + */ + public boolean hasNumStates() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional uint32 num_states = 1; + * @return this + */ + public ProtobufLinearSystem clearNumStates() { + bitField0_ &= ~0x00000001; + numStates = 0; + return this; + } + + /** + * optional uint32 num_states = 1; + * @return the numStates + */ + public int getNumStates() { + return numStates; + } + + /** + * optional uint32 num_states = 1; + * @param value the numStates to set + * @return this + */ + public ProtobufLinearSystem setNumStates(final int value) { + bitField0_ |= 0x00000001; + numStates = value; + return this; + } + + /** + * optional uint32 num_inputs = 2; + * @return whether the numInputs field is set + */ + public boolean hasNumInputs() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional uint32 num_inputs = 2; + * @return this + */ + public ProtobufLinearSystem clearNumInputs() { + bitField0_ &= ~0x00000002; + numInputs = 0; + return this; + } + + /** + * optional uint32 num_inputs = 2; + * @return the numInputs + */ + public int getNumInputs() { + return numInputs; + } + + /** + * optional uint32 num_inputs = 2; + * @param value the numInputs to set + * @return this + */ + public ProtobufLinearSystem setNumInputs(final int value) { + bitField0_ |= 0x00000002; + numInputs = value; + return this; + } + + /** + * optional uint32 num_outputs = 3; + * @return whether the numOutputs field is set + */ + public boolean hasNumOutputs() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional uint32 num_outputs = 3; + * @return this + */ + public ProtobufLinearSystem clearNumOutputs() { + bitField0_ &= ~0x00000004; + numOutputs = 0; + return this; + } + + /** + * optional uint32 num_outputs = 3; + * @return the numOutputs + */ + public int getNumOutputs() { + return numOutputs; + } + + /** + * optional uint32 num_outputs = 3; + * @param value the numOutputs to set + * @return this + */ + public ProtobufLinearSystem setNumOutputs(final int value) { + bitField0_ |= 0x00000004; + numOutputs = value; + return this; + } + + /** + * optional .wpi.proto.ProtobufMatrix a = 4; + * @return whether the a field is set + */ + public boolean hasA() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * optional .wpi.proto.ProtobufMatrix a = 4; + * @return this + */ + public ProtobufLinearSystem clearA() { + bitField0_ &= ~0x00000008; + a.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufMatrix a = 4; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableA()} if you want to modify it. + * + * @return internal storage object for reading + */ + public Wpimath.ProtobufMatrix getA() { + return a; + } + + /** + * optional .wpi.proto.ProtobufMatrix a = 4; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public Wpimath.ProtobufMatrix getMutableA() { + bitField0_ |= 0x00000008; + return a; + } + + /** + * optional .wpi.proto.ProtobufMatrix a = 4; + * @param value the a to set + * @return this + */ + public ProtobufLinearSystem setA(final Wpimath.ProtobufMatrix value) { + bitField0_ |= 0x00000008; + a.copyFrom(value); + return this; + } + + /** + * optional .wpi.proto.ProtobufMatrix b = 5; + * @return whether the b field is set + */ + public boolean hasB() { + return (bitField0_ & 0x00000010) != 0; + } + + /** + * optional .wpi.proto.ProtobufMatrix b = 5; + * @return this + */ + public ProtobufLinearSystem clearB() { + bitField0_ &= ~0x00000010; + b.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufMatrix b = 5; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableB()} if you want to modify it. + * + * @return internal storage object for reading + */ + public Wpimath.ProtobufMatrix getB() { + return b; + } + + /** + * optional .wpi.proto.ProtobufMatrix b = 5; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public Wpimath.ProtobufMatrix getMutableB() { + bitField0_ |= 0x00000010; + return b; + } + + /** + * optional .wpi.proto.ProtobufMatrix b = 5; + * @param value the b to set + * @return this + */ + public ProtobufLinearSystem setB(final Wpimath.ProtobufMatrix value) { + bitField0_ |= 0x00000010; + b.copyFrom(value); + return this; + } + + /** + * optional .wpi.proto.ProtobufMatrix c = 6; + * @return whether the c field is set + */ + public boolean hasC() { + return (bitField0_ & 0x00000020) != 0; + } + + /** + * optional .wpi.proto.ProtobufMatrix c = 6; + * @return this + */ + public ProtobufLinearSystem clearC() { + bitField0_ &= ~0x00000020; + c.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufMatrix c = 6; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableC()} if you want to modify it. + * + * @return internal storage object for reading + */ + public Wpimath.ProtobufMatrix getC() { + return c; + } + + /** + * optional .wpi.proto.ProtobufMatrix c = 6; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public Wpimath.ProtobufMatrix getMutableC() { + bitField0_ |= 0x00000020; + return c; + } + + /** + * optional .wpi.proto.ProtobufMatrix c = 6; + * @param value the c to set + * @return this + */ + public ProtobufLinearSystem setC(final Wpimath.ProtobufMatrix value) { + bitField0_ |= 0x00000020; + c.copyFrom(value); + return this; + } + + /** + * optional .wpi.proto.ProtobufMatrix d = 7; + * @return whether the d field is set + */ + public boolean hasD() { + return (bitField0_ & 0x00000040) != 0; + } + + /** + * optional .wpi.proto.ProtobufMatrix d = 7; + * @return this + */ + public ProtobufLinearSystem clearD() { + bitField0_ &= ~0x00000040; + d.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufMatrix d = 7; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableD()} if you want to modify it. + * + * @return internal storage object for reading + */ + public Wpimath.ProtobufMatrix getD() { + return d; + } + + /** + * optional .wpi.proto.ProtobufMatrix d = 7; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public Wpimath.ProtobufMatrix getMutableD() { + bitField0_ |= 0x00000040; + return d; + } + + /** + * optional .wpi.proto.ProtobufMatrix d = 7; + * @param value the d to set + * @return this + */ + public ProtobufLinearSystem setD(final Wpimath.ProtobufMatrix value) { + bitField0_ |= 0x00000040; + d.copyFrom(value); + return this; + } + + @Override + public ProtobufLinearSystem copyFrom(final ProtobufLinearSystem other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + numStates = other.numStates; + numInputs = other.numInputs; + numOutputs = other.numOutputs; + a.copyFrom(other.a); + b.copyFrom(other.b); + c.copyFrom(other.c); + d.copyFrom(other.d); + } + return this; + } + + @Override + public ProtobufLinearSystem mergeFrom(final ProtobufLinearSystem other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasNumStates()) { + setNumStates(other.numStates); + } + if (other.hasNumInputs()) { + setNumInputs(other.numInputs); + } + if (other.hasNumOutputs()) { + setNumOutputs(other.numOutputs); + } + if (other.hasA()) { + getMutableA().mergeFrom(other.a); + } + if (other.hasB()) { + getMutableB().mergeFrom(other.b); + } + if (other.hasC()) { + getMutableC().mergeFrom(other.c); + } + if (other.hasD()) { + getMutableD().mergeFrom(other.d); + } + return this; + } + + @Override + public ProtobufLinearSystem clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + numStates = 0; + numInputs = 0; + numOutputs = 0; + a.clear(); + b.clear(); + c.clear(); + d.clear(); + return this; + } + + @Override + public ProtobufLinearSystem clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + a.clearQuick(); + b.clearQuick(); + c.clearQuick(); + d.clearQuick(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufLinearSystem)) { + return false; + } + ProtobufLinearSystem other = (ProtobufLinearSystem) o; + return bitField0_ == other.bitField0_ + && (!hasNumStates() || numStates == other.numStates) + && (!hasNumInputs() || numInputs == other.numInputs) + && (!hasNumOutputs() || numOutputs == other.numOutputs) + && (!hasA() || a.equals(other.a)) + && (!hasB() || b.equals(other.b)) + && (!hasC() || c.equals(other.c)) + && (!hasD() || d.equals(other.d)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 8); + output.writeUInt32NoTag(numStates); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 16); + output.writeUInt32NoTag(numInputs); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 24); + output.writeUInt32NoTag(numOutputs); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRawByte((byte) 34); + output.writeMessageNoTag(a); + } + if ((bitField0_ & 0x00000010) != 0) { + output.writeRawByte((byte) 42); + output.writeMessageNoTag(b); + } + if ((bitField0_ & 0x00000020) != 0) { + output.writeRawByte((byte) 50); + output.writeMessageNoTag(c); + } + if ((bitField0_ & 0x00000040) != 0) { + output.writeRawByte((byte) 58); + output.writeMessageNoTag(d); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 1 + ProtoSink.computeUInt32SizeNoTag(numStates); + } + if ((bitField0_ & 0x00000002) != 0) { + size += 1 + ProtoSink.computeUInt32SizeNoTag(numInputs); + } + if ((bitField0_ & 0x00000004) != 0) { + size += 1 + ProtoSink.computeUInt32SizeNoTag(numOutputs); + } + if ((bitField0_ & 0x00000008) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(a); + } + if ((bitField0_ & 0x00000010) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(b); + } + if ((bitField0_ & 0x00000020) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(c); + } + if ((bitField0_ & 0x00000040) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(d); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufLinearSystem mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 8: { + // numStates + numStates = input.readUInt32(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 16) { + break; + } + } + case 16: { + // numInputs + numInputs = input.readUInt32(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 24) { + break; + } + } + case 24: { + // numOutputs + numOutputs = input.readUInt32(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 34) { + break; + } + } + case 34: { + // a + input.readMessage(a); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 42) { + break; + } + } + case 42: { + // b + input.readMessage(b); + bitField0_ |= 0x00000010; + tag = input.readTag(); + if (tag != 50) { + break; + } + } + case 50: { + // c + input.readMessage(c); + bitField0_ |= 0x00000020; + tag = input.readTag(); + if (tag != 58) { + break; + } + } + case 58: { + // d + input.readMessage(d); + bitField0_ |= 0x00000040; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeUInt32(FieldNames.numStates, numStates); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeUInt32(FieldNames.numInputs, numInputs); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeUInt32(FieldNames.numOutputs, numOutputs); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeMessage(FieldNames.a, a); + } + if ((bitField0_ & 0x00000010) != 0) { + output.writeMessage(FieldNames.b, b); + } + if ((bitField0_ & 0x00000020) != 0) { + output.writeMessage(FieldNames.c, c); + } + if ((bitField0_ & 0x00000040) != 0) { + output.writeMessage(FieldNames.d, d); + } + output.endObject(); + } + + @Override + public ProtobufLinearSystem mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 1233856808: + case 1643330779: { + if (input.isAtField(FieldNames.numStates)) { + if (!input.trySkipNullValue()) { + numStates = input.readUInt32(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 942472463: + case 1351946434: { + if (input.isAtField(FieldNames.numInputs)) { + if (!input.trySkipNullValue()) { + numInputs = input.readUInt32(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case 385880364: + case 194671577: { + if (input.isAtField(FieldNames.numOutputs)) { + if (!input.trySkipNullValue()) { + numOutputs = input.readUInt32(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case 97: { + if (input.isAtField(FieldNames.a)) { + if (!input.trySkipNullValue()) { + input.readMessage(a); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + case 98: { + if (input.isAtField(FieldNames.b)) { + if (!input.trySkipNullValue()) { + input.readMessage(b); + bitField0_ |= 0x00000010; + } + } else { + input.skipUnknownField(); + } + break; + } + case 99: { + if (input.isAtField(FieldNames.c)) { + if (!input.trySkipNullValue()) { + input.readMessage(c); + bitField0_ |= 0x00000020; + } + } else { + input.skipUnknownField(); + } + break; + } + case 100: { + if (input.isAtField(FieldNames.d)) { + if (!input.trySkipNullValue()) { + input.readMessage(d); + bitField0_ |= 0x00000040; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufLinearSystem clone() { + return new ProtobufLinearSystem().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufLinearSystem parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufLinearSystem(), data).checkInitialized(); + } + + public static ProtobufLinearSystem parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufLinearSystem(), input).checkInitialized(); + } + + public static ProtobufLinearSystem parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufLinearSystem(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufLinearSystem messages + */ + public static MessageFactory getFactory() { + return ProtobufLinearSystemFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return System.wpi_proto_ProtobufLinearSystem_descriptor; + } + + private enum ProtobufLinearSystemFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufLinearSystem create() { + return ProtobufLinearSystem.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName numStates = FieldName.forField("numStates", "num_states"); + + static final FieldName numInputs = FieldName.forField("numInputs", "num_inputs"); + + static final FieldName numOutputs = FieldName.forField("numOutputs", "num_outputs"); + + static final FieldName a = FieldName.forField("a"); + + static final FieldName b = FieldName.forField("b"); + + static final FieldName c = FieldName.forField("c"); + + static final FieldName d = FieldName.forField("d"); + } + } +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Trajectory.java b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Trajectory.java new file mode 100644 index 00000000000..3ec96f82760 --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Trajectory.java @@ -0,0 +1,928 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. +// Code generated by protocol buffer compiler. Do not edit! +package edu.wpi.first.math.proto; + +import java.io.IOException; +import us.hebi.quickbuf.Descriptors; +import us.hebi.quickbuf.FieldName; +import us.hebi.quickbuf.InvalidProtocolBufferException; +import us.hebi.quickbuf.JsonSink; +import us.hebi.quickbuf.JsonSource; +import us.hebi.quickbuf.MessageFactory; +import us.hebi.quickbuf.ProtoMessage; +import us.hebi.quickbuf.ProtoSink; +import us.hebi.quickbuf.ProtoSource; +import us.hebi.quickbuf.ProtoUtil; +import us.hebi.quickbuf.RepeatedByte; +import us.hebi.quickbuf.RepeatedMessage; + +public final class Trajectory { + private static final RepeatedByte descriptorData = ProtoUtil.decodeBase64(809, + "ChB0cmFqZWN0b3J5LnByb3RvEgl3cGkucHJvdG8aEGdlb21ldHJ5MmQucHJvdG8iugEKF1Byb3RvYnVm" + + "VHJhamVjdG9yeVN0YXRlEhIKBHRpbWUYASABKAFSBHRpbWUSGgoIdmVsb2NpdHkYAiABKAFSCHZlbG9j" + + "aXR5EiIKDGFjY2VsZXJhdGlvbhgDIAEoAVIMYWNjZWxlcmF0aW9uEi0KBHBvc2UYBCABKAsyGS53cGku" + + "cHJvdG8uUHJvdG9idWZQb3NlMmRSBHBvc2USHAoJY3VydmF0dXJlGAUgASgBUgljdXJ2YXR1cmUiUAoS" + + "UHJvdG9idWZUcmFqZWN0b3J5EjoKBnN0YXRlcxgCIAMoCzIiLndwaS5wcm90by5Qcm90b2J1ZlRyYWpl" + + "Y3RvcnlTdGF0ZVIGc3RhdGVzQhoKGGVkdS53cGkuZmlyc3QubWF0aC5wcm90b0rEAwoGEgQAABIBCggK" + + "AQwSAwAAEgoICgECEgMCABIKCQoCAwASAwQAGgoICgEIEgMGADEKCQoCCAESAwYAMQoKCgIEABIECAAO" + + "AQoKCgMEAAESAwgIHwoLCgQEAAIAEgMJAhIKDAoFBAACAAUSAwkCCAoMCgUEAAIAARIDCQkNCgwKBQQA" + + "AgADEgMJEBEKCwoEBAACARIDCgIWCgwKBQQAAgEFEgMKAggKDAoFBAACAQESAwoJEQoMCgUEAAIBAxID" + + "ChQVCgsKBAQAAgISAwsCGgoMCgUEAAICBRIDCwIICgwKBQQAAgIBEgMLCRUKDAoFBAACAgMSAwsYGQoL" + + "CgQEAAIDEgMMAhoKDAoFBAACAwYSAwwCEAoMCgUEAAIDARIDDBEVCgwKBQQAAgMDEgMMGBkKCwoEBAAC" + + "BBIDDQIXCgwKBQQAAgQFEgMNAggKDAoFBAACBAESAw0JEgoMCgUEAAIEAxIDDRUWCgoKAgQBEgQQABIB" + + "CgoKAwQBARIDEAgaCgsKBAQBAgASAxECLgoMCgUEAQIABBIDEQIKCgwKBQQBAgAGEgMRCyIKDAoFBAEC" + + "AAESAxEjKQoMCgUEAQIAAxIDESwtYgZwcm90bzM="); + + static final Descriptors.FileDescriptor descriptor = Descriptors.FileDescriptor.internalBuildGeneratedFileFrom("trajectory.proto", "wpi.proto", descriptorData, Geometry2D.getDescriptor()); + + static final Descriptors.Descriptor wpi_proto_ProtobufTrajectoryState_descriptor = descriptor.internalContainedType(50, 186, "ProtobufTrajectoryState", "wpi.proto.ProtobufTrajectoryState"); + + static final Descriptors.Descriptor wpi_proto_ProtobufTrajectory_descriptor = descriptor.internalContainedType(238, 80, "ProtobufTrajectory", "wpi.proto.ProtobufTrajectory"); + + /** + * @return this proto file's descriptor. + */ + public static Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + /** + * Protobuf type {@code ProtobufTrajectoryState} + */ + public static final class ProtobufTrajectoryState extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional double time = 1; + */ + private double time; + + /** + * optional double velocity = 2; + */ + private double velocity; + + /** + * optional double acceleration = 3; + */ + private double acceleration; + + /** + * optional double curvature = 5; + */ + private double curvature; + + /** + * optional .wpi.proto.ProtobufPose2d pose = 4; + */ + private final Geometry2D.ProtobufPose2d pose = Geometry2D.ProtobufPose2d.newInstance(); + + private ProtobufTrajectoryState() { + } + + /** + * @return a new empty instance of {@code ProtobufTrajectoryState} + */ + public static ProtobufTrajectoryState newInstance() { + return new ProtobufTrajectoryState(); + } + + /** + * optional double time = 1; + * @return whether the time field is set + */ + public boolean hasTime() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional double time = 1; + * @return this + */ + public ProtobufTrajectoryState clearTime() { + bitField0_ &= ~0x00000001; + time = 0D; + return this; + } + + /** + * optional double time = 1; + * @return the time + */ + public double getTime() { + return time; + } + + /** + * optional double time = 1; + * @param value the time to set + * @return this + */ + public ProtobufTrajectoryState setTime(final double value) { + bitField0_ |= 0x00000001; + time = value; + return this; + } + + /** + * optional double velocity = 2; + * @return whether the velocity field is set + */ + public boolean hasVelocity() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional double velocity = 2; + * @return this + */ + public ProtobufTrajectoryState clearVelocity() { + bitField0_ &= ~0x00000002; + velocity = 0D; + return this; + } + + /** + * optional double velocity = 2; + * @return the velocity + */ + public double getVelocity() { + return velocity; + } + + /** + * optional double velocity = 2; + * @param value the velocity to set + * @return this + */ + public ProtobufTrajectoryState setVelocity(final double value) { + bitField0_ |= 0x00000002; + velocity = value; + return this; + } + + /** + * optional double acceleration = 3; + * @return whether the acceleration field is set + */ + public boolean hasAcceleration() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * optional double acceleration = 3; + * @return this + */ + public ProtobufTrajectoryState clearAcceleration() { + bitField0_ &= ~0x00000004; + acceleration = 0D; + return this; + } + + /** + * optional double acceleration = 3; + * @return the acceleration + */ + public double getAcceleration() { + return acceleration; + } + + /** + * optional double acceleration = 3; + * @param value the acceleration to set + * @return this + */ + public ProtobufTrajectoryState setAcceleration(final double value) { + bitField0_ |= 0x00000004; + acceleration = value; + return this; + } + + /** + * optional double curvature = 5; + * @return whether the curvature field is set + */ + public boolean hasCurvature() { + return (bitField0_ & 0x00000008) != 0; + } + + /** + * optional double curvature = 5; + * @return this + */ + public ProtobufTrajectoryState clearCurvature() { + bitField0_ &= ~0x00000008; + curvature = 0D; + return this; + } + + /** + * optional double curvature = 5; + * @return the curvature + */ + public double getCurvature() { + return curvature; + } + + /** + * optional double curvature = 5; + * @param value the curvature to set + * @return this + */ + public ProtobufTrajectoryState setCurvature(final double value) { + bitField0_ |= 0x00000008; + curvature = value; + return this; + } + + /** + * optional .wpi.proto.ProtobufPose2d pose = 4; + * @return whether the pose field is set + */ + public boolean hasPose() { + return (bitField0_ & 0x00000010) != 0; + } + + /** + * optional .wpi.proto.ProtobufPose2d pose = 4; + * @return this + */ + public ProtobufTrajectoryState clearPose() { + bitField0_ &= ~0x00000010; + pose.clear(); + return this; + } + + /** + * optional .wpi.proto.ProtobufPose2d pose = 4; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutablePose()} if you want to modify it. + * + * @return internal storage object for reading + */ + public Geometry2D.ProtobufPose2d getPose() { + return pose; + } + + /** + * optional .wpi.proto.ProtobufPose2d pose = 4; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public Geometry2D.ProtobufPose2d getMutablePose() { + bitField0_ |= 0x00000010; + return pose; + } + + /** + * optional .wpi.proto.ProtobufPose2d pose = 4; + * @param value the pose to set + * @return this + */ + public ProtobufTrajectoryState setPose(final Geometry2D.ProtobufPose2d value) { + bitField0_ |= 0x00000010; + pose.copyFrom(value); + return this; + } + + @Override + public ProtobufTrajectoryState copyFrom(final ProtobufTrajectoryState other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + time = other.time; + velocity = other.velocity; + acceleration = other.acceleration; + curvature = other.curvature; + pose.copyFrom(other.pose); + } + return this; + } + + @Override + public ProtobufTrajectoryState mergeFrom(final ProtobufTrajectoryState other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasTime()) { + setTime(other.time); + } + if (other.hasVelocity()) { + setVelocity(other.velocity); + } + if (other.hasAcceleration()) { + setAcceleration(other.acceleration); + } + if (other.hasCurvature()) { + setCurvature(other.curvature); + } + if (other.hasPose()) { + getMutablePose().mergeFrom(other.pose); + } + return this; + } + + @Override + public ProtobufTrajectoryState clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + time = 0D; + velocity = 0D; + acceleration = 0D; + curvature = 0D; + pose.clear(); + return this; + } + + @Override + public ProtobufTrajectoryState clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + pose.clearQuick(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufTrajectoryState)) { + return false; + } + ProtobufTrajectoryState other = (ProtobufTrajectoryState) o; + return bitField0_ == other.bitField0_ + && (!hasTime() || ProtoUtil.isEqual(time, other.time)) + && (!hasVelocity() || ProtoUtil.isEqual(velocity, other.velocity)) + && (!hasAcceleration() || ProtoUtil.isEqual(acceleration, other.acceleration)) + && (!hasCurvature() || ProtoUtil.isEqual(curvature, other.curvature)) + && (!hasPose() || pose.equals(other.pose)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(time); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 17); + output.writeDoubleNoTag(velocity); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(acceleration); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeRawByte((byte) 41); + output.writeDoubleNoTag(curvature); + } + if ((bitField0_ & 0x00000010) != 0) { + output.writeRawByte((byte) 34); + output.writeMessageNoTag(pose); + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000002) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000004) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000008) != 0) { + size += 9; + } + if ((bitField0_ & 0x00000010) != 0) { + size += 1 + ProtoSink.computeMessageSizeNoTag(pose); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufTrajectoryState mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 9: { + // time + time = input.readDouble(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 17) { + break; + } + } + case 17: { + // velocity + velocity = input.readDouble(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 25) { + break; + } + } + case 25: { + // acceleration + acceleration = input.readDouble(); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 41) { + break; + } + } + case 41: { + // curvature + curvature = input.readDouble(); + bitField0_ |= 0x00000008; + tag = input.readTag(); + if (tag != 34) { + break; + } + } + case 34: { + // pose + input.readMessage(pose); + bitField0_ |= 0x00000010; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeDouble(FieldNames.time, time); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeDouble(FieldNames.velocity, velocity); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeDouble(FieldNames.acceleration, acceleration); + } + if ((bitField0_ & 0x00000008) != 0) { + output.writeDouble(FieldNames.curvature, curvature); + } + if ((bitField0_ & 0x00000010) != 0) { + output.writeMessage(FieldNames.pose, pose); + } + output.endObject(); + } + + @Override + public ProtobufTrajectoryState mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 3560141: { + if (input.isAtField(FieldNames.time)) { + if (!input.trySkipNullValue()) { + time = input.readDouble(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case 2134260957: { + if (input.isAtField(FieldNames.velocity)) { + if (!input.trySkipNullValue()) { + velocity = input.readDouble(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case -267299712: { + if (input.isAtField(FieldNames.acceleration)) { + if (!input.trySkipNullValue()) { + acceleration = input.readDouble(); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + case 768611295: { + if (input.isAtField(FieldNames.curvature)) { + if (!input.trySkipNullValue()) { + curvature = input.readDouble(); + bitField0_ |= 0x00000008; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3446929: { + if (input.isAtField(FieldNames.pose)) { + if (!input.trySkipNullValue()) { + input.readMessage(pose); + bitField0_ |= 0x00000010; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufTrajectoryState clone() { + return new ProtobufTrajectoryState().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufTrajectoryState parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufTrajectoryState(), data).checkInitialized(); + } + + public static ProtobufTrajectoryState parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTrajectoryState(), input).checkInitialized(); + } + + public static ProtobufTrajectoryState parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTrajectoryState(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufTrajectoryState messages + */ + public static MessageFactory getFactory() { + return ProtobufTrajectoryStateFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Trajectory.wpi_proto_ProtobufTrajectoryState_descriptor; + } + + private enum ProtobufTrajectoryStateFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufTrajectoryState create() { + return ProtobufTrajectoryState.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName time = FieldName.forField("time"); + + static final FieldName velocity = FieldName.forField("velocity"); + + static final FieldName acceleration = FieldName.forField("acceleration"); + + static final FieldName curvature = FieldName.forField("curvature"); + + static final FieldName pose = FieldName.forField("pose"); + } + } + + /** + * Protobuf type {@code ProtobufTrajectory} + */ + public static final class ProtobufTrajectory extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * repeated .wpi.proto.ProtobufTrajectoryState states = 2; + */ + private final RepeatedMessage states = RepeatedMessage.newEmptyInstance(ProtobufTrajectoryState.getFactory()); + + private ProtobufTrajectory() { + } + + /** + * @return a new empty instance of {@code ProtobufTrajectory} + */ + public static ProtobufTrajectory newInstance() { + return new ProtobufTrajectory(); + } + + /** + * repeated .wpi.proto.ProtobufTrajectoryState states = 2; + * @return whether the states field is set + */ + public boolean hasStates() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * repeated .wpi.proto.ProtobufTrajectoryState states = 2; + * @return this + */ + public ProtobufTrajectory clearStates() { + bitField0_ &= ~0x00000001; + states.clear(); + return this; + } + + /** + * repeated .wpi.proto.ProtobufTrajectoryState states = 2; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableStates()} if you want to modify it. + * + * @return internal storage object for reading + */ + public RepeatedMessage getStates() { + return states; + } + + /** + * repeated .wpi.proto.ProtobufTrajectoryState states = 2; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public RepeatedMessage getMutableStates() { + bitField0_ |= 0x00000001; + return states; + } + + /** + * repeated .wpi.proto.ProtobufTrajectoryState states = 2; + * @param value the states to add + * @return this + */ + public ProtobufTrajectory addStates(final ProtobufTrajectoryState value) { + bitField0_ |= 0x00000001; + states.add(value); + return this; + } + + /** + * repeated .wpi.proto.ProtobufTrajectoryState states = 2; + * @param values the states to add + * @return this + */ + public ProtobufTrajectory addAllStates(final ProtobufTrajectoryState... values) { + bitField0_ |= 0x00000001; + states.addAll(values); + return this; + } + + @Override + public ProtobufTrajectory copyFrom(final ProtobufTrajectory other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + states.copyFrom(other.states); + } + return this; + } + + @Override + public ProtobufTrajectory mergeFrom(final ProtobufTrajectory other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasStates()) { + getMutableStates().addAll(other.states); + } + return this; + } + + @Override + public ProtobufTrajectory clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + states.clear(); + return this; + } + + @Override + public ProtobufTrajectory clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + states.clearQuick(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufTrajectory)) { + return false; + } + ProtobufTrajectory other = (ProtobufTrajectory) o; + return bitField0_ == other.bitField0_ + && (!hasStates() || states.equals(other.states)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + for (int i = 0; i < states.length(); i++) { + output.writeRawByte((byte) 18); + output.writeMessageNoTag(states.get(i)); + } + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += (1 * states.length()) + ProtoSink.computeRepeatedMessageSizeNoTag(states); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufTrajectory mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 18: { + // states + tag = input.readRepeatedMessage(states, tag); + bitField0_ |= 0x00000001; + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeRepeatedMessage(FieldNames.states, states); + } + output.endObject(); + } + + @Override + public ProtobufTrajectory mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case -892482046: { + if (input.isAtField(FieldNames.states)) { + if (!input.trySkipNullValue()) { + input.readRepeatedMessage(states); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufTrajectory clone() { + return new ProtobufTrajectory().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufTrajectory parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufTrajectory(), data).checkInitialized(); + } + + public static ProtobufTrajectory parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTrajectory(), input).checkInitialized(); + } + + public static ProtobufTrajectory parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufTrajectory(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufTrajectory messages + */ + public static MessageFactory getFactory() { + return ProtobufTrajectoryFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Trajectory.wpi_proto_ProtobufTrajectory_descriptor; + } + + private enum ProtobufTrajectoryFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufTrajectory create() { + return ProtobufTrajectory.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName states = FieldName.forField("states"); + } + } +} diff --git a/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Wpimath.java b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Wpimath.java new file mode 100644 index 00000000000..ce964a2795c --- /dev/null +++ b/wpimath/src/generated/main/java/edu/wpi/first/math/proto/Wpimath.java @@ -0,0 +1,791 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. +// Code generated by protocol buffer compiler. Do not edit! +package edu.wpi.first.math.proto; + +import java.io.IOException; +import us.hebi.quickbuf.Descriptors; +import us.hebi.quickbuf.FieldName; +import us.hebi.quickbuf.InvalidProtocolBufferException; +import us.hebi.quickbuf.JsonSink; +import us.hebi.quickbuf.JsonSource; +import us.hebi.quickbuf.MessageFactory; +import us.hebi.quickbuf.ProtoMessage; +import us.hebi.quickbuf.ProtoSink; +import us.hebi.quickbuf.ProtoSource; +import us.hebi.quickbuf.ProtoUtil; +import us.hebi.quickbuf.RepeatedByte; +import us.hebi.quickbuf.RepeatedDouble; + +public final class Wpimath { + private static final RepeatedByte descriptorData = ProtoUtil.decodeBase64(540, + "Cg13cGltYXRoLnByb3RvEgl3cGkucHJvdG8iWgoOUHJvdG9idWZNYXRyaXgSGQoIbnVtX3Jvd3MYASAB" + + "KA1SB251bVJvd3MSGQoIbnVtX2NvbHMYAiABKA1SB251bUNvbHMSEgoEZGF0YRgDIAMoAVIEZGF0YSIk" + + "Cg5Qcm90b2J1ZlZlY3RvchISCgRyb3dzGAEgAygBUgRyb3dzQhoKGGVkdS53cGkuZmlyc3QubWF0aC5w" + + "cm90b0rZAgoGEgQAAA4BCggKAQwSAwAAEgoICgECEgMCABIKCAoBCBIDBAAxCgkKAggBEgMEADEKCgoC" + + "BAASBAYACgEKCgoDBAABEgMGCBYKCwoEBAACABIDBwIWCgwKBQQAAgAFEgMHAggKDAoFBAACAAESAwcJ" + + "EQoMCgUEAAIAAxIDBxQVCgsKBAQAAgESAwgCFgoMCgUEAAIBBRIDCAIICgwKBQQAAgEBEgMICREKDAoF" + + "BAACAQMSAwgUFQoLCgQEAAICEgMJAhsKDAoFBAACAgQSAwkCCgoMCgUEAAICBRIDCQsRCgwKBQQAAgIB" + + "EgMJEhYKDAoFBAACAgMSAwkZGgoKCgIEARIEDAAOAQoKCgMEAQESAwwIFgoLCgQEAQIAEgMNAhsKDAoF" + + "BAECAAQSAw0CCgoMCgUEAQIABRIDDQsRCgwKBQQBAgABEgMNEhYKDAoFBAECAAMSAw0ZGmIGcHJvdG8z"); + + static final Descriptors.FileDescriptor descriptor = Descriptors.FileDescriptor.internalBuildGeneratedFileFrom("wpimath.proto", "wpi.proto", descriptorData); + + static final Descriptors.Descriptor wpi_proto_ProtobufMatrix_descriptor = descriptor.internalContainedType(28, 90, "ProtobufMatrix", "wpi.proto.ProtobufMatrix"); + + static final Descriptors.Descriptor wpi_proto_ProtobufVector_descriptor = descriptor.internalContainedType(120, 36, "ProtobufVector", "wpi.proto.ProtobufVector"); + + /** + * @return this proto file's descriptor. + */ + public static Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + /** + * Protobuf type {@code ProtobufMatrix} + */ + public static final class ProtobufMatrix extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * optional uint32 num_rows = 1; + */ + private int numRows; + + /** + * optional uint32 num_cols = 2; + */ + private int numCols; + + /** + * repeated double data = 3; + */ + private final RepeatedDouble data = RepeatedDouble.newEmptyInstance(); + + private ProtobufMatrix() { + } + + /** + * @return a new empty instance of {@code ProtobufMatrix} + */ + public static ProtobufMatrix newInstance() { + return new ProtobufMatrix(); + } + + /** + * optional uint32 num_rows = 1; + * @return whether the numRows field is set + */ + public boolean hasNumRows() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * optional uint32 num_rows = 1; + * @return this + */ + public ProtobufMatrix clearNumRows() { + bitField0_ &= ~0x00000001; + numRows = 0; + return this; + } + + /** + * optional uint32 num_rows = 1; + * @return the numRows + */ + public int getNumRows() { + return numRows; + } + + /** + * optional uint32 num_rows = 1; + * @param value the numRows to set + * @return this + */ + public ProtobufMatrix setNumRows(final int value) { + bitField0_ |= 0x00000001; + numRows = value; + return this; + } + + /** + * optional uint32 num_cols = 2; + * @return whether the numCols field is set + */ + public boolean hasNumCols() { + return (bitField0_ & 0x00000002) != 0; + } + + /** + * optional uint32 num_cols = 2; + * @return this + */ + public ProtobufMatrix clearNumCols() { + bitField0_ &= ~0x00000002; + numCols = 0; + return this; + } + + /** + * optional uint32 num_cols = 2; + * @return the numCols + */ + public int getNumCols() { + return numCols; + } + + /** + * optional uint32 num_cols = 2; + * @param value the numCols to set + * @return this + */ + public ProtobufMatrix setNumCols(final int value) { + bitField0_ |= 0x00000002; + numCols = value; + return this; + } + + /** + * repeated double data = 3; + * @return whether the data field is set + */ + public boolean hasData() { + return (bitField0_ & 0x00000004) != 0; + } + + /** + * repeated double data = 3; + * @return this + */ + public ProtobufMatrix clearData() { + bitField0_ &= ~0x00000004; + data.clear(); + return this; + } + + /** + * repeated double data = 3; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableData()} if you want to modify it. + * + * @return internal storage object for reading + */ + public RepeatedDouble getData() { + return data; + } + + /** + * repeated double data = 3; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public RepeatedDouble getMutableData() { + bitField0_ |= 0x00000004; + return data; + } + + /** + * repeated double data = 3; + * @param value the data to add + * @return this + */ + public ProtobufMatrix addData(final double value) { + bitField0_ |= 0x00000004; + data.add(value); + return this; + } + + /** + * repeated double data = 3; + * @param values the data to add + * @return this + */ + public ProtobufMatrix addAllData(final double... values) { + bitField0_ |= 0x00000004; + data.addAll(values); + return this; + } + + @Override + public ProtobufMatrix copyFrom(final ProtobufMatrix other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + numRows = other.numRows; + numCols = other.numCols; + data.copyFrom(other.data); + } + return this; + } + + @Override + public ProtobufMatrix mergeFrom(final ProtobufMatrix other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasNumRows()) { + setNumRows(other.numRows); + } + if (other.hasNumCols()) { + setNumCols(other.numCols); + } + if (other.hasData()) { + getMutableData().addAll(other.data); + } + return this; + } + + @Override + public ProtobufMatrix clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + numRows = 0; + numCols = 0; + data.clear(); + return this; + } + + @Override + public ProtobufMatrix clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + data.clear(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufMatrix)) { + return false; + } + ProtobufMatrix other = (ProtobufMatrix) o; + return bitField0_ == other.bitField0_ + && (!hasNumRows() || numRows == other.numRows) + && (!hasNumCols() || numCols == other.numCols) + && (!hasData() || data.equals(other.data)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + output.writeRawByte((byte) 8); + output.writeUInt32NoTag(numRows); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeRawByte((byte) 16); + output.writeUInt32NoTag(numCols); + } + if ((bitField0_ & 0x00000004) != 0) { + for (int i = 0; i < data.length(); i++) { + output.writeRawByte((byte) 25); + output.writeDoubleNoTag(data.array()[i]); + } + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += 1 + ProtoSink.computeUInt32SizeNoTag(numRows); + } + if ((bitField0_ & 0x00000002) != 0) { + size += 1 + ProtoSink.computeUInt32SizeNoTag(numCols); + } + if ((bitField0_ & 0x00000004) != 0) { + size += (1 + 8) * data.length(); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufMatrix mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 8: { + // numRows + numRows = input.readUInt32(); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 16) { + break; + } + } + case 16: { + // numCols + numCols = input.readUInt32(); + bitField0_ |= 0x00000002; + tag = input.readTag(); + if (tag != 26) { + break; + } + } + case 26: { + // data [packed=true] + input.readPackedDouble(data); + bitField0_ |= 0x00000004; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + case 25: { + // data [packed=false] + tag = input.readRepeatedDouble(data, tag); + bitField0_ |= 0x00000004; + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeUInt32(FieldNames.numRows, numRows); + } + if ((bitField0_ & 0x00000002) != 0) { + output.writeUInt32(FieldNames.numCols, numCols); + } + if ((bitField0_ & 0x00000004) != 0) { + output.writeRepeatedDouble(FieldNames.data, data); + } + output.endObject(); + } + + @Override + public ProtobufMatrix mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case -2000982401: + case -1888824590: { + if (input.isAtField(FieldNames.numRows)) { + if (!input.trySkipNullValue()) { + numRows = input.readUInt32(); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + case -2001429607: + case -1889271796: { + if (input.isAtField(FieldNames.numCols)) { + if (!input.trySkipNullValue()) { + numCols = input.readUInt32(); + bitField0_ |= 0x00000002; + } + } else { + input.skipUnknownField(); + } + break; + } + case 3076010: { + if (input.isAtField(FieldNames.data)) { + if (!input.trySkipNullValue()) { + input.readRepeatedDouble(data); + bitField0_ |= 0x00000004; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufMatrix clone() { + return new ProtobufMatrix().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufMatrix parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufMatrix(), data).checkInitialized(); + } + + public static ProtobufMatrix parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufMatrix(), input).checkInitialized(); + } + + public static ProtobufMatrix parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufMatrix(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufMatrix messages + */ + public static MessageFactory getFactory() { + return ProtobufMatrixFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Wpimath.wpi_proto_ProtobufMatrix_descriptor; + } + + private enum ProtobufMatrixFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufMatrix create() { + return ProtobufMatrix.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName numRows = FieldName.forField("numRows", "num_rows"); + + static final FieldName numCols = FieldName.forField("numCols", "num_cols"); + + static final FieldName data = FieldName.forField("data"); + } + } + + /** + * Protobuf type {@code ProtobufVector} + */ + public static final class ProtobufVector extends ProtoMessage implements Cloneable { + private static final long serialVersionUID = 0L; + + /** + * repeated double rows = 1; + */ + private final RepeatedDouble rows = RepeatedDouble.newEmptyInstance(); + + private ProtobufVector() { + } + + /** + * @return a new empty instance of {@code ProtobufVector} + */ + public static ProtobufVector newInstance() { + return new ProtobufVector(); + } + + /** + * repeated double rows = 1; + * @return whether the rows field is set + */ + public boolean hasRows() { + return (bitField0_ & 0x00000001) != 0; + } + + /** + * repeated double rows = 1; + * @return this + */ + public ProtobufVector clearRows() { + bitField0_ &= ~0x00000001; + rows.clear(); + return this; + } + + /** + * repeated double rows = 1; + * + * This method returns the internal storage object without modifying any has state. + * The returned object should not be modified and be treated as read-only. + * + * Use {@link #getMutableRows()} if you want to modify it. + * + * @return internal storage object for reading + */ + public RepeatedDouble getRows() { + return rows; + } + + /** + * repeated double rows = 1; + * + * This method returns the internal storage object and sets the corresponding + * has state. The returned object will become part of this message and its + * contents may be modified as long as the has state is not cleared. + * + * @return internal storage object for modifications + */ + public RepeatedDouble getMutableRows() { + bitField0_ |= 0x00000001; + return rows; + } + + /** + * repeated double rows = 1; + * @param value the rows to add + * @return this + */ + public ProtobufVector addRows(final double value) { + bitField0_ |= 0x00000001; + rows.add(value); + return this; + } + + /** + * repeated double rows = 1; + * @param values the rows to add + * @return this + */ + public ProtobufVector addAllRows(final double... values) { + bitField0_ |= 0x00000001; + rows.addAll(values); + return this; + } + + @Override + public ProtobufVector copyFrom(final ProtobufVector other) { + cachedSize = other.cachedSize; + if ((bitField0_ | other.bitField0_) != 0) { + bitField0_ = other.bitField0_; + rows.copyFrom(other.rows); + } + return this; + } + + @Override + public ProtobufVector mergeFrom(final ProtobufVector other) { + if (other.isEmpty()) { + return this; + } + cachedSize = -1; + if (other.hasRows()) { + getMutableRows().addAll(other.rows); + } + return this; + } + + @Override + public ProtobufVector clear() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + rows.clear(); + return this; + } + + @Override + public ProtobufVector clearQuick() { + if (isEmpty()) { + return this; + } + cachedSize = -1; + bitField0_ = 0; + rows.clear(); + return this; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ProtobufVector)) { + return false; + } + ProtobufVector other = (ProtobufVector) o; + return bitField0_ == other.bitField0_ + && (!hasRows() || rows.equals(other.rows)); + } + + @Override + public void writeTo(final ProtoSink output) throws IOException { + if ((bitField0_ & 0x00000001) != 0) { + for (int i = 0; i < rows.length(); i++) { + output.writeRawByte((byte) 9); + output.writeDoubleNoTag(rows.array()[i]); + } + } + } + + @Override + protected int computeSerializedSize() { + int size = 0; + if ((bitField0_ & 0x00000001) != 0) { + size += (1 + 8) * rows.length(); + } + return size; + } + + @Override + @SuppressWarnings("fallthrough") + public ProtobufVector mergeFrom(final ProtoSource input) throws IOException { + // Enabled Fall-Through Optimization (QuickBuffers) + int tag = input.readTag(); + while (true) { + switch (tag) { + case 10: { + // rows [packed=true] + input.readPackedDouble(rows); + bitField0_ |= 0x00000001; + tag = input.readTag(); + if (tag != 0) { + break; + } + } + case 0: { + return this; + } + default: { + if (!input.skipField(tag)) { + return this; + } + tag = input.readTag(); + break; + } + case 9: { + // rows [packed=false] + tag = input.readRepeatedDouble(rows, tag); + bitField0_ |= 0x00000001; + break; + } + } + } + } + + @Override + public void writeTo(final JsonSink output) throws IOException { + output.beginObject(); + if ((bitField0_ & 0x00000001) != 0) { + output.writeRepeatedDouble(FieldNames.rows, rows); + } + output.endObject(); + } + + @Override + public ProtobufVector mergeFrom(final JsonSource input) throws IOException { + if (!input.beginObject()) { + return this; + } + while (!input.isAtEnd()) { + switch (input.readFieldHash()) { + case 3506649: { + if (input.isAtField(FieldNames.rows)) { + if (!input.trySkipNullValue()) { + input.readRepeatedDouble(rows); + bitField0_ |= 0x00000001; + } + } else { + input.skipUnknownField(); + } + break; + } + default: { + input.skipUnknownField(); + break; + } + } + } + input.endObject(); + return this; + } + + @Override + public ProtobufVector clone() { + return new ProtobufVector().copyFrom(this); + } + + @Override + public boolean isEmpty() { + return ((bitField0_) == 0); + } + + public static ProtobufVector parseFrom(final byte[] data) throws + InvalidProtocolBufferException { + return ProtoMessage.mergeFrom(new ProtobufVector(), data).checkInitialized(); + } + + public static ProtobufVector parseFrom(final ProtoSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufVector(), input).checkInitialized(); + } + + public static ProtobufVector parseFrom(final JsonSource input) throws IOException { + return ProtoMessage.mergeFrom(new ProtobufVector(), input).checkInitialized(); + } + + /** + * @return factory for creating ProtobufVector messages + */ + public static MessageFactory getFactory() { + return ProtobufVectorFactory.INSTANCE; + } + + /** + * @return this type's descriptor. + */ + public static Descriptors.Descriptor getDescriptor() { + return Wpimath.wpi_proto_ProtobufVector_descriptor; + } + + private enum ProtobufVectorFactory implements MessageFactory { + INSTANCE; + + @Override + public ProtobufVector create() { + return ProtobufVector.newInstance(); + } + } + + /** + * Contains name constants used for serializing JSON + */ + static class FieldNames { + static final FieldName rows = FieldName.forField("rows"); + } + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/ComputerVisionUtil.java b/wpimath/src/main/java/edu/wpi/first/math/ComputerVisionUtil.java index 7b1c3776808..c288d7fb2d7 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/ComputerVisionUtil.java +++ b/wpimath/src/main/java/edu/wpi/first/math/ComputerVisionUtil.java @@ -7,6 +7,7 @@ import edu.wpi.first.math.geometry.Pose3d; import edu.wpi.first.math.geometry.Transform3d; +/** Computer vision utility functions. */ public final class ComputerVisionUtil { private ComputerVisionUtil() { throw new AssertionError("utility class"); @@ -26,7 +27,7 @@ private ComputerVisionUtil() { * either be a constant for a rigidly mounted camera, or variable if the camera is mounted to * a turret. If the camera was mounted 3 inches in front of the "origin" (usually physical * center) of the robot, this would be new Transform3d(Units.inchesToMeters(3.0), 0.0, 0.0, - * new Rotation3d()). + * Rotation3d.kZero). * @return The robot's field-relative pose. */ public static Pose3d objectToRobotPose( diff --git a/wpimath/src/main/java/edu/wpi/first/math/DARE.java b/wpimath/src/main/java/edu/wpi/first/math/DARE.java index ad07d056e7d..44c488dc526 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/DARE.java +++ b/wpimath/src/main/java/edu/wpi/first/math/DARE.java @@ -6,6 +6,7 @@ import org.ejml.simple.SimpleMatrix; +/** DARE solver utility functions. */ public final class DARE { private DARE() { throw new UnsupportedOperationException("This is a utility class!"); diff --git a/wpimath/src/main/java/edu/wpi/first/math/InterpolatingMatrixTreeMap.java b/wpimath/src/main/java/edu/wpi/first/math/InterpolatingMatrixTreeMap.java index a7b922c9696..a0aedef2dcd 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/InterpolatingMatrixTreeMap.java +++ b/wpimath/src/main/java/edu/wpi/first/math/InterpolatingMatrixTreeMap.java @@ -9,10 +9,17 @@ /** * Interpolating Tree Maps are used to get values at points that are not defined by making a guess * from points that are defined. This uses linear interpolation. + * + * @param Key type. + * @param Number of matrix rows. + * @param Number of matrix columns. */ public class InterpolatingMatrixTreeMap { private final TreeMap> m_map = new TreeMap<>(); + /** Default constructor. */ + public InterpolatingMatrixTreeMap() {} + /** * Inserts a key-value pair. * diff --git a/wpimath/src/main/java/edu/wpi/first/math/MatBuilder.java b/wpimath/src/main/java/edu/wpi/first/math/MatBuilder.java index 80c9d0dc9d6..46e42f47f4e 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/MatBuilder.java +++ b/wpimath/src/main/java/edu/wpi/first/math/MatBuilder.java @@ -40,7 +40,10 @@ public static final Matrix fill( return new Matrix<>(new SimpleMatrix(rows.getNum(), cols.getNum(), true, data)); } + /** Number of rows. */ protected final Nat m_rows; + + /** Number of columns. */ protected final Nat m_cols; /** diff --git a/wpimath/src/main/java/edu/wpi/first/math/MathShared.java b/wpimath/src/main/java/edu/wpi/first/math/MathShared.java index 3c2b8433886..ad4e2e81e6c 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/MathShared.java +++ b/wpimath/src/main/java/edu/wpi/first/math/MathShared.java @@ -4,6 +4,7 @@ package edu.wpi.first.math; +/** WPIMath utility functions. */ public interface MathShared { /** * Report an error. diff --git a/wpimath/src/main/java/edu/wpi/first/math/MathSharedStore.java b/wpimath/src/main/java/edu/wpi/first/math/MathSharedStore.java index d6e3e9655fb..d490a6e44ef 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/MathSharedStore.java +++ b/wpimath/src/main/java/edu/wpi/first/math/MathSharedStore.java @@ -6,6 +6,7 @@ import edu.wpi.first.util.WPIUtilJNI; +/** Storage for MathShared object. */ public final class MathSharedStore { private static MathShared mathShared; diff --git a/wpimath/src/main/java/edu/wpi/first/math/MathUsageId.java b/wpimath/src/main/java/edu/wpi/first/math/MathUsageId.java index a3cc2998754..c3449cfc61c 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/MathUsageId.java +++ b/wpimath/src/main/java/edu/wpi/first/math/MathUsageId.java @@ -4,15 +4,35 @@ package edu.wpi.first.math; +/** WPIMath usage reporting IDs. */ public enum MathUsageId { + /** DifferentialDriveKinematics. */ kKinematics_DifferentialDrive, + + /** MecanumDriveKinematics. */ kKinematics_MecanumDrive, + + /** SwerveDriveKinematics. */ kKinematics_SwerveDrive, + + /** TrapezoidProfile. */ kTrajectory_TrapezoidProfile, + + /** LinearFilter. */ kFilter_Linear, + + /** DifferentialDriveOdometry. */ kOdometry_DifferentialDrive, + + /** SwerveDriveOdometry. */ kOdometry_SwerveDrive, + + /** MecanumDriveOdometry. */ kOdometry_MecanumDrive, + + /** PIDController. */ kController_PIDController2, + + /** ProfiledPIDController. */ kController_ProfiledPIDController, } diff --git a/wpimath/src/main/java/edu/wpi/first/math/MathUtil.java b/wpimath/src/main/java/edu/wpi/first/math/MathUtil.java index 3785780a8d0..044cddfab68 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/MathUtil.java +++ b/wpimath/src/main/java/edu/wpi/first/math/MathUtil.java @@ -4,6 +4,7 @@ package edu.wpi.first.math; +/** Math utility functions. */ public final class MathUtil { private MathUtil() { throw new AssertionError("utility class"); diff --git a/wpimath/src/main/java/edu/wpi/first/math/Matrix.java b/wpimath/src/main/java/edu/wpi/first/math/Matrix.java index 8ac8d137e04..cd77283649d 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/Matrix.java +++ b/wpimath/src/main/java/edu/wpi/first/math/Matrix.java @@ -24,6 +24,7 @@ * @param The number of columns in this matrix. */ public class Matrix { + /** Storage for underlying EJML matrix. */ protected final SimpleMatrix m_storage; /** @@ -288,7 +289,7 @@ public final Matrix plus(Matrix value) { * @return The resultant matrix. */ public Matrix div(int value) { - return new Matrix<>(this.m_storage.divide((double) value)); + return new Matrix<>(this.m_storage.divide(value)); } /** @@ -488,7 +489,7 @@ public final Matrix elementPower(double b) { * @return The element by element power of "this" and b. */ public final Matrix elementPower(int b) { - return new Matrix<>(this.m_storage.elementPower((double) b)); + return new Matrix<>(this.m_storage.elementPower(b)); } /** @@ -545,7 +546,7 @@ public final Matrix block( */ public final Matrix block( int height, int width, int startingRow, int startingCol) { - return new Matrix( + return new Matrix<>( this.m_storage.extractMatrix( startingRow, startingRow + height, startingCol, startingCol + width)); } @@ -607,8 +608,7 @@ public Matrix lltDecompose(boolean lowerTriangular) { return new Matrix<>(new SimpleMatrix(temp.getNumRows(), temp.getNumCols())); } - throw new RuntimeException( - "Cholesky decomposition failed! Input matrix:\n" + m_storage.toString()); + throw new RuntimeException("Cholesky decomposition failed! Input matrix:\n" + m_storage); } return new Matrix<>(SimpleMatrix.wrap(chol.getT(null))); @@ -645,23 +645,6 @@ public static Matrix eye(D dim) { return new Matrix<>(SimpleMatrix.identity(Objects.requireNonNull(dim).getNum())); } - /** - * Entrypoint to the {@link MatBuilder} class for creation of custom matrices with the given - * dimensions and contents. - * - * @param rows The number of rows of the desired matrix. - * @param cols The number of columns of the desired matrix. - * @param The number of rows of the desired matrix as a generic. - * @param The number of columns of the desired matrix as a generic. - * @return A builder to construct the matrix. - * @deprecated Use {@link MatBuilder#fill} instead. - */ - @Deprecated(since = "2024", forRemoval = true) - @SuppressWarnings("removal") - public static MatBuilder mat(Nat rows, Nat cols) { - return new MatBuilder<>(Objects.requireNonNull(rows), Objects.requireNonNull(cols)); - } - /** * Reassigns dimensions of a {@link Matrix} to allow for operations with other matrices that have * wildcard dimensions. diff --git a/wpimath/src/main/java/edu/wpi/first/math/Num.java b/wpimath/src/main/java/edu/wpi/first/math/Num.java index ef0fd2d815f..aa31dd79915 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/Num.java +++ b/wpimath/src/main/java/edu/wpi/first/math/Num.java @@ -6,6 +6,9 @@ /** A number expressed as a java class. */ public abstract class Num { + /** Default constructor. */ + public Num() {} + /** * The number this is backing. * diff --git a/wpimath/src/main/java/edu/wpi/first/math/Pair.java b/wpimath/src/main/java/edu/wpi/first/math/Pair.java index 8ddf1ae37be..86cc5053e98 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/Pair.java +++ b/wpimath/src/main/java/edu/wpi/first/math/Pair.java @@ -4,24 +4,85 @@ package edu.wpi.first.math; +import java.util.Objects; + +/** + * Represents a pair of two objects. + * + * @param The first object's type. + * @param The second object's type. + */ public class Pair { private final A m_first; private final B m_second; + /** + * Constructs a pair. + * + * @param first The first object. + * @param second The second object. + */ public Pair(A first, B second) { m_first = first; m_second = second; } + /** + * Returns the first object. + * + * @return The first object. + */ public A getFirst() { return m_first; } + /** + * Returns the second object. + * + * @return The second object. + */ public B getSecond() { return m_second; } + /** + * Returns a pair comprised of the two given objects. + * + * @param The first object's type. + * @param The second object's type. + * @param a The first object. + * @param b The second object. + * @return A pair comprised of the two given objects. + */ public static Pair of(A a, B b) { return new Pair<>(a, b); } + + @Override + public String toString() { + return String.format("Pair(%s, %s)", m_first, m_second); + } + + /** + * Checks equality between this Pair and another object. + * + * @param obj The other object. + * @return Whether the two objects are equal or not. + */ + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj instanceof Pair) { + return Objects.equals(m_first, ((Pair) obj).getFirst()) + && Objects.equals(m_second, ((Pair) obj).getSecond()); + } + return false; + } + + @Override + public int hashCode() { + return Objects.hash(m_first, m_second); + } } diff --git a/wpimath/src/main/java/edu/wpi/first/math/SimpleMatrixUtils.java b/wpimath/src/main/java/edu/wpi/first/math/SimpleMatrixUtils.java deleted file mode 100644 index 487faf474cb..00000000000 --- a/wpimath/src/main/java/edu/wpi/first/math/SimpleMatrixUtils.java +++ /dev/null @@ -1,246 +0,0 @@ -// Copyright (c) FIRST and other WPILib contributors. -// Open Source Software; you can modify and/or share it under the terms of -// the WPILib BSD license file in the root directory of this project. - -package edu.wpi.first.math; - -import java.util.function.BiFunction; -import org.ejml.data.DMatrixRMaj; -import org.ejml.dense.row.NormOps_DDRM; -import org.ejml.dense.row.factory.DecompositionFactory_DDRM; -import org.ejml.interfaces.decomposition.CholeskyDecomposition_F64; -import org.ejml.simple.SimpleBase; -import org.ejml.simple.SimpleMatrix; - -public final class SimpleMatrixUtils { - private SimpleMatrixUtils() {} - - /** - * Compute the matrix exponential, e^M of the given matrix. - * - * @param matrix The matrix to compute the exponential of. - * @return The resultant matrix. - */ - public static SimpleMatrix expm(SimpleMatrix matrix) { - BiFunction solveProvider = SimpleBase::solve; - SimpleMatrix A = matrix; - double A_L1 = NormOps_DDRM.inducedP1(matrix.getDDRM()); - int nSquarings = 0; - - if (A_L1 < 1.495585217958292e-002) { - Pair pair = pade3(A); - return dispatchPade(pair.getFirst(), pair.getSecond(), nSquarings, solveProvider); - } else if (A_L1 < 2.539398330063230e-001) { - Pair pair = pade5(A); - return dispatchPade(pair.getFirst(), pair.getSecond(), nSquarings, solveProvider); - } else if (A_L1 < 9.504178996162932e-001) { - Pair pair = pade7(A); - return dispatchPade(pair.getFirst(), pair.getSecond(), nSquarings, solveProvider); - } else if (A_L1 < 2.097847961257068e+000) { - Pair pair = pade9(A); - return dispatchPade(pair.getFirst(), pair.getSecond(), nSquarings, solveProvider); - } else { - double maxNorm = 5.371920351148152; - double log = Math.log(A_L1 / maxNorm) / Math.log(2); // logb(2, arg) - nSquarings = (int) Math.max(0, Math.ceil(log)); - A = A.divide(Math.pow(2.0, nSquarings)); - Pair pair = pade13(A); - return dispatchPade(pair.getFirst(), pair.getSecond(), nSquarings, solveProvider); - } - } - - private static SimpleMatrix dispatchPade( - SimpleMatrix U, - SimpleMatrix V, - int nSquarings, - BiFunction solveProvider) { - SimpleMatrix P = U.plus(V); - SimpleMatrix Q = U.negative().plus(V); - - SimpleMatrix R = solveProvider.apply(Q, P); - - for (int i = 0; i < nSquarings; i++) { - R = R.mult(R); - } - - return R; - } - - private static Pair pade3(SimpleMatrix A) { - double[] b = new double[] {120, 60, 12, 1}; - SimpleMatrix ident = eye(A.getNumRows(), A.getNumCols()); - - SimpleMatrix A2 = A.mult(A); - SimpleMatrix U = A.mult(A2.mult(ident.scale(b[1]).plus(b[3]))); - SimpleMatrix V = A2.scale(b[2]).plus(ident.scale(b[0])); - return new Pair<>(U, V); - } - - private static Pair pade5(SimpleMatrix A) { - double[] b = new double[] {30240, 15120, 3360, 420, 30, 1}; - SimpleMatrix ident = eye(A.getNumRows(), A.getNumCols()); - SimpleMatrix A2 = A.mult(A); - SimpleMatrix A4 = A2.mult(A2); - - SimpleMatrix U = A.mult(A4.scale(b[5]).plus(A2.scale(b[3])).plus(ident.scale(b[1]))); - SimpleMatrix V = A4.scale(b[4]).plus(A2.scale(b[2])).plus(ident.scale(b[0])); - - return new Pair<>(U, V); - } - - private static Pair pade7(SimpleMatrix A) { - double[] b = new double[] {17297280, 8648640, 1995840, 277200, 25200, 1512, 56, 1}; - SimpleMatrix ident = eye(A.getNumRows(), A.getNumCols()); - SimpleMatrix A2 = A.mult(A); - SimpleMatrix A4 = A2.mult(A2); - SimpleMatrix A6 = A4.mult(A2); - - SimpleMatrix U = - A.mult(A6.scale(b[7]).plus(A4.scale(b[5])).plus(A2.scale(b[3])).plus(ident.scale(b[1]))); - SimpleMatrix V = - A6.scale(b[6]).plus(A4.scale(b[4])).plus(A2.scale(b[2])).plus(ident.scale(b[0])); - - return new Pair<>(U, V); - } - - private static Pair pade9(SimpleMatrix A) { - double[] b = - new double[] { - 17643225600.0, 8821612800.0, 2075673600, 302702400, 30270240, 2162160, 110880, 3960, 90, 1 - }; - SimpleMatrix ident = eye(A.getNumRows(), A.getNumCols()); - SimpleMatrix A2 = A.mult(A); - SimpleMatrix A4 = A2.mult(A2); - SimpleMatrix A6 = A4.mult(A2); - SimpleMatrix A8 = A6.mult(A2); - - SimpleMatrix U = - A.mult( - A8.scale(b[9]) - .plus(A6.scale(b[7])) - .plus(A4.scale(b[5])) - .plus(A2.scale(b[3])) - .plus(ident.scale(b[1]))); - SimpleMatrix V = - A8.scale(b[8]) - .plus(A6.scale(b[6])) - .plus(A4.scale(b[4])) - .plus(A2.scale(b[2])) - .plus(ident.scale(b[0])); - - return new Pair<>(U, V); - } - - private static Pair pade13(SimpleMatrix A) { - double[] b = - new double[] { - 64764752532480000.0, - 32382376266240000.0, - 7771770303897600.0, - 1187353796428800.0, - 129060195264000.0, - 10559470521600.0, - 670442572800.0, - 33522128640.0, - 1323241920, - 40840800, - 960960, - 16380, - 182, - 1 - }; - SimpleMatrix ident = eye(A.getNumRows(), A.getNumCols()); - - SimpleMatrix A2 = A.mult(A); - SimpleMatrix A4 = A2.mult(A2); - SimpleMatrix A6 = A4.mult(A2); - - SimpleMatrix U = - A.mult( - A6.scale(b[13]) - .plus(A4.scale(b[11])) - .plus(A2.scale(b[9])) - .plus(A6.scale(b[7])) - .plus(A4.scale(b[5])) - .plus(A2.scale(b[3])) - .plus(ident.scale(b[1]))); - SimpleMatrix V = - A6.mult(A6.scale(b[12]).plus(A4.scale(b[10])).plus(A2.scale(b[8]))) - .plus(A6.scale(b[6]).plus(A4.scale(b[4])).plus(A2.scale(b[2])).plus(ident.scale(b[0]))); - - return new Pair<>(U, V); - } - - private static SimpleMatrix eye(int rows, int cols) { - return SimpleMatrix.identity(Math.min(rows, cols)); - } - - /** - * The identy of a square matrix. - * - * @param rows the number of rows (and columns) - * @return the identiy matrix, rows x rows. - */ - public static SimpleMatrix eye(int rows) { - return SimpleMatrix.identity(rows); - } - - /** - * Decompose the given matrix using Cholesky Decomposition and return a view of the upper - * triangular matrix (if you want lower triangular see the other overload of this method.) If the - * input matrix is zeros, this will return the zero matrix. - * - * @param src The matrix to decompose. - * @return The decomposed matrix. - * @throws RuntimeException if the matrix could not be decomposed (i.e. is not positive - * semidefinite). - */ - public static SimpleMatrix lltDecompose(SimpleMatrix src) { - return lltDecompose(src, false); - } - - /** - * Decompose the given matrix using Cholesky Decomposition. If the input matrix is zeros, this - * will return the zero matrix. - * - * @param src The matrix to decompose. - * @param lowerTriangular if we want to decompose to the lower triangular Cholesky matrix. - * @return The decomposed matrix. - * @throws RuntimeException if the matrix could not be decomposed (i.e. is not positive - * semidefinite). - */ - public static SimpleMatrix lltDecompose(SimpleMatrix src, boolean lowerTriangular) { - SimpleMatrix temp = src.copy(); - - CholeskyDecomposition_F64 chol = - DecompositionFactory_DDRM.chol(temp.getNumRows(), lowerTriangular); - if (!chol.decompose(temp.getMatrix())) { - // check that the input is not all zeros -- if they are, we special case and return all - // zeros. - var matData = temp.getDDRM().data; - var isZeros = true; - for (double matDatum : matData) { - isZeros &= Math.abs(matDatum) < 1e-6; - } - if (isZeros) { - return new SimpleMatrix(temp.getNumRows(), temp.getNumCols()); - } - - throw new RuntimeException("Cholesky decomposition failed! Input matrix:\n" + src.toString()); - } - - return SimpleMatrix.wrap(chol.getT(null)); - } - - /** - * Computes the matrix exponential using Eigen's solver. - * - * @param A the matrix to exponentiate. - * @return the exponential of A. - */ - public static SimpleMatrix exp(SimpleMatrix A) { - SimpleMatrix toReturn = new SimpleMatrix(A.getNumRows(), A.getNumRows()); - WPIMathJNI.exp(A.getDDRM().getData(), A.getNumRows(), toReturn.getDDRM().getData()); - return toReturn; - } -} diff --git a/wpimath/src/main/java/edu/wpi/first/math/StateSpaceUtil.java b/wpimath/src/main/java/edu/wpi/first/math/StateSpaceUtil.java index 27ed9e0bb09..4e003747693 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/StateSpaceUtil.java +++ b/wpimath/src/main/java/edu/wpi/first/math/StateSpaceUtil.java @@ -11,6 +11,7 @@ import java.util.Random; import org.ejml.simple.SimpleMatrix; +/** State-space utilities. */ public final class StateSpaceUtil { private static Random rand = new Random(); @@ -79,7 +80,7 @@ public static Matrix makeCostMatrix( if (tolerances.get(i, 0) == Double.POSITIVE_INFINITY) { result.set(i, i, 0.0); } else { - result.set(i, i, 1.0 / (Math.pow(tolerances.get(i, 0), 2))); + result.set(i, i, 1.0 / Math.pow(tolerances.get(i, 0), 2)); } } @@ -139,7 +140,7 @@ public static Matrix poseToVector(Pose2d pose) { * @param u The input to clamp. * @param umin The minimum input magnitude. * @param umax The maximum input magnitude. - * @param The number of inputs. + * @param Number of inputs. * @return The clamped input. */ public static Matrix clampInputMaxMagnitude( @@ -157,7 +158,7 @@ public static Matrix clampInputMaxMagnitude( * * @param u The input vector. * @param maxMagnitude The maximum magnitude any input can have. - * @param The number of inputs. + * @param Number of inputs. * @return The normalizedInput */ public static Matrix desaturateInputVector( diff --git a/wpimath/src/main/java/edu/wpi/first/math/Vector.java b/wpimath/src/main/java/edu/wpi/first/math/Vector.java index bc467411259..8784a6c027b 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/Vector.java +++ b/wpimath/src/main/java/edu/wpi/first/math/Vector.java @@ -5,6 +5,7 @@ package edu.wpi.first.math; import edu.wpi.first.math.numbers.N1; +import edu.wpi.first.math.numbers.N3; import java.util.Objects; import org.ejml.simple.SimpleMatrix; @@ -48,6 +49,16 @@ public Vector(Matrix other) { super(other); } + /** + * Returns an element of the vector at a specified row. + * + * @param row The row that the element is located at. + * @return An element of the vector. + */ + public double get(int row) { + return get(row, 0); + } + @Override public Vector times(double value) { return new Vector<>(this.m_storage.scale(value)); @@ -105,12 +116,39 @@ public double dot(Vector other) { * @return The norm. */ public double norm() { - double squaredNorm = 0.0; + return Math.sqrt(dot(this)); + } - for (int i = 0; i < getNumRows(); ++i) { - squaredNorm += get(i, 0) * get(i, 0); - } + /** + * Returns the unit vector parallel with this vector. + * + * @return The unit vector. + */ + public Vector unit() { + return div(norm()); + } + + /** + * Returns the projection of this vector along another. + * + * @param other The vector to project along. + * @return The projection. + */ + public Vector projection(Vector other) { + return other.times(dot(other)).div(other.dot(other)); + } - return Math.sqrt(squaredNorm); + /** + * Returns the cross product of 3 dimensional vectors a and b. + * + * @param a The vector to cross with b. + * @param b The vector to cross with a. + * @return The cross product of a and b. + */ + public static Vector cross(Vector a, Vector b) { + return VecBuilder.fill( + a.get(1) * b.get(2) - a.get(2) * b.get(1), + a.get(2) * b.get(0) - a.get(0) * b.get(2), + a.get(0) * b.get(1) - a.get(1) * b.get(0)); } } diff --git a/wpimath/src/main/java/edu/wpi/first/math/WPIMathJNI.java b/wpimath/src/main/java/edu/wpi/first/math/WPIMathJNI.java index ef47a3b3c24..412c1b1f74b 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/WPIMathJNI.java +++ b/wpimath/src/main/java/edu/wpi/first/math/WPIMathJNI.java @@ -8,6 +8,7 @@ import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; +/** WPIMath JNI. */ public final class WPIMathJNI { static boolean libraryLoaded = false; static RuntimeLoader loader = null; @@ -43,6 +44,33 @@ public static synchronized void forceLoad() throws IOException { libraryLoaded = true; } + // ArmFeedforward wrappers + + /** + * Obtain a feedforward voltage from a single jointed arm feedforward object. + * + *

    Constructs an ArmFeedforward object and runs its currentVelocity and nextVelocity overload + * + * @param ks The ArmFeedforward's static gain in volts. + * @param kv The ArmFeedforward's velocity gain in volt seconds per radian. + * @param ka The ArmFeedforward's acceleration gain in volt seconds² per radian. + * @param kg The ArmFeedforward's gravity gain in volts. + * @param currentAngle The current angle in the calculation in radians. + * @param currentVelocity The current velocity in the calculation in radians per second. + * @param nextVelocity The next velocity in the calculation in radians per second. + * @param dt The time between velocity setpoints in seconds. + * @return The calculated feedforward in volts. + */ + public static native double calculate( + double ks, + double kv, + double ka, + double kg, + double currentAngle, + double currentVelocity, + double nextVelocity, + double dt); + // DARE wrappers /** @@ -385,15 +413,32 @@ public static native double[] logPose3d( */ public static native String serializeTrajectory(double[] elements); + /** Sets whether JNI should be loaded in the static block. */ public static class Helper { private static AtomicBoolean extractOnStaticLoad = new AtomicBoolean(true); + /** + * Returns true if the JNI should be loaded in the static block. + * + * @return True if the JNI should be loaded in the static block. + */ public static boolean getExtractOnStaticLoad() { return extractOnStaticLoad.get(); } + /** + * Sets whether the JNI should be loaded in the static block. + * + * @param load Whether the JNI should be loaded in the static block. + */ public static void setExtractOnStaticLoad(boolean load) { extractOnStaticLoad.set(load); } + + /** Utility class. */ + private Helper() {} } + + /** Utility class. */ + private WPIMathJNI() {} } diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/ArmFeedforward.java b/wpimath/src/main/java/edu/wpi/first/math/controller/ArmFeedforward.java index 2e9a8d84348..0d479418063 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/ArmFeedforward.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/ArmFeedforward.java @@ -4,16 +4,35 @@ package edu.wpi.first.math.controller; +import edu.wpi.first.math.WPIMathJNI; +import edu.wpi.first.math.controller.proto.ArmFeedforwardProto; +import edu.wpi.first.math.controller.struct.ArmFeedforwardStruct; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; + /** * A helper class that computes feedforward outputs for a simple arm (modeled as a motor acting * against the force of gravity on a beam suspended at an angle). */ -public class ArmFeedforward { +public class ArmFeedforward implements ProtobufSerializable, StructSerializable { + /** The static gain, in volts. */ public final double ks; + + /** The gravity gain, in volts. */ public final double kg; + + /** The velocity gain, in volt seconds per radian. */ public final double kv; + + /** The acceleration gain, in volt seconds² per radian. */ public final double ka; + /** Arm feedforward protobuf for serialization. */ + public static final ArmFeedforwardProto proto = new ArmFeedforwardProto(); + + /** Arm feedforward struct for serialization. */ + public static final ArmFeedforwardStruct struct = new ArmFeedforwardStruct(); + /** * Creates a new ArmFeedforward with the specified gains. Units of the gain values will dictate * units of the computed feedforward. @@ -22,12 +41,20 @@ public class ArmFeedforward { * @param kg The gravity gain. * @param kv The velocity gain. * @param ka The acceleration gain. + * @throws IllegalArgumentException for kv < zero. + * @throws IllegalArgumentException for ka < zero. */ public ArmFeedforward(double ks, double kg, double kv, double ka) { this.ks = ks; this.kg = kg; this.kv = kv; this.ka = ka; + if (kv < 0.0) { + throw new IllegalArgumentException("kv must be a non-negative number, got " + kv + "!"); + } + if (ka < 0.0) { + throw new IllegalArgumentException("ka must be a non-negative number, got " + ka + "!"); + } } /** @@ -74,6 +101,22 @@ public double calculate(double positionRadians, double velocity) { return calculate(positionRadians, velocity, 0); } + /** + * Calculates the feedforward from the gains and setpoints. + * + * @param currentAngle The current angle in radians. This angle should be measured from the + * horizontal (i.e. if the provided angle is 0, the arm should be parallel to the floor). If + * your encoder does not follow this convention, an offset should be added. + * @param currentVelocity The current velocity setpoint in radians per second. + * @param nextVelocity The next velocity setpoint in radians per second. + * @param dt Time between velocity setpoints in seconds. + * @return The computed feedforward in volts. + */ + public double calculate( + double currentAngle, double currentVelocity, double nextVelocity, double dt) { + return WPIMathJNI.calculate(ks, kv, ka, kg, currentAngle, currentVelocity, nextVelocity, dt); + } + // Rearranging the main equation from the calculate() method yields the // formulas for the methods below: diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/BangBangController.java b/wpimath/src/main/java/edu/wpi/first/math/controller/BangBangController.java index 7e8c7786bb0..cf852c30d0c 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/BangBangController.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/BangBangController.java @@ -37,6 +37,7 @@ public class BangBangController implements Sendable { * * @param tolerance Tolerance for {@link #atSetpoint() atSetpoint}. */ + @SuppressWarnings("this-escape") public BangBangController(double tolerance) { instances++; @@ -89,7 +90,7 @@ public boolean atSetpoint() { * * @param tolerance Position error which is tolerable. */ - public void setTolerance(double tolerance) { + public final void setTolerance(double tolerance) { m_tolerance = tolerance; } diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/ControlAffinePlantInversionFeedforward.java b/wpimath/src/main/java/edu/wpi/first/math/controller/ControlAffinePlantInversionFeedforward.java index a2a59448c42..9b14542207f 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/ControlAffinePlantInversionFeedforward.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/ControlAffinePlantInversionFeedforward.java @@ -16,9 +16,8 @@ * Constructs a control-affine plant inversion model-based feedforward from given model dynamics. * *

    If given the vector valued function as f(x, u) where x is the state vector and u is the input - * vector, the B matrix(continuous input matrix) is calculated through a {@link - * edu.wpi.first.math.system.NumericalJacobian}. In this case f has to be control-affine (of the - * form f(x) + Bu). + * vector, the B matrix(continuous input matrix) is calculated through a {@link NumericalJacobian}. + * In this case f has to be control-affine (of the form f(x) + Bu). * *

    The feedforward is calculated as u_ff = B+ (rDot - f(x)), where * B+ is the pseudoinverse of B. @@ -26,8 +25,11 @@ *

    This feedforward does not account for a dynamic B matrix, B is either determined or supplied * when the feedforward is created and remains constant. * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + * + * @param Number of states. + * @param Number of inputs. */ public class ControlAffinePlantInversionFeedforward { /** The current reference state. */ @@ -145,13 +147,13 @@ public double getR(int row) { * * @param initialState The initial state vector. */ - public void reset(Matrix initialState) { + public final void reset(Matrix initialState) { m_r = initialState; m_uff.fill(0.0); } /** Resets the feedforward with a zero initial state vector. */ - public void reset() { + public final void reset() { m_r.fill(0.0); m_uff.fill(0.0); } @@ -179,7 +181,7 @@ public Matrix calculate(Matrix nextR) { * @return The calculated feedforward. */ public Matrix calculate(Matrix r, Matrix nextR) { - var rDot = (nextR.minus(r)).div(m_dt); + var rDot = nextR.minus(r).div(m_dt); // ṙ = f(r) + Bu // Bu = ṙ − f(r) diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/DifferentialDriveWheelVoltages.java b/wpimath/src/main/java/edu/wpi/first/math/controller/DifferentialDriveWheelVoltages.java index 2fbd0aa381f..1569be06856 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/DifferentialDriveWheelVoltages.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/DifferentialDriveWheelVoltages.java @@ -4,13 +4,36 @@ package edu.wpi.first.math.controller; +import edu.wpi.first.math.controller.proto.DifferentialDriveWheelVoltagesProto; +import edu.wpi.first.math.controller.struct.DifferentialDriveWheelVoltagesStruct; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; + /** Motor voltages for a differential drive. */ -public class DifferentialDriveWheelVoltages { +public class DifferentialDriveWheelVoltages implements ProtobufSerializable, StructSerializable { + /** Left wheel voltage. */ public double left; + + /** Right wheel voltage. */ public double right; + /** DifferentialDriveWheelVoltages protobuf for serialization. */ + public static final DifferentialDriveWheelVoltagesProto proto = + new DifferentialDriveWheelVoltagesProto(); + + /** DifferentialDriveWheelVoltages struct for serialization. */ + public static final DifferentialDriveWheelVoltagesStruct struct = + new DifferentialDriveWheelVoltagesStruct(); + + /** Default constructor. */ public DifferentialDriveWheelVoltages() {} + /** + * Constructs a DifferentialDriveWheelVoltages. + * + * @param left Left wheel voltage. + * @param right Right wheel voltage. + */ public DifferentialDriveWheelVoltages(double left, double right) { this.left = left; this.right = right; diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/ElevatorFeedforward.java b/wpimath/src/main/java/edu/wpi/first/math/controller/ElevatorFeedforward.java index 476a1c55ad0..dc56ece26a4 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/ElevatorFeedforward.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/ElevatorFeedforward.java @@ -6,18 +6,35 @@ import edu.wpi.first.math.MatBuilder; import edu.wpi.first.math.Nat; +import edu.wpi.first.math.controller.proto.ElevatorFeedforwardProto; +import edu.wpi.first.math.controller.struct.ElevatorFeedforwardStruct; import edu.wpi.first.math.system.plant.LinearSystemId; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; /** * A helper class that computes feedforward outputs for a simple elevator (modeled as a motor acting * against the force of gravity). */ -public class ElevatorFeedforward { +public class ElevatorFeedforward implements ProtobufSerializable, StructSerializable { + /** The static gain. */ public final double ks; + + /** The gravity gain. */ public final double kg; + + /** The velocity gain. */ public final double kv; + + /** The acceleration gain. */ public final double ka; + /** ElevatorFeedforward protobuf for serialization. */ + public static final ElevatorFeedforwardProto proto = new ElevatorFeedforwardProto(); + + /** ElevatorFeedforward struct for serialization. */ + public static final ElevatorFeedforwardStruct struct = new ElevatorFeedforwardStruct(); + /** * Creates a new ElevatorFeedforward with the specified gains. Units of the gain values will * dictate units of the computed feedforward. @@ -26,12 +43,20 @@ public class ElevatorFeedforward { * @param kg The gravity gain. * @param kv The velocity gain. * @param ka The acceleration gain. + * @throws IllegalArgumentException for kv < zero. + * @throws IllegalArgumentException for ka < zero. */ public ElevatorFeedforward(double ks, double kg, double kv, double ka) { this.ks = ks; this.kg = kg; this.kv = kv; this.ka = ka; + if (kv < 0.0) { + throw new IllegalArgumentException("kv must be a non-negative number, got " + kv + "!"); + } + if (ka < 0.0) { + throw new IllegalArgumentException("ka must be a non-negative number, got " + ka + "!"); + } } /** diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/HolonomicDriveController.java b/wpimath/src/main/java/edu/wpi/first/math/controller/HolonomicDriveController.java index 87148a45dbe..7775a30de78 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/HolonomicDriveController.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/HolonomicDriveController.java @@ -22,9 +22,9 @@ * point toward. This heading reference is profiled for smoothness. */ public class HolonomicDriveController { - private Pose2d m_poseError = new Pose2d(); - private Rotation2d m_rotationError = new Rotation2d(); - private Pose2d m_poseTolerance = new Pose2d(); + private Pose2d m_poseError = Pose2d.kZero; + private Rotation2d m_rotationError = Rotation2d.kZero; + private Pose2d m_poseTolerance = Pose2d.kZero; private boolean m_enabled = true; private final PIDController m_xController; diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/ImplicitModelFollower.java b/wpimath/src/main/java/edu/wpi/first/math/controller/ImplicitModelFollower.java index 7aa4cfa9133..29bf0a02be7 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/ImplicitModelFollower.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/ImplicitModelFollower.java @@ -17,8 +17,12 @@ * system and makes it behave like some other system. This can be used to make a drivetrain more * controllable during teleop driving by making it behave like a slower or more benign drivetrain. * - *

    For more on the underlying math, read appendix B.3 in - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + *

    For more on the underlying math, read appendix B.3 in https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + * + * @param Number of states. + * @param Number of inputs. + * @param Number of outputs. */ public class ImplicitModelFollower { // Computed controller output @@ -99,7 +103,7 @@ public double getU(int i) { } /** Resets the controller. */ - public void reset() { + public final void reset() { m_u.fill(0.0); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/LTVDifferentialDriveController.java b/wpimath/src/main/java/edu/wpi/first/math/controller/LTVDifferentialDriveController.java index fa287831bc0..116513eb7f1 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/LTVDifferentialDriveController.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/LTVDifferentialDriveController.java @@ -65,8 +65,8 @@ private enum State { /** * Constructs a linear time-varying differential drive controller. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning * for how to select the tolerances. * * @param plant The differential drive velocity plant. diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/LTVUnicycleController.java b/wpimath/src/main/java/edu/wpi/first/math/controller/LTVUnicycleController.java index c4e7358c9f7..c3c54f32129 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/LTVUnicycleController.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/LTVUnicycleController.java @@ -80,8 +80,8 @@ public LTVUnicycleController(double dt, double maxVelocity) { /** * Constructs a linear time-varying unicycle controller. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning * for how to select the tolerances. * * @param qelems The maximum desired error tolerance for each state. @@ -95,8 +95,8 @@ public LTVUnicycleController(Vector qelems, Vector relems, double dt) { /** * Constructs a linear time-varying unicycle controller. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning * for how to select the tolerances. * * @param qelems The maximum desired error tolerance for each state. diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforward.java b/wpimath/src/main/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforward.java index b0f23a8dcc7..f71465a82a2 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforward.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/LinearPlantInversionFeedforward.java @@ -17,8 +17,12 @@ *

    The feedforward is calculated as u_ff = B+ (r_k+1 - A r_k) , * where B+ is the pseudoinverse of B. * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + * + * @param Number of states. + * @param Number of inputs. + * @param Number of outputs. */ public class LinearPlantInversionFeedforward< States extends Num, Inputs extends Num, Outputs extends Num> { @@ -105,13 +109,13 @@ public double getR(int row) { * * @param initialState The initial state vector. */ - public void reset(Matrix initialState) { + public final void reset(Matrix initialState) { m_r = initialState; m_uff.fill(0.0); } /** Resets the feedforward with a zero initial state vector. */ - public void reset() { + public final void reset() { m_r.fill(0.0); m_uff.fill(0.0); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/LinearQuadraticRegulator.java b/wpimath/src/main/java/edu/wpi/first/math/controller/LinearQuadraticRegulator.java index 658be69317a..660fa8fefac 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/LinearQuadraticRegulator.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/LinearQuadraticRegulator.java @@ -19,8 +19,12 @@ * Contains the controller coefficients and logic for a linear-quadratic regulator (LQR). LQRs use * the control law u = K(r - x). * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + * + * @param Number of states. + * @param Number of inputs. + * @param Number of outputs. */ public class LinearQuadraticRegulator { /** The current reference state. */ @@ -35,8 +39,8 @@ public class LinearQuadraticRegulatorSee - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning * for how to select the tolerances. * * @param plant The plant being controlled. @@ -61,8 +65,8 @@ public LinearQuadraticRegulator( /** * Constructs a controller with the given coefficients and plant. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning * for how to select the tolerances. * * @param A Continuous system matrix of the plant being controlled. @@ -107,14 +111,12 @@ public LinearQuadraticRegulator( var discB = discABPair.getSecond(); if (!StateSpaceUtil.isStabilizable(discA, discB)) { - var builder = new StringBuilder("The system passed to the LQR is uncontrollable!\n\nA =\n"); - builder - .append(discA.getStorage().toString()) - .append("\nB =\n") - .append(discB.getStorage().toString()) - .append('\n'); - - var msg = builder.toString(); + var msg = + "The system passed to the LQR is uncontrollable!\n\nA =\n" + + discA.getStorage().toString() + + "\nB =\n" + + discB.getStorage().toString() + + '\n'; MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace()); throw new IllegalArgumentException(msg); } @@ -223,7 +225,7 @@ public Matrix getK() { } /** Resets the controller. */ - public void reset() { + public final void reset() { m_r.fill(0.0); m_u.fill(0.0); } @@ -258,8 +260,9 @@ public Matrix calculate(Matrix x, Matrix nex * are time-delayed too long, the LQR may be unstable. However, if we know the amount of delay, we * can compute the control based on where the system will be after the time delay. * - *

    See https://file.tavsys.net/control/controls-engineering-in-frc.pdf appendix C.4 for a - * derivation. + *

    See https://file.tavsys.net/control/controls-engineering-in-frc.pdf + * appendix C.4 for a derivation. * * @param plant The plant being controlled. * @param dtSeconds Discretization timestep in seconds. diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/PIDController.java b/wpimath/src/main/java/edu/wpi/first/math/controller/PIDController.java index 1d98900beb1..f7246848c2a 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/PIDController.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/PIDController.java @@ -68,6 +68,9 @@ public class PIDController implements Sendable, AutoCloseable { * @param kp The proportional coefficient. * @param ki The integral coefficient. * @param kd The derivative coefficient. + * @throws IllegalArgumentException if kp < 0 + * @throws IllegalArgumentException if ki < 0 + * @throws IllegalArgumentException if kd < 0 */ public PIDController(double kp, double ki, double kd) { this(kp, ki, kd, 0.02); @@ -79,15 +82,29 @@ public PIDController(double kp, double ki, double kd) { * @param kp The proportional coefficient. * @param ki The integral coefficient. * @param kd The derivative coefficient. - * @param period The period between controller updates in seconds. Must be non-zero and positive. + * @param period The period between controller updates in seconds. + * @throws IllegalArgumentException if kp < 0 + * @throws IllegalArgumentException if ki < 0 + * @throws IllegalArgumentException if kd < 0 + * @throws IllegalArgumentException if period <= 0 */ + @SuppressWarnings("this-escape") public PIDController(double kp, double ki, double kd, double period) { m_kp = kp; m_ki = ki; m_kd = kd; - if (period <= 0) { - throw new IllegalArgumentException("Controller period must be a non-zero positive number!"); + if (kp < 0.0) { + throw new IllegalArgumentException("Kp must be a non-negative number!"); + } + if (ki < 0.0) { + throw new IllegalArgumentException("Ki must be a non-negative number!"); + } + if (kd < 0.0) { + throw new IllegalArgumentException("Kd must be a non-negative number!"); + } + if (period <= 0.0) { + throw new IllegalArgumentException("Controller period must be a positive number!"); } m_period = period; @@ -120,7 +137,7 @@ public void setPID(double kp, double ki, double kd) { /** * Sets the Proportional coefficient of the PID controller gain. * - * @param kp proportional coefficient + * @param kp The proportional coefficient. Must be >= 0. */ public void setP(double kp) { m_kp = kp; @@ -129,7 +146,7 @@ public void setP(double kp) { /** * Sets the Integral coefficient of the PID controller gain. * - * @param ki integral coefficient + * @param ki The integral coefficient. Must be >= 0. */ public void setI(double ki) { m_ki = ki; @@ -138,7 +155,7 @@ public void setI(double ki) { /** * Sets the Differential coefficient of the PID controller gain. * - * @param kd differential coefficient + * @param kd The differential coefficient. Must be >= 0. */ public void setD(double kd) { m_kd = kd; @@ -152,6 +169,7 @@ public void setD(double kd) { * of {@link Double#POSITIVE_INFINITY} disables IZone functionality. * * @param iZone Maximum magnitude of error to allow integral control. + * @throws IllegalArgumentException if iZone < 0 */ public void setIZone(double iZone) { if (iZone < 0) { @@ -408,7 +426,16 @@ public void initSendable(SendableBuilder builder) { builder.addDoubleProperty("p", this::getP, this::setP); builder.addDoubleProperty("i", this::getI, this::setI); builder.addDoubleProperty("d", this::getD, this::setD); - builder.addDoubleProperty("izone", this::getIZone, this::setIZone); + builder.addDoubleProperty( + "izone", + this::getIZone, + (double toSet) -> { + try { + setIZone(toSet); + } catch (IllegalArgumentException e) { + MathSharedStore.reportError("IZone must be a non-negative number!", e.getStackTrace()); + } + }); builder.addDoubleProperty("setpoint", this::getSetpoint, this::setSetpoint); } } diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/ProfiledPIDController.java b/wpimath/src/main/java/edu/wpi/first/math/controller/ProfiledPIDController.java index ba29fa12c43..e69c73f12c5 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/ProfiledPIDController.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/ProfiledPIDController.java @@ -35,6 +35,9 @@ public class ProfiledPIDController implements Sendable { * @param Ki The integral coefficient. * @param Kd The derivative coefficient. * @param constraints Velocity and acceleration constraints for goal. + * @throws IllegalArgumentException if kp < 0 + * @throws IllegalArgumentException if ki < 0 + * @throws IllegalArgumentException if kd < 0 */ public ProfiledPIDController( double Kp, double Ki, double Kd, TrapezoidProfile.Constraints constraints) { @@ -49,7 +52,12 @@ public ProfiledPIDController( * @param Kd The derivative coefficient. * @param constraints Velocity and acceleration constraints for goal. * @param period The period between controller updates in seconds. The default is 0.02 seconds. + * @throws IllegalArgumentException if kp < 0 + * @throws IllegalArgumentException if ki < 0 + * @throws IllegalArgumentException if kd < 0 + * @throws IllegalArgumentException if period <= 0 */ + @SuppressWarnings("this-escape") public ProfiledPIDController( double Kp, double Ki, double Kd, TrapezoidProfile.Constraints constraints, double period) { m_controller = new PIDController(Kp, Ki, Kd, period); @@ -66,9 +74,9 @@ public ProfiledPIDController( * *

    Sets the proportional, integral, and differential coefficients. * - * @param Kp Proportional coefficient - * @param Ki Integral coefficient - * @param Kd Differential coefficient + * @param Kp The proportional coefficient. Must be >= 0. + * @param Ki The integral coefficient. Must be >= 0. + * @param Kd The differential coefficient. Must be >= 0. */ public void setPID(double Kp, double Ki, double Kd) { m_controller.setPID(Kp, Ki, Kd); @@ -77,7 +85,7 @@ public void setPID(double Kp, double Ki, double Kd) { /** * Sets the proportional coefficient of the PID controller gain. * - * @param Kp proportional coefficient + * @param Kp The proportional coefficient. Must be >= 0. */ public void setP(double Kp) { m_controller.setP(Kp); @@ -86,7 +94,7 @@ public void setP(double Kp) { /** * Sets the integral coefficient of the PID controller gain. * - * @param Ki integral coefficient + * @param Ki The integral coefficient. Must be >= 0. */ public void setI(double Ki) { m_controller.setI(Ki); @@ -95,7 +103,7 @@ public void setI(double Ki) { /** * Sets the differential coefficient of the PID controller gain. * - * @param Kd differential coefficient + * @param Kd The differential coefficient. Must be >= 0. */ public void setD(double Kd) { m_controller.setD(Kd); @@ -109,6 +117,7 @@ public void setD(double Kd) { * of {@link Double#POSITIVE_INFINITY} disables IZone functionality. * * @param iZone Maximum magnitude of error to allow integral control. + * @throws IllegalArgumentException if iZone <= 0 */ public void setIZone(double iZone) { m_controller.setIZone(iZone); @@ -425,7 +434,16 @@ public void initSendable(SendableBuilder builder) { builder.addDoubleProperty("p", this::getP, this::setP); builder.addDoubleProperty("i", this::getI, this::setI); builder.addDoubleProperty("d", this::getD, this::setD); - builder.addDoubleProperty("izone", this::getIZone, this::setIZone); + builder.addDoubleProperty( + "izone", + this::getIZone, + (double toSet) -> { + try { + setIZone(toSet); + } catch (IllegalArgumentException e) { + MathSharedStore.reportError("IZone must be a non-negative number!", e.getStackTrace()); + } + }); builder.addDoubleProperty("goal", () -> getGoal().position, this::setGoal); } } diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/RamseteController.java b/wpimath/src/main/java/edu/wpi/first/math/controller/RamseteController.java index 5683987bc6d..d936f9efc82 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/RamseteController.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/RamseteController.java @@ -37,8 +37,8 @@ public class RamseteController { private final double m_zeta; - private Pose2d m_poseError = new Pose2d(); - private Pose2d m_poseTolerance = new Pose2d(); + private Pose2d m_poseError = Pose2d.kZero; + private Pose2d m_poseTolerance = Pose2d.kZero; private boolean m_enabled = true; /** @@ -48,7 +48,9 @@ public class RamseteController { * aggressive like a proportional term. * @param zeta Tuning parameter (0 rad⁻¹ < zeta < 1 rad⁻¹) for which larger values provide * more damping in response. + * @deprecated Use LTVUnicycleController instead. */ + @Deprecated(since = "2024", forRemoval = true) public RamseteController(double b, double zeta) { m_b = b; m_zeta = zeta; @@ -57,7 +59,10 @@ public RamseteController(double b, double zeta) { /** * Construct a Ramsete unicycle controller. The default arguments for b and zeta of 2.0 rad²/m² * and 0.7 rad⁻¹ have been well-tested to produce desirable results. + * + * @deprecated Use LTVUnicycleController instead. */ + @Deprecated(since = "2024", forRemoval = true) public RamseteController() { this(2.0, 0.7); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/SimpleMotorFeedforward.java b/wpimath/src/main/java/edu/wpi/first/math/controller/SimpleMotorFeedforward.java index 63ceb8fa8f9..eeb76db3196 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/controller/SimpleMotorFeedforward.java +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/SimpleMotorFeedforward.java @@ -10,8 +10,13 @@ /** A helper class that computes feedforward outputs for a simple permanent-magnet DC motor. */ public class SimpleMotorFeedforward { + /** The static gain. */ public final double ks; + + /** The velocity gain. */ public final double kv; + + /** The acceleration gain. */ public final double ka; /** @@ -21,11 +26,19 @@ public class SimpleMotorFeedforward { * @param ks The static gain. * @param kv The velocity gain. * @param ka The acceleration gain. + * @throws IllegalArgumentException for kv < zero. + * @throws IllegalArgumentException for ka < zero. */ public SimpleMotorFeedforward(double ks, double kv, double ka) { this.ks = ks; this.kv = kv; this.ka = ka; + if (kv < 0.0) { + throw new IllegalArgumentException("kv must be a non-negative number, got " + kv + "!"); + } + if (ka < 0.0) { + throw new IllegalArgumentException("ka must be a non-negative number, got " + ka + "!"); + } } /** diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/proto/ArmFeedforwardProto.java b/wpimath/src/main/java/edu/wpi/first/math/controller/proto/ArmFeedforwardProto.java new file mode 100644 index 00000000000..ef3953a54d4 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/proto/ArmFeedforwardProto.java @@ -0,0 +1,40 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.controller.proto; + +import edu.wpi.first.math.controller.ArmFeedforward; +import edu.wpi.first.math.proto.Controller.ProtobufArmFeedforward; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class ArmFeedforwardProto implements Protobuf { + @Override + public Class getTypeClass() { + return ArmFeedforward.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufArmFeedforward.getDescriptor(); + } + + @Override + public ProtobufArmFeedforward createMessage() { + return ProtobufArmFeedforward.newInstance(); + } + + @Override + public ArmFeedforward unpack(ProtobufArmFeedforward msg) { + return new ArmFeedforward(msg.getKs(), msg.getKg(), msg.getKv(), msg.getKa()); + } + + @Override + public void pack(ProtobufArmFeedforward msg, ArmFeedforward value) { + msg.setKs(value.ks); + msg.setKg(value.kg); + msg.setKv(value.kv); + msg.setKa(value.ka); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/proto/DifferentialDriveWheelVoltagesProto.java b/wpimath/src/main/java/edu/wpi/first/math/controller/proto/DifferentialDriveWheelVoltagesProto.java new file mode 100644 index 00000000000..c22db5d107e --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/proto/DifferentialDriveWheelVoltagesProto.java @@ -0,0 +1,40 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.controller.proto; + +import edu.wpi.first.math.controller.DifferentialDriveWheelVoltages; +import edu.wpi.first.math.proto.Controller.ProtobufDifferentialDriveWheelVoltages; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class DifferentialDriveWheelVoltagesProto + implements Protobuf { + @Override + public Class getTypeClass() { + return DifferentialDriveWheelVoltages.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufDifferentialDriveWheelVoltages.getDescriptor(); + } + + @Override + public ProtobufDifferentialDriveWheelVoltages createMessage() { + return ProtobufDifferentialDriveWheelVoltages.newInstance(); + } + + @Override + public DifferentialDriveWheelVoltages unpack(ProtobufDifferentialDriveWheelVoltages msg) { + return new DifferentialDriveWheelVoltages(msg.getLeft(), msg.getRight()); + } + + @Override + public void pack( + ProtobufDifferentialDriveWheelVoltages msg, DifferentialDriveWheelVoltages value) { + msg.setLeft(value.left); + msg.setRight(value.right); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/proto/ElevatorFeedforwardProto.java b/wpimath/src/main/java/edu/wpi/first/math/controller/proto/ElevatorFeedforwardProto.java new file mode 100644 index 00000000000..66399e1a0c2 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/proto/ElevatorFeedforwardProto.java @@ -0,0 +1,41 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.controller.proto; + +import edu.wpi.first.math.controller.ElevatorFeedforward; +import edu.wpi.first.math.proto.Controller.ProtobufElevatorFeedforward; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class ElevatorFeedforwardProto + implements Protobuf { + @Override + public Class getTypeClass() { + return ElevatorFeedforward.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufElevatorFeedforward.getDescriptor(); + } + + @Override + public ProtobufElevatorFeedforward createMessage() { + return ProtobufElevatorFeedforward.newInstance(); + } + + @Override + public ElevatorFeedforward unpack(ProtobufElevatorFeedforward msg) { + return new ElevatorFeedforward(msg.getKs(), msg.getKg(), msg.getKv(), msg.getKa()); + } + + @Override + public void pack(ProtobufElevatorFeedforward msg, ElevatorFeedforward value) { + msg.setKs(value.ks); + msg.setKg(value.kg); + msg.setKv(value.kv); + msg.setKa(value.ka); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/struct/ArmFeedforwardStruct.java b/wpimath/src/main/java/edu/wpi/first/math/controller/struct/ArmFeedforwardStruct.java new file mode 100644 index 00000000000..de72fea1bd8 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/struct/ArmFeedforwardStruct.java @@ -0,0 +1,48 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.controller.struct; + +import edu.wpi.first.math.controller.ArmFeedforward; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class ArmFeedforwardStruct implements Struct { + @Override + public Class getTypeClass() { + return ArmFeedforward.class; + } + + @Override + public String getTypeString() { + return "struct:ArmFeedforward"; + } + + @Override + public int getSize() { + return kSizeDouble * 4; + } + + @Override + public String getSchema() { + return "double ks;double kg;double kv;double ka"; + } + + @Override + public ArmFeedforward unpack(ByteBuffer bb) { + double ks = bb.getDouble(); + double kg = bb.getDouble(); + double kv = bb.getDouble(); + double ka = bb.getDouble(); + return new ArmFeedforward(ks, kg, kv, ka); + } + + @Override + public void pack(ByteBuffer bb, ArmFeedforward value) { + bb.putDouble(value.ks); + bb.putDouble(value.kg); + bb.putDouble(value.kv); + bb.putDouble(value.ka); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/struct/DifferentialDriveWheelVoltagesStruct.java b/wpimath/src/main/java/edu/wpi/first/math/controller/struct/DifferentialDriveWheelVoltagesStruct.java new file mode 100644 index 00000000000..1695d812e04 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/struct/DifferentialDriveWheelVoltagesStruct.java @@ -0,0 +1,45 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.controller.struct; + +import edu.wpi.first.math.controller.DifferentialDriveWheelVoltages; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class DifferentialDriveWheelVoltagesStruct + implements Struct { + @Override + public Class getTypeClass() { + return DifferentialDriveWheelVoltages.class; + } + + @Override + public String getTypeString() { + return "struct:DifferentialDriveWheelVoltages"; + } + + @Override + public int getSize() { + return kSizeDouble * 2; + } + + @Override + public String getSchema() { + return "double left;double right"; + } + + @Override + public DifferentialDriveWheelVoltages unpack(ByteBuffer bb) { + double left = bb.getDouble(); + double right = bb.getDouble(); + return new DifferentialDriveWheelVoltages(left, right); + } + + @Override + public void pack(ByteBuffer bb, DifferentialDriveWheelVoltages value) { + bb.putDouble(value.left); + bb.putDouble(value.right); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/controller/struct/ElevatorFeedforwardStruct.java b/wpimath/src/main/java/edu/wpi/first/math/controller/struct/ElevatorFeedforwardStruct.java new file mode 100644 index 00000000000..f8b55595304 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/controller/struct/ElevatorFeedforwardStruct.java @@ -0,0 +1,48 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.controller.struct; + +import edu.wpi.first.math.controller.ElevatorFeedforward; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class ElevatorFeedforwardStruct implements Struct { + @Override + public Class getTypeClass() { + return ElevatorFeedforward.class; + } + + @Override + public String getTypeString() { + return "struct:ElevatorFeedforward"; + } + + @Override + public int getSize() { + return kSizeDouble * 4; + } + + @Override + public String getSchema() { + return "double ks;double kg;double kv;double ka"; + } + + @Override + public ElevatorFeedforward unpack(ByteBuffer bb) { + double ks = bb.getDouble(); + double kg = bb.getDouble(); + double kv = bb.getDouble(); + double ka = bb.getDouble(); + return new ElevatorFeedforward(ks, kg, kv, ka); + } + + @Override + public void pack(ByteBuffer bb, ElevatorFeedforward value) { + bb.putDouble(value.ks); + bb.putDouble(value.kg); + bb.putDouble(value.kv); + bb.putDouble(value.ka); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/AngleStatistics.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/AngleStatistics.java index 0f91a1db83a..8a61526e8a1 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/estimator/AngleStatistics.java +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/AngleStatistics.java @@ -11,10 +11,10 @@ import java.util.function.BiFunction; import org.ejml.simple.SimpleMatrix; +/** Angle statistics functions. */ public final class AngleStatistics { - private AngleStatistics() { - // Utility class - } + /** Utility class. */ + private AngleStatistics() {} /** * Subtracts a and b while normalizing the resulting value in the selected row as if it were an diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/ExtendedKalmanFilter.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/ExtendedKalmanFilter.java index 59323b21d65..055bf9939af 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/estimator/ExtendedKalmanFilter.java +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/ExtendedKalmanFilter.java @@ -30,9 +30,13 @@ * error covariance by linearizing the models around the state estimate, then applying the linear * Kalman filter equations. * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 "Stochastic control - * theory". + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf + * chapter 9 "Stochastic control theory". + * + * @param Number of states. + * @param Number of inputs. + * @param Number of outputs. */ public class ExtendedKalmanFilter implements KalmanTypeFilter { @@ -59,8 +63,8 @@ public class ExtendedKalmanFilterSee - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices * for how to select the standard deviations. * * @param states a Nat representing the number of states. @@ -97,8 +101,8 @@ public ExtendedKalmanFilter( /** * Constructs an extended Kalman filter. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices * for how to select the standard deviations. * * @param states a Nat representing the number of states. @@ -236,7 +240,7 @@ public void setXhat(int row, double value) { } @Override - public void reset() { + public final void reset() { m_xHat = new Matrix<>(m_states, Nat.N1()); m_P = m_initP; } diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanFilter.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanFilter.java index 08e3270606d..9e286255df7 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanFilter.java +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanFilter.java @@ -25,26 +25,32 @@ * amount of the difference between the actual measurements and the measurements predicted by the * model. * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 "Stochastic control - * theory". + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf + * chapter 9 "Stochastic control theory". + * + * @param Number of states. + * @param Number of inputs. + * @param Number of outputs. */ -public class KalmanFilter { +public class KalmanFilter + implements KalmanTypeFilter { private final Nat m_states; private final LinearSystem m_plant; - - /** The steady-state Kalman gain matrix. */ - private final Matrix m_K; - - /** The state estimate. */ private Matrix m_xHat; + private Matrix m_P; + private final Matrix m_contQ; + private final Matrix m_contR; + private double m_dtSeconds; + + private final Matrix m_initP; /** - * Constructs a state-space observer with the given plant. + * Constructs a Kalman filter with the given plant. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices * for how to select the standard deviations. * * @param states A Nat representing the states of the system. @@ -66,115 +72,113 @@ public KalmanFilter( this.m_plant = plant; - var contQ = StateSpaceUtil.makeCovarianceMatrix(states, stateStdDevs); - var contR = StateSpaceUtil.makeCovarianceMatrix(outputs, measurementStdDevs); + m_contQ = StateSpaceUtil.makeCovarianceMatrix(states, stateStdDevs); + m_contR = StateSpaceUtil.makeCovarianceMatrix(outputs, measurementStdDevs); + m_dtSeconds = dtSeconds; - var pair = Discretization.discretizeAQ(plant.getA(), contQ, dtSeconds); + // Find discrete A and Q + var pair = Discretization.discretizeAQ(plant.getA(), m_contQ, dtSeconds); var discA = pair.getFirst(); var discQ = pair.getSecond(); - var discR = Discretization.discretizeR(contR, dtSeconds); + var discR = Discretization.discretizeR(m_contR, dtSeconds); var C = plant.getC(); if (!StateSpaceUtil.isDetectable(discA, C)) { - var builder = - new StringBuilder("The system passed to the Kalman filter is unobservable!\n\nA =\n"); - builder - .append(discA.getStorage().toString()) - .append("\nC =\n") - .append(C.getStorage().toString()) - .append('\n'); - - var msg = builder.toString(); + var msg = + "The system passed to the Kalman filter is unobservable!\n\nA =\n" + + discA.getStorage().toString() + + "\nC =\n" + + C.getStorage().toString() + + '\n'; MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace()); throw new IllegalArgumentException(msg); } - var P = new Matrix<>(DARE.dare(discA.transpose(), C.transpose(), discQ, discR)); - - // S = CPCᵀ + R - var S = C.times(P).times(C.transpose()).plus(discR); - - // We want to put K = PCᵀS⁻¹ into Ax = b form so we can solve it more - // efficiently. - // - // K = PCᵀS⁻¹ - // KS = PCᵀ - // (KS)ᵀ = (PCᵀ)ᵀ - // SᵀKᵀ = CPᵀ - // - // The solution of Ax = b can be found via x = A.solve(b). - // - // Kᵀ = Sᵀ.solve(CPᵀ) - // K = (Sᵀ.solve(CPᵀ))ᵀ - m_K = - new Matrix<>( - S.transpose().getStorage().solve((C.times(P.transpose())).getStorage()).transpose()); + m_initP = new Matrix<>(DARE.dare(discA.transpose(), C.transpose(), discQ, discR)); reset(); } - public void reset() { - m_xHat = new Matrix<>(m_states, Nat.N1()); + /** + * Returns the error covariance matrix P. + * + * @return the error covariance matrix P. + */ + @Override + public Matrix getP() { + return m_P; } /** - * Returns the steady-state Kalman gain matrix K. + * Returns an element of the error covariance matrix P. * - * @return The steady-state Kalman gain matrix K. + * @param row Row of P. + * @param col Column of P. + * @return the value of the error covariance matrix P at (i, j). */ - public Matrix getK() { - return m_K; + @Override + public double getP(int row, int col) { + return m_P.get(row, col); } /** - * Returns an element of the steady-state Kalman gain matrix K. + * Sets the entire error covariance matrix P. * - * @param row Row of K. - * @param col Column of K. - * @return the element (i, j) of the steady-state Kalman gain matrix K. + * @param newP The new value of P to use. */ - public double getK(int row, int col) { - return m_K.get(row, col); + @Override + public void setP(Matrix newP) { + m_P = newP; } /** - * Set initial state estimate x-hat. + * Returns the state estimate x-hat. * - * @param xhat The state estimate x-hat. + * @return the state estimate x-hat. */ - public void setXhat(Matrix xhat) { - this.m_xHat = xhat; + @Override + public Matrix getXhat() { + return m_xHat; } /** - * Set an element of the initial state estimate x-hat. + * Returns an element of the state estimate x-hat. * * @param row Row of x-hat. - * @param value Value for element of x-hat. + * @return the value of the state estimate x-hat at that row. */ - public void setXhat(int row, double value) { - m_xHat.set(row, 0, value); + @Override + public double getXhat(int row) { + return m_xHat.get(row, 0); } /** - * Returns the state estimate x-hat. + * Set initial state estimate x-hat. * - * @return The state estimate x-hat. + * @param xHat The state estimate x-hat. */ - public Matrix getXhat() { - return m_xHat; + @Override + public void setXhat(Matrix xHat) { + m_xHat = xHat; } /** - * Returns an element of the state estimate x-hat. + * Set an element of the initial state estimate x-hat. * * @param row Row of x-hat. - * @return the state estimate x-hat at that row. + * @param value Value for element of x-hat. */ - public double getXhat(int row) { - return m_xHat.get(row, 0); + @Override + public void setXhat(int row, double value) { + m_xHat.set(row, 0, value); + } + + @Override + public final void reset() { + m_xHat = new Matrix<>(m_states, Nat.N1()); + m_P = m_initP; } /** @@ -183,20 +187,73 @@ public double getXhat(int row) { * @param u New control input from controller. * @param dtSeconds Timestep for prediction. */ + @Override public void predict(Matrix u, double dtSeconds) { - this.m_xHat = m_plant.calculateX(m_xHat, u, dtSeconds); + // Find discrete A and Q + final var discPair = Discretization.discretizeAQ(m_plant.getA(), m_contQ, dtSeconds); + final var discA = discPair.getFirst(); + final var discQ = discPair.getSecond(); + + m_xHat = m_plant.calculateX(m_xHat, u, dtSeconds); + + // Pₖ₊₁⁻ = APₖ⁻Aᵀ + Q + m_P = discA.times(m_P).times(discA.transpose()).plus(discQ); + + m_dtSeconds = dtSeconds; } /** * Correct the state estimate x-hat using the measurements in y. * - * @param u Same control input used in the last predict step. + * @param u Same control input used in the predict step. * @param y Measurement vector. */ + @Override public void correct(Matrix u, Matrix y) { + correct(u, y, m_contR); + } + + /** + * Correct the state estimate x-hat using the measurements in y. + * + *

    This is useful for when the measurement noise covariances vary. + * + * @param u Same control input used in the predict step. + * @param y Measurement vector. + * @param R Continuous measurement noise covariance matrix. + */ + public void correct(Matrix u, Matrix y, Matrix R) { final var C = m_plant.getC(); final var D = m_plant.getD(); + + final var discR = Discretization.discretizeR(R, m_dtSeconds); + + final var S = C.times(m_P).times(C.transpose()).plus(discR); + + // We want to put K = PCᵀS⁻¹ into Ax = b form so we can solve it more + // efficiently. + // + // K = PCᵀS⁻¹ + // KS = PCᵀ + // (KS)ᵀ = (PCᵀ)ᵀ + // SᵀKᵀ = CPᵀ + // + // The solution of Ax = b can be found via x = A.solve(b). + // + // Kᵀ = Sᵀ.solve(CPᵀ) + // K = (Sᵀ.solve(CPᵀ))ᵀ + final Matrix K = S.transpose().solve(C.times(m_P.transpose())).transpose(); + // x̂ₖ₊₁⁺ = x̂ₖ₊₁⁻ + K(y − (Cx̂ₖ₊₁⁻ + Duₖ₊₁)) - m_xHat = m_xHat.plus(m_K.times(y.minus(C.times(m_xHat).plus(D.times(u))))); + m_xHat = m_xHat.plus(K.times(y.minus(C.times(m_xHat).plus(D.times(u))))); + + // Pₖ₊₁⁺ = (I−Kₖ₊₁C)Pₖ₊₁⁻(I−Kₖ₊₁C)ᵀ + Kₖ₊₁RKₖ₊₁ᵀ + // Use Joseph form for numerical stability + m_P = + Matrix.eye(m_states) + .minus(K.times(C)) + .times(m_P) + .times(Matrix.eye(m_states).minus(K.times(C)).transpose()) + .plus(K.times(discR).times(K.transpose())); } } diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanFilterLatencyCompensator.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanFilterLatencyCompensator.java index 15e7bd4b6d3..ad4db523377 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanFilterLatencyCompensator.java +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanFilterLatencyCompensator.java @@ -13,11 +13,19 @@ import java.util.Map; import java.util.function.BiConsumer; +/** + * This class incorporates time-delayed measurements into a Kalman filter's state estimate. + * + * @param The number of states. + * @param The number of inputs. + * @param The number of outputs. + */ public class KalmanFilterLatencyCompensator { private static final int kMaxPastObserverStates = 300; private final List> m_pastObserverSnapshots; + /** Default constructor. */ KalmanFilterLatencyCompensator() { m_pastObserverSnapshots = new ArrayList<>(); } @@ -164,9 +172,16 @@ public void applyPastGlobalMeasurement( /** This class contains all the information about our observer at a given time. */ public class ObserverSnapshot { + /** The state estimate. */ public final Matrix xHat; + + /** The error covariance. */ public final Matrix errorCovariances; + + /** The inputs. */ public final Matrix inputs; + + /** The local measurements. */ public final Matrix localMeasurements; private ObserverSnapshot( diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanTypeFilter.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanTypeFilter.java index 7b14839f2a2..ff9856c32df 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanTypeFilter.java +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/KalmanTypeFilter.java @@ -8,24 +8,83 @@ import edu.wpi.first.math.Num; import edu.wpi.first.math.numbers.N1; +/** + * Interface for Kalman filters for use with KalmanFilterLatencyCompensator. + * + * @param The number of states. + * @param The number of inputs. + * @param The number of outputs. + */ public interface KalmanTypeFilter { + /** + * Returns the error covariance matrix. + * + * @return The error covariance matrix. + */ Matrix getP(); + /** + * Returns an element of the error covariance matrix. + * + * @param i The row. + * @param j The column. + * @return An element of the error covariance matrix. + */ double getP(int i, int j); + /** + * Sets the error covariance matrix. + * + * @param newP The error covariance matrix. + */ void setP(Matrix newP); + /** + * Returns the state estimate. + * + * @return The state estimate. + */ Matrix getXhat(); + /** + * Returns an element of the state estimate. + * + * @param i The row. + * @return An element of the state estimate. + */ double getXhat(int i); + /** + * Sets the state estimate. + * + * @param xHat The state estimate. + */ void setXhat(Matrix xHat); + /** + * Sets an element of the state estimate. + * + * @param i The row. + * @param value The value. + */ void setXhat(int i, double value); + /** Resets the observer. */ void reset(); + /** + * Project the model into the future with a new control input u. + * + * @param u New control input from controller. + * @param dtSeconds Timestep for prediction. + */ void predict(Matrix u, double dtSeconds); + /** + * Correct the state estimate x-hat using the measurements in y. + * + * @param u Same control input used in the predict step. + * @param y Measurement vector. + */ void correct(Matrix u, Matrix y); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/MerweScaledSigmaPoints.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/MerweScaledSigmaPoints.java index 24835f6c341..24fa771f339 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/estimator/MerweScaledSigmaPoints.java +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/MerweScaledSigmaPoints.java @@ -21,6 +21,8 @@ * *

    [1] R. Van der Merwe "Sigma-Point Kalman Filters for Probabilitic Inference in Dynamic * State-Space Models" (Doctoral dissertation) + * + * @param The dimensionality of the state. 2 * States + 1 weights will be generated. */ public class MerweScaledSigmaPoints { private final double m_alpha; diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/PoseEstimator.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/PoseEstimator.java index bb30f25b4d1..141844e362e 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/estimator/PoseEstimator.java +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/PoseEstimator.java @@ -21,6 +21,7 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; +import java.util.Optional; /** * This class wraps {@link Odometry} to fuse latency-compensated vision measurements with encoder @@ -34,6 +35,8 @@ * *

    {@link PoseEstimator#addVisionMeasurement} can be called as infrequently as you want; if you * never call it then this class will behave exactly like regular encoder odometry. + * + * @param Wheel positions type. */ public class PoseEstimator> { private final Kinematics m_kinematics; @@ -80,7 +83,7 @@ public PoseEstimator( * numbers to trust global measurements from vision less. This matrix is in the form [x, y, * theta]ᵀ, with units in meters and radians. */ - public void setVisionMeasurementStdDevs(Matrix visionMeasurementStdDevs) { + public final void setVisionMeasurementStdDevs(Matrix visionMeasurementStdDevs) { var r = new double[3]; for (int i = 0; i < 3; ++i) { r[i] = visionMeasurementStdDevs.get(i, 0) * visionMeasurementStdDevs.get(i, 0); @@ -123,6 +126,16 @@ public Pose2d getEstimatedPosition() { return m_odometry.getPoseMeters(); } + /** + * Return the pose at a given timestamp, if the buffer is not empty. + * + * @param timestampSeconds The pose's timestamp in seconds. + * @return The pose at the given timestamp (or Optional.empty() if the buffer is empty). + */ + public Optional sampleAt(double timestampSeconds) { + return m_poseBuffer.getSample(timestampSeconds).map(record -> record.poseMeters); + } + /** * Adds a vision measurement to the Kalman Filter. This will correct the odometry pose estimate * while still accounting for measurement noise. diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/SteadyStateKalmanFilter.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/SteadyStateKalmanFilter.java new file mode 100644 index 00000000000..e29032d7cba --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/SteadyStateKalmanFilter.java @@ -0,0 +1,208 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.estimator; + +import edu.wpi.first.math.DARE; +import edu.wpi.first.math.MathSharedStore; +import edu.wpi.first.math.Matrix; +import edu.wpi.first.math.Nat; +import edu.wpi.first.math.Num; +import edu.wpi.first.math.StateSpaceUtil; +import edu.wpi.first.math.numbers.N1; +import edu.wpi.first.math.system.Discretization; +import edu.wpi.first.math.system.LinearSystem; + +/** + * A Kalman filter combines predictions from a model and measurements to give an estimate of the + * true system state. This is useful because many states cannot be measured directly as a result of + * sensor noise, or because the state is "hidden". + * + *

    Kalman filters use a K gain matrix to determine whether to trust the model or measurements + * more. Kalman filter theory uses statistics to compute an optimal K gain which minimizes the sum + * of squares error in the state estimate. This K gain is used to correct the state estimate by some + * amount of the difference between the actual measurements and the measurements predicted by the + * model. + * + *

    This class assumes predict() and correct() are called in pairs, so the Kalman gain converges + * to a steady-state value. If they aren't, use {@link KalmanFilter} instead. + * + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf + * chapter 9 "Stochastic control theory". + * + * @param Number of states. + * @param Number of inputs. + * @param Number of outputs. + */ +public class SteadyStateKalmanFilter { + private final Nat m_states; + + private final LinearSystem m_plant; + + /** The steady-state Kalman gain matrix. */ + private final Matrix m_K; + + /** The state estimate. */ + private Matrix m_xHat; + + /** + * Constructs a steady-state Kalman filter with the given plant. + * + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + * for how to select the standard deviations. + * + * @param states A Nat representing the states of the system. + * @param outputs A Nat representing the outputs of the system. + * @param plant The plant used for the prediction step. + * @param stateStdDevs Standard deviations of model states. + * @param measurementStdDevs Standard deviations of measurements. + * @param dtSeconds Nominal discretization timestep. + * @throws IllegalArgumentException If the system is unobservable. + */ + public SteadyStateKalmanFilter( + Nat states, + Nat outputs, + LinearSystem plant, + Matrix stateStdDevs, + Matrix measurementStdDevs, + double dtSeconds) { + this.m_states = states; + + this.m_plant = plant; + + var contQ = StateSpaceUtil.makeCovarianceMatrix(states, stateStdDevs); + var contR = StateSpaceUtil.makeCovarianceMatrix(outputs, measurementStdDevs); + + var pair = Discretization.discretizeAQ(plant.getA(), contQ, dtSeconds); + var discA = pair.getFirst(); + var discQ = pair.getSecond(); + + var discR = Discretization.discretizeR(contR, dtSeconds); + + var C = plant.getC(); + + if (!StateSpaceUtil.isDetectable(discA, C)) { + var msg = + "The system passed to the Kalman filter is unobservable!\n\nA =\n" + + discA.getStorage().toString() + + "\nC =\n" + + C.getStorage().toString() + + '\n'; + MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace()); + throw new IllegalArgumentException(msg); + } + + var P = new Matrix<>(DARE.dare(discA.transpose(), C.transpose(), discQ, discR)); + + // S = CPCᵀ + R + var S = C.times(P).times(C.transpose()).plus(discR); + + // We want to put K = PCᵀS⁻¹ into Ax = b form so we can solve it more + // efficiently. + // + // K = PCᵀS⁻¹ + // KS = PCᵀ + // (KS)ᵀ = (PCᵀ)ᵀ + // SᵀKᵀ = CPᵀ + // + // The solution of Ax = b can be found via x = A.solve(b). + // + // Kᵀ = Sᵀ.solve(CPᵀ) + // K = (Sᵀ.solve(CPᵀ))ᵀ + m_K = + new Matrix<>( + S.transpose().getStorage().solve(C.times(P.transpose()).getStorage()).transpose()); + + reset(); + } + + /** Resets the observer. */ + public final void reset() { + m_xHat = new Matrix<>(m_states, Nat.N1()); + } + + /** + * Returns the steady-state Kalman gain matrix K. + * + * @return The steady-state Kalman gain matrix K. + */ + public Matrix getK() { + return m_K; + } + + /** + * Returns an element of the steady-state Kalman gain matrix K. + * + * @param row Row of K. + * @param col Column of K. + * @return the element (i, j) of the steady-state Kalman gain matrix K. + */ + public double getK(int row, int col) { + return m_K.get(row, col); + } + + /** + * Set initial state estimate x-hat. + * + * @param xhat The state estimate x-hat. + */ + public void setXhat(Matrix xhat) { + this.m_xHat = xhat; + } + + /** + * Set an element of the initial state estimate x-hat. + * + * @param row Row of x-hat. + * @param value Value for element of x-hat. + */ + public void setXhat(int row, double value) { + m_xHat.set(row, 0, value); + } + + /** + * Returns the state estimate x-hat. + * + * @return The state estimate x-hat. + */ + public Matrix getXhat() { + return m_xHat; + } + + /** + * Returns an element of the state estimate x-hat. + * + * @param row Row of x-hat. + * @return the state estimate x-hat at that row. + */ + public double getXhat(int row) { + return m_xHat.get(row, 0); + } + + /** + * Project the model into the future with a new control input u. + * + * @param u New control input from controller. + * @param dtSeconds Timestep for prediction. + */ + public void predict(Matrix u, double dtSeconds) { + this.m_xHat = m_plant.calculateX(m_xHat, u, dtSeconds); + } + + /** + * Correct the state estimate x-hat using the measurements in y. + * + * @param u Same control input used in the last predict step. + * @param y Measurement vector. + */ + public void correct(Matrix u, Matrix y) { + final var C = m_plant.getC(); + final var D = m_plant.getD(); + + // x̂ₖ₊₁⁺ = x̂ₖ₊₁⁻ + K(y − (Cx̂ₖ₊₁⁻ + Duₖ₊₁)) + m_xHat = m_xHat.plus(m_K.times(y.minus(C.times(m_xHat).plus(D.times(u))))); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/estimator/UnscentedKalmanFilter.java b/wpimath/src/main/java/edu/wpi/first/math/estimator/UnscentedKalmanFilter.java index a5de856feb0..c64ec85cf9b 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/estimator/UnscentedKalmanFilter.java +++ b/wpimath/src/main/java/edu/wpi/first/math/estimator/UnscentedKalmanFilter.java @@ -31,12 +31,17 @@ *

    An unscented Kalman filter uses nonlinear state and measurement models. It propagates the * error covariance using sigma points chosen to approximate the true probability distribution. * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 "Stochastic control - * theory". + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf + * chapter 9 "Stochastic control theory". * *

    This class implements a square-root-form unscented Kalman filter (SR-UKF). For more - * information about the SR-UKF, see https://www.researchgate.net/publication/3908304. + * information about the SR-UKF, see https://www.researchgate.net/publication/3908304. + * + * @param Number of states. + * @param Number of inputs. + * @param Number of outputs. */ public class UnscentedKalmanFilter implements KalmanTypeFilter { @@ -64,8 +69,8 @@ public class UnscentedKalmanFilterSee - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices * for how to select the standard deviations. * * @param states A Nat representing the number of states. @@ -104,8 +109,8 @@ public UnscentedKalmanFilter( * custom functions for arithmetic can be useful if you have angles in the state or measurements, * because they allow you to correctly account for the modular nature of angle arithmetic. * - *

    See - * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + *

    See https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices * for how to select the standard deviations. * * @param states A Nat representing the number of states. @@ -206,7 +211,7 @@ Pair, Matrix> squareRootUnscentedTransform( var qrStorage = Sbar.transpose().getStorage(); if (!qr.decompose(qrStorage.getDDRM())) { - throw new RuntimeException("QR decomposition failed! Input matrix:\n" + qrStorage.toString()); + throw new RuntimeException("QR decomposition failed! Input matrix:\n" + qrStorage); } Matrix newS = new Matrix<>(new SimpleMatrix(qr.getR(null, true))); @@ -322,7 +327,7 @@ public void setXhat(int row, double value) { /** Resets the observer. */ @Override - public void reset() { + public final void reset() { m_xHat = new Matrix<>(m_states, Nat.N1()); m_S = new Matrix<>(m_states, m_states); m_sigmasF = new Matrix<>(new SimpleMatrix(m_states.getNum(), 2 * m_states.getNum() + 1)); diff --git a/wpimath/src/main/java/edu/wpi/first/math/filter/Debouncer.java b/wpimath/src/main/java/edu/wpi/first/math/filter/Debouncer.java index 3472198d4b4..c113d9655ae 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/filter/Debouncer.java +++ b/wpimath/src/main/java/edu/wpi/first/math/filter/Debouncer.java @@ -11,9 +11,13 @@ * baseline for a specified period of time before the filtered value changes. */ public class Debouncer { + /** Type of debouncing to perform. */ public enum DebounceType { + /** Rising edge. */ kRising, + /** Falling edge. */ kFalling, + /** Both rising and falling edges. */ kBoth } diff --git a/wpimath/src/main/java/edu/wpi/first/math/filter/LinearFilter.java b/wpimath/src/main/java/edu/wpi/first/math/filter/LinearFilter.java index 98dd4e1615c..850b7f2f75c 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/filter/LinearFilter.java +++ b/wpimath/src/main/java/edu/wpi/first/math/filter/LinearFilter.java @@ -6,7 +6,7 @@ import edu.wpi.first.math.MathSharedStore; import edu.wpi.first.math.MathUsageId; -import edu.wpi.first.util.CircularBuffer; +import edu.wpi.first.util.DoubleCircularBuffer; import java.util.Arrays; import org.ejml.simple.SimpleMatrix; @@ -35,9 +35,13 @@ * PID controller out of this class! * *

    For more on filters, we highly recommend the following articles:
    - * https://en.wikipedia.org/wiki/Linear_filter
    - * https://en.wikipedia.org/wiki/Iir_filter
    - * https://en.wikipedia.org/wiki/Fir_filter
    + * https://en.wikipedia.org/wiki/Linear_filter + *
    + * https://en.wikipedia.org/wiki/Iir_filter + *
    + * https://en.wikipedia.org/wiki/Fir_filter + *
    * *

    Note 1: calculate() should be called by the user on a known, regular period. You can use a * Notifier for this or do it "inline" with code in a periodic function. @@ -48,8 +52,8 @@ * to make sure calculate() gets called at the desired, constant frequency! */ public class LinearFilter { - private final CircularBuffer m_inputs; - private final CircularBuffer m_outputs; + private final DoubleCircularBuffer m_inputs; + private final DoubleCircularBuffer m_outputs; private final double[] m_inputGains; private final double[] m_outputGains; @@ -62,8 +66,8 @@ public class LinearFilter { * @param fbGains The "feedback" or IIR gains. */ public LinearFilter(double[] ffGains, double[] fbGains) { - m_inputs = new CircularBuffer(ffGains.length); - m_outputs = new CircularBuffer(fbGains.length); + m_inputs = new DoubleCircularBuffer(ffGains.length); + m_outputs = new DoubleCircularBuffer(fbGains.length); m_inputGains = Arrays.copyOf(ffGains, ffGains.length); m_outputGains = Arrays.copyOf(fbGains, fbGains.length); @@ -242,6 +246,43 @@ public void reset() { m_outputs.clear(); } + /** + * Resets the filter state, initializing internal buffers to the provided values. + * + *

    These are the expected lengths of the buffers, depending on what type of linear filter used: + * + * + * + * + * + * + * + * + * + * + *
    TypeInput Buffer LengthOutput Buffer Length
    Unspecifiedlength of {@code ffGains}length of {@code fbGains}
    Single Pole IIR11
    High-Pass21
    Moving Average{@code taps}0
    Finite Differencelength of {@code stencil}0
    Backward Finite Difference{@code samples}0
    + * + * @param inputBuffer Values to initialize input buffer. + * @param outputBuffer Values to initialize output buffer. + * @throws IllegalArgumentException if length of inputBuffer or outputBuffer does not match the + * length of ffGains and fbGains provided in the constructor. + */ + public void reset(double[] inputBuffer, double[] outputBuffer) { + // Clear buffers + reset(); + + if (inputBuffer.length != m_inputGains.length || outputBuffer.length != m_outputGains.length) { + throw new IllegalArgumentException("Incorrect length of inputBuffer or outputBuffer"); + } + + for (double input : inputBuffer) { + m_inputs.addFirst(input); + } + for (double output : outputBuffer) { + m_outputs.addFirst(output); + } + } + /** * Calculates the next value of the filter. * @@ -272,6 +313,15 @@ public double calculate(double input) { return retVal; } + /** + * Returns the last value calculated by the LinearFilter. + * + * @return The last value. + */ + public double lastValue() { + return m_outputs.getFirst(); + } + /** * Factorial of n. * diff --git a/wpimath/src/main/java/edu/wpi/first/math/filter/MedianFilter.java b/wpimath/src/main/java/edu/wpi/first/math/filter/MedianFilter.java index c24f6e9139f..d1d67b5b524 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/filter/MedianFilter.java +++ b/wpimath/src/main/java/edu/wpi/first/math/filter/MedianFilter.java @@ -4,7 +4,7 @@ package edu.wpi.first.math.filter; -import edu.wpi.first.util.CircularBuffer; +import edu.wpi.first.util.DoubleCircularBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -15,7 +15,7 @@ * processing, LIDAR, or ultrasonic sensors). */ public class MedianFilter { - private final CircularBuffer m_valueBuffer; + private final DoubleCircularBuffer m_valueBuffer; private final List m_orderedValues; private final int m_size; @@ -26,7 +26,7 @@ public class MedianFilter { */ public MedianFilter(int size) { // Circular buffer of values currently in the window, ordered by time - m_valueBuffer = new CircularBuffer(size); + m_valueBuffer = new DoubleCircularBuffer(size); // List of values currently in the window, ordered by value m_orderedValues = new ArrayList<>(size); // Size of rolling window @@ -72,6 +72,15 @@ public double calculate(double next) { } } + /** + * Returns the last value calculated by the MedianFilter. + * + * @return The last value. + */ + public double lastValue() { + return m_valueBuffer.getFirst(); + } + /** Resets the filter, clearing the window of all elements. */ public void reset() { m_orderedValues.clear(); diff --git a/wpimath/src/main/java/edu/wpi/first/math/filter/SlewRateLimiter.java b/wpimath/src/main/java/edu/wpi/first/math/filter/SlewRateLimiter.java index 6c34f35bc08..d9eca58419a 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/filter/SlewRateLimiter.java +++ b/wpimath/src/main/java/edu/wpi/first/math/filter/SlewRateLimiter.java @@ -64,6 +64,15 @@ public double calculate(double input) { return m_prevVal; } + /** + * Returns the value last calculated by the SlewRateLimiter. + * + * @return The last value. + */ + public double lastValue() { + return m_prevVal; + } + /** * Resets the slew rate limiter to the specified value; ignores the rate limit when doing so. * diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/Pose2d.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/Pose2d.java index 032522b864d..d00490f4502 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/geometry/Pose2d.java +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/Pose2d.java @@ -10,30 +10,36 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import edu.wpi.first.math.geometry.proto.Pose2dProto; +import edu.wpi.first.math.geometry.struct.Pose2dStruct; import edu.wpi.first.math.interpolation.Interpolatable; -import edu.wpi.first.math.proto.Geometry2D.ProtobufPose2d; import edu.wpi.first.units.Distance; import edu.wpi.first.units.Measure; -import edu.wpi.first.util.protobuf.Protobuf; -import edu.wpi.first.util.struct.Struct; -import java.nio.ByteBuffer; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; -import us.hebi.quickbuf.Descriptors.Descriptor; /** Represents a 2D pose containing translational and rotational elements. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) -public class Pose2d implements Interpolatable { +public class Pose2d implements Interpolatable, ProtobufSerializable, StructSerializable { + /** + * A preallocated Pose2d representing the origin. + * + *

    This exists to avoid allocations for common poses. + */ + public static final Pose2d kZero = new Pose2d(); + private final Translation2d m_translation; private final Rotation2d m_rotation; /** Constructs a pose at the origin facing toward the positive X axis. */ public Pose2d() { - m_translation = new Translation2d(); - m_rotation = new Rotation2d(); + m_translation = Translation2d.kZero; + m_rotation = Rotation2d.kZero; } /** @@ -327,82 +333,9 @@ public Pose2d interpolate(Pose2d endValue, double t) { } } - public static final class AStruct implements Struct { - @Override - public Class getTypeClass() { - return Pose2d.class; - } - - @Override - public String getTypeString() { - return "struct:Pose2d"; - } - - @Override - public int getSize() { - return Translation2d.struct.getSize() + Rotation2d.struct.getSize(); - } - - @Override - public String getSchema() { - return "Translation2d translation;Rotation2d rotation"; - } - - @Override - public Struct[] getNested() { - return new Struct[] {Translation2d.struct, Rotation2d.struct}; - } - - @Override - public Pose2d unpack(ByteBuffer bb) { - Translation2d translation = Translation2d.struct.unpack(bb); - Rotation2d rotation = Rotation2d.struct.unpack(bb); - return new Pose2d(translation, rotation); - } - - @Override - public void pack(ByteBuffer bb, Pose2d value) { - Translation2d.struct.pack(bb, value.m_translation); - Rotation2d.struct.pack(bb, value.m_rotation); - } - } - - public static final AStruct struct = new AStruct(); - - public static final class AProto implements Protobuf { - @Override - public Class getTypeClass() { - return Pose2d.class; - } - - @Override - public Descriptor getDescriptor() { - return ProtobufPose2d.getDescriptor(); - } - - @Override - public Protobuf[] getNested() { - return new Protobuf[] {Translation2d.proto, Rotation2d.proto}; - } - - @Override - public ProtobufPose2d createMessage() { - return ProtobufPose2d.newInstance(); - } - - @Override - public Pose2d unpack(ProtobufPose2d msg) { - return new Pose2d( - Translation2d.proto.unpack(msg.getTranslation()), - Rotation2d.proto.unpack(msg.getRotation())); - } - - @Override - public void pack(ProtobufPose2d msg, Pose2d value) { - Translation2d.proto.pack(msg.getMutableTranslation(), value.m_translation); - Rotation2d.proto.pack(msg.getMutableRotation(), value.m_rotation); - } - } + /** Pose2d protobuf for serialization. */ + public static final Pose2dProto proto = new Pose2dProto(); - public static final AProto proto = new AProto(); + /** Pose2d struct for serialization. */ + public static final Pose2dStruct struct = new Pose2dStruct(); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/Pose3d.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/Pose3d.java index 2ea709439ac..9cebf0882d0 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/geometry/Pose3d.java +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/Pose3d.java @@ -9,25 +9,31 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import edu.wpi.first.math.WPIMathJNI; +import edu.wpi.first.math.geometry.proto.Pose3dProto; +import edu.wpi.first.math.geometry.struct.Pose3dStruct; import edu.wpi.first.math.interpolation.Interpolatable; -import edu.wpi.first.math.proto.Geometry3D.ProtobufPose3d; -import edu.wpi.first.util.protobuf.Protobuf; -import edu.wpi.first.util.struct.Struct; -import java.nio.ByteBuffer; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Objects; -import us.hebi.quickbuf.Descriptors.Descriptor; /** Represents a 3D pose containing translational and rotational elements. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) -public class Pose3d implements Interpolatable { +public class Pose3d implements Interpolatable, ProtobufSerializable, StructSerializable { + /** + * A preallocated Pose3d representing the origin. + * + *

    This exists to avoid allocations for common poses. + */ + public static final Pose3d kZero = new Pose3d(); + private final Translation3d m_translation; private final Rotation3d m_rotation; /** Constructs a pose at the origin facing toward the positive X axis. */ public Pose3d() { - m_translation = new Translation3d(); - m_rotation = new Rotation3d(); + m_translation = Translation3d.kZero; + m_rotation = Rotation3d.kZero; } /** @@ -324,82 +330,9 @@ public Pose3d interpolate(Pose3d endValue, double t) { } } - public static final class AStruct implements Struct { - @Override - public Class getTypeClass() { - return Pose3d.class; - } - - @Override - public String getTypeString() { - return "struct:Pose3d"; - } - - @Override - public int getSize() { - return Translation3d.struct.getSize() + Rotation3d.struct.getSize(); - } - - @Override - public String getSchema() { - return "Translation3d translation;Rotation3d rotation"; - } - - @Override - public Struct[] getNested() { - return new Struct[] {Translation3d.struct, Rotation3d.struct}; - } - - @Override - public Pose3d unpack(ByteBuffer bb) { - Translation3d translation = Translation3d.struct.unpack(bb); - Rotation3d rotation = Rotation3d.struct.unpack(bb); - return new Pose3d(translation, rotation); - } - - @Override - public void pack(ByteBuffer bb, Pose3d value) { - Translation3d.struct.pack(bb, value.m_translation); - Rotation3d.struct.pack(bb, value.m_rotation); - } - } - - public static final AStruct struct = new AStruct(); - - public static final class AProto implements Protobuf { - @Override - public Class getTypeClass() { - return Pose3d.class; - } - - @Override - public Descriptor getDescriptor() { - return ProtobufPose3d.getDescriptor(); - } - - @Override - public Protobuf[] getNested() { - return new Protobuf[] {Translation3d.proto, Rotation3d.proto}; - } - - @Override - public ProtobufPose3d createMessage() { - return ProtobufPose3d.newInstance(); - } - - @Override - public Pose3d unpack(ProtobufPose3d msg) { - return new Pose3d( - Translation3d.proto.unpack(msg.getTranslation()), - Rotation3d.proto.unpack(msg.getRotation())); - } - - @Override - public void pack(ProtobufPose3d msg, Pose3d value) { - Translation3d.proto.pack(msg.getMutableTranslation(), value.m_translation); - Rotation3d.proto.pack(msg.getMutableRotation(), value.m_rotation); - } - } + /** Pose3d protobuf for serialization. */ + public static final Pose3dProto proto = new Pose3dProto(); - public static final AProto proto = new AProto(); + /** Pose3d struct for serialization. */ + public static final Pose3dStruct struct = new Pose3dStruct(); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/Quaternion.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/Quaternion.java index 23fd26b6c05..5e1b581e54a 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/geometry/Quaternion.java +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/Quaternion.java @@ -10,17 +10,17 @@ import com.fasterxml.jackson.annotation.JsonProperty; import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.Vector; +import edu.wpi.first.math.geometry.proto.QuaternionProto; +import edu.wpi.first.math.geometry.struct.QuaternionStruct; import edu.wpi.first.math.numbers.N3; -import edu.wpi.first.math.proto.Geometry3D.ProtobufQuaternion; -import edu.wpi.first.util.protobuf.Protobuf; -import edu.wpi.first.util.struct.Struct; -import java.nio.ByteBuffer; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Objects; -import us.hebi.quickbuf.Descriptors.Descriptor; +/** Represents a quaternion. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) -public class Quaternion { +public class Quaternion implements ProtobufSerializable, StructSerializable { // Scalar r in versor form private final double m_w; @@ -285,11 +285,12 @@ public Quaternion log(Quaternion end) { * @return The logarithm of this quaternion. */ public Quaternion log() { - var scalar = Math.log(norm()); + var norm = norm(); + var scalar = Math.log(norm); var v_norm = Math.sqrt(getX() * getX() + getY() * getY() + getZ() * getZ()); - var s_norm = getW() / norm(); + var s_norm = getW() / norm; if (Math.abs(s_norm + 1) < 1e-9) { return new Quaternion(scalar, -Math.PI, 0, 0); @@ -406,73 +407,9 @@ public Vector toRotationVector() { return VecBuilder.fill(coeff * getX(), coeff * getY(), coeff * getZ()); } - public static final class AStruct implements Struct { - @Override - public Class getTypeClass() { - return Quaternion.class; - } - - @Override - public String getTypeString() { - return "struct:Quaternion"; - } - - @Override - public int getSize() { - return kSizeDouble * 4; - } - - @Override - public String getSchema() { - return "double w;double x;double y;double z"; - } - - @Override - public Quaternion unpack(ByteBuffer bb) { - double w = bb.getDouble(); - double x = bb.getDouble(); - double y = bb.getDouble(); - double z = bb.getDouble(); - return new Quaternion(w, x, y, z); - } - - @Override - public void pack(ByteBuffer bb, Quaternion value) { - bb.putDouble(value.getW()); - bb.putDouble(value.getX()); - bb.putDouble(value.getY()); - bb.putDouble(value.getZ()); - } - } - - public static final AStruct struct = new AStruct(); - - public static final class AProto implements Protobuf { - @Override - public Class getTypeClass() { - return Quaternion.class; - } - - @Override - public Descriptor getDescriptor() { - return ProtobufQuaternion.getDescriptor(); - } - - @Override - public ProtobufQuaternion createMessage() { - return ProtobufQuaternion.newInstance(); - } - - @Override - public Quaternion unpack(ProtobufQuaternion msg) { - return new Quaternion(msg.getW(), msg.getX(), msg.getY(), msg.getZ()); - } - - @Override - public void pack(ProtobufQuaternion msg, Quaternion value) { - msg.setW(value.getW()).setX(value.getX()).setY(value.getY()).setZ(value.getZ()); - } - } + /** Quaternion protobuf for serialization. */ + public static final QuaternionProto proto = new QuaternionProto(); - public static final AProto proto = new AProto(); + /** Quaternion struct for serialization. */ + public static final QuaternionStruct struct = new QuaternionStruct(); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/Rotation2d.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/Rotation2d.java index 55f42e601db..126a6df9d36 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/geometry/Rotation2d.java +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/Rotation2d.java @@ -11,16 +11,15 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import edu.wpi.first.math.MathUtil; +import edu.wpi.first.math.geometry.proto.Rotation2dProto; +import edu.wpi.first.math.geometry.struct.Rotation2dStruct; import edu.wpi.first.math.interpolation.Interpolatable; -import edu.wpi.first.math.proto.Geometry2D.ProtobufRotation2d; import edu.wpi.first.math.util.Units; import edu.wpi.first.units.Angle; import edu.wpi.first.units.Measure; -import edu.wpi.first.util.protobuf.Protobuf; -import edu.wpi.first.util.struct.Struct; -import java.nio.ByteBuffer; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Objects; -import us.hebi.quickbuf.Descriptors.Descriptor; /** * A rotation in a 2D coordinate frame represented by a point on the unit circle (cosine and sine). @@ -31,7 +30,57 @@ */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) -public class Rotation2d implements Interpolatable { +public class Rotation2d + implements Interpolatable, ProtobufSerializable, StructSerializable { + /** + * A preallocated Rotation2d representing no rotation. + * + *

    This exists to avoid allocations for common rotations. + */ + public static final Rotation2d kZero = new Rotation2d(); + + /** + * A preallocated Rotation2d representing a clockwise rotation by π/2 rad (90°). + * + *

    This exists to avoid allocations for common rotations. + */ + public static final Rotation2d kCW_Pi_2 = new Rotation2d(-Math.PI / 2); + + /** + * A preallocated Rotation2d representing a clockwise rotation by 90° (π/2 rad). + * + *

    This exists to avoid allocations for common rotations. + */ + public static final Rotation2d kCW_90deg = kCW_Pi_2; + + /** + * A preallocated Rotation2d representing a counterclockwise rotation by π/2 rad (90°). + * + *

    This exists to avoid allocations for common rotations. + */ + public static final Rotation2d kCCW_Pi_2 = new Rotation2d(Math.PI / 2); + + /** + * A preallocated Rotation2d representing a counterclockwise rotation by 90° (π/2 rad). + * + *

    This exists to avoid allocations for common rotations. + */ + public static final Rotation2d kCCW_90deg = kCCW_Pi_2; + + /** + * A preallocated Rotation2d representing a counterclockwise rotation by π rad (180°). + * + *

    This exists to avoid allocations for common rotations. + */ + public static final Rotation2d kPi = new Rotation2d(Math.PI); + + /** + * A preallocated Rotation2d representing a counterclockwise rotation by 180° (π rad). + * + *

    This exists to avoid allocations for common rotations. + */ + public static final Rotation2d k180deg = kPi; + private final double m_value; private final double m_cos; private final double m_sin; @@ -187,6 +236,15 @@ public Rotation2d rotateBy(Rotation2d other) { m_cos * other.m_cos - m_sin * other.m_sin, m_cos * other.m_sin + m_sin * other.m_cos); } + /** + * Returns the measure of the Rotation2d. + * + * @return The measure of the Rotation2d. + */ + public Measure getMeasure() { + return Radians.of(getRadians()); + } + /** * Returns the radian value of the Rotation2d. * @@ -275,66 +333,9 @@ public Rotation2d interpolate(Rotation2d endValue, double t) { return plus(endValue.minus(this).times(MathUtil.clamp(t, 0, 1))); } - public static final class AStruct implements Struct { - @Override - public Class getTypeClass() { - return Rotation2d.class; - } - - @Override - public String getTypeString() { - return "struct:Rotation2d"; - } - - @Override - public int getSize() { - return kSizeDouble; - } - - @Override - public String getSchema() { - return "double value"; - } - - @Override - public Rotation2d unpack(ByteBuffer bb) { - return new Rotation2d(bb.getDouble()); - } - - @Override - public void pack(ByteBuffer bb, Rotation2d value) { - bb.putDouble(value.m_value); - } - } - - public static final AStruct struct = new AStruct(); - - public static final class AProto implements Protobuf { - @Override - public Class getTypeClass() { - return Rotation2d.class; - } - - @Override - public Descriptor getDescriptor() { - return ProtobufRotation2d.getDescriptor(); - } - - @Override - public ProtobufRotation2d createMessage() { - return ProtobufRotation2d.newInstance(); - } - - @Override - public Rotation2d unpack(ProtobufRotation2d msg) { - return new Rotation2d(msg.getValue()); - } - - @Override - public void pack(ProtobufRotation2d msg, Rotation2d value) { - msg.setValue(value.m_value); - } - } + /** Rotation2d protobuf for serialization. */ + public static final Rotation2dProto proto = new Rotation2dProto(); - public static final AProto proto = new AProto(); + /** Rotation2d struct for serialization. */ + public static final Rotation2dStruct struct = new Rotation2dStruct(); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/Rotation3d.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/Rotation3d.java index 6b7ab6eface..001c648cf09 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/geometry/Rotation3d.java +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/Rotation3d.java @@ -14,23 +14,30 @@ import edu.wpi.first.math.Nat; import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.Vector; +import edu.wpi.first.math.geometry.proto.Rotation3dProto; +import edu.wpi.first.math.geometry.struct.Rotation3dStruct; import edu.wpi.first.math.interpolation.Interpolatable; import edu.wpi.first.math.numbers.N3; -import edu.wpi.first.math.proto.Geometry3D.ProtobufRotation3d; -import edu.wpi.first.util.protobuf.Protobuf; -import edu.wpi.first.util.struct.Struct; -import java.nio.ByteBuffer; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Objects; import org.ejml.dense.row.factory.DecompositionFactory_DDRM; -import us.hebi.quickbuf.Descriptors.Descriptor; /** A rotation in a 3D coordinate frame represented by a quaternion. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) -public class Rotation3d implements Interpolatable { +public class Rotation3d + implements Interpolatable, ProtobufSerializable, StructSerializable { + /** + * A preallocated Rotation3d representing no rotation. + * + *

    This exists to avoid allocations for common rotations. + */ + public static final Rotation3d kZero = new Rotation3d(); + private final Quaternion m_q; - /** Constructs a Rotation3d with a default angle of 0 degrees. */ + /** Constructs a Rotation3d representing no rotation. */ public Rotation3d() { m_q = new Quaternion(); } @@ -120,19 +127,15 @@ public Rotation3d(Matrix rotationMatrix) { // Require that the rotation matrix is special orthogonal. This is true if // the matrix is orthogonal (RRᵀ = I) and normalized (determinant is 1). if (R.times(R.transpose()).minus(Matrix.eye(Nat.N3())).normF() > 1e-9) { - var builder = new StringBuilder("Rotation matrix isn't orthogonal\n\nR =\n"); - builder.append(R.getStorage().toString()).append('\n'); - - var msg = builder.toString(); + var msg = "Rotation matrix isn't orthogonal\n\nR =\n" + R.getStorage().toString() + '\n'; MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace()); throw new IllegalArgumentException(msg); } if (Math.abs(R.det() - 1.0) > 1e-9) { - var builder = - new StringBuilder("Rotation matrix is orthogonal but not special orthogonal\n\nR =\n"); - builder.append(R.getStorage().toString()).append('\n'); - - var msg = builder.toString(); + var msg = + "Rotation matrix is orthogonal but not special orthogonal\n\nR =\n" + + R.getStorage().toString() + + '\n'; MathSharedStore.reportError(msg, Thread.currentThread().getStackTrace()); throw new IllegalArgumentException(msg); } @@ -194,7 +197,6 @@ public Rotation3d(Vector initial, Vector last) { // If the dot product is 1, the two vectors point in the same direction so // there's no rotation. The default initialization of m_q will work. m_q = new Quaternion(); - return; } else if (dotNorm < -1.0 + 1E-9) { // If the dot product is -1, the two vectors point in opposite directions // so a 180 degree rotation is required. Any orthogonal vector can be used @@ -437,76 +439,9 @@ public Rotation3d interpolate(Rotation3d endValue, double t) { return plus(endValue.minus(this).times(MathUtil.clamp(t, 0, 1))); } - public static final class AStruct implements Struct { - @Override - public Class getTypeClass() { - return Rotation3d.class; - } - - @Override - public String getTypeString() { - return "struct:Rotation3d"; - } - - @Override - public int getSize() { - return Quaternion.struct.getSize(); - } - - @Override - public String getSchema() { - return "Quaternion q"; - } - - @Override - public Struct[] getNested() { - return new Struct[] {Quaternion.struct}; - } - - @Override - public Rotation3d unpack(ByteBuffer bb) { - return new Rotation3d(Quaternion.struct.unpack(bb)); - } - - @Override - public void pack(ByteBuffer bb, Rotation3d value) { - Quaternion.struct.pack(bb, value.m_q); - } - } - - public static final AStruct struct = new AStruct(); - - public static final class AProto implements Protobuf { - @Override - public Class getTypeClass() { - return Rotation3d.class; - } - - @Override - public Descriptor getDescriptor() { - return ProtobufRotation3d.getDescriptor(); - } - - @Override - public Protobuf[] getNested() { - return new Protobuf[] {Quaternion.proto}; - } - - @Override - public ProtobufRotation3d createMessage() { - return ProtobufRotation3d.newInstance(); - } - - @Override - public Rotation3d unpack(ProtobufRotation3d msg) { - return new Rotation3d(Quaternion.proto.unpack(msg.getQ())); - } - - @Override - public void pack(ProtobufRotation3d msg, Rotation3d value) { - Quaternion.proto.pack(msg.getMutableQ(), value.m_q); - } - } + /** Rotation3d protobuf for serialization. */ + public static final Rotation3dProto proto = new Rotation3dProto(); - public static final AProto proto = new AProto(); + /** Rotation3d struct for serialization. */ + public static final Rotation3dStruct struct = new Rotation3dStruct(); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/Transform2d.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/Transform2d.java index ea39127b5cf..8667f6d6e6d 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/geometry/Transform2d.java +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/Transform2d.java @@ -6,17 +6,23 @@ import static edu.wpi.first.units.Units.Meters; -import edu.wpi.first.math.proto.Geometry2D.ProtobufTransform2d; +import edu.wpi.first.math.geometry.proto.Transform2dProto; +import edu.wpi.first.math.geometry.struct.Transform2dStruct; import edu.wpi.first.units.Distance; import edu.wpi.first.units.Measure; -import edu.wpi.first.util.protobuf.Protobuf; -import edu.wpi.first.util.struct.Struct; -import java.nio.ByteBuffer; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Objects; -import us.hebi.quickbuf.Descriptors.Descriptor; /** Represents a transformation for a Pose2d in the pose's frame. */ -public class Transform2d { +public class Transform2d implements ProtobufSerializable, StructSerializable { + /** + * A preallocated Transform2d representing no transformation. + * + *

    This exists to avoid allocations for common transformations. + */ + public static final Transform2d kZero = new Transform2d(); + private final Translation2d m_translation; private final Rotation2d m_rotation; @@ -75,8 +81,8 @@ public Transform2d(Measure x, Measure y, Rotation2d rotation /** Constructs the identity transform -- maps an initial pose to itself. */ public Transform2d() { - m_translation = new Translation2d(); - m_rotation = new Rotation2d(); + m_translation = Translation2d.kZero; + m_rotation = Rotation2d.kZero; } /** @@ -107,7 +113,7 @@ public Transform2d div(double scalar) { * @return The composition of the two transformations. */ public Transform2d plus(Transform2d other) { - return new Transform2d(new Pose2d(), new Pose2d().transformBy(this).transformBy(other)); + return new Transform2d(Pose2d.kZero, Pose2d.kZero.transformBy(this).transformBy(other)); } /** @@ -185,82 +191,9 @@ public int hashCode() { return Objects.hash(m_translation, m_rotation); } - public static final class AStruct implements Struct { - @Override - public Class getTypeClass() { - return Transform2d.class; - } - - @Override - public String getTypeString() { - return "struct:Transform2d"; - } - - @Override - public int getSize() { - return Translation2d.struct.getSize() + Rotation2d.struct.getSize(); - } - - @Override - public String getSchema() { - return "Translation2d translation;Rotation2d rotation"; - } - - @Override - public Struct[] getNested() { - return new Struct[] {Translation2d.struct, Rotation2d.struct}; - } - - @Override - public Transform2d unpack(ByteBuffer bb) { - Translation2d translation = Translation2d.struct.unpack(bb); - Rotation2d rotation = Rotation2d.struct.unpack(bb); - return new Transform2d(translation, rotation); - } - - @Override - public void pack(ByteBuffer bb, Transform2d value) { - Translation2d.struct.pack(bb, value.m_translation); - Rotation2d.struct.pack(bb, value.m_rotation); - } - } - - public static final AStruct struct = new AStruct(); - - public static final class AProto implements Protobuf { - @Override - public Class getTypeClass() { - return Transform2d.class; - } - - @Override - public Descriptor getDescriptor() { - return ProtobufTransform2d.getDescriptor(); - } - - @Override - public Protobuf[] getNested() { - return new Protobuf[] {Translation2d.proto, Rotation2d.proto}; - } - - @Override - public ProtobufTransform2d createMessage() { - return ProtobufTransform2d.newInstance(); - } - - @Override - public Transform2d unpack(ProtobufTransform2d msg) { - return new Transform2d( - Translation2d.proto.unpack(msg.getTranslation()), - Rotation2d.proto.unpack(msg.getRotation())); - } - - @Override - public void pack(ProtobufTransform2d msg, Transform2d value) { - Translation2d.proto.pack(msg.getMutableTranslation(), value.m_translation); - Rotation2d.proto.pack(msg.getMutableRotation(), value.m_rotation); - } - } + /** Transform2d protobuf for serialization. */ + public static final Transform2dProto proto = new Transform2dProto(); - public static final AProto proto = new AProto(); + /** Transform2d struct for serialization. */ + public static final Transform2dStruct struct = new Transform2dStruct(); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/Transform3d.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/Transform3d.java index 223a14b18f6..2f986ff29d4 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/geometry/Transform3d.java +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/Transform3d.java @@ -4,15 +4,21 @@ package edu.wpi.first.math.geometry; -import edu.wpi.first.math.proto.Geometry3D.ProtobufTransform3d; -import edu.wpi.first.util.protobuf.Protobuf; -import edu.wpi.first.util.struct.Struct; -import java.nio.ByteBuffer; +import edu.wpi.first.math.geometry.proto.Transform3dProto; +import edu.wpi.first.math.geometry.struct.Transform3dStruct; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Objects; -import us.hebi.quickbuf.Descriptors.Descriptor; /** Represents a transformation for a Pose3d in the pose's frame. */ -public class Transform3d { +public class Transform3d implements ProtobufSerializable, StructSerializable { + /** + * A preallocated Transform3d representing no transformation. + * + *

    This exists to avoid allocations for common transformations. + */ + public static final Transform3d kZero = new Transform3d(); + private final Translation3d m_translation; private final Rotation3d m_rotation; @@ -60,8 +66,8 @@ public Transform3d(double x, double y, double z, Rotation3d rotation) { /** Constructs the identity transform -- maps an initial pose to itself. */ public Transform3d() { - m_translation = new Translation3d(); - m_rotation = new Rotation3d(); + m_translation = Translation3d.kZero; + m_rotation = Rotation3d.kZero; } /** @@ -92,7 +98,7 @@ public Transform3d div(double scalar) { * @return The composition of the two transformations. */ public Transform3d plus(Transform3d other) { - return new Transform3d(new Pose3d(), new Pose3d().transformBy(this).transformBy(other)); + return new Transform3d(Pose3d.kZero, Pose3d.kZero.transformBy(this).transformBy(other)); } /** @@ -179,82 +185,9 @@ public int hashCode() { return Objects.hash(m_translation, m_rotation); } - public static final class AStruct implements Struct { - @Override - public Class getTypeClass() { - return Transform3d.class; - } - - @Override - public String getTypeString() { - return "struct:Transform3d"; - } - - @Override - public int getSize() { - return Translation3d.struct.getSize() + Rotation3d.struct.getSize(); - } - - @Override - public String getSchema() { - return "Translation3d translation;Rotation3d rotation"; - } - - @Override - public Struct[] getNested() { - return new Struct[] {Translation3d.struct, Rotation3d.struct}; - } - - @Override - public Transform3d unpack(ByteBuffer bb) { - Translation3d translation = Translation3d.struct.unpack(bb); - Rotation3d rotation = Rotation3d.struct.unpack(bb); - return new Transform3d(translation, rotation); - } - - @Override - public void pack(ByteBuffer bb, Transform3d value) { - Translation3d.struct.pack(bb, value.m_translation); - Rotation3d.struct.pack(bb, value.m_rotation); - } - } - - public static final AStruct struct = new AStruct(); - - public static final class AProto implements Protobuf { - @Override - public Class getTypeClass() { - return Transform3d.class; - } - - @Override - public Descriptor getDescriptor() { - return ProtobufTransform3d.getDescriptor(); - } - - @Override - public Protobuf[] getNested() { - return new Protobuf[] {Translation3d.proto, Rotation3d.proto}; - } - - @Override - public ProtobufTransform3d createMessage() { - return ProtobufTransform3d.newInstance(); - } - - @Override - public Transform3d unpack(ProtobufTransform3d msg) { - return new Transform3d( - Translation3d.proto.unpack(msg.getTranslation()), - Rotation3d.proto.unpack(msg.getRotation())); - } - - @Override - public void pack(ProtobufTransform3d msg, Transform3d value) { - Translation3d.proto.pack(msg.getMutableTranslation(), value.m_translation); - Rotation3d.proto.pack(msg.getMutableRotation(), value.m_rotation); - } - } + /** Transform3d protobuf for serialization. */ + public static final Transform3dProto proto = new Transform3dProto(); - public static final AProto proto = new AProto(); + /** Transform3d struct for serialization. */ + public static final Transform3dStruct struct = new Transform3dStruct(); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/Translation2d.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/Translation2d.java index ebfce320458..d0357e80aea 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/geometry/Translation2d.java +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/Translation2d.java @@ -11,18 +11,20 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import edu.wpi.first.math.MathUtil; +import edu.wpi.first.math.VecBuilder; +import edu.wpi.first.math.Vector; +import edu.wpi.first.math.geometry.proto.Translation2dProto; +import edu.wpi.first.math.geometry.struct.Translation2dStruct; import edu.wpi.first.math.interpolation.Interpolatable; -import edu.wpi.first.math.proto.Geometry2D.ProtobufTranslation2d; +import edu.wpi.first.math.numbers.N2; import edu.wpi.first.units.Distance; import edu.wpi.first.units.Measure; -import edu.wpi.first.util.protobuf.Protobuf; -import edu.wpi.first.util.struct.Struct; -import java.nio.ByteBuffer; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; -import us.hebi.quickbuf.Descriptors.Descriptor; /** * Represents a translation in 2D space. This object can be used to represent a point or a vector. @@ -32,7 +34,15 @@ */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) -public class Translation2d implements Interpolatable { +public class Translation2d + implements Interpolatable, ProtobufSerializable, StructSerializable { + /** + * A preallocated Translation2d representing the origin. + * + *

    This exists to avoid allocations for common translations. + */ + public static final Translation2d kZero = new Translation2d(); + private final double m_x; private final double m_y; @@ -78,6 +88,16 @@ public Translation2d(Measure x, Measure y) { this(x.in(Meters), y.in(Meters)); } + /** + * Constructs a Translation2d from the provided translation vector's X and Y components. The + * values are assumed to be in meters. + * + * @param vector The translation vector to represent. + */ + public Translation2d(Vector vector) { + this(vector.get(0), vector.get(1)); + } + /** * Calculates the distance between two translations in 2D space. * @@ -110,6 +130,15 @@ public double getY() { return m_y; } + /** + * Returns a vector representation of this translation. + * + * @return A Vector representation of this translation. + */ + public Vector toVector() { + return VecBuilder.fill(m_x, m_y); + } + /** * Returns the norm, or distance from the origin to the translation. * @@ -250,69 +279,9 @@ public Translation2d interpolate(Translation2d endValue, double t) { MathUtil.interpolate(this.getY(), endValue.getY(), t)); } - public static final class AStruct implements Struct { - @Override - public Class getTypeClass() { - return Translation2d.class; - } - - @Override - public String getTypeString() { - return "struct:Translation2d"; - } - - @Override - public int getSize() { - return kSizeDouble * 2; - } - - @Override - public String getSchema() { - return "double x;double y"; - } - - @Override - public Translation2d unpack(ByteBuffer bb) { - double x = bb.getDouble(); - double y = bb.getDouble(); - return new Translation2d(x, y); - } - - @Override - public void pack(ByteBuffer bb, Translation2d value) { - bb.putDouble(value.m_x); - bb.putDouble(value.m_y); - } - } - - public static final AStruct struct = new AStruct(); - - public static final class AProto implements Protobuf { - @Override - public Class getTypeClass() { - return Translation2d.class; - } - - @Override - public Descriptor getDescriptor() { - return ProtobufTranslation2d.getDescriptor(); - } - - @Override - public ProtobufTranslation2d createMessage() { - return ProtobufTranslation2d.newInstance(); - } - - @Override - public Translation2d unpack(ProtobufTranslation2d msg) { - return new Translation2d(msg.getX(), msg.getY()); - } - - @Override - public void pack(ProtobufTranslation2d msg, Translation2d value) { - msg.setX(value.m_x).setY(value.m_y); - } - } + /** Translation2d protobuf for serialization. */ + public static final Translation2dProto proto = new Translation2dProto(); - public static final AProto proto = new AProto(); + /** Translation2d struct for serialization. */ + public static final Translation2dStruct struct = new Translation2dStruct(); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/Translation3d.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/Translation3d.java index 7b690dfedf9..ba8c699dc45 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/geometry/Translation3d.java +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/Translation3d.java @@ -11,15 +11,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import edu.wpi.first.math.MathUtil; +import edu.wpi.first.math.VecBuilder; +import edu.wpi.first.math.Vector; +import edu.wpi.first.math.geometry.proto.Translation3dProto; +import edu.wpi.first.math.geometry.struct.Translation3dStruct; import edu.wpi.first.math.interpolation.Interpolatable; -import edu.wpi.first.math.proto.Geometry3D.ProtobufTranslation3d; +import edu.wpi.first.math.numbers.N3; import edu.wpi.first.units.Distance; import edu.wpi.first.units.Measure; -import edu.wpi.first.util.protobuf.Protobuf; -import edu.wpi.first.util.struct.Struct; -import java.nio.ByteBuffer; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Objects; -import us.hebi.quickbuf.Descriptors.Descriptor; /** * Represents a translation in 3D space. This object can be used to represent a point or a vector. @@ -30,7 +32,15 @@ */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) -public class Translation3d implements Interpolatable { +public class Translation3d + implements Interpolatable, ProtobufSerializable, StructSerializable { + /** + * A preallocated Translation3d representing the origin. + * + *

    This exists to avoid allocations for common translations. + */ + public static final Translation3d kZero = new Translation3d(); + private final double m_x; private final double m_y; private final double m_z; @@ -83,6 +93,16 @@ public Translation3d(Measure x, Measure y, Measure this(x.in(Meters), y.in(Meters), z.in(Meters)); } + /** + * Constructs a Translation3d from the provided translation vector's X, Y, and Z components. The + * values are assumed to be in meters. + * + * @param vector The translation vector to represent. + */ + public Translation3d(Vector vector) { + this(vector.get(0), vector.get(1), vector.get(2)); + } + /** * Calculates the distance between two translations in 3D space. * @@ -126,6 +146,15 @@ public double getZ() { return m_z; } + /** + * Returns a vector representation of this translation. + * + * @return A Vector representation of this translation. + */ + public Vector toVector() { + return VecBuilder.fill(m_x, m_y, m_z); + } + /** * Returns the norm, or distance from the origin to the translation. * @@ -253,71 +282,9 @@ public Translation3d interpolate(Translation3d endValue, double t) { MathUtil.interpolate(this.getZ(), endValue.getZ(), t)); } - public static final class AStruct implements Struct { - @Override - public Class getTypeClass() { - return Translation3d.class; - } - - @Override - public String getTypeString() { - return "struct:Translation3d"; - } - - @Override - public int getSize() { - return kSizeDouble * 3; - } - - @Override - public String getSchema() { - return "double x;double y;double z"; - } - - @Override - public Translation3d unpack(ByteBuffer bb) { - double x = bb.getDouble(); - double y = bb.getDouble(); - double z = bb.getDouble(); - return new Translation3d(x, y, z); - } - - @Override - public void pack(ByteBuffer bb, Translation3d value) { - bb.putDouble(value.m_x); - bb.putDouble(value.m_y); - bb.putDouble(value.m_z); - } - } - - public static final AStruct struct = new AStruct(); - - public static final class AProto implements Protobuf { - @Override - public Class getTypeClass() { - return Translation3d.class; - } - - @Override - public Descriptor getDescriptor() { - return ProtobufTranslation3d.getDescriptor(); - } - - @Override - public ProtobufTranslation3d createMessage() { - return ProtobufTranslation3d.newInstance(); - } - - @Override - public Translation3d unpack(ProtobufTranslation3d msg) { - return new Translation3d(msg.getX(), msg.getY(), msg.getZ()); - } - - @Override - public void pack(ProtobufTranslation3d msg, Translation3d value) { - msg.setX(value.m_x).setY(value.m_y).setZ(value.m_z); - } - } + /** Translation3d protobuf for serialization. */ + public static final Translation3dProto proto = new Translation3dProto(); - public static final AProto proto = new AProto(); + /** Translation3d struct for serialization. */ + public static final Translation3dStruct struct = new Translation3dStruct(); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/Twist2d.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/Twist2d.java index a4ae9f83ac9..53ab6ba9c2a 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/geometry/Twist2d.java +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/Twist2d.java @@ -4,12 +4,11 @@ package edu.wpi.first.math.geometry; -import edu.wpi.first.math.proto.Geometry2D.ProtobufTwist2d; -import edu.wpi.first.util.protobuf.Protobuf; -import edu.wpi.first.util.struct.Struct; -import java.nio.ByteBuffer; +import edu.wpi.first.math.geometry.proto.Twist2dProto; +import edu.wpi.first.math.geometry.struct.Twist2dStruct; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Objects; -import us.hebi.quickbuf.Descriptors.Descriptor; /** * A change in distance along a 2D arc since the last pose update. We can use ideas from @@ -17,7 +16,7 @@ * *

    A Twist can be used to represent a difference between two poses. */ -public class Twist2d { +public class Twist2d implements ProtobufSerializable, StructSerializable { /** Linear "dx" component. */ public double dx; @@ -27,6 +26,7 @@ public class Twist2d { /** Angular "dtheta" component (radians). */ public double dtheta; + /** Default constructor. */ public Twist2d() {} /** @@ -68,71 +68,9 @@ public int hashCode() { return Objects.hash(dx, dy, dtheta); } - public static final class AStruct implements Struct { - @Override - public Class getTypeClass() { - return Twist2d.class; - } - - @Override - public String getTypeString() { - return "struct:Twist2d"; - } - - @Override - public int getSize() { - return kSizeDouble * 3; - } - - @Override - public String getSchema() { - return "double dx;double dy;double dtheta"; - } - - @Override - public Twist2d unpack(ByteBuffer bb) { - double dx = bb.getDouble(); - double dy = bb.getDouble(); - double dtheta = bb.getDouble(); - return new Twist2d(dx, dy, dtheta); - } - - @Override - public void pack(ByteBuffer bb, Twist2d value) { - bb.putDouble(value.dx); - bb.putDouble(value.dy); - bb.putDouble(value.dtheta); - } - } - - public static final AStruct struct = new AStruct(); - - public static final class AProto implements Protobuf { - @Override - public Class getTypeClass() { - return Twist2d.class; - } - - @Override - public Descriptor getDescriptor() { - return ProtobufTwist2d.getDescriptor(); - } - - @Override - public ProtobufTwist2d createMessage() { - return ProtobufTwist2d.newInstance(); - } - - @Override - public Twist2d unpack(ProtobufTwist2d msg) { - return new Twist2d(msg.getDx(), msg.getDy(), msg.getDtheta()); - } - - @Override - public void pack(ProtobufTwist2d msg, Twist2d value) { - msg.setDx(value.dx).setDy(value.dy).setDtheta(value.dtheta); - } - } + /** Twist2d protobuf for serialization. */ + public static final Twist2dProto proto = new Twist2dProto(); - public static final AProto proto = new AProto(); + /** Twist2d struct for serialization. */ + public static final Twist2dStruct struct = new Twist2dStruct(); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/Twist3d.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/Twist3d.java index d08d5cf158a..80786029efd 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/geometry/Twist3d.java +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/Twist3d.java @@ -4,12 +4,11 @@ package edu.wpi.first.math.geometry; -import edu.wpi.first.math.proto.Geometry3D.ProtobufTwist3d; -import edu.wpi.first.util.protobuf.Protobuf; -import edu.wpi.first.util.struct.Struct; -import java.nio.ByteBuffer; +import edu.wpi.first.math.geometry.proto.Twist3dProto; +import edu.wpi.first.math.geometry.struct.Twist3dStruct; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Objects; -import us.hebi.quickbuf.Descriptors.Descriptor; /** * A change in distance along a 3D arc since the last pose update. We can use ideas from @@ -17,7 +16,7 @@ * *

    A Twist can be used to represent a difference between two poses. */ -public class Twist3d { +public class Twist3d implements ProtobufSerializable, StructSerializable { /** Linear "dx" component. */ public double dx; @@ -36,6 +35,7 @@ public class Twist3d { /** Rotation vector z component (radians). */ public double rz; + /** Default constructor. */ public Twist3d() {} /** @@ -88,83 +88,9 @@ public int hashCode() { return Objects.hash(dx, dy, dz, rx, ry, rz); } - public static final class AStruct implements Struct { - @Override - public Class getTypeClass() { - return Twist3d.class; - } - - @Override - public String getTypeString() { - return "struct:Twist3d"; - } - - @Override - public int getSize() { - return kSizeDouble * 6; - } - - @Override - public String getSchema() { - return "double dx;double dy;double dz;double rx;double ry;double rz"; - } - - @Override - public Twist3d unpack(ByteBuffer bb) { - double dx = bb.getDouble(); - double dy = bb.getDouble(); - double dz = bb.getDouble(); - double rx = bb.getDouble(); - double ry = bb.getDouble(); - double rz = bb.getDouble(); - return new Twist3d(dx, dy, dz, rx, ry, rz); - } - - @Override - public void pack(ByteBuffer bb, Twist3d value) { - bb.putDouble(value.dx); - bb.putDouble(value.dy); - bb.putDouble(value.dz); - bb.putDouble(value.rx); - bb.putDouble(value.ry); - bb.putDouble(value.rz); - } - } - - public static final AStruct struct = new AStruct(); - - public static final class AProto implements Protobuf { - @Override - public Class getTypeClass() { - return Twist3d.class; - } - - @Override - public Descriptor getDescriptor() { - return ProtobufTwist3d.getDescriptor(); - } - - @Override - public ProtobufTwist3d createMessage() { - return ProtobufTwist3d.newInstance(); - } - - @Override - public Twist3d unpack(ProtobufTwist3d msg) { - return new Twist3d( - msg.getDx(), msg.getDy(), msg.getDz(), msg.getRx(), msg.getRy(), msg.getRz()); - } - - @Override - public void pack(ProtobufTwist3d msg, Twist3d value) { - msg.setDx(value.dx) - .setDy(value.dy) - .setDz(value.dz) - .setRx(value.rx) - .setRy(value.ry) - .setRz(value.rz); - } - } + /** Twist3d protobuf for serialization. */ + public static final Twist3dProto proto = new Twist3dProto(); - public static final AProto proto = new AProto(); + /** Twist3d struct for serialization. */ + public static final Twist3dStruct struct = new Twist3dStruct(); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Pose2dProto.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Pose2dProto.java new file mode 100644 index 00000000000..7921100d6e7 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Pose2dProto.java @@ -0,0 +1,47 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.proto; + +import edu.wpi.first.math.geometry.Pose2d; +import edu.wpi.first.math.geometry.Rotation2d; +import edu.wpi.first.math.geometry.Translation2d; +import edu.wpi.first.math.proto.Geometry2D.ProtobufPose2d; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class Pose2dProto implements Protobuf { + @Override + public Class getTypeClass() { + return Pose2d.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufPose2d.getDescriptor(); + } + + @Override + public Protobuf[] getNested() { + return new Protobuf[] {Translation2d.proto, Rotation2d.proto}; + } + + @Override + public ProtobufPose2d createMessage() { + return ProtobufPose2d.newInstance(); + } + + @Override + public Pose2d unpack(ProtobufPose2d msg) { + return new Pose2d( + Translation2d.proto.unpack(msg.getTranslation()), + Rotation2d.proto.unpack(msg.getRotation())); + } + + @Override + public void pack(ProtobufPose2d msg, Pose2d value) { + Translation2d.proto.pack(msg.getMutableTranslation(), value.getTranslation()); + Rotation2d.proto.pack(msg.getMutableRotation(), value.getRotation()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Pose3dProto.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Pose3dProto.java new file mode 100644 index 00000000000..69d6ba29264 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Pose3dProto.java @@ -0,0 +1,47 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.proto; + +import edu.wpi.first.math.geometry.Pose3d; +import edu.wpi.first.math.geometry.Rotation3d; +import edu.wpi.first.math.geometry.Translation3d; +import edu.wpi.first.math.proto.Geometry3D.ProtobufPose3d; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class Pose3dProto implements Protobuf { + @Override + public Class getTypeClass() { + return Pose3d.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufPose3d.getDescriptor(); + } + + @Override + public Protobuf[] getNested() { + return new Protobuf[] {Translation3d.proto, Rotation3d.proto}; + } + + @Override + public ProtobufPose3d createMessage() { + return ProtobufPose3d.newInstance(); + } + + @Override + public Pose3d unpack(ProtobufPose3d msg) { + return new Pose3d( + Translation3d.proto.unpack(msg.getTranslation()), + Rotation3d.proto.unpack(msg.getRotation())); + } + + @Override + public void pack(ProtobufPose3d msg, Pose3d value) { + Translation3d.proto.pack(msg.getMutableTranslation(), value.getTranslation()); + Rotation3d.proto.pack(msg.getMutableRotation(), value.getRotation()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/QuaternionProto.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/QuaternionProto.java new file mode 100644 index 00000000000..c464ba270c7 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/QuaternionProto.java @@ -0,0 +1,40 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.proto; + +import edu.wpi.first.math.geometry.Quaternion; +import edu.wpi.first.math.proto.Geometry3D.ProtobufQuaternion; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class QuaternionProto implements Protobuf { + @Override + public Class getTypeClass() { + return Quaternion.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufQuaternion.getDescriptor(); + } + + @Override + public ProtobufQuaternion createMessage() { + return ProtobufQuaternion.newInstance(); + } + + @Override + public Quaternion unpack(ProtobufQuaternion msg) { + return new Quaternion(msg.getW(), msg.getX(), msg.getY(), msg.getZ()); + } + + @Override + public void pack(ProtobufQuaternion msg, Quaternion value) { + msg.setW(value.getW()); + msg.setX(value.getX()); + msg.setY(value.getY()); + msg.setZ(value.getZ()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Rotation2dProto.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Rotation2dProto.java new file mode 100644 index 00000000000..98ad5c7bcfe --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Rotation2dProto.java @@ -0,0 +1,37 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.proto; + +import edu.wpi.first.math.geometry.Rotation2d; +import edu.wpi.first.math.proto.Geometry2D.ProtobufRotation2d; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class Rotation2dProto implements Protobuf { + @Override + public Class getTypeClass() { + return Rotation2d.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufRotation2d.getDescriptor(); + } + + @Override + public ProtobufRotation2d createMessage() { + return ProtobufRotation2d.newInstance(); + } + + @Override + public Rotation2d unpack(ProtobufRotation2d msg) { + return new Rotation2d(msg.getValue()); + } + + @Override + public void pack(ProtobufRotation2d msg, Rotation2d value) { + msg.setValue(value.getRadians()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Rotation3dProto.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Rotation3dProto.java new file mode 100644 index 00000000000..9c9b01a93b4 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Rotation3dProto.java @@ -0,0 +1,43 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.proto; + +import edu.wpi.first.math.geometry.Quaternion; +import edu.wpi.first.math.geometry.Rotation3d; +import edu.wpi.first.math.proto.Geometry3D.ProtobufRotation3d; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class Rotation3dProto implements Protobuf { + @Override + public Class getTypeClass() { + return Rotation3d.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufRotation3d.getDescriptor(); + } + + @Override + public Protobuf[] getNested() { + return new Protobuf[] {Quaternion.proto}; + } + + @Override + public ProtobufRotation3d createMessage() { + return ProtobufRotation3d.newInstance(); + } + + @Override + public Rotation3d unpack(ProtobufRotation3d msg) { + return new Rotation3d(Quaternion.proto.unpack(msg.getQ())); + } + + @Override + public void pack(ProtobufRotation3d msg, Rotation3d value) { + Quaternion.proto.pack(msg.getMutableQ(), value.getQuaternion()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Transform2dProto.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Transform2dProto.java new file mode 100644 index 00000000000..ecc05287cf6 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Transform2dProto.java @@ -0,0 +1,47 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.proto; + +import edu.wpi.first.math.geometry.Rotation2d; +import edu.wpi.first.math.geometry.Transform2d; +import edu.wpi.first.math.geometry.Translation2d; +import edu.wpi.first.math.proto.Geometry2D.ProtobufTransform2d; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class Transform2dProto implements Protobuf { + @Override + public Class getTypeClass() { + return Transform2d.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufTransform2d.getDescriptor(); + } + + @Override + public Protobuf[] getNested() { + return new Protobuf[] {Translation2d.proto, Rotation2d.proto}; + } + + @Override + public ProtobufTransform2d createMessage() { + return ProtobufTransform2d.newInstance(); + } + + @Override + public Transform2d unpack(ProtobufTransform2d msg) { + return new Transform2d( + Translation2d.proto.unpack(msg.getTranslation()), + Rotation2d.proto.unpack(msg.getRotation())); + } + + @Override + public void pack(ProtobufTransform2d msg, Transform2d value) { + Translation2d.proto.pack(msg.getMutableTranslation(), value.getTranslation()); + Rotation2d.proto.pack(msg.getMutableRotation(), value.getRotation()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Transform3dProto.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Transform3dProto.java new file mode 100644 index 00000000000..29ea793e600 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Transform3dProto.java @@ -0,0 +1,47 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.proto; + +import edu.wpi.first.math.geometry.Rotation3d; +import edu.wpi.first.math.geometry.Transform3d; +import edu.wpi.first.math.geometry.Translation3d; +import edu.wpi.first.math.proto.Geometry3D.ProtobufTransform3d; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class Transform3dProto implements Protobuf { + @Override + public Class getTypeClass() { + return Transform3d.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufTransform3d.getDescriptor(); + } + + @Override + public Protobuf[] getNested() { + return new Protobuf[] {Translation3d.proto, Rotation3d.proto}; + } + + @Override + public ProtobufTransform3d createMessage() { + return ProtobufTransform3d.newInstance(); + } + + @Override + public Transform3d unpack(ProtobufTransform3d msg) { + return new Transform3d( + Translation3d.proto.unpack(msg.getTranslation()), + Rotation3d.proto.unpack(msg.getRotation())); + } + + @Override + public void pack(ProtobufTransform3d msg, Transform3d value) { + Translation3d.proto.pack(msg.getMutableTranslation(), value.getTranslation()); + Rotation3d.proto.pack(msg.getMutableRotation(), value.getRotation()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Translation2dProto.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Translation2dProto.java new file mode 100644 index 00000000000..a63fec35bdd --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Translation2dProto.java @@ -0,0 +1,38 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.proto; + +import edu.wpi.first.math.geometry.Translation2d; +import edu.wpi.first.math.proto.Geometry2D.ProtobufTranslation2d; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class Translation2dProto implements Protobuf { + @Override + public Class getTypeClass() { + return Translation2d.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufTranslation2d.getDescriptor(); + } + + @Override + public ProtobufTranslation2d createMessage() { + return ProtobufTranslation2d.newInstance(); + } + + @Override + public Translation2d unpack(ProtobufTranslation2d msg) { + return new Translation2d(msg.getX(), msg.getY()); + } + + @Override + public void pack(ProtobufTranslation2d msg, Translation2d value) { + msg.setX(value.getX()); + msg.setY(value.getY()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Translation3dProto.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Translation3dProto.java new file mode 100644 index 00000000000..b854a343f5e --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Translation3dProto.java @@ -0,0 +1,39 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.proto; + +import edu.wpi.first.math.geometry.Translation3d; +import edu.wpi.first.math.proto.Geometry3D.ProtobufTranslation3d; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class Translation3dProto implements Protobuf { + @Override + public Class getTypeClass() { + return Translation3d.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufTranslation3d.getDescriptor(); + } + + @Override + public ProtobufTranslation3d createMessage() { + return ProtobufTranslation3d.newInstance(); + } + + @Override + public Translation3d unpack(ProtobufTranslation3d msg) { + return new Translation3d(msg.getX(), msg.getY(), msg.getZ()); + } + + @Override + public void pack(ProtobufTranslation3d msg, Translation3d value) { + msg.setX(value.getX()); + msg.setY(value.getY()); + msg.setZ(value.getZ()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Twist2dProto.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Twist2dProto.java new file mode 100644 index 00000000000..bc9da6b3418 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Twist2dProto.java @@ -0,0 +1,39 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.proto; + +import edu.wpi.first.math.geometry.Twist2d; +import edu.wpi.first.math.proto.Geometry2D.ProtobufTwist2d; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class Twist2dProto implements Protobuf { + @Override + public Class getTypeClass() { + return Twist2d.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufTwist2d.getDescriptor(); + } + + @Override + public ProtobufTwist2d createMessage() { + return ProtobufTwist2d.newInstance(); + } + + @Override + public Twist2d unpack(ProtobufTwist2d msg) { + return new Twist2d(msg.getDx(), msg.getDy(), msg.getDtheta()); + } + + @Override + public void pack(ProtobufTwist2d msg, Twist2d value) { + msg.setDx(value.dx); + msg.setDy(value.dy); + msg.setDtheta(value.dtheta); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Twist3dProto.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Twist3dProto.java new file mode 100644 index 00000000000..356c18f7a18 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/proto/Twist3dProto.java @@ -0,0 +1,43 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.proto; + +import edu.wpi.first.math.geometry.Twist3d; +import edu.wpi.first.math.proto.Geometry3D.ProtobufTwist3d; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class Twist3dProto implements Protobuf { + @Override + public Class getTypeClass() { + return Twist3d.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufTwist3d.getDescriptor(); + } + + @Override + public ProtobufTwist3d createMessage() { + return ProtobufTwist3d.newInstance(); + } + + @Override + public Twist3d unpack(ProtobufTwist3d msg) { + return new Twist3d( + msg.getDx(), msg.getDy(), msg.getDz(), msg.getRx(), msg.getRy(), msg.getRz()); + } + + @Override + public void pack(ProtobufTwist3d msg, Twist3d value) { + msg.setDx(value.dx); + msg.setDy(value.dy); + msg.setDz(value.dz); + msg.setRx(value.rx); + msg.setRy(value.ry); + msg.setRz(value.rz); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Pose2dStruct.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Pose2dStruct.java new file mode 100644 index 00000000000..8435354db50 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Pose2dStruct.java @@ -0,0 +1,51 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.struct; + +import edu.wpi.first.math.geometry.Pose2d; +import edu.wpi.first.math.geometry.Rotation2d; +import edu.wpi.first.math.geometry.Translation2d; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class Pose2dStruct implements Struct { + @Override + public Class getTypeClass() { + return Pose2d.class; + } + + @Override + public String getTypeString() { + return "struct:Pose2d"; + } + + @Override + public int getSize() { + return Translation2d.struct.getSize() + Rotation2d.struct.getSize(); + } + + @Override + public String getSchema() { + return "Translation2d translation;Rotation2d rotation"; + } + + @Override + public Struct[] getNested() { + return new Struct[] {Translation2d.struct, Rotation2d.struct}; + } + + @Override + public Pose2d unpack(ByteBuffer bb) { + Translation2d translation = Translation2d.struct.unpack(bb); + Rotation2d rotation = Rotation2d.struct.unpack(bb); + return new Pose2d(translation, rotation); + } + + @Override + public void pack(ByteBuffer bb, Pose2d value) { + Translation2d.struct.pack(bb, value.getTranslation()); + Rotation2d.struct.pack(bb, value.getRotation()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Pose3dStruct.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Pose3dStruct.java new file mode 100644 index 00000000000..db380f6f904 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Pose3dStruct.java @@ -0,0 +1,51 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.struct; + +import edu.wpi.first.math.geometry.Pose3d; +import edu.wpi.first.math.geometry.Rotation3d; +import edu.wpi.first.math.geometry.Translation3d; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class Pose3dStruct implements Struct { + @Override + public Class getTypeClass() { + return Pose3d.class; + } + + @Override + public String getTypeString() { + return "struct:Pose3d"; + } + + @Override + public int getSize() { + return Translation3d.struct.getSize() + Rotation3d.struct.getSize(); + } + + @Override + public String getSchema() { + return "Translation3d translation;Rotation3d rotation"; + } + + @Override + public Struct[] getNested() { + return new Struct[] {Translation3d.struct, Rotation3d.struct}; + } + + @Override + public Pose3d unpack(ByteBuffer bb) { + Translation3d translation = Translation3d.struct.unpack(bb); + Rotation3d rotation = Rotation3d.struct.unpack(bb); + return new Pose3d(translation, rotation); + } + + @Override + public void pack(ByteBuffer bb, Pose3d value) { + Translation3d.struct.pack(bb, value.getTranslation()); + Rotation3d.struct.pack(bb, value.getRotation()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/QuaternionStruct.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/QuaternionStruct.java new file mode 100644 index 00000000000..fec8452b0ef --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/QuaternionStruct.java @@ -0,0 +1,48 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.struct; + +import edu.wpi.first.math.geometry.Quaternion; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class QuaternionStruct implements Struct { + @Override + public Class getTypeClass() { + return Quaternion.class; + } + + @Override + public String getTypeString() { + return "struct:Quaternion"; + } + + @Override + public int getSize() { + return kSizeDouble * 4; + } + + @Override + public String getSchema() { + return "double w;double x;double y;double z"; + } + + @Override + public Quaternion unpack(ByteBuffer bb) { + double w = bb.getDouble(); + double x = bb.getDouble(); + double y = bb.getDouble(); + double z = bb.getDouble(); + return new Quaternion(w, x, y, z); + } + + @Override + public void pack(ByteBuffer bb, Quaternion value) { + bb.putDouble(value.getW()); + bb.putDouble(value.getX()); + bb.putDouble(value.getY()); + bb.putDouble(value.getZ()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Rotation2dStruct.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Rotation2dStruct.java new file mode 100644 index 00000000000..b22e3d15eb1 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Rotation2dStruct.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.struct; + +import edu.wpi.first.math.geometry.Rotation2d; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class Rotation2dStruct implements Struct { + @Override + public Class getTypeClass() { + return Rotation2d.class; + } + + @Override + public String getTypeString() { + return "struct:Rotation2d"; + } + + @Override + public int getSize() { + return kSizeDouble; + } + + @Override + public String getSchema() { + return "double value"; + } + + @Override + public Rotation2d unpack(ByteBuffer bb) { + double value = bb.getDouble(); + return new Rotation2d(value); + } + + @Override + public void pack(ByteBuffer bb, Rotation2d value) { + bb.putDouble(value.getRadians()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Rotation3dStruct.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Rotation3dStruct.java new file mode 100644 index 00000000000..4184990a22f --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Rotation3dStruct.java @@ -0,0 +1,48 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.struct; + +import edu.wpi.first.math.geometry.Quaternion; +import edu.wpi.first.math.geometry.Rotation3d; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class Rotation3dStruct implements Struct { + @Override + public Class getTypeClass() { + return Rotation3d.class; + } + + @Override + public String getTypeString() { + return "struct:Rotation3d"; + } + + @Override + public int getSize() { + return Quaternion.struct.getSize(); + } + + @Override + public String getSchema() { + return "Quaternion q"; + } + + @Override + public Struct[] getNested() { + return new Struct[] {Quaternion.struct}; + } + + @Override + public Rotation3d unpack(ByteBuffer bb) { + Quaternion q = Quaternion.struct.unpack(bb); + return new Rotation3d(q); + } + + @Override + public void pack(ByteBuffer bb, Rotation3d value) { + Quaternion.struct.pack(bb, value.getQuaternion()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Transform2dStruct.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Transform2dStruct.java new file mode 100644 index 00000000000..298d6db4e28 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Transform2dStruct.java @@ -0,0 +1,51 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.struct; + +import edu.wpi.first.math.geometry.Rotation2d; +import edu.wpi.first.math.geometry.Transform2d; +import edu.wpi.first.math.geometry.Translation2d; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class Transform2dStruct implements Struct { + @Override + public Class getTypeClass() { + return Transform2d.class; + } + + @Override + public String getTypeString() { + return "struct:Transform2d"; + } + + @Override + public int getSize() { + return Translation2d.struct.getSize() + Rotation2d.struct.getSize(); + } + + @Override + public String getSchema() { + return "Translation2d translation;Rotation2d rotation"; + } + + @Override + public Struct[] getNested() { + return new Struct[] {Translation2d.struct, Rotation2d.struct}; + } + + @Override + public Transform2d unpack(ByteBuffer bb) { + Translation2d translation = Translation2d.struct.unpack(bb); + Rotation2d rotation = Rotation2d.struct.unpack(bb); + return new Transform2d(translation, rotation); + } + + @Override + public void pack(ByteBuffer bb, Transform2d value) { + Translation2d.struct.pack(bb, value.getTranslation()); + Rotation2d.struct.pack(bb, value.getRotation()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Transform3dStruct.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Transform3dStruct.java new file mode 100644 index 00000000000..2ad5bc153b8 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Transform3dStruct.java @@ -0,0 +1,51 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.struct; + +import edu.wpi.first.math.geometry.Rotation3d; +import edu.wpi.first.math.geometry.Transform3d; +import edu.wpi.first.math.geometry.Translation3d; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class Transform3dStruct implements Struct { + @Override + public Class getTypeClass() { + return Transform3d.class; + } + + @Override + public String getTypeString() { + return "struct:Transform3d"; + } + + @Override + public int getSize() { + return Translation3d.struct.getSize() + Rotation3d.struct.getSize(); + } + + @Override + public String getSchema() { + return "Translation3d translation;Rotation3d rotation"; + } + + @Override + public Struct[] getNested() { + return new Struct[] {Translation3d.struct, Rotation3d.struct}; + } + + @Override + public Transform3d unpack(ByteBuffer bb) { + Translation3d translation = Translation3d.struct.unpack(bb); + Rotation3d rotation = Rotation3d.struct.unpack(bb); + return new Transform3d(translation, rotation); + } + + @Override + public void pack(ByteBuffer bb, Transform3d value) { + Translation3d.struct.pack(bb, value.getTranslation()); + Rotation3d.struct.pack(bb, value.getRotation()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Translation2dStruct.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Translation2dStruct.java new file mode 100644 index 00000000000..aac179aacbc --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Translation2dStruct.java @@ -0,0 +1,44 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.struct; + +import edu.wpi.first.math.geometry.Translation2d; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class Translation2dStruct implements Struct { + @Override + public Class getTypeClass() { + return Translation2d.class; + } + + @Override + public String getTypeString() { + return "struct:Translation2d"; + } + + @Override + public int getSize() { + return kSizeDouble * 2; + } + + @Override + public String getSchema() { + return "double x;double y"; + } + + @Override + public Translation2d unpack(ByteBuffer bb) { + double x = bb.getDouble(); + double y = bb.getDouble(); + return new Translation2d(x, y); + } + + @Override + public void pack(ByteBuffer bb, Translation2d value) { + bb.putDouble(value.getX()); + bb.putDouble(value.getY()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Translation3dStruct.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Translation3dStruct.java new file mode 100644 index 00000000000..f4e10299fda --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Translation3dStruct.java @@ -0,0 +1,46 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.struct; + +import edu.wpi.first.math.geometry.Translation3d; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class Translation3dStruct implements Struct { + @Override + public Class getTypeClass() { + return Translation3d.class; + } + + @Override + public String getTypeString() { + return "struct:Translation3d"; + } + + @Override + public int getSize() { + return kSizeDouble * 3; + } + + @Override + public String getSchema() { + return "double x;double y;double z"; + } + + @Override + public Translation3d unpack(ByteBuffer bb) { + double x = bb.getDouble(); + double y = bb.getDouble(); + double z = bb.getDouble(); + return new Translation3d(x, y, z); + } + + @Override + public void pack(ByteBuffer bb, Translation3d value) { + bb.putDouble(value.getX()); + bb.putDouble(value.getY()); + bb.putDouble(value.getZ()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Twist2dStruct.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Twist2dStruct.java new file mode 100644 index 00000000000..7797f3ac9d1 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Twist2dStruct.java @@ -0,0 +1,46 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.struct; + +import edu.wpi.first.math.geometry.Twist2d; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class Twist2dStruct implements Struct { + @Override + public Class getTypeClass() { + return Twist2d.class; + } + + @Override + public String getTypeString() { + return "struct:Twist2d"; + } + + @Override + public int getSize() { + return kSizeDouble * 3; + } + + @Override + public String getSchema() { + return "double dx;double dy;double dtheta"; + } + + @Override + public Twist2d unpack(ByteBuffer bb) { + double dx = bb.getDouble(); + double dy = bb.getDouble(); + double dtheta = bb.getDouble(); + return new Twist2d(dx, dy, dtheta); + } + + @Override + public void pack(ByteBuffer bb, Twist2d value) { + bb.putDouble(value.dx); + bb.putDouble(value.dy); + bb.putDouble(value.dtheta); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Twist3dStruct.java b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Twist3dStruct.java new file mode 100644 index 00000000000..68926a4c41f --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/geometry/struct/Twist3dStruct.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.geometry.struct; + +import edu.wpi.first.math.geometry.Twist3d; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class Twist3dStruct implements Struct { + @Override + public Class getTypeClass() { + return Twist3d.class; + } + + @Override + public String getTypeString() { + return "struct:Twist3d"; + } + + @Override + public int getSize() { + return kSizeDouble * 6; + } + + @Override + public String getSchema() { + return "double dx;double dy;double dz;double rx;double ry;double rz"; + } + + @Override + public Twist3d unpack(ByteBuffer bb) { + double dx = bb.getDouble(); + double dy = bb.getDouble(); + double dz = bb.getDouble(); + double rx = bb.getDouble(); + double ry = bb.getDouble(); + double rz = bb.getDouble(); + return new Twist3d(dx, dy, dz, rx, ry, rz); + } + + @Override + public void pack(ByteBuffer bb, Twist3d value) { + bb.putDouble(value.dx); + bb.putDouble(value.dy); + bb.putDouble(value.dz); + bb.putDouble(value.rx); + bb.putDouble(value.ry); + bb.putDouble(value.rz); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/interpolation/InterpolatingDoubleTreeMap.java b/wpimath/src/main/java/edu/wpi/first/math/interpolation/InterpolatingDoubleTreeMap.java index bcd57a392e3..010d2321469 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/interpolation/InterpolatingDoubleTreeMap.java +++ b/wpimath/src/main/java/edu/wpi/first/math/interpolation/InterpolatingDoubleTreeMap.java @@ -4,12 +4,30 @@ package edu.wpi.first.math.interpolation; +import java.util.Map; + /** * Interpolating Tree Maps are used to get values at points that are not defined by making a guess * from points that are defined. This uses linear interpolation. */ public class InterpolatingDoubleTreeMap extends InterpolatingTreeMap { + /** Default constructor. */ public InterpolatingDoubleTreeMap() { super(InverseInterpolator.forDouble(), Interpolator.forDouble()); } + + /** + * Creates an {@link InterpolatingDoubleTreeMap} from the given entries. + * + * @param entries The entries to add to the map. + * @return The map filled with the {@code entries}. + */ + @SafeVarargs + public static InterpolatingDoubleTreeMap ofEntries(Map.Entry... entries) { + InterpolatingDoubleTreeMap map = new InterpolatingDoubleTreeMap(); + for (var entry : entries) { + map.put(entry.getKey(), entry.getValue()); + } + return map; + } } diff --git a/wpimath/src/main/java/edu/wpi/first/math/interpolation/Interpolator.java b/wpimath/src/main/java/edu/wpi/first/math/interpolation/Interpolator.java index be6d8a2d26b..5fe1a8f28a5 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/interpolation/Interpolator.java +++ b/wpimath/src/main/java/edu/wpi/first/math/interpolation/Interpolator.java @@ -24,6 +24,11 @@ public interface Interpolator { */ T interpolate(T startValue, T endValue, double t); + /** + * Returns interpolator for Double. + * + * @return Interpolator for Double. + */ static Interpolator forDouble() { return MathUtil::interpolate; } diff --git a/wpimath/src/main/java/edu/wpi/first/math/interpolation/InverseInterpolator.java b/wpimath/src/main/java/edu/wpi/first/math/interpolation/InverseInterpolator.java index 8278af3f458..d6d0bc8c5be 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/interpolation/InverseInterpolator.java +++ b/wpimath/src/main/java/edu/wpi/first/math/interpolation/InverseInterpolator.java @@ -24,6 +24,11 @@ public interface InverseInterpolator { */ double inverseInterpolate(T startValue, T endValue, T q); + /** + * Returns inverse interpolator for Double. + * + * @return Inverse interpolator for Double. + */ static InverseInterpolator forDouble() { return MathUtil::inverseInterpolate; } diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/ChassisSpeeds.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/ChassisSpeeds.java index 43b67405d3e..608c735e9e4 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/ChassisSpeeds.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/ChassisSpeeds.java @@ -11,11 +11,16 @@ import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Translation2d; +import edu.wpi.first.math.geometry.Twist2d; +import edu.wpi.first.math.kinematics.proto.ChassisSpeedsProto; +import edu.wpi.first.math.kinematics.struct.ChassisSpeedsStruct; import edu.wpi.first.units.Angle; import edu.wpi.first.units.Distance; import edu.wpi.first.units.Measure; import edu.wpi.first.units.Time; import edu.wpi.first.units.Velocity; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; /** * Represents the speed of a robot chassis. Although this class contains similar members compared to @@ -26,7 +31,7 @@ * component because it can never move sideways. Holonomic drivetrains such as swerve and mecanum * will often have all three components. */ -public class ChassisSpeeds { +public class ChassisSpeeds implements ProtobufSerializable, StructSerializable { /** Velocity along the x-axis. (Fwd is +) */ public double vxMetersPerSecond; @@ -36,6 +41,12 @@ public class ChassisSpeeds { /** Represents the angular velocity of the robot frame. (CCW is +) */ public double omegaRadiansPerSecond; + /** ChassisSpeeds protobuf for serialization. */ + public static final ChassisSpeedsProto proto = new ChassisSpeedsProto(); + + /** ChassisSpeeds struct for serialization. */ + public static final ChassisSpeedsStruct struct = new ChassisSpeedsStruct(); + /** Constructs a ChassisSpeeds with zeros for dx, dy, and theta. */ public ChassisSpeeds() {} @@ -67,6 +78,19 @@ public ChassisSpeeds( this(vx.in(MetersPerSecond), vy.in(MetersPerSecond), omega.in(RadiansPerSecond)); } + /** + * Creates a Twist2d from ChassisSpeeds. + * + * @param dtSeconds The duration of the timestep. + * @return Twist2d. + */ + public Twist2d toTwist2d(double dtSeconds) { + return new Twist2d( + vxMetersPerSecond * dtSeconds, + vyMetersPerSecond * dtSeconds, + omegaRadiansPerSecond * dtSeconds); + } + /** * Discretizes a continuous-time chassis speed. * @@ -89,12 +113,19 @@ public static ChassisSpeeds discretize( double vyMetersPerSecond, double omegaRadiansPerSecond, double dtSeconds) { + // Construct the desired pose after a timestep, relative to the current pose. The desired pose + // has decoupled translation and rotation. var desiredDeltaPose = new Pose2d( vxMetersPerSecond * dtSeconds, vyMetersPerSecond * dtSeconds, new Rotation2d(omegaRadiansPerSecond * dtSeconds)); - var twist = new Pose2d().log(desiredDeltaPose); + + // Find the chassis translation/rotation deltas in the robot frame that move the robot from its + // current pose to the desired pose + var twist = Pose2d.kZero.log(desiredDeltaPose); + + // Turn the chassis translation/rotation deltas into average velocities return new ChassisSpeeds(twist.dx / dtSeconds, twist.dy / dtSeconds, twist.dtheta / dtSeconds); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveKinematics.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveKinematics.java index 87907249e7c..1d18b005daa 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveKinematics.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveKinematics.java @@ -9,8 +9,12 @@ import edu.wpi.first.math.MathSharedStore; import edu.wpi.first.math.MathUsageId; import edu.wpi.first.math.geometry.Twist2d; +import edu.wpi.first.math.kinematics.proto.DifferentialDriveKinematicsProto; +import edu.wpi.first.math.kinematics.struct.DifferentialDriveKinematicsStruct; import edu.wpi.first.units.Distance; import edu.wpi.first.units.Measure; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; /** * Helper class that converts a chassis velocity (dx and dtheta components) to left and right wheel @@ -21,9 +25,20 @@ * chassis speed. */ public class DifferentialDriveKinematics - implements Kinematics { + implements Kinematics, + ProtobufSerializable, + StructSerializable { + /** Differential drive trackwidth. */ public final double trackWidthMeters; + /** DifferentialDriveKinematics protobuf for serialization. */ + public static final DifferentialDriveKinematicsProto proto = + new DifferentialDriveKinematicsProto(); + + /** DifferentialDriveKinematics struct for serialization. */ + public static final DifferentialDriveKinematicsStruct struct = + new DifferentialDriveKinematicsStruct(); + /** * Constructs a differential drive kinematics object. * diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveOdometry.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveOdometry.java index 87d7bbf77fc..ad2199e4b98 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveOdometry.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveOdometry.java @@ -70,7 +70,7 @@ public DifferentialDriveOdometry( */ public DifferentialDriveOdometry( Rotation2d gyroAngle, double leftDistanceMeters, double rightDistanceMeters) { - this(gyroAngle, leftDistanceMeters, rightDistanceMeters, new Pose2d()); + this(gyroAngle, leftDistanceMeters, rightDistanceMeters, Pose2d.kZero); } /** @@ -82,7 +82,7 @@ public DifferentialDriveOdometry( */ public DifferentialDriveOdometry( Rotation2d gyroAngle, Measure leftDistance, Measure rightDistance) { - this(gyroAngle, leftDistance, rightDistance, new Pose2d()); + this(gyroAngle, leftDistance, rightDistance, Pose2d.kZero); } /** diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveWheelPositions.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveWheelPositions.java index c0a211e049b..d6036b8747b 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveWheelPositions.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveWheelPositions.java @@ -7,10 +7,13 @@ import static edu.wpi.first.units.Units.Meters; import edu.wpi.first.math.MathUtil; +import edu.wpi.first.math.kinematics.proto.DifferentialDriveWheelPositionsProto; +import edu.wpi.first.math.kinematics.struct.DifferentialDriveWheelPositionsStruct; import edu.wpi.first.units.Distance; import edu.wpi.first.units.Measure; import java.util.Objects; +/** Represents the wheel positions for a differential drive drivetrain. */ public class DifferentialDriveWheelPositions implements WheelPositions { /** Distance measured by the left side. */ @@ -19,6 +22,14 @@ public class DifferentialDriveWheelPositions /** Distance measured by the right side. */ public double rightMeters; + /** DifferentialDriveWheelPostions struct for serialization. */ + public static final DifferentialDriveWheelPositionsStruct struct = + new DifferentialDriveWheelPositionsStruct(); + + /** DifferentialDriveWheelPostions struct for serialization. */ + public static final DifferentialDriveWheelPositionsProto proto = + new DifferentialDriveWheelPositionsProto(); + /** * Constructs a DifferentialDriveWheelPositions. * diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveWheelSpeeds.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveWheelSpeeds.java index 72578226bb7..de188179534 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveWheelSpeeds.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/DifferentialDriveWheelSpeeds.java @@ -6,18 +6,30 @@ import static edu.wpi.first.units.Units.MetersPerSecond; +import edu.wpi.first.math.kinematics.proto.DifferentialDriveWheelSpeedsProto; +import edu.wpi.first.math.kinematics.struct.DifferentialDriveWheelSpeedsStruct; import edu.wpi.first.units.Distance; import edu.wpi.first.units.Measure; import edu.wpi.first.units.Velocity; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; /** Represents the wheel speeds for a differential drive drivetrain. */ -public class DifferentialDriveWheelSpeeds { +public class DifferentialDriveWheelSpeeds implements ProtobufSerializable, StructSerializable { /** Speed of the left side of the robot. */ public double leftMetersPerSecond; /** Speed of the right side of the robot. */ public double rightMetersPerSecond; + /** DifferentialDriveWheelSpeeds protobuf for serialization. */ + public static final DifferentialDriveWheelSpeedsProto proto = + new DifferentialDriveWheelSpeedsProto(); + + /** DifferentialDriveWheelSpeeds struct for serialization. */ + public static final DifferentialDriveWheelSpeedsStruct struct = + new DifferentialDriveWheelSpeedsStruct(); + /** Constructs a DifferentialDriveWheelSpeeds with zeros for left and right speeds. */ public DifferentialDriveWheelSpeeds() {} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/MecanumDriveKinematics.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/MecanumDriveKinematics.java index 76c857adcc1..f638b14b7cf 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/MecanumDriveKinematics.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/MecanumDriveKinematics.java @@ -8,6 +8,10 @@ import edu.wpi.first.math.MathUsageId; import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.math.geometry.Twist2d; +import edu.wpi.first.math.kinematics.proto.MecanumDriveKinematicsProto; +import edu.wpi.first.math.kinematics.struct.MecanumDriveKinematicsStruct; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import org.ejml.simple.SimpleMatrix; /** @@ -31,7 +35,9 @@ * field using encoders and a gyro. */ public class MecanumDriveKinematics - implements Kinematics { + implements Kinematics, + ProtobufSerializable, + StructSerializable { private final SimpleMatrix m_inverseKinematics; private final SimpleMatrix m_forwardKinematics; @@ -40,7 +46,13 @@ public class MecanumDriveKinematics private final Translation2d m_rearLeftWheelMeters; private final Translation2d m_rearRightWheelMeters; - private Translation2d m_prevCoR = new Translation2d(); + private Translation2d m_prevCoR = Translation2d.kZero; + + /** MecanumDriveKinematics protobuf for serialization. */ + public static final MecanumDriveKinematicsProto proto = new MecanumDriveKinematicsProto(); + + /** MecanumDriveKinematics struct for serialization. */ + public static final MecanumDriveKinematicsStruct struct = new MecanumDriveKinematicsStruct(); /** * Constructs a mecanum drive kinematics object. @@ -128,7 +140,7 @@ public MecanumDriveWheelSpeeds toWheelSpeeds( */ @Override public MecanumDriveWheelSpeeds toWheelSpeeds(ChassisSpeeds chassisSpeeds) { - return toWheelSpeeds(chassisSpeeds, new Translation2d()); + return toWheelSpeeds(chassisSpeeds, Translation2d.kZero); } /** @@ -207,4 +219,40 @@ private void setInverseKinematics( m_inverseKinematics.setRow(2, 0, 1, 1, rl.getX() - rl.getY()); m_inverseKinematics.setRow(3, 0, 1, -1, -(rr.getX() + rr.getY())); } + + /** + * Returns the front-left wheel translation. + * + * @return The front-left wheel translation. + */ + public Translation2d getFrontLeft() { + return m_frontLeftWheelMeters; + } + + /** + * Returns the front-right wheel translation. + * + * @return The front-right wheel translation. + */ + public Translation2d getFrontRight() { + return m_frontRightWheelMeters; + } + + /** + * Returns the rear-left wheel translation. + * + * @return The rear-left wheel translation. + */ + public Translation2d getRearLeft() { + return m_rearLeftWheelMeters; + } + + /** + * Returns the rear-right wheel translation. + * + * @return The rear-right wheel translation. + */ + public Translation2d getRearRight() { + return m_rearRightWheelMeters; + } } diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/MecanumDriveOdometry.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/MecanumDriveOdometry.java index 32bc9bff056..0fd4b374169 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/MecanumDriveOdometry.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/MecanumDriveOdometry.java @@ -45,6 +45,6 @@ public MecanumDriveOdometry( MecanumDriveKinematics kinematics, Rotation2d gyroAngle, MecanumDriveWheelPositions wheelPositions) { - this(kinematics, gyroAngle, wheelPositions, new Pose2d()); + this(kinematics, gyroAngle, wheelPositions, Pose2d.kZero); } } diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/MecanumDriveWheelPositions.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/MecanumDriveWheelPositions.java index 2ebb77a1344..179e1bf14b5 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/MecanumDriveWheelPositions.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/MecanumDriveWheelPositions.java @@ -7,11 +7,19 @@ import static edu.wpi.first.units.Units.Meters; import edu.wpi.first.math.MathUtil; +import edu.wpi.first.math.kinematics.proto.MecanumDriveWheelPositionsProto; +import edu.wpi.first.math.kinematics.struct.MecanumDriveWheelPositionsStruct; import edu.wpi.first.units.Distance; import edu.wpi.first.units.Measure; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Objects; -public class MecanumDriveWheelPositions implements WheelPositions { +/** Represents the wheel positions for a mecanum drive drivetrain. */ +public class MecanumDriveWheelPositions + implements WheelPositions, + ProtobufSerializable, + StructSerializable { /** Distance measured by the front left wheel. */ public double frontLeftMeters; @@ -24,6 +32,13 @@ public class MecanumDriveWheelPositions implements WheelPositions attainableMaxSpeedMetersPerSecond) { frontLeftMetersPerSecond = diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/Odometry.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/Odometry.java index b2e5054eb83..427c92d8a18 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/Odometry.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/Odometry.java @@ -15,6 +15,8 @@ * *

    Teams can use odometry during the autonomous period for complex tasks like path following. * Furthermore, odometry can be used for latency compensation when using computer-vision systems. + * + * @param Wheel positions type. */ public class Odometry> { private final Kinematics m_kinematics; diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveDriveKinematics.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveDriveKinematics.java index 2498b337427..9e780942685 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveDriveKinematics.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveDriveKinematics.java @@ -41,7 +41,9 @@ */ public class SwerveDriveKinematics implements Kinematics { + /** Wrapper class for swerve module states. */ public static class SwerveDriveWheelStates { + /** Swerve module states. */ public SwerveModuleState[] states; /** @@ -63,7 +65,7 @@ public SwerveDriveWheelStates(SwerveModuleState[] states) { private final int m_numModules; private final Translation2d[] m_modules; private Rotation2d[] m_moduleHeadings; - private Translation2d m_prevCoR = new Translation2d(); + private Translation2d m_prevCoR = Translation2d.kZero; /** * Constructs a swerve drive kinematics object. This takes in a variable number of module @@ -82,7 +84,7 @@ public SwerveDriveKinematics(Translation2d... moduleTranslationsMeters) { m_numModules = moduleTranslationsMeters.length; m_modules = Arrays.copyOf(moduleTranslationsMeters, m_numModules); m_moduleHeadings = new Rotation2d[m_numModules]; - Arrays.fill(m_moduleHeadings, new Rotation2d()); + Arrays.fill(m_moduleHeadings, Rotation2d.kZero); m_inverseKinematics = new SimpleMatrix(m_numModules * 2, 3); for (int i = 0; i < m_numModules; i++) { @@ -194,7 +196,7 @@ public SwerveModuleState[] toSwerveModuleStates( * @return An array containing the module states. */ public SwerveModuleState[] toSwerveModuleStates(ChassisSpeeds chassisSpeeds) { - return toSwerveModuleStates(chassisSpeeds, new Translation2d()); + return toSwerveModuleStates(chassisSpeeds, Translation2d.kZero); } @Override diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveDriveOdometry.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveDriveOdometry.java index 4f954e930e0..14f62b2f206 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveDriveOdometry.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveDriveOdometry.java @@ -51,7 +51,7 @@ public SwerveDriveOdometry( SwerveDriveKinematics kinematics, Rotation2d gyroAngle, SwerveModulePosition[] modulePositions) { - this(kinematics, gyroAngle, modulePositions, new Pose2d()); + this(kinematics, gyroAngle, modulePositions, Pose2d.kZero); } /** diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveDriveWheelPositions.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveDriveWheelPositions.java index e88f044803d..5d0f0af113a 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveDriveWheelPositions.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveDriveWheelPositions.java @@ -7,7 +7,9 @@ import java.util.Arrays; import java.util.Objects; +/** Represents the wheel positions for a swerve drive drivetrain. */ public class SwerveDriveWheelPositions implements WheelPositions { + /** The distances driven by the wheels. */ public SwerveModulePosition[] positions; /** diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveModulePosition.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveModulePosition.java index 58467ce313a..ec430331e9f 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveModulePosition.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveModulePosition.java @@ -9,18 +9,31 @@ import edu.wpi.first.math.MathUtil; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.interpolation.Interpolatable; +import edu.wpi.first.math.kinematics.proto.SwerveModulePositionProto; +import edu.wpi.first.math.kinematics.struct.SwerveModulePositionStruct; import edu.wpi.first.units.Distance; import edu.wpi.first.units.Measure; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Objects; /** Represents the state of one swerve module. */ public class SwerveModulePosition - implements Comparable, Interpolatable { + implements Comparable, + Interpolatable, + ProtobufSerializable, + StructSerializable { /** Distance measured by the wheel of the module. */ public double distanceMeters; /** Angle of the module. */ - public Rotation2d angle = Rotation2d.fromDegrees(0); + public Rotation2d angle = Rotation2d.kZero; + + /** SwerveModulePosition protobuf for serialization. */ + public static final SwerveModulePositionProto proto = new SwerveModulePositionProto(); + + /** SwerveModulePosition struct for serialization. */ + public static final SwerveModulePositionStruct struct = new SwerveModulePositionStruct(); /** Constructs a SwerveModulePosition with zeros for distance and angle. */ public SwerveModulePosition() {} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveModuleState.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveModuleState.java index e4529d6b9d9..a5db3972601 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveModuleState.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/SwerveModuleState.java @@ -7,18 +7,29 @@ import static edu.wpi.first.units.Units.MetersPerSecond; import edu.wpi.first.math.geometry.Rotation2d; +import edu.wpi.first.math.kinematics.proto.SwerveModuleStateProto; +import edu.wpi.first.math.kinematics.struct.SwerveModuleStateStruct; import edu.wpi.first.units.Distance; import edu.wpi.first.units.Measure; import edu.wpi.first.units.Velocity; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; import java.util.Objects; /** Represents the state of one swerve module. */ -public class SwerveModuleState implements Comparable { +public class SwerveModuleState + implements Comparable, ProtobufSerializable, StructSerializable { /** Speed of the wheel of the module. */ public double speedMetersPerSecond; /** Angle of the module. */ - public Rotation2d angle = Rotation2d.fromDegrees(0); + public Rotation2d angle = Rotation2d.kZero; + + /** SwerveModuleState protobuf for serialization. */ + public static final SwerveModuleStateProto proto = new SwerveModuleStateProto(); + + /** SwerveModuleState struct for serialization. */ + public static final SwerveModuleStateStruct struct = new SwerveModuleStateStruct(); /** Constructs a SwerveModuleState with zeros for speed and angle. */ public SwerveModuleState() {} @@ -91,8 +102,7 @@ public static SwerveModuleState optimize( var delta = desiredState.angle.minus(currentAngle); if (Math.abs(delta.getDegrees()) > 90.0) { return new SwerveModuleState( - -desiredState.speedMetersPerSecond, - desiredState.angle.rotateBy(Rotation2d.fromDegrees(180.0))); + -desiredState.speedMetersPerSecond, desiredState.angle.rotateBy(Rotation2d.kPi)); } else { return new SwerveModuleState(desiredState.speedMetersPerSecond, desiredState.angle); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/WheelPositions.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/WheelPositions.java index 029a0ac40d7..c0167e3e866 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/kinematics/WheelPositions.java +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/WheelPositions.java @@ -6,6 +6,11 @@ import edu.wpi.first.math.interpolation.Interpolatable; +/** + * Interface for wheel positions. + * + * @param Wheel positions type. + */ public interface WheelPositions> extends Interpolatable { /** * Returns a copy of this instance. diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/ChassisSpeedsProto.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/ChassisSpeedsProto.java new file mode 100644 index 00000000000..b20d23bbc9f --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/ChassisSpeedsProto.java @@ -0,0 +1,39 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.proto; + +import edu.wpi.first.math.kinematics.ChassisSpeeds; +import edu.wpi.first.math.proto.Kinematics.ProtobufChassisSpeeds; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class ChassisSpeedsProto implements Protobuf { + @Override + public Class getTypeClass() { + return ChassisSpeeds.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufChassisSpeeds.getDescriptor(); + } + + @Override + public ProtobufChassisSpeeds createMessage() { + return ProtobufChassisSpeeds.newInstance(); + } + + @Override + public ChassisSpeeds unpack(ProtobufChassisSpeeds msg) { + return new ChassisSpeeds(msg.getVx(), msg.getVy(), msg.getOmega()); + } + + @Override + public void pack(ProtobufChassisSpeeds msg, ChassisSpeeds value) { + msg.setVx(value.vxMetersPerSecond); + msg.setVy(value.vyMetersPerSecond); + msg.setOmega(value.omegaRadiansPerSecond); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/DifferentialDriveKinematicsProto.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/DifferentialDriveKinematicsProto.java new file mode 100644 index 00000000000..d1a8969d162 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/DifferentialDriveKinematicsProto.java @@ -0,0 +1,38 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.proto; + +import edu.wpi.first.math.kinematics.DifferentialDriveKinematics; +import edu.wpi.first.math.proto.Kinematics.ProtobufDifferentialDriveKinematics; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class DifferentialDriveKinematicsProto + implements Protobuf { + @Override + public Class getTypeClass() { + return DifferentialDriveKinematics.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufDifferentialDriveKinematics.getDescriptor(); + } + + @Override + public ProtobufDifferentialDriveKinematics createMessage() { + return ProtobufDifferentialDriveKinematics.newInstance(); + } + + @Override + public DifferentialDriveKinematics unpack(ProtobufDifferentialDriveKinematics msg) { + return new DifferentialDriveKinematics(msg.getTrackWidth()); + } + + @Override + public void pack(ProtobufDifferentialDriveKinematics msg, DifferentialDriveKinematics value) { + msg.setTrackWidth(value.trackWidthMeters); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/DifferentialDriveWheelPositionsProto.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/DifferentialDriveWheelPositionsProto.java new file mode 100644 index 00000000000..982756b5b7c --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/DifferentialDriveWheelPositionsProto.java @@ -0,0 +1,40 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.proto; + +import edu.wpi.first.math.kinematics.DifferentialDriveWheelPositions; +import edu.wpi.first.math.proto.Kinematics.ProtobufDifferentialDriveWheelPositions; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class DifferentialDriveWheelPositionsProto + implements Protobuf { + @Override + public Class getTypeClass() { + return DifferentialDriveWheelPositions.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufDifferentialDriveWheelPositions.getDescriptor(); + } + + @Override + public ProtobufDifferentialDriveWheelPositions createMessage() { + return ProtobufDifferentialDriveWheelPositions.newInstance(); + } + + @Override + public DifferentialDriveWheelPositions unpack(ProtobufDifferentialDriveWheelPositions msg) { + return new DifferentialDriveWheelPositions(msg.getLeft(), msg.getRight()); + } + + @Override + public void pack( + ProtobufDifferentialDriveWheelPositions msg, DifferentialDriveWheelPositions value) { + msg.setLeft(value.leftMeters); + msg.setRight(value.rightMeters); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/DifferentialDriveWheelSpeedsProto.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/DifferentialDriveWheelSpeedsProto.java new file mode 100644 index 00000000000..e30df565749 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/DifferentialDriveWheelSpeedsProto.java @@ -0,0 +1,39 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.proto; + +import edu.wpi.first.math.kinematics.DifferentialDriveWheelSpeeds; +import edu.wpi.first.math.proto.Kinematics.ProtobufDifferentialDriveWheelSpeeds; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class DifferentialDriveWheelSpeedsProto + implements Protobuf { + @Override + public Class getTypeClass() { + return DifferentialDriveWheelSpeeds.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufDifferentialDriveWheelSpeeds.getDescriptor(); + } + + @Override + public ProtobufDifferentialDriveWheelSpeeds createMessage() { + return ProtobufDifferentialDriveWheelSpeeds.newInstance(); + } + + @Override + public DifferentialDriveWheelSpeeds unpack(ProtobufDifferentialDriveWheelSpeeds msg) { + return new DifferentialDriveWheelSpeeds(msg.getLeft(), msg.getRight()); + } + + @Override + public void pack(ProtobufDifferentialDriveWheelSpeeds msg, DifferentialDriveWheelSpeeds value) { + msg.setLeft(value.leftMetersPerSecond); + msg.setRight(value.rightMetersPerSecond); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/MecanumDriveKinematicsProto.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/MecanumDriveKinematicsProto.java new file mode 100644 index 00000000000..f5b8f3bdfb0 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/MecanumDriveKinematicsProto.java @@ -0,0 +1,51 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.proto; + +import edu.wpi.first.math.geometry.Translation2d; +import edu.wpi.first.math.kinematics.MecanumDriveKinematics; +import edu.wpi.first.math.proto.Kinematics.ProtobufMecanumDriveKinematics; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class MecanumDriveKinematicsProto + implements Protobuf { + @Override + public Class getTypeClass() { + return MecanumDriveKinematics.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufMecanumDriveKinematics.getDescriptor(); + } + + @Override + public Protobuf[] getNested() { + return new Protobuf[] {Translation2d.proto}; + } + + @Override + public ProtobufMecanumDriveKinematics createMessage() { + return ProtobufMecanumDriveKinematics.newInstance(); + } + + @Override + public MecanumDriveKinematics unpack(ProtobufMecanumDriveKinematics msg) { + return new MecanumDriveKinematics( + Translation2d.proto.unpack(msg.getFrontLeft()), + Translation2d.proto.unpack(msg.getFrontRight()), + Translation2d.proto.unpack(msg.getRearLeft()), + Translation2d.proto.unpack(msg.getRearRight())); + } + + @Override + public void pack(ProtobufMecanumDriveKinematics msg, MecanumDriveKinematics value) { + Translation2d.proto.pack(msg.getMutableFrontLeft(), value.getFrontLeft()); + Translation2d.proto.pack(msg.getMutableFrontRight(), value.getFrontRight()); + Translation2d.proto.pack(msg.getMutableRearLeft(), value.getRearLeft()); + Translation2d.proto.pack(msg.getMutableRearRight(), value.getRearRight()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/MecanumDriveWheelPositionsProto.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/MecanumDriveWheelPositionsProto.java new file mode 100644 index 00000000000..d4f0f5a3ce4 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/MecanumDriveWheelPositionsProto.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.proto; + +import edu.wpi.first.math.kinematics.MecanumDriveWheelPositions; +import edu.wpi.first.math.proto.Kinematics.ProtobufMecanumDriveWheelPositions; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class MecanumDriveWheelPositionsProto + implements Protobuf { + @Override + public Class getTypeClass() { + return MecanumDriveWheelPositions.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufMecanumDriveWheelPositions.getDescriptor(); + } + + @Override + public ProtobufMecanumDriveWheelPositions createMessage() { + return ProtobufMecanumDriveWheelPositions.newInstance(); + } + + @Override + public MecanumDriveWheelPositions unpack(ProtobufMecanumDriveWheelPositions msg) { + return new MecanumDriveWheelPositions( + msg.getFrontLeft(), msg.getFrontRight(), msg.getRearLeft(), msg.getRearRight()); + } + + @Override + public void pack(ProtobufMecanumDriveWheelPositions msg, MecanumDriveWheelPositions value) { + msg.setFrontLeft(value.frontLeftMeters); + msg.setFrontRight(value.frontRightMeters); + msg.setRearLeft(value.rearLeftMeters); + msg.setRearRight(value.rearRightMeters); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/MecanumDriveWheelSpeedsProto.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/MecanumDriveWheelSpeedsProto.java new file mode 100644 index 00000000000..85e8fd10a35 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/MecanumDriveWheelSpeedsProto.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.proto; + +import edu.wpi.first.math.kinematics.MecanumDriveWheelSpeeds; +import edu.wpi.first.math.proto.Kinematics.ProtobufMecanumDriveWheelSpeeds; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class MecanumDriveWheelSpeedsProto + implements Protobuf { + @Override + public Class getTypeClass() { + return MecanumDriveWheelSpeeds.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufMecanumDriveWheelSpeeds.getDescriptor(); + } + + @Override + public ProtobufMecanumDriveWheelSpeeds createMessage() { + return ProtobufMecanumDriveWheelSpeeds.newInstance(); + } + + @Override + public MecanumDriveWheelSpeeds unpack(ProtobufMecanumDriveWheelSpeeds msg) { + return new MecanumDriveWheelSpeeds( + msg.getFrontLeft(), msg.getFrontRight(), msg.getRearLeft(), msg.getRearRight()); + } + + @Override + public void pack(ProtobufMecanumDriveWheelSpeeds msg, MecanumDriveWheelSpeeds value) { + msg.setFrontLeft(value.frontLeftMetersPerSecond); + msg.setFrontRight(value.frontRightMetersPerSecond); + msg.setRearLeft(value.rearLeftMetersPerSecond); + msg.setRearRight(value.rearRightMetersPerSecond); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/SwerveModulePositionProto.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/SwerveModulePositionProto.java new file mode 100644 index 00000000000..fe5ec5fc661 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/SwerveModulePositionProto.java @@ -0,0 +1,45 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.proto; + +import edu.wpi.first.math.geometry.Rotation2d; +import edu.wpi.first.math.kinematics.SwerveModulePosition; +import edu.wpi.first.math.proto.Kinematics.ProtobufSwerveModulePosition; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class SwerveModulePositionProto + implements Protobuf { + @Override + public Class getTypeClass() { + return SwerveModulePosition.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufSwerveModulePosition.getDescriptor(); + } + + @Override + public Protobuf[] getNested() { + return new Protobuf[] {Rotation2d.proto}; + } + + @Override + public ProtobufSwerveModulePosition createMessage() { + return ProtobufSwerveModulePosition.newInstance(); + } + + @Override + public SwerveModulePosition unpack(ProtobufSwerveModulePosition msg) { + return new SwerveModulePosition(msg.getDistance(), Rotation2d.proto.unpack(msg.getAngle())); + } + + @Override + public void pack(ProtobufSwerveModulePosition msg, SwerveModulePosition value) { + msg.setDistance(value.distanceMeters); + Rotation2d.proto.pack(msg.getMutableAngle(), value.angle); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/SwerveModuleStateProto.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/SwerveModuleStateProto.java new file mode 100644 index 00000000000..dc30f91117b --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/proto/SwerveModuleStateProto.java @@ -0,0 +1,45 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.proto; + +import edu.wpi.first.math.geometry.Rotation2d; +import edu.wpi.first.math.kinematics.SwerveModuleState; +import edu.wpi.first.math.proto.Kinematics.ProtobufSwerveModuleState; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class SwerveModuleStateProto + implements Protobuf { + @Override + public Class getTypeClass() { + return SwerveModuleState.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufSwerveModuleState.getDescriptor(); + } + + @Override + public Protobuf[] getNested() { + return new Protobuf[] {Rotation2d.proto}; + } + + @Override + public ProtobufSwerveModuleState createMessage() { + return ProtobufSwerveModuleState.newInstance(); + } + + @Override + public SwerveModuleState unpack(ProtobufSwerveModuleState msg) { + return new SwerveModuleState(msg.getSpeed(), Rotation2d.proto.unpack(msg.getAngle())); + } + + @Override + public void pack(ProtobufSwerveModuleState msg, SwerveModuleState value) { + msg.setSpeed(value.speedMetersPerSecond); + Rotation2d.proto.pack(msg.getMutableAngle(), value.angle); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/ChassisSpeedsStruct.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/ChassisSpeedsStruct.java new file mode 100644 index 00000000000..ea26f86e629 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/ChassisSpeedsStruct.java @@ -0,0 +1,46 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.struct; + +import edu.wpi.first.math.kinematics.ChassisSpeeds; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class ChassisSpeedsStruct implements Struct { + @Override + public Class getTypeClass() { + return ChassisSpeeds.class; + } + + @Override + public String getTypeString() { + return "struct:ChassisSpeeds"; + } + + @Override + public int getSize() { + return kSizeDouble * 3; + } + + @Override + public String getSchema() { + return "double vx;double vy;double omega"; + } + + @Override + public ChassisSpeeds unpack(ByteBuffer bb) { + double vx = bb.getDouble(); + double vy = bb.getDouble(); + double omega = bb.getDouble(); + return new ChassisSpeeds(vx, vy, omega); + } + + @Override + public void pack(ByteBuffer bb, ChassisSpeeds value) { + bb.putDouble(value.vxMetersPerSecond); + bb.putDouble(value.vyMetersPerSecond); + bb.putDouble(value.omegaRadiansPerSecond); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/DifferentialDriveKinematicsStruct.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/DifferentialDriveKinematicsStruct.java new file mode 100644 index 00000000000..1ddadaac1ff --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/DifferentialDriveKinematicsStruct.java @@ -0,0 +1,42 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.struct; + +import edu.wpi.first.math.kinematics.DifferentialDriveKinematics; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class DifferentialDriveKinematicsStruct implements Struct { + @Override + public Class getTypeClass() { + return DifferentialDriveKinematics.class; + } + + @Override + public String getTypeString() { + return "struct:DifferentialDriveKinematics"; + } + + @Override + public int getSize() { + return kSizeDouble; + } + + @Override + public String getSchema() { + return "double track_width"; + } + + @Override + public DifferentialDriveKinematics unpack(ByteBuffer bb) { + double trackWidth = bb.getDouble(); + return new DifferentialDriveKinematics(trackWidth); + } + + @Override + public void pack(ByteBuffer bb, DifferentialDriveKinematics value) { + bb.putDouble(value.trackWidthMeters); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/DifferentialDriveWheelPositionsStruct.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/DifferentialDriveWheelPositionsStruct.java new file mode 100644 index 00000000000..efa80ebd177 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/DifferentialDriveWheelPositionsStruct.java @@ -0,0 +1,45 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.struct; + +import edu.wpi.first.math.kinematics.DifferentialDriveWheelPositions; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class DifferentialDriveWheelPositionsStruct + implements Struct { + @Override + public Class getTypeClass() { + return DifferentialDriveWheelPositions.class; + } + + @Override + public String getTypeString() { + return "struct:DifferentialDriveWheelPositions"; + } + + @Override + public int getSize() { + return kSizeDouble * 2; + } + + @Override + public String getSchema() { + return "double left;double right"; + } + + @Override + public DifferentialDriveWheelPositions unpack(ByteBuffer bb) { + double left = bb.getDouble(); + double right = bb.getDouble(); + return new DifferentialDriveWheelPositions(left, right); + } + + @Override + public void pack(ByteBuffer bb, DifferentialDriveWheelPositions value) { + bb.putDouble(value.leftMeters); + bb.putDouble(value.rightMeters); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/DifferentialDriveWheelSpeedsStruct.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/DifferentialDriveWheelSpeedsStruct.java new file mode 100644 index 00000000000..c1242479056 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/DifferentialDriveWheelSpeedsStruct.java @@ -0,0 +1,44 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.struct; + +import edu.wpi.first.math.kinematics.DifferentialDriveWheelSpeeds; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class DifferentialDriveWheelSpeedsStruct implements Struct { + @Override + public Class getTypeClass() { + return DifferentialDriveWheelSpeeds.class; + } + + @Override + public String getTypeString() { + return "struct:DifferentialDriveWheelSpeeds"; + } + + @Override + public int getSize() { + return kSizeDouble * 2; + } + + @Override + public String getSchema() { + return "double left;double right"; + } + + @Override + public DifferentialDriveWheelSpeeds unpack(ByteBuffer bb) { + double left = bb.getDouble(); + double right = bb.getDouble(); + return new DifferentialDriveWheelSpeeds(left, right); + } + + @Override + public void pack(ByteBuffer bb, DifferentialDriveWheelSpeeds value) { + bb.putDouble(value.leftMetersPerSecond); + bb.putDouble(value.rightMetersPerSecond); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/MecanumDriveKinematicsStruct.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/MecanumDriveKinematicsStruct.java new file mode 100644 index 00000000000..227f80ed402 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/MecanumDriveKinematicsStruct.java @@ -0,0 +1,55 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.struct; + +import edu.wpi.first.math.geometry.Translation2d; +import edu.wpi.first.math.kinematics.MecanumDriveKinematics; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class MecanumDriveKinematicsStruct implements Struct { + @Override + public Class getTypeClass() { + return MecanumDriveKinematics.class; + } + + @Override + public String getTypeString() { + return "struct:MecanumDriveKinematics"; + } + + @Override + public int getSize() { + return 4 * Translation2d.struct.getSize(); + } + + @Override + public String getSchema() { + return "Translation2d front_left;Translation2d front_right;Translation2d rear_left;" + + "Translation2d rear_right"; + } + + @Override + public Struct[] getNested() { + return new Struct[] {Translation2d.struct}; + } + + @Override + public MecanumDriveKinematics unpack(ByteBuffer bb) { + Translation2d frontLeft = Translation2d.struct.unpack(bb); + Translation2d frontRight = Translation2d.struct.unpack(bb); + Translation2d rearLeft = Translation2d.struct.unpack(bb); + Translation2d rearRight = Translation2d.struct.unpack(bb); + return new MecanumDriveKinematics(frontLeft, frontRight, rearLeft, rearRight); + } + + @Override + public void pack(ByteBuffer bb, MecanumDriveKinematics value) { + Translation2d.struct.pack(bb, value.getFrontLeft()); + Translation2d.struct.pack(bb, value.getFrontRight()); + Translation2d.struct.pack(bb, value.getRearLeft()); + Translation2d.struct.pack(bb, value.getRearRight()); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/MecanumDriveWheelPositionsStruct.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/MecanumDriveWheelPositionsStruct.java new file mode 100644 index 00000000000..9f8b1824712 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/MecanumDriveWheelPositionsStruct.java @@ -0,0 +1,48 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.struct; + +import edu.wpi.first.math.kinematics.MecanumDriveWheelPositions; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class MecanumDriveWheelPositionsStruct implements Struct { + @Override + public Class getTypeClass() { + return MecanumDriveWheelPositions.class; + } + + @Override + public String getTypeString() { + return "struct:MecanumDriveWheelPositions"; + } + + @Override + public int getSize() { + return kSizeDouble * 4; + } + + @Override + public String getSchema() { + return "double front_left;double front_right;double rear_left;double rear_right"; + } + + @Override + public MecanumDriveWheelPositions unpack(ByteBuffer bb) { + double frontLeft = bb.getDouble(); + double frontRight = bb.getDouble(); + double rearLeft = bb.getDouble(); + double rearRight = bb.getDouble(); + return new MecanumDriveWheelPositions(frontLeft, frontRight, rearLeft, rearRight); + } + + @Override + public void pack(ByteBuffer bb, MecanumDriveWheelPositions value) { + bb.putDouble(value.frontLeftMeters); + bb.putDouble(value.frontRightMeters); + bb.putDouble(value.rearLeftMeters); + bb.putDouble(value.rearRightMeters); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/MecanumDriveWheelSpeedsStruct.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/MecanumDriveWheelSpeedsStruct.java new file mode 100644 index 00000000000..46d12763cd4 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/MecanumDriveWheelSpeedsStruct.java @@ -0,0 +1,48 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.struct; + +import edu.wpi.first.math.kinematics.MecanumDriveWheelSpeeds; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class MecanumDriveWheelSpeedsStruct implements Struct { + @Override + public Class getTypeClass() { + return MecanumDriveWheelSpeeds.class; + } + + @Override + public String getTypeString() { + return "struct:MecanumDriveWheelSpeeds"; + } + + @Override + public int getSize() { + return kSizeDouble * 4; + } + + @Override + public String getSchema() { + return "double front_left;double front_right;double rear_left;double rear_right"; + } + + @Override + public MecanumDriveWheelSpeeds unpack(ByteBuffer bb) { + double frontLeft = bb.getDouble(); + double frontRight = bb.getDouble(); + double rearLeft = bb.getDouble(); + double rearRight = bb.getDouble(); + return new MecanumDriveWheelSpeeds(frontLeft, frontRight, rearLeft, rearRight); + } + + @Override + public void pack(ByteBuffer bb, MecanumDriveWheelSpeeds value) { + bb.putDouble(value.frontLeftMetersPerSecond); + bb.putDouble(value.frontRightMetersPerSecond); + bb.putDouble(value.rearLeftMetersPerSecond); + bb.putDouble(value.rearRightMetersPerSecond); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/SwerveModulePositionStruct.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/SwerveModulePositionStruct.java new file mode 100644 index 00000000000..21567328e94 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/SwerveModulePositionStruct.java @@ -0,0 +1,50 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.struct; + +import edu.wpi.first.math.geometry.Rotation2d; +import edu.wpi.first.math.kinematics.SwerveModulePosition; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class SwerveModulePositionStruct implements Struct { + @Override + public Class getTypeClass() { + return SwerveModulePosition.class; + } + + @Override + public String getTypeString() { + return "struct:SwerveModulePosition"; + } + + @Override + public int getSize() { + return kSizeDouble + Rotation2d.struct.getSize(); + } + + @Override + public String getSchema() { + return "double distance;Rotation2d angle"; + } + + @Override + public Struct[] getNested() { + return new Struct[] {Rotation2d.struct}; + } + + @Override + public SwerveModulePosition unpack(ByteBuffer bb) { + double distance = bb.getDouble(); + Rotation2d angle = Rotation2d.struct.unpack(bb); + return new SwerveModulePosition(distance, angle); + } + + @Override + public void pack(ByteBuffer bb, SwerveModulePosition value) { + bb.putDouble(value.distanceMeters); + Rotation2d.struct.pack(bb, value.angle); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/SwerveModuleStateStruct.java b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/SwerveModuleStateStruct.java new file mode 100644 index 00000000000..51dd61f045b --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/kinematics/struct/SwerveModuleStateStruct.java @@ -0,0 +1,50 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.kinematics.struct; + +import edu.wpi.first.math.geometry.Rotation2d; +import edu.wpi.first.math.kinematics.SwerveModuleState; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class SwerveModuleStateStruct implements Struct { + @Override + public Class getTypeClass() { + return SwerveModuleState.class; + } + + @Override + public String getTypeString() { + return "struct:SwerveModuleState"; + } + + @Override + public int getSize() { + return kSizeDouble + Rotation2d.struct.getSize(); + } + + @Override + public String getSchema() { + return "double speed;Rotation2d angle"; + } + + @Override + public Struct[] getNested() { + return new Struct[] {Rotation2d.struct}; + } + + @Override + public SwerveModuleState unpack(ByteBuffer bb) { + double speed = bb.getDouble(); + Rotation2d angle = Rotation2d.struct.unpack(bb); + return new SwerveModuleState(speed, angle); + } + + @Override + public void pack(ByteBuffer bb, SwerveModuleState value) { + bb.putDouble(value.speedMetersPerSecond); + Rotation2d.struct.pack(bb, value.angle); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/optimization/SimulatedAnnealing.java b/wpimath/src/main/java/edu/wpi/first/math/optimization/SimulatedAnnealing.java new file mode 100644 index 00000000000..f0ead5b4593 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/optimization/SimulatedAnnealing.java @@ -0,0 +1,85 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.optimization; + +import java.util.function.Function; +import java.util.function.ToDoubleFunction; + +/** + * An implementation of the Simulated Annealing stochastic nonlinear optimization method. + * + *

    Solving optimization problems involves tweaking decision variables to try to minimize some + * cost function. Simulated annealing is good for solving optimization problems with many local + * minima and a very large search space (it’s a heuristic solver rather than an exact solver like, + * say, SQP or interior-point method). Simulated annealing is a popular choice for solving the + * traveling salesman problem (see {@link edu.wpi.first.math.path.TravelingSalesman}). + * + * @see https://en.wikipedia.org/wiki/Simulated_annealing + * @param The type of the state to optimize. + */ +public final class SimulatedAnnealing { + private final double m_initialTemperature; + private final Function m_neighbor; + private final ToDoubleFunction m_cost; + + /** + * Constructor for Simulated Annealing that can be used for the same functions but with different + * initial states. + * + * @param initialTemperature The initial temperature. Higher temperatures make it more likely a + * worse state will be accepted during iteration, helping to avoid local minima. The + * temperature is decreased over time. + * @param neighbor Function that generates a random neighbor of the current state. + * @param cost Function that returns the scalar cost of a state. + */ + public SimulatedAnnealing( + double initialTemperature, Function neighbor, ToDoubleFunction cost) { + m_initialTemperature = initialTemperature; + m_neighbor = neighbor; + m_cost = cost; + } + + /** + * Runs the Simulated Annealing algorithm. + * + * @param initialGuess The initial state. + * @param iterations Number of iterations to run the solver. + * @return The optimized stater. + */ + public State solve(State initialGuess, int iterations) { + State minState = initialGuess; + double minCost = Double.MAX_VALUE; + + State state = initialGuess; + double cost = m_cost.applyAsDouble(state); + + for (int i = 0; i < iterations; ++i) { + double temperature = m_initialTemperature / i; + + State proposedState = m_neighbor.apply(state); + double proposedCost = m_cost.applyAsDouble(proposedState); + double deltaCost = proposedCost - cost; + + double acceptanceProbability = Math.exp(-deltaCost / temperature); + + // If cost went down or random number exceeded acceptance probability, + // accept the proposed state + if (deltaCost < 0 || acceptanceProbability >= Math.random()) { + state = proposedState; + cost = proposedCost; + } + + // If proposed cost is less than minimum, the proposed state becomes the + // new minimum + if (proposedCost < minCost) { + minState = proposedState; + minCost = proposedCost; + } + } + + return minState; + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/path/TravelingSalesman.java b/wpimath/src/main/java/edu/wpi/first/math/path/TravelingSalesman.java new file mode 100644 index 00000000000..b81db2036bc --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/path/TravelingSalesman.java @@ -0,0 +1,114 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.path; + +import edu.wpi.first.math.Num; +import edu.wpi.first.math.Vector; +import edu.wpi.first.math.geometry.Pose2d; +import edu.wpi.first.math.optimization.SimulatedAnnealing; +import java.util.Arrays; +import java.util.Collections; +import java.util.function.ToDoubleBiFunction; + +/** + * Given a list of poses, this class finds the shortest possible route that visits each pose exactly + * once and returns to the origin pose. + * + * @see https://en.wikipedia.org/wiki/Travelling_salesman_problem + */ +public class TravelingSalesman { + // Default cost is 2D distance between poses + private final ToDoubleBiFunction m_cost; + + /** + * Constructs a traveling salesman problem solver with a cost function defined as the 2D distance + * between poses. + */ + public TravelingSalesman() { + this((Pose2d a, Pose2d b) -> Math.hypot(a.getX() - b.getX(), a.getY() - b.getY())); + } + + /** + * Constructs a traveling salesman problem solver with a user-provided cost function. + * + * @param cost Function that returns the cost between two poses. The sum of the costs for every + * pair of poses is minimized. + */ + public TravelingSalesman(ToDoubleBiFunction cost) { + m_cost = cost; + } + + /** + * Finds the path through every pose that minimizes the cost. The first pose in the returned array + * is the first pose that was passed in. + * + * @param A Num defining the length of the path and the number of poses. + * @param poses An array of Pose2ds the path must pass through. + * @param iterations The number of times the solver attempts to find a better random neighbor. + * @return The optimized path as an array of Pose2ds. + */ + public Pose2d[] solve(Pose2d[] poses, int iterations) { + var solver = + new SimulatedAnnealing<>( + 1.0, + this::neighbor, + // Total cost is sum of all costs between adjacent pose pairs in path + (Vector state) -> { + double sum = 0.0; + for (int i = 0; i < state.getNumRows(); ++i) { + sum += + m_cost.applyAsDouble( + poses[(int) state.get(i, 0)], + poses[(int) state.get((i + 1) % poses.length, 0)]); + } + return sum; + }); + + var initial = new Vector(() -> poses.length); + for (int i = 0; i < poses.length; ++i) { + initial.set(i, 0, i); + } + + var indices = solver.solve(initial, iterations); + + var solution = new Pose2d[poses.length]; + for (int i = 0; i < poses.length; ++i) { + solution[i] = poses[(int) indices.get(i, 0)]; + } + + // Rotate solution list until solution[0] = poses[0] + Collections.rotate(Arrays.asList(solution), -Arrays.asList(solution).indexOf(poses[0])); + + return solution; + } + + /** + * A random neighbor is generated to try to replace the current one. + * + * @param state A vector that is a list of indices that defines the path through the path array. + * @return Generates a random neighbor of the current state by flipping a random range in the path + * array. + */ + private Vector neighbor(Vector state) { + var proposedState = new Vector<>(state); + + int rangeStart = (int) (Math.random() * (state.getNumRows() - 1)); + int rangeEnd = (int) (Math.random() * (state.getNumRows() - 1)); + if (rangeEnd < rangeStart) { + int temp = rangeEnd; + rangeEnd = rangeStart; + rangeStart = temp; + } + + for (int i = rangeStart; i <= (rangeStart + rangeEnd) / 2; ++i) { + double temp = proposedState.get(i, 0); + proposedState.set(i, 0, state.get(rangeEnd - (i - rangeStart), 0)); + proposedState.set(rangeEnd - (i - rangeStart), 0, temp); + } + + return proposedState; + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/spline/CubicHermiteSpline.java b/wpimath/src/main/java/edu/wpi/first/math/spline/CubicHermiteSpline.java index 6e130399405..72108a5deb5 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/spline/CubicHermiteSpline.java +++ b/wpimath/src/main/java/edu/wpi/first/math/spline/CubicHermiteSpline.java @@ -6,10 +6,14 @@ import org.ejml.simple.SimpleMatrix; +/** Represents a hermite spline of degree 3. */ public class CubicHermiteSpline extends Spline { private static SimpleMatrix hermiteBasis; private final SimpleMatrix m_coefficients; + private final ControlVector m_initialControlVector; + private final ControlVector m_finalControlVector; + /** * Constructs a cubic hermite spline with the specified control vectors. Each control vector * contains info about the location of the point and its first derivative. @@ -60,6 +64,10 @@ public CubicHermiteSpline( m_coefficients.set(4, i, m_coefficients.get(2, i) * (2 - i)); m_coefficients.set(5, i, m_coefficients.get(3, i) * (2 - i)); } + + // Assign member variables. + m_initialControlVector = new ControlVector(xInitialControlVector, yInitialControlVector); + m_finalControlVector = new ControlVector(xFinalControlVector, yFinalControlVector); } /** @@ -68,10 +76,30 @@ public CubicHermiteSpline( * @return The coefficients matrix. */ @Override - protected SimpleMatrix getCoefficients() { + public SimpleMatrix getCoefficients() { return m_coefficients; } + /** + * Returns the initial control vector that created this spline. + * + * @return The initial control vector that created this spline. + */ + @Override + public ControlVector getInitialControlVector() { + return m_initialControlVector; + } + + /** + * Returns the final control vector that created this spline. + * + * @return The final control vector that created this spline. + */ + @Override + public ControlVector getFinalControlVector() { + return m_finalControlVector; + } + /** * Returns the hermite basis matrix for cubic hermite spline interpolation. * @@ -121,8 +149,8 @@ private SimpleMatrix makeHermiteBasis() { * @return The control vector matrix for a dimension. */ private SimpleMatrix getControlVectorFromArrays(double[] initialVector, double[] finalVector) { - if (initialVector.length != 2 || finalVector.length != 2) { - throw new IllegalArgumentException("Size of vectors must be 2"); + if (initialVector.length < 2 || finalVector.length < 2) { + throw new IllegalArgumentException("Size of vectors must be 2 or greater."); } return new SimpleMatrix( 4, diff --git a/wpimath/src/main/java/edu/wpi/first/math/spline/PoseWithCurvature.java b/wpimath/src/main/java/edu/wpi/first/math/spline/PoseWithCurvature.java index 30b3caefef6..94ab7616d00 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/spline/PoseWithCurvature.java +++ b/wpimath/src/main/java/edu/wpi/first/math/spline/PoseWithCurvature.java @@ -8,10 +8,10 @@ /** Represents a pair of a pose and a curvature. */ public class PoseWithCurvature { - // Represents the pose. + /** Represents the pose. */ public Pose2d poseMeters; - // Represents the curvature. + /** Represents the curvature. */ public double curvatureRadPerMeter; /** @@ -27,6 +27,6 @@ public PoseWithCurvature(Pose2d poseMeters, double curvatureRadPerMeter) { /** Constructs a PoseWithCurvature with default values. */ public PoseWithCurvature() { - poseMeters = new Pose2d(); + poseMeters = Pose2d.kZero; } } diff --git a/wpimath/src/main/java/edu/wpi/first/math/spline/QuinticHermiteSpline.java b/wpimath/src/main/java/edu/wpi/first/math/spline/QuinticHermiteSpline.java index be909993198..5d38bef60a7 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/spline/QuinticHermiteSpline.java +++ b/wpimath/src/main/java/edu/wpi/first/math/spline/QuinticHermiteSpline.java @@ -6,10 +6,14 @@ import org.ejml.simple.SimpleMatrix; +/** Represents a hermite spline of degree 5. */ public class QuinticHermiteSpline extends Spline { private static SimpleMatrix hermiteBasis; private final SimpleMatrix m_coefficients; + private final ControlVector m_initialControlVector; + private final ControlVector m_finalControlVector; + /** * Constructs a quintic hermite spline with the specified control vectors. Each control vector * contains into about the location of the point, its first derivative, and its second derivative. @@ -60,6 +64,10 @@ public QuinticHermiteSpline( m_coefficients.set(4, i, m_coefficients.get(2, i) * (4 - i)); m_coefficients.set(5, i, m_coefficients.get(3, i) * (4 - i)); } + + // Assign member variables. + m_initialControlVector = new ControlVector(xInitialControlVector, yInitialControlVector); + m_finalControlVector = new ControlVector(xFinalControlVector, yFinalControlVector); } /** @@ -68,10 +76,30 @@ public QuinticHermiteSpline( * @return The coefficients matrix. */ @Override - protected SimpleMatrix getCoefficients() { + public SimpleMatrix getCoefficients() { return m_coefficients; } + /** + * Returns the initial control vector that created this spline. + * + * @return The initial control vector that created this spline. + */ + @Override + public ControlVector getInitialControlVector() { + return m_initialControlVector; + } + + /** + * Returns the final control vector that created this spline. + * + * @return The final control vector that created this spline. + */ + @Override + public ControlVector getFinalControlVector() { + return m_finalControlVector; + } + /** * Returns the hermite basis matrix for quintic hermite spline interpolation. * diff --git a/wpimath/src/main/java/edu/wpi/first/math/spline/Spline.java b/wpimath/src/main/java/edu/wpi/first/math/spline/Spline.java index 83b35f35477..dc6c5e69969 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/spline/Spline.java +++ b/wpimath/src/main/java/edu/wpi/first/math/spline/Spline.java @@ -27,7 +27,21 @@ public abstract class Spline { * * @return The coefficients of the spline. */ - protected abstract SimpleMatrix getCoefficients(); + public abstract SimpleMatrix getCoefficients(); + + /** + * Returns the initial control vector that created this spline. + * + * @return The initial control vector that created this spline. + */ + public abstract ControlVector getInitialControlVector(); + + /** + * Returns the final control vector that created this spline. + * + * @return The final control vector that created this spline. + */ + public abstract ControlVector getFinalControlVector(); /** * Gets the pose and curvature at some point t on the spline. @@ -85,7 +99,10 @@ public PoseWithCurvature getPoint(double t) { * the value of x[2] is the second derivative in the x dimension. */ public static class ControlVector { + /** The x components of the control vector. */ public double[] x; + + /** The y components of the control vector. */ public double[] y; /** diff --git a/wpimath/src/main/java/edu/wpi/first/math/spline/SplineHelper.java b/wpimath/src/main/java/edu/wpi/first/math/spline/SplineHelper.java index 651b028c180..3ba27144039 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/spline/SplineHelper.java +++ b/wpimath/src/main/java/edu/wpi/first/math/spline/SplineHelper.java @@ -8,7 +8,9 @@ import edu.wpi.first.math.geometry.Translation2d; import java.util.Arrays; import java.util.List; +import org.ejml.simple.SimpleMatrix; +/** Helper class that is used to generate cubic and quintic splines from user provided waypoints. */ public final class SplineHelper { /** Private constructor because this is a utility class. */ private SplineHelper() {} @@ -217,6 +219,79 @@ public static QuinticHermiteSpline[] getQuinticSplinesFromControlVectors( return splines; } + /** + * Optimizes the curvature of 2 or more quintic splines at knot points. Overall, this reduces the + * integral of the absolute value of the second derivative across the set of splines. + * + * @param splines An array of un-optimized quintic splines. + * @return An array of optimized quintic splines. + */ + @SuppressWarnings({"LocalVariableName", "PMD.AvoidInstantiatingObjectsInLoops"}) + public static QuinticHermiteSpline[] optimizeCurvature(QuinticHermiteSpline[] splines) { + // If there's only spline in the array, we can't optimize anything so just return that. + if (splines.length < 2) { + return splines; + } + + // Implements Section 4.1.2 of + // http://www2.informatik.uni-freiburg.de/~lau/students/Sprunk2008.pdf. + + // Cubic splines minimize the integral of the second derivative's absolute value. Therefore, we + // can create cubic splines with the same 0th and 1st derivatives and the provided quintic + // splines, find the second derivative of those cubic splines and then use a weighted average + // for the second derivatives of the quintic splines. + + QuinticHermiteSpline[] optimizedSplines = new QuinticHermiteSpline[splines.length]; + for (int i = 0; i < splines.length - 1; ++i) { + QuinticHermiteSpline a = splines[i]; + QuinticHermiteSpline b = splines[i + 1]; + + // Get the control vectors that created the quintic splines above. + Spline.ControlVector aInitial = a.getInitialControlVector(); + Spline.ControlVector aFinal = a.getFinalControlVector(); + Spline.ControlVector bInitial = b.getInitialControlVector(); + Spline.ControlVector bFinal = b.getFinalControlVector(); + + // Create cubic splines with the same control vectors. + CubicHermiteSpline ca = new CubicHermiteSpline(aInitial.x, aFinal.x, aInitial.y, aFinal.y); + CubicHermiteSpline cb = new CubicHermiteSpline(bInitial.x, bFinal.x, bInitial.y, bFinal.y); + + // Calculate the second derivatives at the knot points. + SimpleMatrix bases = new SimpleMatrix(4, 1, true, new double[] {1, 1, 1, 1}); + SimpleMatrix combinedA = ca.getCoefficients().mult(bases); + + double ddxA = combinedA.get(4, 0); + double ddyA = combinedA.get(5, 0); + double ddxB = cb.getCoefficients().get(4, 1); + double ddyB = cb.getCoefficients().get(5, 1); + + // Calculate the parameters for the weighted average. + double dAB = Math.hypot(aFinal.x[0] - aInitial.x[0], aFinal.y[0] - aInitial.y[0]); + double dBC = Math.hypot(bFinal.x[0] - bInitial.x[0], bFinal.y[0] - bInitial.y[0]); + double alpha = dBC / (dAB + dBC); + double beta = dAB / (dAB + dBC); + + // Calculate the weighted average. + double ddx = alpha * ddxA + beta * ddxB; + double ddy = alpha * ddyA + beta * ddyB; + + // Create new splines. + optimizedSplines[i] = + new QuinticHermiteSpline( + aInitial.x, + new double[] {aFinal.x[0], aFinal.x[1], ddx}, + aInitial.y, + new double[] {aFinal.y[0], aFinal.y[1], ddy}); + optimizedSplines[i + 1] = + new QuinticHermiteSpline( + new double[] {bInitial.x[0], bInitial.x[1], ddx}, + bFinal.x, + new double[] {bInitial.y[0], bInitial.y[1], ddy}, + bFinal.y); + } + return optimizedSplines; + } + /** * Thomas algorithm for solving tridiagonal systems Af = d. * diff --git a/wpimath/src/main/java/edu/wpi/first/math/spline/SplineParameterizer.java b/wpimath/src/main/java/edu/wpi/first/math/spline/SplineParameterizer.java index b2a34a5db5d..5cf742b3da4 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/spline/SplineParameterizer.java +++ b/wpimath/src/main/java/edu/wpi/first/math/spline/SplineParameterizer.java @@ -56,6 +56,7 @@ private static class StackContents { } } + /** Exception for malformed splines. */ public static class MalformedSplineException extends RuntimeException { /** * Create a new exception with the given message. diff --git a/wpimath/src/main/java/edu/wpi/first/math/system/Discretization.java b/wpimath/src/main/java/edu/wpi/first/math/system/Discretization.java index b2fe9c8c8ec..b4afdf476af 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/system/Discretization.java +++ b/wpimath/src/main/java/edu/wpi/first/math/system/Discretization.java @@ -9,6 +9,7 @@ import edu.wpi.first.math.Pair; import org.ejml.simple.SimpleMatrix; +/** Discretization helper functions. */ public final class Discretization { private Discretization() { // Utility class diff --git a/wpimath/src/main/java/edu/wpi/first/math/system/LinearSystem.java b/wpimath/src/main/java/edu/wpi/first/math/system/LinearSystem.java index d7b660298ad..923f11e48fc 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/system/LinearSystem.java +++ b/wpimath/src/main/java/edu/wpi/first/math/system/LinearSystem.java @@ -7,7 +7,43 @@ import edu.wpi.first.math.Matrix; import edu.wpi.first.math.Num; import edu.wpi.first.math.numbers.N1; +import edu.wpi.first.math.numbers.N10; +import edu.wpi.first.math.numbers.N11; +import edu.wpi.first.math.numbers.N12; +import edu.wpi.first.math.numbers.N13; +import edu.wpi.first.math.numbers.N14; +import edu.wpi.first.math.numbers.N15; +import edu.wpi.first.math.numbers.N16; +import edu.wpi.first.math.numbers.N17; +import edu.wpi.first.math.numbers.N18; +import edu.wpi.first.math.numbers.N19; +import edu.wpi.first.math.numbers.N2; +import edu.wpi.first.math.numbers.N20; +import edu.wpi.first.math.numbers.N3; +import edu.wpi.first.math.numbers.N4; +import edu.wpi.first.math.numbers.N5; +import edu.wpi.first.math.numbers.N6; +import edu.wpi.first.math.numbers.N7; +import edu.wpi.first.math.numbers.N8; +import edu.wpi.first.math.numbers.N9; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import org.ejml.simple.SimpleMatrix; +/** + * A plant defined using state-space notation. + * + *

    A plant is a mathematical model of a system's dynamics. + * + *

    For more on the underlying math, read + * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + * + * @param Number of states. + * @param Number of inputs. + * @param Number of outputs. + */ public class LinearSystem { /** Continuous system matrix. */ private final Matrix m_A; @@ -168,7 +204,7 @@ public Matrix calculateX( Matrix x, Matrix clampedU, double dtSeconds) { var discABpair = Discretization.discretizeAB(m_A, m_B, dtSeconds); - return (discABpair.getFirst().times(x)).plus(discABpair.getSecond().times(clampedU)); + return discABpair.getFirst().times(x).plus(discABpair.getSecond().times(clampedU)); } /** @@ -184,6 +220,141 @@ public Matrix calculateY(Matrix x, Matrix c return m_C.times(x).plus(m_D.times(clampedU)); } + /** + * Returns the LinearSystem with the outputs listed in outputIndices. + * + *

    This is used by state observers such as the Kalman Filter. + * + * @param outputIndices the list of output indices to include in the sliced system. + * @return the sliced LinearSystem with outputs set to row vectors of LinearSystem. + * @throws IllegalArgumentException if any outputIndices are outside the range of system outputs. + * @throws IllegalArgumentException if number of outputIndices exceeds the number of system + * outputs. + * @throws IllegalArgumentException if duplication exists in outputIndices. + */ + public LinearSystem slice(int... outputIndices) { + for (int index : outputIndices) { + if (index < 0 || index >= m_C.getNumRows()) { + throw new IllegalArgumentException( + "Output indices out of range. This is usually due to model implementation errors."); + } + } + + if (outputIndices.length >= m_C.getNumRows()) { + throw new IllegalArgumentException( + "More outputs requested than available. This is usually due to model implementation " + + "errors."); + } + + List outputIndicesList = + Arrays.stream(outputIndices).distinct().boxed().collect(Collectors.toList()); + Collections.sort(outputIndicesList); + + if (outputIndices.length != outputIndicesList.size()) { + throw new IllegalArgumentException( + "Duplicate indices exist. This is usually due to model implementation " + "errors."); + } + + SimpleMatrix new_C_Storage = new SimpleMatrix(outputIndices.length, m_C.getNumCols()); + int row = 0; + for (var index : outputIndicesList) { + var current_row_data = m_C.extractRowVector(index).getData(); + new_C_Storage.setRow(row, 0, current_row_data); + row++; + } + + SimpleMatrix new_D_Storage = new SimpleMatrix(outputIndices.length, m_D.getNumCols()); + row = 0; + for (var index : outputIndicesList) { + var current_row_data = m_D.extractRowVector(index).getData(); + new_D_Storage.setRow(row, 0, current_row_data); + row++; + } + + switch (outputIndices.length) { + case 20: + Matrix new_C20 = new Matrix<>(new_C_Storage); + Matrix new_D20 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C20, new_D20); + case 19: + Matrix new_C19 = new Matrix<>(new_C_Storage); + Matrix new_D19 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C19, new_D19); + case 18: + Matrix new_C18 = new Matrix<>(new_C_Storage); + Matrix new_D18 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C18, new_D18); + case 17: + Matrix new_C17 = new Matrix<>(new_C_Storage); + Matrix new_D17 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C17, new_D17); + case 16: + Matrix new_C16 = new Matrix<>(new_C_Storage); + Matrix new_D16 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C16, new_D16); + case 15: + Matrix new_C15 = new Matrix<>(new_C_Storage); + Matrix new_D15 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C15, new_D15); + case 14: + Matrix new_C14 = new Matrix<>(new_C_Storage); + Matrix new_D14 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C14, new_D14); + case 13: + Matrix new_C13 = new Matrix<>(new_C_Storage); + Matrix new_D13 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C13, new_D13); + case 12: + Matrix new_C12 = new Matrix<>(new_C_Storage); + Matrix new_D12 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C12, new_D12); + case 11: + Matrix new_C11 = new Matrix<>(new_C_Storage); + Matrix new_D11 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C11, new_D11); + case 10: + Matrix new_C10 = new Matrix<>(new_C_Storage); + Matrix new_D10 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C10, new_D10); + case 9: + Matrix new_C9 = new Matrix<>(new_C_Storage); + Matrix new_D9 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C9, new_D9); + case 8: + Matrix new_C8 = new Matrix<>(new_C_Storage); + Matrix new_D8 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C8, new_D8); + case 7: + Matrix new_C7 = new Matrix<>(new_C_Storage); + Matrix new_D7 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C7, new_D7); + case 6: + Matrix new_C6 = new Matrix<>(new_C_Storage); + Matrix new_D6 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C6, new_D6); + case 5: + Matrix new_C5 = new Matrix<>(new_C_Storage); + Matrix new_D5 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C5, new_D5); + case 4: + Matrix new_C4 = new Matrix<>(new_C_Storage); + Matrix new_D4 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C4, new_D4); + case 3: + Matrix new_C3 = new Matrix<>(new_C_Storage); + Matrix new_D3 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C3, new_D3); + case 2: + Matrix new_C2 = new Matrix<>(new_C_Storage); + Matrix new_D2 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C2, new_D2); + default: + Matrix new_C1 = new Matrix<>(new_C_Storage); + Matrix new_D1 = new Matrix<>(new_D_Storage); + return new LinearSystem<>(m_A, m_B, new_C1, new_D1); + } + } + @Override public String toString() { return String.format( diff --git a/wpimath/src/main/java/edu/wpi/first/math/system/LinearSystemLoop.java b/wpimath/src/main/java/edu/wpi/first/math/system/LinearSystemLoop.java index 02b1da0aef2..78cace9a21d 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/system/LinearSystemLoop.java +++ b/wpimath/src/main/java/edu/wpi/first/math/system/LinearSystemLoop.java @@ -25,8 +25,12 @@ * of the controller (U is an output because that's what goes to the motors and Y is an input * because that's what comes back from the sensors). * - *

    For more on the underlying math, read - * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + *

    For more on the underlying math, read https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + * + * @param Number of states. + * @param Number of inputs. + * @param Number of outputs. */ public class LinearSystemLoop { private final LinearQuadraticRegulator m_controller; @@ -265,7 +269,7 @@ public KalmanFilter getObserver() { * * @param initialState The initial state. */ - public void reset(Matrix initialState) { + public final void reset(Matrix initialState) { m_nextR.fill(0.0); m_controller.reset(); m_feedforward.reset(initialState); @@ -288,7 +292,7 @@ public Matrix getError() { * @return The error at that index. */ public double getError(int index) { - return (getController().getR().minus(m_observer.getXhat())).get(index, 0); + return getController().getR().minus(m_observer.getXhat()).get(index, 0); } /** diff --git a/wpimath/src/main/java/edu/wpi/first/math/system/NumericalIntegration.java b/wpimath/src/main/java/edu/wpi/first/math/system/NumericalIntegration.java index e9b46fcbe1d..36d7bcb7a74 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/system/NumericalIntegration.java +++ b/wpimath/src/main/java/edu/wpi/first/math/system/NumericalIntegration.java @@ -11,6 +11,7 @@ import java.util.function.DoubleFunction; import java.util.function.Function; +/** Numerical integration utilities. */ public final class NumericalIntegration { private NumericalIntegration() { // utility Class diff --git a/wpimath/src/main/java/edu/wpi/first/math/system/NumericalJacobian.java b/wpimath/src/main/java/edu/wpi/first/math/system/NumericalJacobian.java index 43eba93bbe7..1be22a8fca5 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/system/NumericalJacobian.java +++ b/wpimath/src/main/java/edu/wpi/first/math/system/NumericalJacobian.java @@ -11,6 +11,7 @@ import java.util.function.BiFunction; import java.util.function.Function; +/** Numerical Jacobian utilities. */ public final class NumericalJacobian { private NumericalJacobian() { // Utility Class. diff --git a/wpimath/src/main/java/edu/wpi/first/math/system/plant/DCMotor.java b/wpimath/src/main/java/edu/wpi/first/math/system/plant/DCMotor.java index 0c6e3346b2c..6d18846f254 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/system/plant/DCMotor.java +++ b/wpimath/src/main/java/edu/wpi/first/math/system/plant/DCMotor.java @@ -4,19 +4,44 @@ package edu.wpi.first.math.system.plant; +import edu.wpi.first.math.system.plant.proto.DCMotorProto; +import edu.wpi.first.math.system.plant.struct.DCMotorStruct; import edu.wpi.first.math.util.Units; +import edu.wpi.first.util.protobuf.ProtobufSerializable; +import edu.wpi.first.util.struct.StructSerializable; /** Holds the constants for a DC motor. */ -public class DCMotor { +public class DCMotor implements ProtobufSerializable, StructSerializable { + /** Voltage at which the motor constants were measured. */ public final double nominalVoltageVolts; + + /** Torque when stalled. */ public final double stallTorqueNewtonMeters; + + /** Current draw when stalled. */ public final double stallCurrentAmps; + + /** Current draw under no load. */ public final double freeCurrentAmps; + + /** Angular velocity under no load. */ public final double freeSpeedRadPerSec; + + /** Motor internal resistance. */ public final double rOhms; + + /** Motor velocity constant. */ public final double KvRadPerSecPerVolt; + + /** Motor torque constant. */ public final double KtNMPerAmp; + /** DCMotor protobuf for serialization. */ + public static final DCMotorProto proto = new DCMotorProto(); + + /** DCMotor struct for serialization. */ + public static final DCMotorStruct struct = new DCMotorStruct(); + /** * Constructs a DC motor. * diff --git a/wpimath/src/main/java/edu/wpi/first/math/system/plant/LinearSystemId.java b/wpimath/src/main/java/edu/wpi/first/math/system/plant/LinearSystemId.java index 3ab305872db..761148a0f2c 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/system/plant/LinearSystemId.java +++ b/wpimath/src/main/java/edu/wpi/first/math/system/plant/LinearSystemId.java @@ -12,6 +12,7 @@ import edu.wpi.first.math.numbers.N2; import edu.wpi.first.math.system.LinearSystem; +/** Linear system ID utility functions. */ public final class LinearSystemId { private LinearSystemId() { // Utility class @@ -28,7 +29,7 @@ private LinearSystemId() { * @return A LinearSystem representing the given characterized constants. * @throws IllegalArgumentException if massKg <= 0, radiusMeters <= 0, or gearing <= 0. */ - public static LinearSystem createElevatorSystem( + public static LinearSystem createElevatorSystem( DCMotor motor, double massKg, double radiusMeters, double gearing) { if (massKg <= 0.0) { throw new IllegalArgumentException("massKg must be greater than zero."); @@ -51,8 +52,8 @@ public static LinearSystem createElevatorSystem( * motor.KtNMPerAmp / (motor.rOhms * radiusMeters * radiusMeters * massKg * motor.KvRadPerSecPerVolt)), VecBuilder.fill(0, gearing * motor.KtNMPerAmp / (motor.rOhms * radiusMeters * massKg)), - MatBuilder.fill(Nat.N1(), Nat.N2(), 1, 0), - new Matrix<>(Nat.N1(), Nat.N1())); + Matrix.eye(Nat.N2()), + new Matrix<>(Nat.N2(), Nat.N1())); } /** @@ -134,14 +135,14 @@ public static LinearSystem createDCMotorSystem( *

    u = K_v v + K_a a * * @param kV The velocity gain, in volts/(unit/sec) - * @param kA The acceleration gain, in volts/(unit/sec^2) + * @param kA The acceleration gain, in volts/(unit/sec²) * @return A LinearSystem representing the given characterized constants. - * @throws IllegalArgumentException if kV <= 0 or kA <= 0. + * @throws IllegalArgumentException if kV < 0 or kA <= 0. * @see https://github.com/wpilibsuite/sysid */ public static LinearSystem createDCMotorSystem(double kV, double kA) { - if (kV <= 0.0) { - throw new IllegalArgumentException("Kv must be greater than zero."); + if (kV < 0.0) { + throw new IllegalArgumentException("Kv must be greater than or equal to zero."); } if (kA <= 0.0) { throw new IllegalArgumentException("Ka must be greater than zero."); @@ -218,7 +219,7 @@ public static LinearSystem createDrivetrainVelocitySystem( * this will be greater than 1. * @return A LinearSystem representing the given characterized constants. */ - public static LinearSystem createSingleJointedArmSystem( + public static LinearSystem createSingleJointedArmSystem( DCMotor motor, double JKgSquaredMeters, double gearing) { if (JKgSquaredMeters <= 0.0) { throw new IllegalArgumentException("JKgSquaredMeters must be greater than zero."); @@ -238,8 +239,8 @@ public static LinearSystem createSingleJointedArmSystem( * motor.KtNMPerAmp / (motor.KvRadPerSecPerVolt * motor.rOhms * JKgSquaredMeters)), VecBuilder.fill(0, gearing * motor.KtNMPerAmp / (motor.rOhms * JKgSquaredMeters)), - MatBuilder.fill(Nat.N1(), Nat.N2(), 1, 0), - new Matrix<>(Nat.N1(), Nat.N1())); + Matrix.eye(Nat.N2()), + new Matrix<>(Nat.N2(), Nat.N1())); } /** @@ -255,14 +256,14 @@ public static LinearSystem createSingleJointedArmSystem( *

    u = K_v v + K_a a * * @param kV The velocity gain, in volts/(unit/sec) - * @param kA The acceleration gain, in volts/(unit/sec^2) + * @param kA The acceleration gain, in volts/(unit/sec²) * @return A LinearSystem representing the given characterized constants. - * @throws IllegalArgumentException if kV <= 0 or kA <= 0. + * @throws IllegalArgumentException if kV < 0 or kA <= 0. * @see https://github.com/wpilibsuite/sysid */ public static LinearSystem identifyVelocitySystem(double kV, double kA) { - if (kV <= 0.0) { - throw new IllegalArgumentException("Kv must be greater than zero."); + if (kV < 0.0) { + throw new IllegalArgumentException("Kv must be greater than or equal to zero."); } if (kA <= 0.0) { throw new IllegalArgumentException("Ka must be greater than zero."); @@ -290,12 +291,12 @@ public static LinearSystem identifyVelocitySystem(double kV, double * @param kV The velocity gain, in volts/(unit/sec) * @param kA The acceleration gain, in volts/(unit/sec²) * @return A LinearSystem representing the given characterized constants. - * @throws IllegalArgumentException if kV <= 0 or kA <= 0. + * @throws IllegalArgumentException if kV < 0 or kA <= 0. * @see https://github.com/wpilibsuite/sysid */ - public static LinearSystem identifyPositionSystem(double kV, double kA) { - if (kV <= 0.0) { - throw new IllegalArgumentException("Kv must be greater than zero."); + public static LinearSystem identifyPositionSystem(double kV, double kA) { + if (kV < 0.0) { + throw new IllegalArgumentException("Kv must be greater than or equal to zero."); } if (kA <= 0.0) { throw new IllegalArgumentException("Ka must be greater than zero."); @@ -304,8 +305,8 @@ public static LinearSystem identifyPositionSystem(double kV, double return new LinearSystem<>( MatBuilder.fill(Nat.N2(), Nat.N2(), 0.0, 1.0, 0.0, -kV / kA), VecBuilder.fill(0.0, 1.0 / kA), - MatBuilder.fill(Nat.N1(), Nat.N2(), 1.0, 0.0), - VecBuilder.fill(0.0)); + Matrix.eye(Nat.N2()), + new Matrix<>(Nat.N2(), Nat.N1())); } /** diff --git a/wpimath/src/main/java/edu/wpi/first/math/system/plant/proto/DCMotorProto.java b/wpimath/src/main/java/edu/wpi/first/math/system/plant/proto/DCMotorProto.java new file mode 100644 index 00000000000..f9e4aa39576 --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/system/plant/proto/DCMotorProto.java @@ -0,0 +1,47 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.system.plant.proto; + +import edu.wpi.first.math.proto.Plant.ProtobufDCMotor; +import edu.wpi.first.math.system.plant.DCMotor; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class DCMotorProto implements Protobuf { + @Override + public Class getTypeClass() { + return DCMotor.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufDCMotor.getDescriptor(); + } + + @Override + public ProtobufDCMotor createMessage() { + return ProtobufDCMotor.newInstance(); + } + + @Override + public DCMotor unpack(ProtobufDCMotor msg) { + return new DCMotor( + msg.getNominalVoltage(), + msg.getStallTorque(), + msg.getStallCurrent(), + msg.getFreeCurrent(), + msg.getFreeSpeed(), + 1); + } + + @Override + public void pack(ProtobufDCMotor msg, DCMotor value) { + msg.setNominalVoltage(value.nominalVoltageVolts); + msg.setStallTorque(value.stallTorqueNewtonMeters); + msg.setStallCurrent(value.stallCurrentAmps); + msg.setFreeCurrent(value.freeCurrentAmps); + msg.setFreeSpeed(value.freeSpeedRadPerSec); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/system/plant/struct/DCMotorStruct.java b/wpimath/src/main/java/edu/wpi/first/math/system/plant/struct/DCMotorStruct.java new file mode 100644 index 00000000000..da159fc63ad --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/system/plant/struct/DCMotorStruct.java @@ -0,0 +1,51 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.system.plant.struct; + +import edu.wpi.first.math.system.plant.DCMotor; +import edu.wpi.first.util.struct.Struct; +import java.nio.ByteBuffer; + +public class DCMotorStruct implements Struct { + @Override + public Class getTypeClass() { + return DCMotor.class; + } + + @Override + public String getTypeString() { + return "struct:DCMotor"; + } + + @Override + public int getSize() { + return kSizeDouble * 5; + } + + @Override + public String getSchema() { + return "double nominal_voltage;double stall_torque;double stall_current;" + + "double free_current;double free_speed"; + } + + @Override + public DCMotor unpack(ByteBuffer bb) { + double nominalVoltage = bb.getDouble(); + double stallTorque = bb.getDouble(); + double stallCurrent = bb.getDouble(); + double freeCurrent = bb.getDouble(); + double freeSpeed = bb.getDouble(); + return new DCMotor(nominalVoltage, stallTorque, stallCurrent, freeCurrent, freeSpeed, 1); + } + + @Override + public void pack(ByteBuffer bb, DCMotor value) { + bb.putDouble(value.nominalVoltageVolts); + bb.putDouble(value.stallTorqueNewtonMeters); + bb.putDouble(value.stallCurrentAmps); + bb.putDouble(value.freeCurrentAmps); + bb.putDouble(value.freeSpeedRadPerSec); + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/trajectory/ExponentialProfile.java b/wpimath/src/main/java/edu/wpi/first/math/trajectory/ExponentialProfile.java index 1580e853c77..76b7d6e764a 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/trajectory/ExponentialProfile.java +++ b/wpimath/src/main/java/edu/wpi/first/math/trajectory/ExponentialProfile.java @@ -39,10 +39,20 @@ public class ExponentialProfile { private final Constraints m_constraints; + /** Profile timing. */ public static class ProfileTiming { + /** Profile inflection time. */ public final double inflectionTime; + + /** Total profile time. */ public final double totalTime; + /** + * Constructs a ProfileTiming. + * + * @param inflectionTime Profile inflection time. + * @param totalTime Total profile time. + */ protected ProfileTiming(double inflectionTime, double totalTime) { this.inflectionTime = inflectionTime; this.totalTime = totalTime; @@ -55,18 +65,23 @@ protected ProfileTiming(double inflectionTime, double totalTime) { * @return if the profile is finished at time t. */ public boolean isFinished(double t) { - return t > inflectionTime; + return t >= inflectionTime; } } + /** Profile constraints. */ public static class Constraints { + /** Maximum unsigned input voltage. */ public final double maxInput; + /** The State-Space 1x1 system matrix. */ public final double A; + + /** The State-Space 1x1 input matrix. */ public final double B; /** - * Construct constraints for an ExponentialProfile. + * Constructs constraints for an ExponentialProfile. * * @param maxInput maximum unsigned input voltage * @param A The State-Space 1x1 system matrix. @@ -88,7 +103,7 @@ public double maxVelocity() { } /** - * Construct constraints for an ExponentialProfile from characteristics. + * Constructs constraints for an ExponentialProfile from characteristics. * * @param maxInput maximum unsigned input voltage * @param kV The velocity gain. @@ -100,7 +115,7 @@ public static Constraints fromCharacteristics(double maxInput, double kV, double } /** - * Construct constraints for an ExponentialProfile from State-Space parameters. + * Constructs constraints for an ExponentialProfile from State-Space parameters. * * @param maxInput maximum unsigned input voltage * @param A The State-Space 1x1 system matrix. @@ -112,13 +127,19 @@ public static Constraints fromStateSpace(double maxInput, double A, double B) { } } + /** Profile state. */ public static class State { - public final double position; + /** The position at this state. */ + public double position; + + /** The velocity at this state. */ + public double velocity; - public final double velocity; + /** Default constructor. */ + public State() {} /** - * Construct a state within an exponential profile. + * Constructs a state within an exponential profile. * * @param position The position at this state. * @param velocity The velocity at this state. @@ -145,7 +166,7 @@ public int hashCode() { } /** - * Construct an ExponentialProfile. + * Constructs an ExponentialProfile. * * @param constraints The constraints on the profile, like maximum input. */ @@ -154,10 +175,10 @@ public ExponentialProfile(Constraints constraints) { } /** - * Calculate the correct position and velocity for the profile at a time t where the current state - * is at time t = 0. + * Calculates the position and velocity for the profile at a time t where the current state is at + * time t = 0. * - * @param t The time since the beginning of the profile. + * @param t How long to advance from the current state toward the desired state. * @param current The current state. * @param goal The desired state when the profile is complete. * @return The position and velocity of the profile at time t. @@ -170,7 +191,7 @@ public State calculate(double t, State current, State goal) { var timing = calculateProfileTiming(current, inflectionPoint, goal, u); if (t < 0) { - return current; + return new State(current.position, current.velocity); } else if (t < timing.inflectionTime) { return new State( computeDistanceFromTime(t, u, current), computeVelocityFromTime(t, u, current)); @@ -179,12 +200,12 @@ public State calculate(double t, State current, State goal) { computeDistanceFromTime(t - timing.totalTime, -u, goal), computeVelocityFromTime(t - timing.totalTime, -u, goal)); } else { - return goal; + return new State(goal.position, goal.velocity); } } /** - * Calculate the point after which the fastest way to reach the goal state is to apply input in + * Calculates the point after which the fastest way to reach the goal state is to apply input in * the opposite direction. * * @param current The current state. @@ -199,7 +220,7 @@ public State calculateInflectionPoint(State current, State goal) { } /** - * Calculate the point after which the fastest way to reach the goal state is to apply input in + * Calculates the point after which the fastest way to reach the goal state is to apply input in * the opposite direction. * * @param current The current state. @@ -221,7 +242,7 @@ private State calculateInflectionPoint(State current, State goal, double input) } /** - * Calculate the time it will take for this profile to reach the goal state. + * Calculates the time it will take for this profile to reach the goal state. * * @param current The current state. * @param goal The desired state when the profile is complete. @@ -234,8 +255,8 @@ public double timeLeftUntil(State current, State goal) { } /** - * Calculate the time it will take for this profile to reach the inflection point, and the time it - * will take for this profile to reach the goal state. + * Calculates the time it will take for this profile to reach the inflection point, and the time + * it will take for this profile to reach the goal state. * * @param current The current state. * @param goal The desired state when the profile is complete. @@ -250,8 +271,8 @@ public ProfileTiming calculateProfileTiming(State current, State goal) { } /** - * Calculate the time it will take for this profile to reach the inflection point, and the time it - * will take for this profile to reach the goal state. + * Calculates the time it will take for this profile to reach the inflection point, and the time + * it will take for this profile to reach the goal state. * * @param current The current state. * @param inflectionPoint The inflection point of this profile. @@ -311,7 +332,7 @@ private ProfileTiming calculateProfileTiming( } /** - * Calculate the position reached after t seconds when applying an input from the initial state. + * Calculates the position reached after t seconds when applying an input from the initial state. * * @param t The time since the initial state. * @param input The signed input applied to this profile from the initial state. @@ -328,7 +349,7 @@ private double computeDistanceFromTime(double t, double input, State initial) { } /** - * Calculate the velocity reached after t seconds when applying an input from the initial state. + * Calculates the velocity reached after t seconds when applying an input from the initial state. * * @param t The time since the initial state. * @param input The signed input applied to this profile from the initial state. @@ -344,7 +365,7 @@ private double computeVelocityFromTime(double t, double input, State initial) { } /** - * Calculate the time required to reach a specified velocity given the initial velocity. + * Calculates the time required to reach a specified velocity given the initial velocity. * * @param velocity The goal velocity. * @param input The signed input applied to this profile from the initial state. @@ -360,7 +381,7 @@ private double computeTimeFromVelocity(double velocity, double input, double ini } /** - * Calculate the distance reached at the same time as the given velocity when applying the given + * Calculates the distance reached at the same time as the given velocity when applying the given * input from the initial state. * * @param velocity The velocity reached by this profile @@ -379,7 +400,7 @@ private double computeDistanceFromVelocity(double velocity, double input, State } /** - * Calculate the velocity at which input should be reversed in order to reach the goal state from + * Calculates the velocity at which input should be reversed in order to reach the goal state from * the current state. * * @param input The signed input applied to this profile from the current state. diff --git a/wpimath/src/main/java/edu/wpi/first/math/trajectory/Trajectory.java b/wpimath/src/main/java/edu/wpi/first/math/trajectory/Trajectory.java index f7120be7df1..cdcac9ef488 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/trajectory/Trajectory.java +++ b/wpimath/src/main/java/edu/wpi/first/math/trajectory/Trajectory.java @@ -7,6 +7,9 @@ import com.fasterxml.jackson.annotation.JsonProperty; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Transform2d; +import edu.wpi.first.math.trajectory.proto.TrajectoryProto; +import edu.wpi.first.math.trajectory.proto.TrajectoryStateProto; +import edu.wpi.first.util.protobuf.ProtobufSerializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -16,7 +19,10 @@ * Represents a time-parameterized trajectory. The trajectory contains of various States that * represent the pose, curvature, time elapsed, velocity, and acceleration at that point. */ -public class Trajectory { +public class Trajectory implements ProtobufSerializable { + /** Trajectory protobuf for serialization. */ + public static final TrajectoryProto proto = new TrajectoryProto(); + private final double m_totalTimeSeconds; private final List m_states; @@ -263,29 +269,33 @@ public Trajectory concatenate(Trajectory other) { * Represents a time-parameterized trajectory. The trajectory contains of various States that * represent the pose, curvature, time elapsed, velocity, and acceleration at that point. */ - public static class State { - // The time elapsed since the beginning of the trajectory. + public static class State implements ProtobufSerializable { + /** Trajectory.State protobuf for serialization. */ + public static final TrajectoryStateProto proto = new TrajectoryStateProto(); + + /** The time elapsed since the beginning of the trajectory. */ @JsonProperty("time") public double timeSeconds; - // The speed at that point of the trajectory. + /** The speed at that point of the trajectory. */ @JsonProperty("velocity") public double velocityMetersPerSecond; - // The acceleration at that point of the trajectory. + /** The acceleration at that point of the trajectory. */ @JsonProperty("acceleration") public double accelerationMetersPerSecondSq; - // The pose at that point of the trajectory. + /** The pose at that point of the trajectory. */ @JsonProperty("pose") public Pose2d poseMeters; - // The curvature at that point of the trajectory. + /** The curvature at that point of the trajectory. */ @JsonProperty("curvature") public double curvatureRadPerMeter; + /** Default constructor. */ public State() { - poseMeters = new Pose2d(); + poseMeters = Pose2d.kZero; } /** diff --git a/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrajectoryGenerator.java b/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrajectoryGenerator.java index ce90ce60019..3de3effd826 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrajectoryGenerator.java +++ b/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrajectoryGenerator.java @@ -19,7 +19,10 @@ import java.util.List; import java.util.function.BiConsumer; +/** Helper class used to generate trajectories with various constraints. */ public final class TrajectoryGenerator { + private static final Transform2d kFlip = new Transform2d(Translation2d.kZero, Rotation2d.kPi); + private static final Trajectory kDoNothingTrajectory = new Trajectory(List.of(new Trajectory.State())); private static BiConsumer errorFunc; @@ -61,8 +64,6 @@ public static Trajectory generateTrajectory( List interiorWaypoints, Spline.ControlVector end, TrajectoryConfig config) { - final var flip = new Transform2d(new Translation2d(), Rotation2d.fromDegrees(180.0)); - // Clone the control vectors. var newInitial = new Spline.ControlVector(initial.x, initial.y); var newEnd = new Spline.ControlVector(end.x, end.y); @@ -90,7 +91,7 @@ public static Trajectory generateTrajectory( // Change the points back to their original orientation. if (config.isReversed()) { for (var point : points) { - point.poseMeters = point.poseMeters.plus(flip); + point.poseMeters = point.poseMeters.plus(kFlip); point.curvatureRadPerMeter *= -1; } } @@ -139,7 +140,6 @@ public static Trajectory generateTrajectory( */ public static Trajectory generateTrajectory( ControlVectorList controlVectors, TrajectoryConfig config) { - final var flip = new Transform2d(new Translation2d(), Rotation2d.fromDegrees(180.0)); final var newControlVectors = new ArrayList(controlVectors.size()); // Create a new control vector list, flipping the orientation if reversed. @@ -167,7 +167,7 @@ public static Trajectory generateTrajectory( // Change the points back to their original orientation. if (config.isReversed()) { for (var point : points) { - point.poseMeters = point.poseMeters.plus(flip); + point.poseMeters = point.poseMeters.plus(kFlip); point.curvatureRadPerMeter *= -1; } } @@ -193,12 +193,10 @@ public static Trajectory generateTrajectory( * @return The generated trajectory. */ public static Trajectory generateTrajectory(List waypoints, TrajectoryConfig config) { - final var flip = new Transform2d(new Translation2d(), Rotation2d.fromDegrees(180.0)); - List newWaypoints = new ArrayList<>(); if (config.isReversed()) { for (Pose2d originalWaypoint : waypoints) { - newWaypoints.add(originalWaypoint.plus(flip)); + newWaypoints.add(originalWaypoint.plus(kFlip)); } } else { newWaypoints.addAll(waypoints); @@ -207,7 +205,10 @@ public static Trajectory generateTrajectory(List waypoints, TrajectoryCo // Get the spline points List points; try { - points = splinePointsFromSplines(SplineHelper.getQuinticSplinesFromWaypoints(newWaypoints)); + points = + splinePointsFromSplines( + SplineHelper.optimizeCurvature( + SplineHelper.getQuinticSplinesFromWaypoints(newWaypoints))); } catch (MalformedSplineException ex) { reportError(ex.getMessage(), ex.getStackTrace()); return kDoNothingTrajectory; @@ -216,7 +217,7 @@ public static Trajectory generateTrajectory(List waypoints, TrajectoryCo // Change the points back to their original orientation. if (config.isReversed()) { for (var point : points) { - point.poseMeters = point.poseMeters.plus(flip); + point.poseMeters = point.poseMeters.plus(kFlip); point.curvatureRadPerMeter *= -1; } } @@ -260,16 +261,27 @@ public static List splinePointsFromSplines(Spline[] splines) return splinePoints; } - // Work around type erasure signatures + /** Control vector list type that works around type erasure signatures. */ public static class ControlVectorList extends ArrayList { - public ControlVectorList(int initialCapacity) { - super(initialCapacity); - } - + /** Default constructor. */ public ControlVectorList() { super(); } + /** + * Constructs a ControlVectorList. + * + * @param initialCapacity The initial list capacity. + */ + public ControlVectorList(int initialCapacity) { + super(initialCapacity); + } + + /** + * Constructs a ControlVectorList. + * + * @param collection A collection of spline control vectors. + */ public ControlVectorList(Collection collection) { super(collection); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrajectoryParameterizer.java b/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrajectoryParameterizer.java index a741aa09db2..35b2a465056 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrajectoryParameterizer.java +++ b/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrajectoryParameterizer.java @@ -315,7 +315,13 @@ private static class ConstrainedState { } } + /** Exception for trajectory generation failure. */ public static class TrajectoryGenerationException extends RuntimeException { + /** + * Constructs a TrajectoryGenerationException. + * + * @param message Exception message. + */ public TrajectoryGenerationException(String message) { super(message); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrajectoryUtil.java b/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrajectoryUtil.java index 2cbba908615..f1b2d6a97b6 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrajectoryUtil.java +++ b/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrajectoryUtil.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.List; +/** Trajectory utilities. */ public final class TrajectoryUtil { private TrajectoryUtil() { throw new UnsupportedOperationException("This is a utility class!"); @@ -111,7 +112,13 @@ public static String serializeTrajectory(Trajectory trajectory) { return WPIMathJNI.serializeTrajectory(getElementsFromTrajectory(trajectory)); } + /** Exception for trajectory serialization failure. */ public static class TrajectorySerializationException extends RuntimeException { + /** + * Constructs a TrajectorySerializationException. + * + * @param message The exception message. + */ public TrajectorySerializationException(String message) { super(message); } diff --git a/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrapezoidProfile.java b/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrapezoidProfile.java index f14aea78f0a..7d785a2d40f 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrapezoidProfile.java +++ b/wpimath/src/main/java/edu/wpi/first/math/trajectory/TrapezoidProfile.java @@ -47,20 +47,21 @@ public class TrapezoidProfile { private final Constraints m_constraints; private State m_current; - private State m_goal; // TODO: Remove - private final boolean m_newAPI; // TODO: Remove private double m_endAccel; private double m_endFullSpeed; private double m_endDeccel; + /** Profile constraints. */ public static class Constraints { + /** Maximum velocity. */ public final double maxVelocity; + /** Maximum acceleration. */ public final double maxAcceleration; /** - * Construct constraints for a TrapezoidProfile. + * Constructs constraints for a TrapezoidProfile. * * @param maxVelocity maximum velocity * @param maxAcceleration maximum acceleration @@ -71,24 +72,48 @@ public Constraints(double maxVelocity, double maxAcceleration) { MathSharedStore.reportUsage(MathUsageId.kTrajectory_TrapezoidProfile, 1); } + /** + * Constructs constraints for a TrapezoidProfile. + * + * @param Unit type. + * @param maxVelocity maximum velocity + * @param maxAcceleration maximum acceleration + */ public > Constraints( Measure> maxVelocity, Measure>> maxAcceleration) { this(maxVelocity.baseUnitMagnitude(), maxAcceleration.baseUnitMagnitude()); } } + /** Profile state. */ public static class State { + /** The position at this state. */ public double position; + /** The velocity at this state. */ public double velocity; + /** Default constructor. */ public State() {} + /** + * Constructs constraints for a Trapezoid Profile. + * + * @param position The position at this state. + * @param velocity The velocity at this state. + */ public State(double position, double velocity) { this.position = position; this.velocity = velocity; } + /** + * Constructs constraints for a Trapezoid Profile. + * + * @param Unit type. + * @param position The position at this state. + * @param velocity The velocity at this state. + */ public > State(Measure position, Measure> velocity) { this(position.baseUnitMagnitude(), velocity.baseUnitMagnitude()); } @@ -110,120 +135,19 @@ public int hashCode() { } /** - * Construct a TrapezoidProfile. + * Constructs a TrapezoidProfile. * * @param constraints The constraints on the profile, like maximum velocity. */ public TrapezoidProfile(Constraints constraints) { m_constraints = constraints; - m_newAPI = true; } /** - * Construct a TrapezoidProfile. + * Calculates the position and velocity for the profile at a time t where the current state is at + * time t = 0. * - * @param constraints The constraints on the profile, like maximum velocity. - * @param goal The desired state when the profile is complete. - * @param initial The initial state (usually the current state). - * @deprecated Pass the desired and current state into calculate instead of constructing a new - * TrapezoidProfile with the desired and current state - */ - @Deprecated(since = "2024", forRemoval = true) - public TrapezoidProfile(Constraints constraints, State goal, State initial) { - m_direction = shouldFlipAcceleration(initial, goal) ? -1 : 1; - m_constraints = constraints; - m_current = direct(initial); - m_goal = direct(goal); - m_newAPI = false; - if (m_current.velocity > m_constraints.maxVelocity) { - m_current.velocity = m_constraints.maxVelocity; - } - - // Deal with a possibly truncated motion profile (with nonzero initial or - // final velocity) by calculating the parameters as if the profile began and - // ended at zero velocity - double cutoffBegin = m_current.velocity / m_constraints.maxAcceleration; - double cutoffDistBegin = cutoffBegin * cutoffBegin * m_constraints.maxAcceleration / 2.0; - - double cutoffEnd = m_goal.velocity / m_constraints.maxAcceleration; - double cutoffDistEnd = cutoffEnd * cutoffEnd * m_constraints.maxAcceleration / 2.0; - - // Now we can calculate the parameters as if it was a full trapezoid instead - // of a truncated one - - double fullTrapezoidDist = - cutoffDistBegin + (m_goal.position - m_current.position) + cutoffDistEnd; - double accelerationTime = m_constraints.maxVelocity / m_constraints.maxAcceleration; - - double fullSpeedDist = - fullTrapezoidDist - accelerationTime * accelerationTime * m_constraints.maxAcceleration; - - // Handle the case where the profile never reaches full speed - if (fullSpeedDist < 0) { - accelerationTime = Math.sqrt(fullTrapezoidDist / m_constraints.maxAcceleration); - fullSpeedDist = 0; - } - - m_endAccel = accelerationTime - cutoffBegin; - m_endFullSpeed = m_endAccel + fullSpeedDist / m_constraints.maxVelocity; - m_endDeccel = m_endFullSpeed + accelerationTime - cutoffEnd; - } - - /** - * Construct a TrapezoidProfile. - * - * @param constraints The constraints on the profile, like maximum velocity. - * @param goal The desired state when the profile is complete. - * @deprecated Pass the desired and current state into calculate instead of constructing a new - * TrapezoidProfile with the desired and current state - */ - @Deprecated(since = "2024", forRemoval = true) - public TrapezoidProfile(Constraints constraints, State goal) { - this(constraints, goal, new State(0, 0)); - } - - /** - * Calculate the correct position and velocity for the profile at a time t where the beginning of - * the profile was at time t = 0. - * - * @param t The time since the beginning of the profile. - * @return The position and velocity of the profile at time t. - * @deprecated Pass the desired and current state into calculate instead of constructing a new - * TrapezoidProfile with the desired and current state - */ - @Deprecated(since = "2024", forRemoval = true) - public State calculate(double t) { - if (m_newAPI) { - throw new RuntimeException("Cannot use new constructor with deprecated calculate()"); - } - State result = new State(m_current.position, m_current.velocity); - - if (t < m_endAccel) { - result.velocity += t * m_constraints.maxAcceleration; - result.position += (m_current.velocity + t * m_constraints.maxAcceleration / 2.0) * t; - } else if (t < m_endFullSpeed) { - result.velocity = m_constraints.maxVelocity; - result.position += - (m_current.velocity + m_endAccel * m_constraints.maxAcceleration / 2.0) * m_endAccel - + m_constraints.maxVelocity * (t - m_endAccel); - } else if (t <= m_endDeccel) { - result.velocity = m_goal.velocity + (m_endDeccel - t) * m_constraints.maxAcceleration; - double timeLeft = m_endDeccel - t; - result.position = - m_goal.position - - (m_goal.velocity + timeLeft * m_constraints.maxAcceleration / 2.0) * timeLeft; - } else { - result = m_goal; - } - - return direct(result); - } - - /** - * Calculate the correct position and velocity for the profile at a time t where the beginning of - * the profile was at time t = 0. - * - * @param t The time since the beginning of the profile. + * @param t How long to advance from the current state toward the desired state. * @param current The current state. * @param goal The desired state when the profile is complete. * @return The position and velocity of the profile at time t. diff --git a/wpimath/src/main/java/edu/wpi/first/math/trajectory/constraint/TrajectoryConstraint.java b/wpimath/src/main/java/edu/wpi/first/math/trajectory/constraint/TrajectoryConstraint.java index cc0087c6dbb..48490d4eba5 100644 --- a/wpimath/src/main/java/edu/wpi/first/math/trajectory/constraint/TrajectoryConstraint.java +++ b/wpimath/src/main/java/edu/wpi/first/math/trajectory/constraint/TrajectoryConstraint.java @@ -37,8 +37,11 @@ MinMax getMinMaxAccelerationMetersPerSecondSq( /** Represents a minimum and maximum acceleration. */ class MinMax { + /** The minimum acceleration. */ public double minAccelerationMetersPerSecondSq = -Double.MAX_VALUE; - public double maxAccelerationMetersPerSecondSq = +Double.MAX_VALUE; + + /** The maximum acceleration. */ + public double maxAccelerationMetersPerSecondSq = Double.MAX_VALUE; /** * Constructs a MinMax. diff --git a/wpimath/src/main/java/edu/wpi/first/math/trajectory/proto/TrajectoryProto.java b/wpimath/src/main/java/edu/wpi/first/math/trajectory/proto/TrajectoryProto.java new file mode 100644 index 00000000000..92e5ac7d2cd --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/trajectory/proto/TrajectoryProto.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.trajectory.proto; + +import edu.wpi.first.math.proto.Trajectory.ProtobufTrajectory; +import edu.wpi.first.math.proto.Trajectory.ProtobufTrajectoryState; +import edu.wpi.first.math.trajectory.Trajectory; +import edu.wpi.first.util.protobuf.Protobuf; +import java.util.ArrayList; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class TrajectoryProto implements Protobuf { + @Override + public Class getTypeClass() { + return Trajectory.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufTrajectory.getDescriptor(); + } + + @Override + public Protobuf[] getNested() { + return new Protobuf[] {Trajectory.State.proto}; + } + + @Override + public ProtobufTrajectory createMessage() { + return ProtobufTrajectory.newInstance(); + } + + @Override + public Trajectory unpack(ProtobufTrajectory msg) { + ArrayList states = new ArrayList<>(msg.getStates().length()); + for (ProtobufTrajectoryState protoState : msg.getStates()) { + states.add(Trajectory.State.proto.unpack(protoState)); + } + + return new Trajectory(states); + } + + @Override + public void pack(ProtobufTrajectory msg, Trajectory value) { + var states = msg.getMutableStates().reserve(value.getStates().size()); + for (var item : value.getStates()) { + Trajectory.State.proto.pack(states.next(), item); + } + } +} diff --git a/wpimath/src/main/java/edu/wpi/first/math/trajectory/proto/TrajectoryStateProto.java b/wpimath/src/main/java/edu/wpi/first/math/trajectory/proto/TrajectoryStateProto.java new file mode 100644 index 00000000000..e8900bfbd7b --- /dev/null +++ b/wpimath/src/main/java/edu/wpi/first/math/trajectory/proto/TrajectoryStateProto.java @@ -0,0 +1,52 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +package edu.wpi.first.math.trajectory.proto; + +import edu.wpi.first.math.geometry.Pose2d; +import edu.wpi.first.math.proto.Trajectory.ProtobufTrajectoryState; +import edu.wpi.first.math.trajectory.Trajectory; +import edu.wpi.first.util.protobuf.Protobuf; +import us.hebi.quickbuf.Descriptors.Descriptor; + +public class TrajectoryStateProto implements Protobuf { + @Override + public Class getTypeClass() { + return Trajectory.State.class; + } + + @Override + public Descriptor getDescriptor() { + return ProtobufTrajectoryState.getDescriptor(); + } + + @Override + public Protobuf[] getNested() { + return new Protobuf[] {Pose2d.proto}; + } + + @Override + public ProtobufTrajectoryState createMessage() { + return ProtobufTrajectoryState.newInstance(); + } + + @Override + public Trajectory.State unpack(ProtobufTrajectoryState msg) { + return new Trajectory.State( + msg.getTime(), + msg.getVelocity(), + msg.getAcceleration(), + Pose2d.proto.unpack(msg.getPose()), + msg.getCurvature()); + } + + @Override + public void pack(ProtobufTrajectoryState msg, Trajectory.State value) { + msg.setTime(value.timeSeconds); + msg.setVelocity(value.velocityMetersPerSecond); + msg.setAcceleration(value.accelerationMetersPerSecondSq); + Pose2d.proto.pack(msg.getMutablePose(), value.poseMeters); + msg.setCurvature(value.curvatureRadPerMeter); + } +} diff --git a/wpimath/src/main/native/cpp/controller/ArmFeedforward.cpp b/wpimath/src/main/native/cpp/controller/ArmFeedforward.cpp new file mode 100644 index 00000000000..3c677c0267c --- /dev/null +++ b/wpimath/src/main/native/cpp/controller/ArmFeedforward.cpp @@ -0,0 +1,100 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/controller/ArmFeedforward.h" + +#include + +#include +#include + +#include "frc/EigenCore.h" +#include "frc/system/NumericalIntegration.h" + +using namespace frc; + +units::volt_t ArmFeedforward::Calculate(units::unit_t currentAngle, + units::unit_t currentVelocity, + units::unit_t nextVelocity, + units::second_t dt) const { + using VarMat = sleipnir::VariableMatrix; + + // Arm dynamics + Matrixd<2, 2> A{{0.0, 1.0}, {0.0, -kV.value() / kA.value()}}; + Matrixd<2, 1> B{{0.0}, {1.0 / kA.value()}}; + const auto& f = [&](const VarMat& x, const VarMat& u) -> VarMat { + VarMat c{{0.0}, + {-(kS / kA).value() * sleipnir::sign(x(1)) - + (kG / kA).value() * sleipnir::cos(x(0))}}; + return A * x + B * u + c; + }; + + Vectord<2> r_k{currentAngle.value(), currentVelocity.value()}; + + sleipnir::Variable u_k; + + // Initial guess + auto acceleration = (nextVelocity - currentVelocity) / dt; + u_k.SetValue((kS * wpi::sgn(currentVelocity.value()) + kV * currentVelocity + + kA * acceleration + kG * units::math::cos(currentAngle)) + .value()); + + auto r_k1 = RK4(f, r_k, u_k, dt); + + // Minimize difference between desired and actual next velocity + auto cost = + (nextVelocity.value() - r_k1(1)) * (nextVelocity.value() - r_k1(1)); + + // Refine solution via Newton's method + { + auto xAD = u_k; + double x = xAD.Value(); + + sleipnir::Gradient gradientF{cost, xAD}; + Eigen::SparseVector g = gradientF.Value(); + + sleipnir::Hessian hessianF{cost, xAD}; + Eigen::SparseMatrix H = hessianF.Value(); + + double error = std::numeric_limits::infinity(); + while (error > 1e-8) { + // Iterate via Newton's method. + // + // xₖ₊₁ = xₖ − H⁻¹g + // + // The Hessian is regularized to at least 1e-4. + double p_x = -g.coeff(0) / std::max(H.coeff(0, 0), 1e-4); + + // Shrink step until cost goes down + { + double oldCost = cost.Value(); + + double α = 1.0; + double trial_x = x + α * p_x; + + xAD.SetValue(trial_x); + cost.Update(); + + while (cost.Value() > oldCost) { + α *= 0.5; + trial_x = x + α * p_x; + + xAD.SetValue(trial_x); + cost.Update(); + } + + x = trial_x; + } + + xAD.SetValue(x); + + g = gradientF.Value(); + H = hessianF.Value(); + + error = std::abs(g.coeff(0)); + } + } + + return units::volt_t{u_k.Value()}; +} diff --git a/wpimath/src/main/native/cpp/controller/BangBangController.cpp b/wpimath/src/main/native/cpp/controller/BangBangController.cpp index 4a093d68c14..c60517a0956 100644 --- a/wpimath/src/main/native/cpp/controller/BangBangController.cpp +++ b/wpimath/src/main/native/cpp/controller/BangBangController.cpp @@ -62,8 +62,7 @@ void BangBangController::InitSendable(wpi::SendableBuilder& builder) { [this](double setpoint) { SetSetpoint(setpoint); }); builder.AddDoubleProperty( "measurement", [this] { return GetMeasurement(); }, nullptr); - builder.AddDoubleProperty( - "error", [this] { return GetError(); }, nullptr); + builder.AddDoubleProperty("error", [this] { return GetError(); }, nullptr); builder.AddBooleanProperty( "atSetpoint", [this] { return AtSetpoint(); }, nullptr); } diff --git a/wpimath/src/main/native/cpp/controller/LTVDifferentialDriveController.cpp b/wpimath/src/main/native/cpp/controller/LTVDifferentialDriveController.cpp index 173f2ea7bdd..e100c7f8c89 100644 --- a/wpimath/src/main/native/cpp/controller/LTVDifferentialDriveController.cpp +++ b/wpimath/src/main/native/cpp/controller/LTVDifferentialDriveController.cpp @@ -24,7 +24,8 @@ namespace { class State { public: /// X position in global coordinate frame. - [[maybe_unused]] static constexpr int kX = 0; + [[maybe_unused]] + static constexpr int kX = 0; /// Y position in global coordinate frame. static constexpr int kY = 1; @@ -33,10 +34,12 @@ class State { static constexpr int kHeading = 2; /// Left encoder velocity. - [[maybe_unused]] static constexpr int kLeftVelocity = 3; + [[maybe_unused]] + static constexpr int kLeftVelocity = 3; /// Right encoder velocity. - [[maybe_unused]] static constexpr int kRightVelocity = 4; + [[maybe_unused]] + static constexpr int kRightVelocity = 4; }; } // namespace diff --git a/wpimath/src/main/native/cpp/controller/LTVUnicycleController.cpp b/wpimath/src/main/native/cpp/controller/LTVUnicycleController.cpp index aca317a4bb3..505569981cf 100644 --- a/wpimath/src/main/native/cpp/controller/LTVUnicycleController.cpp +++ b/wpimath/src/main/native/cpp/controller/LTVUnicycleController.cpp @@ -23,7 +23,8 @@ namespace { class State { public: /// X position in global coordinate frame. - [[maybe_unused]] static constexpr int kX = 0; + [[maybe_unused]] + static constexpr int kX = 0; /// Y position in global coordinate frame. static constexpr int kY = 1; diff --git a/wpimath/src/main/native/cpp/controller/PIDController.cpp b/wpimath/src/main/native/cpp/controller/PIDController.cpp index 2638f9ec09a..a67d56d0ea9 100644 --- a/wpimath/src/main/native/cpp/controller/PIDController.cpp +++ b/wpimath/src/main/native/cpp/controller/PIDController.cpp @@ -18,10 +18,32 @@ using namespace frc; PIDController::PIDController(double Kp, double Ki, double Kd, units::second_t period) : m_Kp(Kp), m_Ki(Ki), m_Kd(Kd), m_period(period) { + bool invalidGains = false; + if (Kp < 0.0) { + wpi::math::MathSharedStore::ReportError( + "Kp must be a non-negative number, got {}!", Kp); + invalidGains = true; + } + if (Ki < 0.0) { + wpi::math::MathSharedStore::ReportError( + "Ki must be a non-negative number, got {}!", Ki); + invalidGains = true; + } + if (Kd < 0.0) { + wpi::math::MathSharedStore::ReportError( + "Kd must be a non-negative number, got {}!", Kd); + invalidGains = true; + } + if (invalidGains) { + m_Kp = 0.0; + m_Ki = 0.0; + m_Kd = 0.0; + wpi::math::MathSharedStore::ReportWarning("PID gains defaulted to 0."); + } + if (period <= 0_s) { wpi::math::MathSharedStore::ReportError( - "Controller period must be a non-zero positive number, got {}!", - period.value()); + "Controller period must be a positive number, got {}!", period.value()); m_period = 20_ms; wpi::math::MathSharedStore::ReportWarning( "Controller period defaulted to 20ms."); diff --git a/wpimath/src/main/native/cpp/controller/RamseteController.cpp b/wpimath/src/main/native/cpp/controller/RamseteController.cpp index 576b0a9575d..70a64af1b5d 100644 --- a/wpimath/src/main/native/cpp/controller/RamseteController.cpp +++ b/wpimath/src/main/native/cpp/controller/RamseteController.cpp @@ -4,7 +4,7 @@ #include "frc/controller/RamseteController.h" -#include +#include #include "units/angle.h" #include "units/math.h" @@ -28,10 +28,14 @@ RamseteController::RamseteController(units::unit_t b, units::unit_t zeta) : m_b{b}, m_zeta{zeta} {} +WPI_IGNORE_DEPRECATED + RamseteController::RamseteController() : RamseteController{units::unit_t{2.0}, units::unit_t{0.7}} {} +WPI_UNIGNORE_DEPRECATED + bool RamseteController::AtReference() const { const auto& eTranslate = m_poseError.Translation(); const auto& eRotate = m_poseError.Rotation(); diff --git a/wpimath/src/main/native/cpp/controller/proto/ArmFeedforwardProto.cpp b/wpimath/src/main/native/cpp/controller/proto/ArmFeedforwardProto.cpp new file mode 100644 index 00000000000..37a55cf631e --- /dev/null +++ b/wpimath/src/main/native/cpp/controller/proto/ArmFeedforwardProto.cpp @@ -0,0 +1,33 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/controller/proto/ArmFeedforwardProto.h" + +#include "controller.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufArmFeedforward>(arena); +} + +frc::ArmFeedforward wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::ArmFeedforward{ + units::volt_t{m->ks()}, + units::volt_t{m->kg()}, + units::unit_t{m->kv()}, + units::unit_t{m->ka()}, + }; +} + +void wpi::Protobuf::Pack( + google::protobuf::Message* msg, const frc::ArmFeedforward& value) { + auto m = static_cast(msg); + m->set_ks(value.kS.value()); + m->set_kg(value.kG.value()); + m->set_kv(value.kV.value()); + m->set_ka(value.kA.value()); +} diff --git a/wpimath/src/main/native/cpp/controller/proto/DifferentialDriveWheelVoltagesProto.cpp b/wpimath/src/main/native/cpp/controller/proto/DifferentialDriveWheelVoltagesProto.cpp new file mode 100644 index 00000000000..b0b16b955d6 --- /dev/null +++ b/wpimath/src/main/native/cpp/controller/proto/DifferentialDriveWheelVoltagesProto.cpp @@ -0,0 +1,34 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/controller/proto/DifferentialDriveWheelVoltagesProto.h" + +#include "controller.pb.h" + +google::protobuf::Message* wpi::Protobuf< + frc::DifferentialDriveWheelVoltages>::New(google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufDifferentialDriveWheelVoltages>(arena); +} + +frc::DifferentialDriveWheelVoltages +wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = + static_cast( + &msg); + return frc::DifferentialDriveWheelVoltages{ + units::volt_t{m->left()}, + units::volt_t{m->right()}, + }; +} + +void wpi::Protobuf::Pack( + google::protobuf::Message* msg, + const frc::DifferentialDriveWheelVoltages& value) { + auto m = + static_cast(msg); + m->set_left(value.left.value()); + m->set_right(value.right.value()); +} diff --git a/wpimath/src/main/native/cpp/controller/proto/ElevatorFeedforwardProto.cpp b/wpimath/src/main/native/cpp/controller/proto/ElevatorFeedforwardProto.cpp new file mode 100644 index 00000000000..4b4bce2df6a --- /dev/null +++ b/wpimath/src/main/native/cpp/controller/proto/ElevatorFeedforwardProto.cpp @@ -0,0 +1,33 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/controller/proto/ElevatorFeedforwardProto.h" + +#include "controller.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufElevatorFeedforward>(arena); +} + +frc::ElevatorFeedforward wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::ElevatorFeedforward{ + units::volt_t{m->ks()}, + units::volt_t{m->kg()}, + units::unit_t{m->kv()}, + units::unit_t{m->ka()}, + }; +} + +void wpi::Protobuf::Pack( + google::protobuf::Message* msg, const frc::ElevatorFeedforward& value) { + auto m = static_cast(msg); + m->set_ks(value.kS()); + m->set_kg(value.kG()); + m->set_kv(value.kV()); + m->set_ka(value.kA()); +} diff --git a/wpimath/src/main/native/cpp/controller/struct/ArmFeedforwardStruct.cpp b/wpimath/src/main/native/cpp/controller/struct/ArmFeedforwardStruct.cpp new file mode 100644 index 00000000000..6b0070cb1e1 --- /dev/null +++ b/wpimath/src/main/native/cpp/controller/struct/ArmFeedforwardStruct.cpp @@ -0,0 +1,33 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/controller/struct/ArmFeedforwardStruct.h" + +namespace { +constexpr size_t kKsOff = 0; +constexpr size_t kKgOff = kKsOff + 8; +constexpr size_t kKvOff = kKgOff + 8; +constexpr size_t kKaOff = kKvOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::ArmFeedforward StructType::Unpack(std::span data) { + return frc::ArmFeedforward{ + units::volt_t{wpi::UnpackStruct(data)}, + units::volt_t{wpi::UnpackStruct(data)}, + units::unit_t{ + wpi::UnpackStruct(data)}, + units::unit_t{ + wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, + const frc::ArmFeedforward& value) { + wpi::PackStruct(data, value.kS()); + wpi::PackStruct(data, value.kG()); + wpi::PackStruct(data, value.kV()); + wpi::PackStruct(data, value.kA()); +} diff --git a/wpimath/src/main/native/cpp/controller/struct/DifferentialDriveWheelVoltagesStruct.cpp b/wpimath/src/main/native/cpp/controller/struct/DifferentialDriveWheelVoltagesStruct.cpp new file mode 100644 index 00000000000..22a79302b6a --- /dev/null +++ b/wpimath/src/main/native/cpp/controller/struct/DifferentialDriveWheelVoltagesStruct.cpp @@ -0,0 +1,26 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/controller/struct/DifferentialDriveWheelVoltagesStruct.h" + +namespace { +constexpr size_t kLeftOff = 0; +constexpr size_t kRightOff = kLeftOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::DifferentialDriveWheelVoltages StructType::Unpack( + std::span data) { + return frc::DifferentialDriveWheelVoltages{ + units::volt_t{wpi::UnpackStruct(data)}, + units::volt_t{wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, + const frc::DifferentialDriveWheelVoltages& value) { + wpi::PackStruct(data, value.left.value()); + wpi::PackStruct(data, value.right.value()); +} diff --git a/wpimath/src/main/native/cpp/controller/struct/ElevatorFeedforwardStruct.cpp b/wpimath/src/main/native/cpp/controller/struct/ElevatorFeedforwardStruct.cpp new file mode 100644 index 00000000000..ff28357bbba --- /dev/null +++ b/wpimath/src/main/native/cpp/controller/struct/ElevatorFeedforwardStruct.cpp @@ -0,0 +1,33 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/controller/struct/ElevatorFeedforwardStruct.h" + +namespace { +constexpr size_t kKsOff = 0; +constexpr size_t kKgOff = kKsOff + 8; +constexpr size_t kKvOff = kKgOff + 8; +constexpr size_t kKaOff = kKvOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::ElevatorFeedforward StructType::Unpack(std::span data) { + return frc::ElevatorFeedforward{ + units::volt_t{wpi::UnpackStruct(data)}, + units::volt_t{wpi::UnpackStruct(data)}, + units::unit_t{ + wpi::UnpackStruct(data)}, + units::unit_t{ + wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, + const frc::ElevatorFeedforward& value) { + wpi::PackStruct(data, value.kS()); + wpi::PackStruct(data, value.kG()); + wpi::PackStruct(data, value.kV()); + wpi::PackStruct(data, value.kA()); +} diff --git a/wpimath/src/main/native/cpp/estimator/SteadyStateKalmanFilter.cpp b/wpimath/src/main/native/cpp/estimator/SteadyStateKalmanFilter.cpp new file mode 100644 index 00000000000..24586232c5a --- /dev/null +++ b/wpimath/src/main/native/cpp/estimator/SteadyStateKalmanFilter.cpp @@ -0,0 +1,14 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/estimator/SteadyStateKalmanFilter.h" + +namespace frc { + +template class EXPORT_TEMPLATE_DEFINE(WPILIB_DLLEXPORT) + SteadyStateKalmanFilter<1, 1, 1>; +template class EXPORT_TEMPLATE_DEFINE(WPILIB_DLLEXPORT) + SteadyStateKalmanFilter<2, 1, 1>; + +} // namespace frc diff --git a/wpimath/src/main/native/cpp/geometry/Pose2d.cpp b/wpimath/src/main/native/cpp/geometry/Pose2d.cpp index 2e152165274..53779d05c83 100644 --- a/wpimath/src/main/native/cpp/geometry/Pose2d.cpp +++ b/wpimath/src/main/native/cpp/geometry/Pose2d.cpp @@ -9,7 +9,6 @@ #include #include "frc/MathUtil.h" -#include "geometry2d.pb.h" using namespace frc; @@ -109,23 +108,3 @@ void frc::from_json(const wpi::json& json, Pose2d& pose) { pose = Pose2d{json.at("translation").get(), json.at("rotation").get()}; } - -google::protobuf::Message* wpi::Protobuf::New( - google::protobuf::Arena* arena) { - return google::protobuf::Arena::CreateMessage( - arena); -} - -frc::Pose2d wpi::Protobuf::Unpack( - const google::protobuf::Message& msg) { - auto m = static_cast(&msg); - return Pose2d{wpi::UnpackProtobuf(m->translation()), - wpi::UnpackProtobuf(m->rotation())}; -} - -void wpi::Protobuf::Pack(google::protobuf::Message* msg, - const frc::Pose2d& value) { - auto m = static_cast(msg); - wpi::PackProtobuf(m->mutable_translation(), value.Translation()); - wpi::PackProtobuf(m->mutable_rotation(), value.Rotation()); -} diff --git a/wpimath/src/main/native/cpp/geometry/Pose3d.cpp b/wpimath/src/main/native/cpp/geometry/Pose3d.cpp index ffbaecbff43..bd7ab8681e8 100644 --- a/wpimath/src/main/native/cpp/geometry/Pose3d.cpp +++ b/wpimath/src/main/native/cpp/geometry/Pose3d.cpp @@ -36,15 +36,15 @@ Eigen::Matrix3d RotationVectorToMatrix(const Eigen::Vector3d& rotation) { } // namespace Pose3d::Pose3d(Translation3d translation, Rotation3d rotation) - : m_translation(std::move(translation)), m_rotation(std::move(rotation)) {} + : m_translation{std::move(translation)}, m_rotation{std::move(rotation)} {} Pose3d::Pose3d(units::meter_t x, units::meter_t y, units::meter_t z, Rotation3d rotation) - : m_translation(x, y, z), m_rotation(std::move(rotation)) {} + : m_translation{x, y, z}, m_rotation{std::move(rotation)} {} Pose3d::Pose3d(const Pose2d& pose) - : m_translation(pose.X(), pose.Y(), 0_m), - m_rotation(0_rad, 0_rad, pose.Rotation().Radians()) {} + : m_translation{pose.X(), pose.Y(), 0_m}, + m_rotation{0_rad, 0_rad, pose.Rotation().Radians()} {} Pose3d Pose3d::operator+(const Transform3d& other) const { return TransformBy(other); @@ -189,23 +189,3 @@ void frc::from_json(const wpi::json& json, Pose3d& pose) { pose = Pose3d{json.at("translation").get(), json.at("rotation").get()}; } - -google::protobuf::Message* wpi::Protobuf::New( - google::protobuf::Arena* arena) { - return google::protobuf::Arena::CreateMessage( - arena); -} - -frc::Pose3d wpi::Protobuf::Unpack( - const google::protobuf::Message& msg) { - auto m = static_cast(&msg); - return Pose3d{wpi::UnpackProtobuf(m->translation()), - wpi::UnpackProtobuf(m->rotation())}; -} - -void wpi::Protobuf::Pack(google::protobuf::Message* msg, - const frc::Pose3d& value) { - auto m = static_cast(msg); - wpi::PackProtobuf(m->mutable_translation(), value.Translation()); - wpi::PackProtobuf(m->mutable_rotation(), value.Rotation()); -} diff --git a/wpimath/src/main/native/cpp/geometry/Quaternion.cpp b/wpimath/src/main/native/cpp/geometry/Quaternion.cpp index 37afbb88a32..136f48db0c6 100644 --- a/wpimath/src/main/native/cpp/geometry/Quaternion.cpp +++ b/wpimath/src/main/native/cpp/geometry/Quaternion.cpp @@ -8,8 +8,6 @@ #include -#include "geometry3d.pb.h" - using namespace frc; Quaternion::Quaternion(double w, double x, double y, double z) @@ -138,11 +136,12 @@ Quaternion Quaternion::Log(const Quaternion& other) const { } Quaternion Quaternion::Log() const { - double scalar = std::log(Norm()); + double norm = Norm(); + double scalar = std::log(norm); double v_norm = m_v.norm(); - double s_norm = W() / Norm(); + double s_norm = W() / norm; if (std::abs(s_norm + 1) < 1e-9) { return Quaternion{scalar, -std::numbers::pi, 0, 0}; @@ -232,24 +231,3 @@ void frc::from_json(const wpi::json& json, Quaternion& quaternion) { Quaternion{json.at("W").get(), json.at("X").get(), json.at("Y").get(), json.at("Z").get()}; } - -google::protobuf::Message* wpi::Protobuf::New( - google::protobuf::Arena* arena) { - return google::protobuf::Arena::CreateMessage( - arena); -} - -frc::Quaternion wpi::Protobuf::Unpack( - const google::protobuf::Message& msg) { - auto m = static_cast(&msg); - return frc::Quaternion{m->w(), m->x(), m->y(), m->z()}; -} - -void wpi::Protobuf::Pack(google::protobuf::Message* msg, - const frc::Quaternion& value) { - auto m = static_cast(msg); - m->set_w(value.W()); - m->set_x(value.X()); - m->set_y(value.Y()); - m->set_z(value.Z()); -} diff --git a/wpimath/src/main/native/cpp/geometry/Rotation2d.cpp b/wpimath/src/main/native/cpp/geometry/Rotation2d.cpp index 05a644ea2bd..69193028f77 100644 --- a/wpimath/src/main/native/cpp/geometry/Rotation2d.cpp +++ b/wpimath/src/main/native/cpp/geometry/Rotation2d.cpp @@ -20,21 +20,3 @@ void frc::to_json(wpi::json& json, const Rotation2d& rotation) { void frc::from_json(const wpi::json& json, Rotation2d& rotation) { rotation = Rotation2d{units::radian_t{json.at("radians").get()}}; } - -google::protobuf::Message* wpi::Protobuf::New( - google::protobuf::Arena* arena) { - return google::protobuf::Arena::CreateMessage( - arena); -} - -frc::Rotation2d wpi::Protobuf::Unpack( - const google::protobuf::Message& msg) { - auto m = static_cast(&msg); - return frc::Rotation2d{units::radian_t{m->value()}}; -} - -void wpi::Protobuf::Pack(google::protobuf::Message* msg, - const frc::Rotation2d& value) { - auto m = static_cast(msg); - m->set_value(value.Radians().value()); -} diff --git a/wpimath/src/main/native/cpp/geometry/Rotation3d.cpp b/wpimath/src/main/native/cpp/geometry/Rotation3d.cpp index 3a688700453..072d023cb28 100644 --- a/wpimath/src/main/native/cpp/geometry/Rotation3d.cpp +++ b/wpimath/src/main/native/cpp/geometry/Rotation3d.cpp @@ -262,21 +262,3 @@ void frc::to_json(wpi::json& json, const Rotation3d& rotation) { void frc::from_json(const wpi::json& json, Rotation3d& rotation) { rotation = Rotation3d{json.at("quaternion").get()}; } - -google::protobuf::Message* wpi::Protobuf::New( - google::protobuf::Arena* arena) { - return google::protobuf::Arena::CreateMessage( - arena); -} - -frc::Rotation3d wpi::Protobuf::Unpack( - const google::protobuf::Message& msg) { - auto m = static_cast(&msg); - return Rotation3d{wpi::UnpackProtobuf(m->q())}; -} - -void wpi::Protobuf::Pack(google::protobuf::Message* msg, - const frc::Rotation3d& value) { - auto m = static_cast(msg); - wpi::PackProtobuf(m->mutable_q(), value.GetQuaternion()); -} diff --git a/wpimath/src/main/native/cpp/geometry/Transform2d.cpp b/wpimath/src/main/native/cpp/geometry/Transform2d.cpp index 77f3ceed2d4..157359bfbc5 100644 --- a/wpimath/src/main/native/cpp/geometry/Transform2d.cpp +++ b/wpimath/src/main/native/cpp/geometry/Transform2d.cpp @@ -22,23 +22,3 @@ Transform2d::Transform2d(Pose2d initial, Pose2d final) { Transform2d Transform2d::operator+(const Transform2d& other) const { return Transform2d{Pose2d{}, Pose2d{}.TransformBy(*this).TransformBy(other)}; } - -google::protobuf::Message* wpi::Protobuf::New( - google::protobuf::Arena* arena) { - return google::protobuf::Arena::CreateMessage< - wpi::proto::ProtobufTransform2d>(arena); -} - -frc::Transform2d wpi::Protobuf::Unpack( - const google::protobuf::Message& msg) { - auto m = static_cast(&msg); - return Transform2d{wpi::UnpackProtobuf(m->translation()), - wpi::UnpackProtobuf(m->rotation())}; -} - -void wpi::Protobuf::Pack(google::protobuf::Message* msg, - const frc::Transform2d& value) { - auto m = static_cast(msg); - wpi::PackProtobuf(m->mutable_translation(), value.Translation()); - wpi::PackProtobuf(m->mutable_rotation(), value.Rotation()); -} diff --git a/wpimath/src/main/native/cpp/geometry/Transform3d.cpp b/wpimath/src/main/native/cpp/geometry/Transform3d.cpp index de6c2533c97..4879bb12ad5 100644 --- a/wpimath/src/main/native/cpp/geometry/Transform3d.cpp +++ b/wpimath/src/main/native/cpp/geometry/Transform3d.cpp @@ -5,7 +5,6 @@ #include "frc/geometry/Transform3d.h" #include "frc/geometry/Pose3d.h" -#include "geometry3d.pb.h" using namespace frc; @@ -20,11 +19,11 @@ Transform3d::Transform3d(Pose3d initial, Pose3d final) { } Transform3d::Transform3d(Translation3d translation, Rotation3d rotation) - : m_translation(std::move(translation)), m_rotation(std::move(rotation)) {} + : m_translation{std::move(translation)}, m_rotation{std::move(rotation)} {} Transform3d::Transform3d(units::meter_t x, units::meter_t y, units::meter_t z, Rotation3d rotation) - : m_translation(x, y, z), m_rotation(std::move(rotation)) {} + : m_translation{x, y, z}, m_rotation{std::move(rotation)} {} Transform3d Transform3d::Inverse() const { // We are rotating the difference between the translations @@ -36,23 +35,3 @@ Transform3d Transform3d::Inverse() const { Transform3d Transform3d::operator+(const Transform3d& other) const { return Transform3d{Pose3d{}, Pose3d{}.TransformBy(*this).TransformBy(other)}; } - -google::protobuf::Message* wpi::Protobuf::New( - google::protobuf::Arena* arena) { - return google::protobuf::Arena::CreateMessage< - wpi::proto::ProtobufTransform3d>(arena); -} - -frc::Transform3d wpi::Protobuf::Unpack( - const google::protobuf::Message& msg) { - auto m = static_cast(&msg); - return Transform3d{wpi::UnpackProtobuf(m->translation()), - wpi::UnpackProtobuf(m->rotation())}; -} - -void wpi::Protobuf::Pack(google::protobuf::Message* msg, - const frc::Transform3d& value) { - auto m = static_cast(msg); - wpi::PackProtobuf(m->mutable_translation(), value.Translation()); - wpi::PackProtobuf(m->mutable_rotation(), value.Rotation()); -} diff --git a/wpimath/src/main/native/cpp/geometry/Translation2d.cpp b/wpimath/src/main/native/cpp/geometry/Translation2d.cpp index 6d5f3153ae1..90162018ed7 100644 --- a/wpimath/src/main/native/cpp/geometry/Translation2d.cpp +++ b/wpimath/src/main/native/cpp/geometry/Translation2d.cpp @@ -11,6 +11,9 @@ using namespace frc; +Translation2d::Translation2d(const Eigen::Vector2d& vector) + : m_x{units::meter_t{vector.x()}}, m_y{units::meter_t{vector.y()}} {} + units::meter_t Translation2d::Distance(const Translation2d& other) const { return units::math::hypot(other.m_x - m_x, other.m_y - m_y); } @@ -49,22 +52,3 @@ void frc::from_json(const wpi::json& json, Translation2d& translation) { translation = Translation2d{units::meter_t{json.at("x").get()}, units::meter_t{json.at("y").get()}}; } - -google::protobuf::Message* wpi::Protobuf::New( - google::protobuf::Arena* arena) { - return google::protobuf::Arena::CreateMessage< - wpi::proto::ProtobufTranslation2d>(arena); -} - -frc::Translation2d wpi::Protobuf::Unpack( - const google::protobuf::Message& msg) { - auto m = static_cast(&msg); - return frc::Translation2d{units::meter_t{m->x()}, units::meter_t{m->y()}}; -} - -void wpi::Protobuf::Pack(google::protobuf::Message* msg, - const frc::Translation2d& value) { - auto m = static_cast(msg); - m->set_x(value.X().value()); - m->set_y(value.Y().value()); -} diff --git a/wpimath/src/main/native/cpp/geometry/Translation3d.cpp b/wpimath/src/main/native/cpp/geometry/Translation3d.cpp index 90e94ae8258..c3b8cb4b775 100644 --- a/wpimath/src/main/native/cpp/geometry/Translation3d.cpp +++ b/wpimath/src/main/native/cpp/geometry/Translation3d.cpp @@ -19,6 +19,11 @@ Translation3d::Translation3d(units::meter_t distance, const Rotation3d& angle) { m_z = rectangular.Z(); } +Translation3d::Translation3d(const Eigen::Vector3d& vector) + : m_x{units::meter_t{vector.x()}}, + m_y{units::meter_t{vector.y()}}, + m_z{units::meter_t{vector.z()}} {} + units::meter_t Translation3d::Distance(const Translation3d& other) const { return units::math::sqrt(units::math::pow<2>(other.m_x - m_x) + units::math::pow<2>(other.m_y - m_y) + @@ -53,24 +58,3 @@ void frc::from_json(const wpi::json& json, Translation3d& translation) { units::meter_t{json.at("y").get()}, units::meter_t{json.at("z").get()}}; } - -google::protobuf::Message* wpi::Protobuf::New( - google::protobuf::Arena* arena) { - return google::protobuf::Arena::CreateMessage< - wpi::proto::ProtobufTranslation3d>(arena); -} - -frc::Translation3d wpi::Protobuf::Unpack( - const google::protobuf::Message& msg) { - auto m = static_cast(&msg); - return frc::Translation3d{units::meter_t{m->x()}, units::meter_t{m->y()}, - units::meter_t{m->z()}}; -} - -void wpi::Protobuf::Pack(google::protobuf::Message* msg, - const frc::Translation3d& value) { - auto m = static_cast(msg); - m->set_x(value.X().value()); - m->set_y(value.Y().value()); - m->set_z(value.Z().value()); -} diff --git a/wpimath/src/main/native/cpp/geometry/proto/Pose2dProto.cpp b/wpimath/src/main/native/cpp/geometry/proto/Pose2dProto.cpp new file mode 100644 index 00000000000..2b8bf5ff665 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/proto/Pose2dProto.cpp @@ -0,0 +1,29 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/proto/Pose2dProto.h" + +#include "geometry2d.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage( + arena); +} + +frc::Pose2d wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::Pose2d{ + wpi::UnpackProtobuf(m->translation()), + wpi::UnpackProtobuf(m->rotation()), + }; +} + +void wpi::Protobuf::Pack(google::protobuf::Message* msg, + const frc::Pose2d& value) { + auto m = static_cast(msg); + wpi::PackProtobuf(m->mutable_translation(), value.Translation()); + wpi::PackProtobuf(m->mutable_rotation(), value.Rotation()); +} diff --git a/wpimath/src/main/native/cpp/geometry/proto/Pose3dProto.cpp b/wpimath/src/main/native/cpp/geometry/proto/Pose3dProto.cpp new file mode 100644 index 00000000000..581cafb0f48 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/proto/Pose3dProto.cpp @@ -0,0 +1,29 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/proto/Pose3dProto.h" + +#include "geometry3d.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage( + arena); +} + +frc::Pose3d wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::Pose3d{ + wpi::UnpackProtobuf(m->translation()), + wpi::UnpackProtobuf(m->rotation()), + }; +} + +void wpi::Protobuf::Pack(google::protobuf::Message* msg, + const frc::Pose3d& value) { + auto m = static_cast(msg); + wpi::PackProtobuf(m->mutable_translation(), value.Translation()); + wpi::PackProtobuf(m->mutable_rotation(), value.Rotation()); +} diff --git a/wpimath/src/main/native/cpp/geometry/proto/QuaternionProto.cpp b/wpimath/src/main/native/cpp/geometry/proto/QuaternionProto.cpp new file mode 100644 index 00000000000..aadefa03918 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/proto/QuaternionProto.cpp @@ -0,0 +1,33 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/proto/QuaternionProto.h" + +#include "geometry3d.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage( + arena); +} + +frc::Quaternion wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::Quaternion{ + m->w(), + m->x(), + m->y(), + m->z(), + }; +} + +void wpi::Protobuf::Pack(google::protobuf::Message* msg, + const frc::Quaternion& value) { + auto m = static_cast(msg); + m->set_w(value.W()); + m->set_x(value.X()); + m->set_y(value.Y()); + m->set_z(value.Z()); +} diff --git a/wpimath/src/main/native/cpp/geometry/proto/Rotation2dProto.cpp b/wpimath/src/main/native/cpp/geometry/proto/Rotation2dProto.cpp new file mode 100644 index 00000000000..c9005f2bf87 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/proto/Rotation2dProto.cpp @@ -0,0 +1,27 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/proto/Rotation2dProto.h" + +#include "geometry2d.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage( + arena); +} + +frc::Rotation2d wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::Rotation2d{ + units::radian_t{m->value()}, + }; +} + +void wpi::Protobuf::Pack(google::protobuf::Message* msg, + const frc::Rotation2d& value) { + auto m = static_cast(msg); + m->set_value(value.Radians().value()); +} diff --git a/wpimath/src/main/native/cpp/geometry/proto/Rotation3dProto.cpp b/wpimath/src/main/native/cpp/geometry/proto/Rotation3dProto.cpp new file mode 100644 index 00000000000..72645e1952b --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/proto/Rotation3dProto.cpp @@ -0,0 +1,27 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/proto/Rotation3dProto.h" + +#include "geometry3d.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage( + arena); +} + +frc::Rotation3d wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::Rotation3d{ + wpi::UnpackProtobuf(m->q()), + }; +} + +void wpi::Protobuf::Pack(google::protobuf::Message* msg, + const frc::Rotation3d& value) { + auto m = static_cast(msg); + wpi::PackProtobuf(m->mutable_q(), value.GetQuaternion()); +} diff --git a/wpimath/src/main/native/cpp/geometry/proto/Transform2dProto.cpp b/wpimath/src/main/native/cpp/geometry/proto/Transform2dProto.cpp new file mode 100644 index 00000000000..4d38b812786 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/proto/Transform2dProto.cpp @@ -0,0 +1,29 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/proto/Transform2dProto.h" + +#include "geometry2d.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufTransform2d>(arena); +} + +frc::Transform2d wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::Transform2d{ + wpi::UnpackProtobuf(m->translation()), + wpi::UnpackProtobuf(m->rotation()), + }; +} + +void wpi::Protobuf::Pack(google::protobuf::Message* msg, + const frc::Transform2d& value) { + auto m = static_cast(msg); + wpi::PackProtobuf(m->mutable_translation(), value.Translation()); + wpi::PackProtobuf(m->mutable_rotation(), value.Rotation()); +} diff --git a/wpimath/src/main/native/cpp/geometry/proto/Transform3dProto.cpp b/wpimath/src/main/native/cpp/geometry/proto/Transform3dProto.cpp new file mode 100644 index 00000000000..4a8fbfd326d --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/proto/Transform3dProto.cpp @@ -0,0 +1,29 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/proto/Transform3dProto.h" + +#include "geometry3d.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufTransform3d>(arena); +} + +frc::Transform3d wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::Transform3d{ + wpi::UnpackProtobuf(m->translation()), + wpi::UnpackProtobuf(m->rotation()), + }; +} + +void wpi::Protobuf::Pack(google::protobuf::Message* msg, + const frc::Transform3d& value) { + auto m = static_cast(msg); + wpi::PackProtobuf(m->mutable_translation(), value.Translation()); + wpi::PackProtobuf(m->mutable_rotation(), value.Rotation()); +} diff --git a/wpimath/src/main/native/cpp/geometry/proto/Translation2dProto.cpp b/wpimath/src/main/native/cpp/geometry/proto/Translation2dProto.cpp new file mode 100644 index 00000000000..739dc99f34b --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/proto/Translation2dProto.cpp @@ -0,0 +1,29 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/proto/Translation2dProto.h" + +#include "geometry2d.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufTranslation2d>(arena); +} + +frc::Translation2d wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::Translation2d{ + units::meter_t{m->x()}, + units::meter_t{m->y()}, + }; +} + +void wpi::Protobuf::Pack(google::protobuf::Message* msg, + const frc::Translation2d& value) { + auto m = static_cast(msg); + m->set_x(value.X().value()); + m->set_y(value.Y().value()); +} diff --git a/wpimath/src/main/native/cpp/geometry/proto/Translation3dProto.cpp b/wpimath/src/main/native/cpp/geometry/proto/Translation3dProto.cpp new file mode 100644 index 00000000000..6285b2b8528 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/proto/Translation3dProto.cpp @@ -0,0 +1,31 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/proto/Translation3dProto.h" + +#include "geometry3d.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufTranslation3d>(arena); +} + +frc::Translation3d wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::Translation3d{ + units::meter_t{m->x()}, + units::meter_t{m->y()}, + units::meter_t{m->z()}, + }; +} + +void wpi::Protobuf::Pack(google::protobuf::Message* msg, + const frc::Translation3d& value) { + auto m = static_cast(msg); + m->set_x(value.X().value()); + m->set_y(value.Y().value()); + m->set_z(value.Z().value()); +} diff --git a/wpimath/src/main/native/cpp/geometry/Twist2d.cpp b/wpimath/src/main/native/cpp/geometry/proto/Twist2dProto.cpp similarity index 83% rename from wpimath/src/main/native/cpp/geometry/Twist2d.cpp rename to wpimath/src/main/native/cpp/geometry/proto/Twist2dProto.cpp index 6c106eb436e..2590fc96a38 100644 --- a/wpimath/src/main/native/cpp/geometry/Twist2d.cpp +++ b/wpimath/src/main/native/cpp/geometry/proto/Twist2dProto.cpp @@ -2,12 +2,10 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -#include "frc/geometry/Twist2d.h" +#include "frc/geometry/proto/Twist2dProto.h" #include "geometry2d.pb.h" -using namespace frc; - google::protobuf::Message* wpi::Protobuf::New( google::protobuf::Arena* arena) { return google::protobuf::Arena::CreateMessage( @@ -17,8 +15,11 @@ google::protobuf::Message* wpi::Protobuf::New( frc::Twist2d wpi::Protobuf::Unpack( const google::protobuf::Message& msg) { auto m = static_cast(&msg); - return frc::Twist2d{units::meter_t{m->dx()}, units::meter_t{m->dy()}, - units::radian_t{m->dtheta()}}; + return frc::Twist2d{ + units::meter_t{m->dx()}, + units::meter_t{m->dy()}, + units::radian_t{m->dtheta()}, + }; } void wpi::Protobuf::Pack(google::protobuf::Message* msg, diff --git a/wpimath/src/main/native/cpp/geometry/Twist3d.cpp b/wpimath/src/main/native/cpp/geometry/proto/Twist3dProto.cpp similarity index 77% rename from wpimath/src/main/native/cpp/geometry/Twist3d.cpp rename to wpimath/src/main/native/cpp/geometry/proto/Twist3dProto.cpp index 4f4ce86b4bd..e2d91e4e16b 100644 --- a/wpimath/src/main/native/cpp/geometry/Twist3d.cpp +++ b/wpimath/src/main/native/cpp/geometry/proto/Twist3dProto.cpp @@ -2,12 +2,10 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -#include "frc/geometry/Twist3d.h" +#include "frc/geometry/proto/Twist3dProto.h" #include "geometry3d.pb.h" -using namespace frc; - google::protobuf::Message* wpi::Protobuf::New( google::protobuf::Arena* arena) { return google::protobuf::Arena::CreateMessage( @@ -17,9 +15,11 @@ google::protobuf::Message* wpi::Protobuf::New( frc::Twist3d wpi::Protobuf::Unpack( const google::protobuf::Message& msg) { auto m = static_cast(&msg); - return frc::Twist3d{units::meter_t{m->dx()}, units::meter_t{m->dy()}, - units::meter_t{m->dz()}, units::radian_t{m->rx()}, - units::radian_t{m->ry()}, units::radian_t{m->rz()}}; + return frc::Twist3d{ + units::meter_t{m->dx()}, units::meter_t{m->dy()}, + units::meter_t{m->dz()}, units::radian_t{m->rx()}, + units::radian_t{m->ry()}, units::radian_t{m->rz()}, + }; } void wpi::Protobuf::Pack(google::protobuf::Message* msg, diff --git a/wpimath/src/main/native/cpp/geometry/struct/Pose2dStruct.cpp b/wpimath/src/main/native/cpp/geometry/struct/Pose2dStruct.cpp new file mode 100644 index 00000000000..b1bb9aef52c --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/struct/Pose2dStruct.cpp @@ -0,0 +1,25 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/struct/Pose2dStruct.h" + +namespace { +constexpr size_t kTranslationOff = 0; +constexpr size_t kRotationOff = + kTranslationOff + wpi::GetStructSize(); +} // namespace + +using StructType = wpi::Struct; + +frc::Pose2d StructType::Unpack(std::span data) { + return frc::Pose2d{ + wpi::UnpackStruct(data), + wpi::UnpackStruct(data), + }; +} + +void StructType::Pack(std::span data, const frc::Pose2d& value) { + wpi::PackStruct(data, value.Translation()); + wpi::PackStruct(data, value.Rotation()); +} diff --git a/wpimath/src/main/native/cpp/geometry/struct/Pose3dStruct.cpp b/wpimath/src/main/native/cpp/geometry/struct/Pose3dStruct.cpp new file mode 100644 index 00000000000..104a51b935b --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/struct/Pose3dStruct.cpp @@ -0,0 +1,25 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/struct/Pose3dStruct.h" + +namespace { +constexpr size_t kTranslationOff = 0; +constexpr size_t kRotationOff = + kTranslationOff + wpi::GetStructSize(); +} // namespace + +using StructType = wpi::Struct; + +frc::Pose3d StructType::Unpack(std::span data) { + return frc::Pose3d{ + wpi::UnpackStruct(data), + wpi::UnpackStruct(data), + }; +} + +void StructType::Pack(std::span data, const frc::Pose3d& value) { + wpi::PackStruct(data, value.Translation()); + wpi::PackStruct(data, value.Rotation()); +} diff --git a/wpimath/src/main/native/cpp/geometry/struct/QuaternionStruct.cpp b/wpimath/src/main/native/cpp/geometry/struct/QuaternionStruct.cpp new file mode 100644 index 00000000000..df5b7815e48 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/struct/QuaternionStruct.cpp @@ -0,0 +1,30 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/struct/QuaternionStruct.h" + +namespace { +constexpr size_t kWOff = 0; +constexpr size_t kXOff = kWOff + 8; +constexpr size_t kYOff = kXOff + 8; +constexpr size_t kZOff = kYOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::Quaternion StructType::Unpack(std::span data) { + return frc::Quaternion{ + wpi::UnpackStruct(data), + wpi::UnpackStruct(data), + wpi::UnpackStruct(data), + wpi::UnpackStruct(data), + }; +} + +void StructType::Pack(std::span data, const frc::Quaternion& value) { + wpi::PackStruct(data, value.W()); + wpi::PackStruct(data, value.X()); + wpi::PackStruct(data, value.Y()); + wpi::PackStruct(data, value.Z()); +} diff --git a/wpimath/src/main/native/cpp/geometry/struct/Rotation2dStruct.cpp b/wpimath/src/main/native/cpp/geometry/struct/Rotation2dStruct.cpp new file mode 100644 index 00000000000..16d3b40d18e --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/struct/Rotation2dStruct.cpp @@ -0,0 +1,21 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/struct/Rotation2dStruct.h" + +namespace { +constexpr size_t kValueOff = 0; +} // namespace + +using StructType = wpi::Struct; + +frc::Rotation2d StructType::Unpack(std::span data) { + return frc::Rotation2d{ + units::radian_t{wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, const frc::Rotation2d& value) { + wpi::PackStruct(data, value.Radians().value()); +} diff --git a/wpimath/src/main/native/cpp/geometry/struct/Rotation3dStruct.cpp b/wpimath/src/main/native/cpp/geometry/struct/Rotation3dStruct.cpp new file mode 100644 index 00000000000..926c7c154a2 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/struct/Rotation3dStruct.cpp @@ -0,0 +1,21 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/struct/Rotation3dStruct.h" + +namespace { +constexpr size_t kQOff = 0; +} // namespace + +using StructType = wpi::Struct; + +frc::Rotation3d StructType::Unpack(std::span data) { + return frc::Rotation3d{ + wpi::UnpackStruct(data), + }; +} + +void StructType::Pack(std::span data, const frc::Rotation3d& value) { + wpi::PackStruct(data, value.GetQuaternion()); +} diff --git a/wpimath/src/main/native/cpp/geometry/struct/Transform2dStruct.cpp b/wpimath/src/main/native/cpp/geometry/struct/Transform2dStruct.cpp new file mode 100644 index 00000000000..35fa6bf8f38 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/struct/Transform2dStruct.cpp @@ -0,0 +1,25 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/struct/Transform2dStruct.h" + +namespace { +constexpr size_t kTranslationOff = 0; +constexpr size_t kRotationOff = + kTranslationOff + wpi::GetStructSize(); +} // namespace + +using StructType = wpi::Struct; + +frc::Transform2d StructType::Unpack(std::span data) { + return frc::Transform2d{ + wpi::UnpackStruct(data), + wpi::UnpackStruct(data), + }; +} + +void StructType::Pack(std::span data, const frc::Transform2d& value) { + wpi::PackStruct(data, value.Translation()); + wpi::PackStruct(data, value.Rotation()); +} diff --git a/wpimath/src/main/native/cpp/geometry/struct/Transform3dStruct.cpp b/wpimath/src/main/native/cpp/geometry/struct/Transform3dStruct.cpp new file mode 100644 index 00000000000..b428346df50 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/struct/Transform3dStruct.cpp @@ -0,0 +1,25 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/struct/Transform3dStruct.h" + +namespace { +constexpr size_t kTranslationOff = 0; +constexpr size_t kRotationOff = + kTranslationOff + wpi::GetStructSize(); +} // namespace + +using StructType = wpi::Struct; + +frc::Transform3d StructType::Unpack(std::span data) { + return frc::Transform3d{ + wpi::UnpackStruct(data), + wpi::UnpackStruct(data), + }; +} + +void StructType::Pack(std::span data, const frc::Transform3d& value) { + wpi::PackStruct(data, value.Translation()); + wpi::PackStruct(data, value.Rotation()); +} diff --git a/wpimath/src/main/native/cpp/geometry/struct/Translation2dStruct.cpp b/wpimath/src/main/native/cpp/geometry/struct/Translation2dStruct.cpp new file mode 100644 index 00000000000..edf2574b9a7 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/struct/Translation2dStruct.cpp @@ -0,0 +1,25 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/struct/Translation2dStruct.h" + +namespace { +constexpr size_t kXOff = 0; +constexpr size_t kYOff = kXOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::Translation2d StructType::Unpack(std::span data) { + return frc::Translation2d{ + units::meter_t{wpi::UnpackStruct(data)}, + units::meter_t{wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, + const frc::Translation2d& value) { + wpi::PackStruct(data, value.X().value()); + wpi::PackStruct(data, value.Y().value()); +} diff --git a/wpimath/src/main/native/cpp/geometry/struct/Translation3dStruct.cpp b/wpimath/src/main/native/cpp/geometry/struct/Translation3dStruct.cpp new file mode 100644 index 00000000000..f69306c994c --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/struct/Translation3dStruct.cpp @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/struct/Translation3dStruct.h" + +namespace { +constexpr size_t kXOff = 0; +constexpr size_t kYOff = kXOff + 8; +constexpr size_t kZOff = kYOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::Translation3d StructType::Unpack(std::span data) { + return frc::Translation3d{ + units::meter_t{wpi::UnpackStruct(data)}, + units::meter_t{wpi::UnpackStruct(data)}, + units::meter_t{wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, + const frc::Translation3d& value) { + wpi::PackStruct(data, value.X().value()); + wpi::PackStruct(data, value.Y().value()); + wpi::PackStruct(data, value.Z().value()); +} diff --git a/wpimath/src/main/native/cpp/geometry/struct/Twist2dStruct.cpp b/wpimath/src/main/native/cpp/geometry/struct/Twist2dStruct.cpp new file mode 100644 index 00000000000..5c71c620185 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/struct/Twist2dStruct.cpp @@ -0,0 +1,27 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/struct/Twist2dStruct.h" + +namespace { +constexpr size_t kDxOff = 0; +constexpr size_t kDyOff = kDxOff + 8; +constexpr size_t kDthetaOff = kDyOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::Twist2d StructType::Unpack(std::span data) { + return frc::Twist2d{ + units::meter_t{wpi::UnpackStruct(data)}, + units::meter_t{wpi::UnpackStruct(data)}, + units::radian_t{wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, const frc::Twist2d& value) { + wpi::PackStruct(data, value.dx.value()); + wpi::PackStruct(data, value.dy.value()); + wpi::PackStruct(data, value.dtheta.value()); +} diff --git a/wpimath/src/main/native/cpp/geometry/struct/Twist3dStruct.cpp b/wpimath/src/main/native/cpp/geometry/struct/Twist3dStruct.cpp new file mode 100644 index 00000000000..d933d4b3945 --- /dev/null +++ b/wpimath/src/main/native/cpp/geometry/struct/Twist3dStruct.cpp @@ -0,0 +1,36 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/geometry/struct/Twist3dStruct.h" + +namespace { +constexpr size_t kDxOff = 0; +constexpr size_t kDyOff = kDxOff + 8; +constexpr size_t kDzOff = kDyOff + 8; +constexpr size_t kRxOff = kDzOff + 8; +constexpr size_t kRyOff = kRxOff + 8; +constexpr size_t kRzOff = kRyOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::Twist3d StructType::Unpack(std::span data) { + return frc::Twist3d{ + units::meter_t{wpi::UnpackStruct(data)}, + units::meter_t{wpi::UnpackStruct(data)}, + units::meter_t{wpi::UnpackStruct(data)}, + units::radian_t{wpi::UnpackStruct(data)}, + units::radian_t{wpi::UnpackStruct(data)}, + units::radian_t{wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, const frc::Twist3d& value) { + wpi::PackStruct(data, value.dx.value()); + wpi::PackStruct(data, value.dy.value()); + wpi::PackStruct(data, value.dz.value()); + wpi::PackStruct(data, value.rx.value()); + wpi::PackStruct(data, value.ry.value()); + wpi::PackStruct(data, value.rz.value()); +} diff --git a/wpimath/src/main/native/cpp/jni/WPIMathJNI_ArmFeedforward.cpp b/wpimath/src/main/native/cpp/jni/WPIMathJNI_ArmFeedforward.cpp new file mode 100644 index 00000000000..3428c52688e --- /dev/null +++ b/wpimath/src/main/native/cpp/jni/WPIMathJNI_ArmFeedforward.cpp @@ -0,0 +1,36 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include + +#include + +#include "edu_wpi_first_math_WPIMathJNI.h" +#include "frc/controller/ArmFeedforward.h" + +using namespace wpi::java; + +extern "C" { + +/* + * Class: edu_wpi_first_math_WPIMathJNI + * Method: calculate + * Signature: (DDDDDDDD)D + */ +JNIEXPORT jdouble JNICALL +Java_edu_wpi_first_math_WPIMathJNI_calculate + (JNIEnv* env, jclass, jdouble ks, jdouble kv, jdouble ka, jdouble kg, + jdouble currentAngle, jdouble currentVelocity, jdouble nextVelocity, + jdouble dt) +{ + return frc::ArmFeedforward{units::volt_t{ks}, units::volt_t{kg}, + units::unit_t{kv}, + units::unit_t{ka}} + .Calculate(units::radian_t{currentAngle}, + units::radians_per_second_t{currentVelocity}, + units::radians_per_second_t{nextVelocity}, units::second_t{dt}) + .value(); +} + +} // extern "C" diff --git a/wpimath/src/main/native/cpp/kinematics/MecanumDriveWheelSpeeds.cpp b/wpimath/src/main/native/cpp/kinematics/MecanumDriveWheelSpeeds.cpp index dd30263fbcf..0f5de422e26 100644 --- a/wpimath/src/main/native/cpp/kinematics/MecanumDriveWheelSpeeds.cpp +++ b/wpimath/src/main/native/cpp/kinematics/MecanumDriveWheelSpeeds.cpp @@ -16,10 +16,10 @@ void MecanumDriveWheelSpeeds::Desaturate( units::meters_per_second_t attainableMaxSpeed) { std::array wheelSpeeds{frontLeft, frontRight, rearLeft, rearRight}; - units::meters_per_second_t realMaxSpeed = *std::max_element( + units::meters_per_second_t realMaxSpeed = units::math::abs(*std::max_element( wheelSpeeds.begin(), wheelSpeeds.end(), [](const auto& a, const auto& b) { return units::math::abs(a) < units::math::abs(b); - }); + })); if (realMaxSpeed > attainableMaxSpeed) { for (int i = 0; i < 4; ++i) { diff --git a/wpimath/src/main/native/cpp/kinematics/proto/ChassisSpeedsProto.cpp b/wpimath/src/main/native/cpp/kinematics/proto/ChassisSpeedsProto.cpp new file mode 100644 index 00000000000..097a2fba2e5 --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/proto/ChassisSpeedsProto.cpp @@ -0,0 +1,31 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/proto/ChassisSpeedsProto.h" + +#include "kinematics.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufChassisSpeeds>(arena); +} + +frc::ChassisSpeeds wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::ChassisSpeeds{ + units::meters_per_second_t{m->vx()}, + units::meters_per_second_t{m->vy()}, + units::radians_per_second_t{m->omega()}, + }; +} + +void wpi::Protobuf::Pack(google::protobuf::Message* msg, + const frc::ChassisSpeeds& value) { + auto m = static_cast(msg); + m->set_vx(value.vx.value()); + m->set_vy(value.vy.value()); + m->set_omega(value.omega.value()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/proto/DifferentialDriveKinematicsProto.cpp b/wpimath/src/main/native/cpp/kinematics/proto/DifferentialDriveKinematicsProto.cpp new file mode 100644 index 00000000000..a79e565572a --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/proto/DifferentialDriveKinematicsProto.cpp @@ -0,0 +1,30 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/proto/DifferentialDriveKinematicsProto.h" + +#include "kinematics.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufDifferentialDriveKinematics>(arena); +} + +frc::DifferentialDriveKinematics +wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = + static_cast(&msg); + return frc::DifferentialDriveKinematics{ + units::meter_t{m->track_width()}, + }; +} + +void wpi::Protobuf::Pack( + google::protobuf::Message* msg, + const frc::DifferentialDriveKinematics& value) { + auto m = static_cast(msg); + m->set_track_width(value.trackWidth.value()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/proto/DifferentialDriveWheelPositionsProto.cpp b/wpimath/src/main/native/cpp/kinematics/proto/DifferentialDriveWheelPositionsProto.cpp new file mode 100644 index 00000000000..8a0af6f6fba --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/proto/DifferentialDriveWheelPositionsProto.cpp @@ -0,0 +1,34 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/proto/DifferentialDriveWheelPositionsProto.h" + +#include "kinematics.pb.h" + +google::protobuf::Message* wpi::Protobuf< + frc::DifferentialDriveWheelPositions>::New(google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufDifferentialDriveWheelPositions>(arena); +} + +frc::DifferentialDriveWheelPositions +wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = + static_cast( + &msg); + return frc::DifferentialDriveWheelPositions{ + units::meter_t{m->left()}, + units::meter_t{m->right()}, + }; +} + +void wpi::Protobuf::Pack( + google::protobuf::Message* msg, + const frc::DifferentialDriveWheelPositions& value) { + auto m = + static_cast(msg); + m->set_left(value.left.value()); + m->set_right(value.right.value()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/proto/DifferentialDriveWheelSpeedsProto.cpp b/wpimath/src/main/native/cpp/kinematics/proto/DifferentialDriveWheelSpeedsProto.cpp new file mode 100644 index 00000000000..cb38b844c47 --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/proto/DifferentialDriveWheelSpeedsProto.cpp @@ -0,0 +1,32 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/proto/DifferentialDriveWheelSpeedsProto.h" + +#include "kinematics.pb.h" + +google::protobuf::Message* wpi::Protobuf< + frc::DifferentialDriveWheelSpeeds>::New(google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufDifferentialDriveWheelSpeeds>(arena); +} + +frc::DifferentialDriveWheelSpeeds +wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast( + &msg); + return frc::DifferentialDriveWheelSpeeds{ + units::meters_per_second_t{m->left()}, + units::meters_per_second_t{m->right()}, + }; +} + +void wpi::Protobuf::Pack( + google::protobuf::Message* msg, + const frc::DifferentialDriveWheelSpeeds& value) { + auto m = static_cast(msg); + m->set_left(value.left.value()); + m->set_right(value.right.value()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/proto/MecanumDriveKinematicsProto.cpp b/wpimath/src/main/native/cpp/kinematics/proto/MecanumDriveKinematicsProto.cpp new file mode 100644 index 00000000000..e17102ffbfd --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/proto/MecanumDriveKinematicsProto.cpp @@ -0,0 +1,33 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/proto/MecanumDriveKinematicsProto.h" + +#include "kinematics.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufMecanumDriveKinematics>(arena); +} + +frc::MecanumDriveKinematics wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::MecanumDriveKinematics{ + wpi::UnpackProtobuf(m->front_left()), + wpi::UnpackProtobuf(m->front_right()), + wpi::UnpackProtobuf(m->rear_left()), + wpi::UnpackProtobuf(m->rear_right()), + }; +} + +void wpi::Protobuf::Pack( + google::protobuf::Message* msg, const frc::MecanumDriveKinematics& value) { + auto m = static_cast(msg); + wpi::PackProtobuf(m->mutable_front_left(), value.GetFrontLeft()); + wpi::PackProtobuf(m->mutable_front_right(), value.GetFrontRight()); + wpi::PackProtobuf(m->mutable_rear_left(), value.GetRearLeft()); + wpi::PackProtobuf(m->mutable_rear_right(), value.GetRearRight()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/proto/MecanumDriveWheelPositionsProto.cpp b/wpimath/src/main/native/cpp/kinematics/proto/MecanumDriveWheelPositionsProto.cpp new file mode 100644 index 00000000000..94ca982cfa6 --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/proto/MecanumDriveWheelPositionsProto.cpp @@ -0,0 +1,36 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/proto/MecanumDriveWheelPositionsProto.h" + +#include "kinematics.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufMecanumDriveWheelPositions>(arena); +} + +frc::MecanumDriveWheelPositions +wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = + static_cast(&msg); + return frc::MecanumDriveWheelPositions{ + units::meter_t{m->front_left()}, + units::meter_t{m->front_right()}, + units::meter_t{m->rear_left()}, + units::meter_t{m->rear_right()}, + }; +} + +void wpi::Protobuf::Pack( + google::protobuf::Message* msg, + const frc::MecanumDriveWheelPositions& value) { + auto m = static_cast(msg); + m->set_front_left(value.frontLeft.value()); + m->set_front_right(value.frontRight.value()); + m->set_rear_left(value.rearLeft.value()); + m->set_rear_right(value.rearRight.value()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/proto/MecanumDriveWheelSpeedsProto.cpp b/wpimath/src/main/native/cpp/kinematics/proto/MecanumDriveWheelSpeedsProto.cpp new file mode 100644 index 00000000000..049a088eda0 --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/proto/MecanumDriveWheelSpeedsProto.cpp @@ -0,0 +1,35 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/proto/MecanumDriveWheelSpeedsProto.h" + +#include "kinematics.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufMecanumDriveWheelSpeeds>(arena); +} + +frc::MecanumDriveWheelSpeeds +wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = + static_cast(&msg); + return frc::MecanumDriveWheelSpeeds{ + units::meters_per_second_t{m->front_left()}, + units::meters_per_second_t{m->front_right()}, + units::meters_per_second_t{m->rear_left()}, + units::meters_per_second_t{m->rear_right()}, + }; +} + +void wpi::Protobuf::Pack( + google::protobuf::Message* msg, const frc::MecanumDriveWheelSpeeds& value) { + auto m = static_cast(msg); + m->set_front_left(value.frontLeft.value()); + m->set_front_right(value.frontRight.value()); + m->set_rear_left(value.rearLeft.value()); + m->set_rear_right(value.rearRight.value()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/proto/SwerveModulePositionProto.cpp b/wpimath/src/main/native/cpp/kinematics/proto/SwerveModulePositionProto.cpp new file mode 100644 index 00000000000..4e85ec8eb4b --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/proto/SwerveModulePositionProto.cpp @@ -0,0 +1,29 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/proto/SwerveModulePositionProto.h" + +#include "kinematics.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufSwerveModulePosition>(arena); +} + +frc::SwerveModulePosition wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::SwerveModulePosition{ + units::meter_t{m->distance()}, + wpi::UnpackProtobuf(m->angle()), + }; +} + +void wpi::Protobuf::Pack( + google::protobuf::Message* msg, const frc::SwerveModulePosition& value) { + auto m = static_cast(msg); + m->set_distance(value.distance.value()); + wpi::PackProtobuf(m->mutable_angle(), value.angle); +} diff --git a/wpimath/src/main/native/cpp/kinematics/proto/SwerveModuleStateProto.cpp b/wpimath/src/main/native/cpp/kinematics/proto/SwerveModuleStateProto.cpp new file mode 100644 index 00000000000..f5d5a0fa1d6 --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/proto/SwerveModuleStateProto.cpp @@ -0,0 +1,29 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/proto/SwerveModuleStateProto.h" + +#include "kinematics.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufSwerveModuleState>(arena); +} + +frc::SwerveModuleState wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::SwerveModuleState{ + units::meters_per_second_t{m->speed()}, + wpi::UnpackProtobuf(m->angle()), + }; +} + +void wpi::Protobuf::Pack( + google::protobuf::Message* msg, const frc::SwerveModuleState& value) { + auto m = static_cast(msg); + m->set_speed(value.speed.value()); + wpi::PackProtobuf(m->mutable_angle(), value.angle); +} diff --git a/wpimath/src/main/native/cpp/kinematics/struct/ChassisSpeedsStruct.cpp b/wpimath/src/main/native/cpp/kinematics/struct/ChassisSpeedsStruct.cpp new file mode 100644 index 00000000000..3b9ec2bd3cd --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/struct/ChassisSpeedsStruct.cpp @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/struct/ChassisSpeedsStruct.h" + +namespace { +constexpr size_t kVxOff = 0; +constexpr size_t kVyOff = kVxOff + 8; +constexpr size_t kOmegaOff = kVyOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::ChassisSpeeds StructType::Unpack(std::span data) { + return frc::ChassisSpeeds{ + units::meters_per_second_t{wpi::UnpackStruct(data)}, + units::meters_per_second_t{wpi::UnpackStruct(data)}, + units::radians_per_second_t{wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, + const frc::ChassisSpeeds& value) { + wpi::PackStruct(data, value.vx.value()); + wpi::PackStruct(data, value.vy.value()); + wpi::PackStruct(data, value.omega.value()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/struct/DifferentialDriveKinematicsStruct.cpp b/wpimath/src/main/native/cpp/kinematics/struct/DifferentialDriveKinematicsStruct.cpp new file mode 100644 index 00000000000..b7be0d2266b --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/struct/DifferentialDriveKinematicsStruct.cpp @@ -0,0 +1,23 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/struct/DifferentialDriveKinematicsStruct.h" + +namespace { +constexpr size_t kTrackWidthOff = 0; +} // namespace + +using StructType = wpi::Struct; + +frc::DifferentialDriveKinematics StructType::Unpack( + std::span data) { + return frc::DifferentialDriveKinematics{ + units::meter_t{wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, + const frc::DifferentialDriveKinematics& value) { + wpi::PackStruct(data, value.trackWidth.value()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/struct/DifferentialDriveWheelPositionsStruct.cpp b/wpimath/src/main/native/cpp/kinematics/struct/DifferentialDriveWheelPositionsStruct.cpp new file mode 100644 index 00000000000..757ce62760c --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/struct/DifferentialDriveWheelPositionsStruct.cpp @@ -0,0 +1,26 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/struct/DifferentialDriveWheelPositionsStruct.h" + +namespace { +constexpr size_t kLeftOff = 0; +constexpr size_t kRightOff = kLeftOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::DifferentialDriveWheelPositions StructType::Unpack( + std::span data) { + return frc::DifferentialDriveWheelPositions{ + units::meter_t{wpi::UnpackStruct(data)}, + units::meter_t{wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, + const frc::DifferentialDriveWheelPositions& value) { + wpi::PackStruct(data, value.left.value()); + wpi::PackStruct(data, value.right.value()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/struct/DifferentialDriveWheelSpeedsStruct.cpp b/wpimath/src/main/native/cpp/kinematics/struct/DifferentialDriveWheelSpeedsStruct.cpp new file mode 100644 index 00000000000..e2ae13131cf --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/struct/DifferentialDriveWheelSpeedsStruct.cpp @@ -0,0 +1,26 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/struct/DifferentialDriveWheelSpeedsStruct.h" + +namespace { +constexpr size_t kLeftOff = 0; +constexpr size_t kRightOff = kLeftOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::DifferentialDriveWheelSpeeds StructType::Unpack( + std::span data) { + return frc::DifferentialDriveWheelSpeeds{ + units::meters_per_second_t{wpi::UnpackStruct(data)}, + units::meters_per_second_t{wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, + const frc::DifferentialDriveWheelSpeeds& value) { + wpi::PackStruct(data, value.left.value()); + wpi::PackStruct(data, value.right.value()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/struct/MecanumDriveKinematicsStruct.cpp b/wpimath/src/main/native/cpp/kinematics/struct/MecanumDriveKinematicsStruct.cpp new file mode 100644 index 00000000000..1a27a286a6e --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/struct/MecanumDriveKinematicsStruct.cpp @@ -0,0 +1,34 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/struct/MecanumDriveKinematicsStruct.h" + +namespace { +constexpr size_t kFrontLeftOff = 0; +constexpr size_t kFrontRightOff = + kFrontLeftOff + wpi::GetStructSize(); +constexpr size_t kRearLeftOff = + kFrontRightOff + wpi::GetStructSize(); +constexpr size_t kRearRightOff = + kRearLeftOff + wpi::GetStructSize(); +} // namespace + +using StructType = wpi::Struct; + +frc::MecanumDriveKinematics StructType::Unpack(std::span data) { + return frc::MecanumDriveKinematics{ + wpi::UnpackStruct(data), + wpi::UnpackStruct(data), + wpi::UnpackStruct(data), + wpi::UnpackStruct(data), + }; +} + +void StructType::Pack(std::span data, + const frc::MecanumDriveKinematics& value) { + wpi::PackStruct(data, value.GetFrontLeft()); + wpi::PackStruct(data, value.GetFrontRight()); + wpi::PackStruct(data, value.GetRearLeft()); + wpi::PackStruct(data, value.GetRearRight()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/struct/MecanumDriveWheelPositionsStruct.cpp b/wpimath/src/main/native/cpp/kinematics/struct/MecanumDriveWheelPositionsStruct.cpp new file mode 100644 index 00000000000..c857f4de527 --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/struct/MecanumDriveWheelPositionsStruct.cpp @@ -0,0 +1,32 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/struct/MecanumDriveWheelPositionsStruct.h" + +namespace { +constexpr size_t kFrontLeftOff = 0; +constexpr size_t kFrontRightOff = kFrontLeftOff + 8; +constexpr size_t kRearLeftOff = kFrontRightOff + 8; +constexpr size_t kRearRightOff = kRearLeftOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::MecanumDriveWheelPositions StructType::Unpack( + std::span data) { + return frc::MecanumDriveWheelPositions{ + units::meter_t{wpi::UnpackStruct(data)}, + units::meter_t{wpi::UnpackStruct(data)}, + units::meter_t{wpi::UnpackStruct(data)}, + units::meter_t{wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, + const frc::MecanumDriveWheelPositions& value) { + wpi::PackStruct(data, value.frontLeft.value()); + wpi::PackStruct(data, value.frontRight.value()); + wpi::PackStruct(data, value.rearLeft.value()); + wpi::PackStruct(data, value.rearRight.value()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/struct/MecanumDriveWheelSpeedsStruct.cpp b/wpimath/src/main/native/cpp/kinematics/struct/MecanumDriveWheelSpeedsStruct.cpp new file mode 100644 index 00000000000..c232cc9828f --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/struct/MecanumDriveWheelSpeedsStruct.cpp @@ -0,0 +1,34 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/struct/MecanumDriveWheelSpeedsStruct.h" + +namespace { +constexpr size_t kFrontLeftOff = 0; +constexpr size_t kFrontRightOff = kFrontLeftOff + 8; +constexpr size_t kRearLeftOff = kFrontRightOff + 8; +constexpr size_t kRearRightOff = kRearLeftOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::MecanumDriveWheelSpeeds StructType::Unpack(std::span data) { + return frc::MecanumDriveWheelSpeeds{ + units::meters_per_second_t{ + wpi::UnpackStruct(data)}, + units::meters_per_second_t{ + wpi::UnpackStruct(data)}, + units::meters_per_second_t{wpi::UnpackStruct(data)}, + units::meters_per_second_t{ + wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, + const frc::MecanumDriveWheelSpeeds& value) { + wpi::PackStruct(data, value.frontLeft.value()); + wpi::PackStruct(data, value.frontRight.value()); + wpi::PackStruct(data, value.rearLeft.value()); + wpi::PackStruct(data, value.rearRight.value()); +} diff --git a/wpimath/src/main/native/cpp/kinematics/struct/SwerveModulePositionStruct.cpp b/wpimath/src/main/native/cpp/kinematics/struct/SwerveModulePositionStruct.cpp new file mode 100644 index 00000000000..12ae0a111c6 --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/struct/SwerveModulePositionStruct.cpp @@ -0,0 +1,25 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/struct/SwerveModulePositionStruct.h" + +namespace { +constexpr size_t kDistanceOff = 0; +constexpr size_t kAngleOff = kDistanceOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::SwerveModulePosition StructType::Unpack(std::span data) { + return frc::SwerveModulePosition{ + units::meter_t{wpi::UnpackStruct(data)}, + wpi::UnpackStruct(data), + }; +} + +void StructType::Pack(std::span data, + const frc::SwerveModulePosition& value) { + wpi::PackStruct(data, value.distance.value()); + wpi::PackStruct(data, value.angle); +} diff --git a/wpimath/src/main/native/cpp/kinematics/struct/SwerveModuleStateStruct.cpp b/wpimath/src/main/native/cpp/kinematics/struct/SwerveModuleStateStruct.cpp new file mode 100644 index 00000000000..b045178c10f --- /dev/null +++ b/wpimath/src/main/native/cpp/kinematics/struct/SwerveModuleStateStruct.cpp @@ -0,0 +1,25 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/kinematics/struct/SwerveModuleStateStruct.h" + +namespace { +constexpr size_t kSpeedOff = 0; +constexpr size_t kAngleOff = kSpeedOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::SwerveModuleState StructType::Unpack(std::span data) { + return frc::SwerveModuleState{ + units::meters_per_second_t{wpi::UnpackStruct(data)}, + wpi::UnpackStruct(data), + }; +} + +void StructType::Pack(std::span data, + const frc::SwerveModuleState& value) { + wpi::PackStruct(data, value.speed.value()); + wpi::PackStruct(data, value.angle); +} diff --git a/wpimath/src/main/native/cpp/spline/CubicHermiteSpline.cpp b/wpimath/src/main/native/cpp/spline/CubicHermiteSpline.cpp index b643849aaa6..38854437190 100644 --- a/wpimath/src/main/native/cpp/spline/CubicHermiteSpline.cpp +++ b/wpimath/src/main/native/cpp/spline/CubicHermiteSpline.cpp @@ -10,7 +10,9 @@ CubicHermiteSpline::CubicHermiteSpline( wpi::array xInitialControlVector, wpi::array xFinalControlVector, wpi::array yInitialControlVector, - wpi::array yFinalControlVector) { + wpi::array yFinalControlVector) + : m_initialControlVector{xInitialControlVector, yInitialControlVector}, + m_finalControlVector{xFinalControlVector, yFinalControlVector} { const auto hermite = MakeHermiteBasis(); const auto x = ControlVectorFromArrays(xInitialControlVector, xFinalControlVector); diff --git a/wpimath/src/main/native/cpp/spline/QuinticHermiteSpline.cpp b/wpimath/src/main/native/cpp/spline/QuinticHermiteSpline.cpp index 5362b7c6ba4..65d7986a4ec 100644 --- a/wpimath/src/main/native/cpp/spline/QuinticHermiteSpline.cpp +++ b/wpimath/src/main/native/cpp/spline/QuinticHermiteSpline.cpp @@ -10,7 +10,9 @@ QuinticHermiteSpline::QuinticHermiteSpline( wpi::array xInitialControlVector, wpi::array xFinalControlVector, wpi::array yInitialControlVector, - wpi::array yFinalControlVector) { + wpi::array yFinalControlVector) + : m_initialControlVector{xInitialControlVector, yInitialControlVector}, + m_finalControlVector{xFinalControlVector, yFinalControlVector} { const auto hermite = MakeHermiteBasis(); const auto x = ControlVectorFromArrays(xInitialControlVector, xFinalControlVector); diff --git a/wpimath/src/main/native/cpp/spline/SplineHelper.cpp b/wpimath/src/main/native/cpp/spline/SplineHelper.cpp index e8bbb46ee1e..c78a54f4645 100644 --- a/wpimath/src/main/native/cpp/spline/SplineHelper.cpp +++ b/wpimath/src/main/native/cpp/spline/SplineHelper.cpp @@ -169,6 +169,81 @@ std::vector SplineHelper::QuinticSplinesFromWaypoints( return splines; } +std::vector SplineHelper::OptimizeCurvature( + const std::vector& splines) { + // If there's only one spline in the vector, we can't optimize anything so + // just return that. + if (splines.size() < 2) { + return splines; + } + + // Implements Section 4.1.2 of + // http://www2.informatik.uni-freiburg.de/~lau/students/Sprunk2008.pdf. + + // Cubic splines minimize the integral of the second derivative's absolute + // value. Therefore, we can create cubic splines with the same 0th and 1st + // derivatives and the provided quintic splines, find the second derivative of + // those cubic splines and then use a weighted average for the second + // derivatives of the quintic splines. + + std::vector optimizedSplines; + optimizedSplines.reserve(splines.size()); + optimizedSplines.push_back(splines[0]); + + for (size_t i = 0; i < splines.size() - 1; ++i) { + const auto& a = splines[i]; + const auto& b = splines[i + 1]; + + // Get the control vectors that created the quintic splines above. + const auto& aInitial = a.GetInitialControlVector(); + const auto& aFinal = a.GetFinalControlVector(); + const auto& bInitial = b.GetInitialControlVector(); + const auto& bFinal = b.GetFinalControlVector(); + + // Create cubic splines with the same control vectors. + auto Trim = [](const wpi::array& a) { + return wpi::array{a[0], a[1]}; + }; + CubicHermiteSpline ca{Trim(aInitial.x), Trim(aFinal.x), Trim(aInitial.y), + Trim(aFinal.y)}; + CubicHermiteSpline cb{Trim(bInitial.x), Trim(bFinal.x), Trim(bInitial.y), + Trim(bFinal.y)}; + + // Calculate the second derivatives at the knot points. + frc::Vectord<4> bases{1.0, 1.0, 1.0, 1.0}; + frc::Vectord<6> combinedA = ca.Coefficients() * bases; + + double ddxA = combinedA(4); + double ddyA = combinedA(5); + double ddxB = cb.Coefficients()(4, 1); + double ddyB = cb.Coefficients()(5, 1); + + // Calculate the parameters for weighted average. + double dAB = + std::hypot(aFinal.x[0] - aInitial.x[0], aFinal.y[0] - aInitial.y[0]); + double dBC = + std::hypot(bFinal.x[0] - bInitial.x[0], bFinal.y[0] - bInitial.y[0]); + double alpha = dBC / (dAB + dBC); + double beta = dAB / (dAB + dBC); + + // Calculate the weighted average. + double ddx = alpha * ddxA + beta * ddxB; + double ddy = alpha * ddyA + beta * ddyB; + + // Create new splines. + optimizedSplines[i] = {aInitial.x, + {aFinal.x[0], aFinal.x[1], ddx}, + aInitial.y, + {aFinal.y[0], aFinal.y[1], ddy}}; + optimizedSplines.push_back({{bInitial.x[0], bInitial.x[1], ddx}, + bFinal.x, + {bInitial.y[0], bInitial.y[1], ddy}, + bFinal.y}); + } + + return optimizedSplines; +} + void SplineHelper::ThomasAlgorithm(const std::vector& a, const std::vector& b, const std::vector& c, diff --git a/wpimath/src/main/native/cpp/system/plant/LinearSystemId.cpp b/wpimath/src/main/native/cpp/system/plant/LinearSystemId.cpp index 11c65eada35..26d239fed4c 100644 --- a/wpimath/src/main/native/cpp/system/plant/LinearSystemId.cpp +++ b/wpimath/src/main/native/cpp/system/plant/LinearSystemId.cpp @@ -6,7 +6,7 @@ using namespace frc; -LinearSystem<2, 1, 1> LinearSystemId::ElevatorSystem(DCMotor motor, +LinearSystem<2, 1, 2> LinearSystemId::ElevatorSystem(DCMotor motor, units::kilogram_t mass, units::meter_t radius, double gearing) { @@ -27,13 +27,13 @@ LinearSystem<2, 1, 1> LinearSystemId::ElevatorSystem(DCMotor motor, .value()}}; Matrixd<2, 1> B{0.0, (gearing * motor.Kt / (motor.R * radius * mass)).value()}; - Matrixd<1, 2> C{1.0, 0.0}; - Matrixd<1, 1> D{0.0}; + Matrixd<2, 2> C{{1.0, 0.0}, {0.0, 1.0}}; + Matrixd<2, 1> D{0.0, 0.0}; - return LinearSystem<2, 1, 1>(A, B, C, D); + return LinearSystem<2, 1, 2>(A, B, C, D); } -LinearSystem<2, 1, 1> LinearSystemId::SingleJointedArmSystem( +LinearSystem<2, 1, 2> LinearSystemId::SingleJointedArmSystem( DCMotor motor, units::kilogram_square_meter_t J, double gearing) { if (J <= 0_kg_sq_m) { throw std::domain_error("J must be greater than zero."); @@ -47,10 +47,10 @@ LinearSystem<2, 1, 1> LinearSystemId::SingleJointedArmSystem( {0.0, (-std::pow(gearing, 2) * motor.Kt / (motor.Kv * motor.R * J)).value()}}; Matrixd<2, 1> B{0.0, (gearing * motor.Kt / (motor.R * J)).value()}; - Matrixd<1, 2> C{1.0, 0.0}; - Matrixd<1, 1> D{0.0}; + Matrixd<2, 2> C{{1.0, 0.0}, {0.0, 1.0}}; + Matrixd<2, 1> D{{0.0}, {0.0}}; - return LinearSystem<2, 1, 1>(A, B, C, D); + return LinearSystem<2, 1, 2>(A, B, C, D); } LinearSystem<2, 2, 2> LinearSystemId::IdentifyDrivetrainSystem( diff --git a/wpimath/src/main/native/cpp/system/plant/proto/DCMotorProto.cpp b/wpimath/src/main/native/cpp/system/plant/proto/DCMotorProto.cpp new file mode 100644 index 00000000000..83632702090 --- /dev/null +++ b/wpimath/src/main/native/cpp/system/plant/proto/DCMotorProto.cpp @@ -0,0 +1,35 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/system/plant/proto/DCMotorProto.h" + +#include "plant.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage( + arena); +} + +frc::DCMotor wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::DCMotor{ + units::volt_t{m->nominal_voltage()}, + units::newton_meter_t{m->stall_torque()}, + units::ampere_t{m->stall_current()}, + units::ampere_t{m->free_current()}, + units::radians_per_second_t{m->free_speed()}, + }; +} + +void wpi::Protobuf::Pack(google::protobuf::Message* msg, + const frc::DCMotor& value) { + auto m = static_cast(msg); + m->set_nominal_voltage(value.nominalVoltage.value()); + m->set_stall_torque(value.stallTorque.value()); + m->set_stall_current(value.stallCurrent.value()); + m->set_free_current(value.freeCurrent.value()); + m->set_free_speed(value.freeSpeed.value()); +} diff --git a/wpimath/src/main/native/cpp/system/plant/struct/DCMotorStruct.cpp b/wpimath/src/main/native/cpp/system/plant/struct/DCMotorStruct.cpp new file mode 100644 index 00000000000..e7389a17efb --- /dev/null +++ b/wpimath/src/main/native/cpp/system/plant/struct/DCMotorStruct.cpp @@ -0,0 +1,34 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/system/plant/struct/DCMotorStruct.h" + +namespace { +constexpr size_t kNominalVoltageOff = 0; +constexpr size_t kStallTorqueOff = kNominalVoltageOff + 8; +constexpr size_t kStallCurrentOff = kStallTorqueOff + 8; +constexpr size_t kFreeCurrentOff = kStallCurrentOff + 8; +constexpr size_t kFreeSpeedOff = kFreeCurrentOff + 8; +} // namespace + +using StructType = wpi::Struct; + +frc::DCMotor StructType::Unpack(std::span data) { + return frc::DCMotor{ + units::volt_t{wpi::UnpackStruct(data)}, + units::newton_meter_t{wpi::UnpackStruct(data)}, + units::ampere_t{wpi::UnpackStruct(data)}, + units::ampere_t{wpi::UnpackStruct(data)}, + units::radians_per_second_t{ + wpi::UnpackStruct(data)}, + }; +} + +void StructType::Pack(std::span data, const frc::DCMotor& value) { + wpi::PackStruct(data, value.nominalVoltage.value()); + wpi::PackStruct(data, value.stallTorque.value()); + wpi::PackStruct(data, value.stallCurrent.value()); + wpi::PackStruct(data, value.freeCurrent.value()); + wpi::PackStruct(data, value.freeSpeed.value()); +} diff --git a/wpimath/src/main/native/cpp/trajectory/TrajectoryGenerator.cpp b/wpimath/src/main/native/cpp/trajectory/TrajectoryGenerator.cpp index c7a7e9a7ff4..daf6670385a 100644 --- a/wpimath/src/main/native/cpp/trajectory/TrajectoryGenerator.cpp +++ b/wpimath/src/main/native/cpp/trajectory/TrajectoryGenerator.cpp @@ -6,7 +6,7 @@ #include -#include +#include #include "frc/spline/SplineHelper.h" #include "frc/spline/SplineParameterizer.h" @@ -22,7 +22,7 @@ void TrajectoryGenerator::ReportError(const char* error) { if (s_errorFunc) { s_errorFunc(error); } else { - fmt::print(stderr, "TrajectoryGenerator error: {}\n", error); + wpi::print(stderr, "TrajectoryGenerator error: {}\n", error); } } @@ -121,8 +121,8 @@ Trajectory TrajectoryGenerator::GenerateTrajectory( std::vector points; try { - points = SplinePointsFromSplines( - SplineHelper::QuinticSplinesFromWaypoints(newWaypoints)); + points = SplinePointsFromSplines(SplineHelper::OptimizeCurvature( + SplineHelper::QuinticSplinesFromWaypoints(newWaypoints))); } catch (SplineParameterizer::MalformedSplineException& e) { ReportError(e.what()); return kDoNothingTrajectory; diff --git a/wpimath/src/main/native/cpp/trajectory/proto/TrajectoryProto.cpp b/wpimath/src/main/native/cpp/trajectory/proto/TrajectoryProto.cpp new file mode 100644 index 00000000000..d5bbe2b3b57 --- /dev/null +++ b/wpimath/src/main/native/cpp/trajectory/proto/TrajectoryProto.cpp @@ -0,0 +1,33 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/trajectory/proto/TrajectoryProto.h" + +#include "trajectory.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage( + arena); +} + +frc::Trajectory wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + std::vector states; + states.reserve(m->states().size()); + for (const auto& protoState : m->states()) { + states.push_back(wpi::UnpackProtobuf(protoState)); + } + return frc::Trajectory{states}; +} + +void wpi::Protobuf::Pack(google::protobuf::Message* msg, + const frc::Trajectory& value) { + auto m = static_cast(msg); + m->mutable_states()->Reserve(value.States().size()); + for (const auto& state : value.States()) { + wpi::PackProtobuf(m->add_states(), state); + } +} diff --git a/wpimath/src/main/native/cpp/trajectory/proto/TrajectoryStateProto.cpp b/wpimath/src/main/native/cpp/trajectory/proto/TrajectoryStateProto.cpp new file mode 100644 index 00000000000..f2b80abe8ab --- /dev/null +++ b/wpimath/src/main/native/cpp/trajectory/proto/TrajectoryStateProto.cpp @@ -0,0 +1,35 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "frc/trajectory/proto/TrajectoryStateProto.h" + +#include "trajectory.pb.h" + +google::protobuf::Message* wpi::Protobuf::New( + google::protobuf::Arena* arena) { + return google::protobuf::Arena::CreateMessage< + wpi::proto::ProtobufTrajectoryState>(arena); +} + +frc::Trajectory::State wpi::Protobuf::Unpack( + const google::protobuf::Message& msg) { + auto m = static_cast(&msg); + return frc::Trajectory::State{ + units::second_t{m->time()}, + units::meters_per_second_t{m->velocity()}, + units::meters_per_second_squared_t{m->acceleration()}, + wpi::UnpackProtobuf(m->pose()), + units::curvature_t{m->curvature()}, + }; +} + +void wpi::Protobuf::Pack( + google::protobuf::Message* msg, const frc::Trajectory::State& value) { + auto m = static_cast(msg); + m->set_time(value.t.value()); + m->set_velocity(value.velocity.value()); + m->set_acceleration(value.acceleration.value()); + wpi::PackProtobuf(m->mutable_pose(), value.pose); + m->set_curvature(value.curvature.value()); +} diff --git a/wpimath/src/main/native/include/frc/DARE.h b/wpimath/src/main/native/include/frc/DARE.h index 6a3104e5c15..4681d3c8250 100644 --- a/wpimath/src/main/native/include/frc/DARE.h +++ b/wpimath/src/main/native/include/frc/DARE.h @@ -75,14 +75,12 @@ void CheckDARE_ABQ(const Eigen::Matrix& A, // Require (A, C) pair be detectable where Q = CᵀC // // Q = CᵀC = PᵀLDLᵀP - // Cᵀ = PᵀL√(D) - // C = (PᵀL√(D))ᵀ + // C = √(D)LᵀP { Eigen::Matrix C = - (Q_ldlt.transpositionsP().transpose() * - Eigen::Matrix{Q_ldlt.matrixL()} * - Q_ldlt.vectorD().cwiseSqrt().asDiagonal()) - .transpose(); + Q_ldlt.vectorD().cwiseSqrt().asDiagonal() * + Eigen::Matrix{Q_ldlt.matrixL().transpose()} * + Q_ldlt.transpositionsP(); if (!IsDetectable(A, C)) { std::string msg = fmt::format( diff --git a/wpimath/src/main/native/include/frc/StateSpaceUtil.h b/wpimath/src/main/native/include/frc/StateSpaceUtil.h index e2b638ca24b..f851c03e393 100644 --- a/wpimath/src/main/native/include/frc/StateSpaceUtil.h +++ b/wpimath/src/main/native/include/frc/StateSpaceUtil.h @@ -34,18 +34,28 @@ namespace frc { * @return State excursion or control effort cost matrix. */ template ... Ts> -Matrixd MakeCostMatrix(Ts... tolerances) { - Eigen::DiagonalMatrix result; - auto& diag = result.diagonal(); +constexpr Matrixd MakeCostMatrix( + Ts... tolerances) { + Matrixd result; + + for (int row = 0; row < result.rows(); ++row) { + for (int col = 0; col < result.cols(); ++col) { + if (row != col) { + result.coeffRef(row, col) = 0.0; + } + } + } + wpi::for_each( [&](int i, double tolerance) { if (tolerance == std::numeric_limits::infinity()) { - diag(i) = 0.0; + result.coeffRef(i, i) = 0.0; } else { - diag(i) = 1.0 / std::pow(tolerance, 2); + result.coeffRef(i, i) = 1.0 / (tolerance * tolerance); } }, tolerances...); + return result; } @@ -62,11 +72,21 @@ Matrixd MakeCostMatrix(Ts... tolerances) { * @return Process noise or measurement noise covariance matrix. */ template ... Ts> -Matrixd MakeCovMatrix(Ts... stdDevs) { - Eigen::DiagonalMatrix result; - auto& diag = result.diagonal(); - wpi::for_each([&](int i, double stdDev) { diag(i) = std::pow(stdDev, 2); }, - stdDevs...); +constexpr Matrixd MakeCovMatrix(Ts... stdDevs) { + Matrixd result; + + for (int row = 0; row < result.rows(); ++row) { + for (int col = 0; col < result.cols(); ++col) { + if (row != col) { + result.coeffRef(row, col) = 0.0; + } + } + } + + wpi::for_each( + [&](int i, double stdDev) { result.coeffRef(i, i) = stdDev * stdDev; }, + stdDevs...); + return result; } @@ -84,16 +104,23 @@ Matrixd MakeCovMatrix(Ts... stdDevs) { * @return State excursion or control effort cost matrix. */ template -Matrixd MakeCostMatrix(const std::array& costs) { - Eigen::DiagonalMatrix result; - auto& diag = result.diagonal(); - for (size_t i = 0; i < costs.size(); ++i) { - if (costs[i] == std::numeric_limits::infinity()) { - diag(i) = 0.0; - } else { - diag(i) = 1.0 / std::pow(costs[i], 2); +constexpr Matrixd MakeCostMatrix(const std::array& costs) { + Matrixd result; + + for (int row = 0; row < result.rows(); ++row) { + for (int col = 0; col < result.cols(); ++col) { + if (row == col) { + if (costs[row] == std::numeric_limits::infinity()) { + result.coeffRef(row, col) = 0.0; + } else { + result.coeffRef(row, col) = 1.0 / (costs[row] * costs[row]); + } + } else { + result.coeffRef(row, col) = 0.0; + } } } + return result; } @@ -110,12 +137,19 @@ Matrixd MakeCostMatrix(const std::array& costs) { * @return Process noise or measurement noise covariance matrix. */ template -Matrixd MakeCovMatrix(const std::array& stdDevs) { - Eigen::DiagonalMatrix result; - auto& diag = result.diagonal(); - for (size_t i = 0; i < N; ++i) { - diag(i) = std::pow(stdDevs[i], 2); +constexpr Matrixd MakeCovMatrix(const std::array& stdDevs) { + Matrixd result; + + for (int row = 0; row < result.rows(); ++row) { + for (int col = 0; col < result.cols(); ++col) { + if (row == col) { + result.coeffRef(row, col) = stdDevs[row] * stdDevs[row]; + } else { + result.coeffRef(row, col) = 0.0; + } + } } + return result; } @@ -194,8 +228,8 @@ Eigen::Vector4d PoseTo4dVector(const Pose2d& pose); * any, have absolute values less than one, where an eigenvalue is * uncontrollable if rank([λI - A, B]) < n where n is the number of states. * - * @tparam States The number of states. - * @tparam Inputs The number of inputs. + * @tparam States Number of states. + * @tparam Inputs Number of inputs. * @param A System matrix. * @param B Input matrix. */ @@ -253,8 +287,8 @@ IsStabilizable(const Eigen::MatrixXd& A, * any, have absolute values less than one, where an eigenvalue is unobservable * if rank([λI - A; C]) < n where n is the number of states. * - * @tparam States The number of states. - * @tparam Outputs The number of outputs. + * @tparam States Number of states. + * @tparam Outputs Number of outputs. * @param A System matrix. * @param C Output matrix. */ @@ -277,7 +311,7 @@ Eigen::Vector3d PoseToVector(const Pose2d& pose); /** * Clamps input vector between system's minimum and maximum allowable input. * - * @tparam Inputs The number of inputs. + * @tparam Inputs Number of inputs. * @param u Input vector to clamp. * @param umin The minimum input magnitude. * @param umax The maximum input magnitude. @@ -298,7 +332,7 @@ Vectord ClampInputMaxMagnitude(const Vectord& u, * Renormalize all inputs if any exceeds the maximum magnitude. Useful for * systems such as differential drivetrains. * - * @tparam Inputs The number of inputs. + * @tparam Inputs Number of inputs. * @param u The input vector. * @param maxMagnitude The maximum magnitude any input can have. * @return The normalizedInput diff --git a/wpimath/src/main/native/include/frc/controller/ArmFeedforward.h b/wpimath/src/main/native/include/frc/controller/ArmFeedforward.h index 5621803f228..28713003c9d 100644 --- a/wpimath/src/main/native/include/frc/controller/ArmFeedforward.h +++ b/wpimath/src/main/native/include/frc/controller/ArmFeedforward.h @@ -11,6 +11,7 @@ #include "units/angular_velocity.h" #include "units/math.h" #include "units/voltage.h" +#include "wpimath/MathShared.h" namespace frc { /** @@ -29,20 +30,31 @@ class WPILIB_DLLEXPORT ArmFeedforward { using ka_unit = units::compound_unit>; - constexpr ArmFeedforward() = default; - /** * Creates a new ArmFeedforward with the specified gains. * - * @param kS The static gain, in volts. + * @param kS The static gain, in volts. * @param kG The gravity gain, in volts. - * @param kV The velocity gain, in volt seconds per radian. - * @param kA The acceleration gain, in volt seconds² per radian. + * @param kV The velocity gain, in volt seconds per radian. + * @param kA The acceleration gain, in volt seconds² per radian. */ constexpr ArmFeedforward( units::volt_t kS, units::volt_t kG, units::unit_t kV, units::unit_t kA = units::unit_t(0)) - : kS(kS), kG(kG), kV(kV), kA(kA) {} + : kS(kS), kG(kG), kV(kV), kA(kA) { + if (kV.value() < 0) { + wpi::math::MathSharedStore::ReportError( + "kV must be a non-negative number, got {}!", kV.value()); + kV = units::unit_t{0}; + wpi::math::MathSharedStore::ReportWarning("kV defaulted to 0."); + } + if (kA.value() < 0) { + wpi::math::MathSharedStore::ReportError( + "kA must be a non-negative number, got {}!", kA.value()); + kA = units::unit_t{0}; + wpi::math::MathSharedStore::ReportWarning("kA defaulted to 0;"); + } + } /** * Calculates the feedforward from the gains and setpoints. @@ -64,6 +76,23 @@ class WPILIB_DLLEXPORT ArmFeedforward { kV * velocity + kA * acceleration; } + /** + * Calculates the feedforward from the gains and setpoints. + * + * @param currentAngle The current angle in radians. This angle should be + * measured from the horizontal (i.e. if the provided angle is 0, the arm + * should be parallel to the floor). If your encoder does not follow this + * convention, an offset should be added. + * @param currentVelocity The current velocity setpoint in radians per second. + * @param nextVelocity The next velocity setpoint in radians per second. + * @param dt Time between velocity setpoints in seconds. + * @return The computed feedforward in volts. + */ + units::volt_t Calculate(units::unit_t currentAngle, + units::unit_t currentVelocity, + units::unit_t nextVelocity, + units::second_t dt) const; + // Rearranging the main equation from the calculate() method yields the // formulas for the methods below: @@ -163,9 +192,19 @@ class WPILIB_DLLEXPORT ArmFeedforward { return MaxAchievableAcceleration(-maxVoltage, angle, velocity); } - units::volt_t kS{0}; - units::volt_t kG{0}; - units::unit_t kV{0}; - units::unit_t kA{0}; + /// The static gain, in volts. + const units::volt_t kS; + + /// The gravity gain, in volts. + const units::volt_t kG; + + /// The velocity gain, in volt seconds per radian. + const units::unit_t kV; + + /// The acceleration gain, in volt seconds² per radian. + const units::unit_t kA; }; } // namespace frc + +#include "frc/controller/proto/ArmFeedforwardProto.h" +#include "frc/controller/struct/ArmFeedforwardStruct.h" diff --git a/wpimath/src/main/native/include/frc/controller/ControlAffinePlantInversionFeedforward.h b/wpimath/src/main/native/include/frc/controller/ControlAffinePlantInversionFeedforward.h index 63064576557..c3c282d3e63 100644 --- a/wpimath/src/main/native/include/frc/controller/ControlAffinePlantInversionFeedforward.h +++ b/wpimath/src/main/native/include/frc/controller/ControlAffinePlantInversionFeedforward.h @@ -34,8 +34,8 @@ namespace frc { * For more on the underlying math, read * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. * - * @tparam States The number of states. - * @tparam Inputs the number of inputs. + * @tparam States Number of states. + * @tparam Inputs Number of inputs. */ template class ControlAffinePlantInversionFeedforward { diff --git a/wpimath/src/main/native/include/frc/controller/DifferentialDriveWheelVoltages.h b/wpimath/src/main/native/include/frc/controller/DifferentialDriveWheelVoltages.h index 48f341e6d66..424cd2d1b39 100644 --- a/wpimath/src/main/native/include/frc/controller/DifferentialDriveWheelVoltages.h +++ b/wpimath/src/main/native/include/frc/controller/DifferentialDriveWheelVoltages.h @@ -12,8 +12,14 @@ namespace frc { * Motor voltages for a differential drive. */ struct DifferentialDriveWheelVoltages { + /// Left wheel voltage. units::volt_t left = 0_V; + + /// Right wheel voltage. units::volt_t right = 0_V; }; } // namespace frc + +#include "frc/controller/proto/DifferentialDriveWheelVoltagesProto.h" +#include "frc/controller/struct/DifferentialDriveWheelVoltagesStruct.h" diff --git a/wpimath/src/main/native/include/frc/controller/ElevatorFeedforward.h b/wpimath/src/main/native/include/frc/controller/ElevatorFeedforward.h index 62a7bad8676..07a0499a53c 100644 --- a/wpimath/src/main/native/include/frc/controller/ElevatorFeedforward.h +++ b/wpimath/src/main/native/include/frc/controller/ElevatorFeedforward.h @@ -12,6 +12,7 @@ #include "units/length.h" #include "units/time.h" #include "units/voltage.h" +#include "wpimath/MathShared.h" namespace frc { /** @@ -29,8 +30,6 @@ class ElevatorFeedforward { using ka_unit = units::compound_unit>; - ElevatorFeedforward() = default; - /** * Creates a new ElevatorFeedforward with the specified gains. * @@ -42,7 +41,20 @@ class ElevatorFeedforward { constexpr ElevatorFeedforward( units::volt_t kS, units::volt_t kG, units::unit_t kV, units::unit_t kA = units::unit_t(0)) - : kS(kS), kG(kG), kV(kV), kA(kA) {} + : kS(kS), kG(kG), kV(kV), kA(kA) { + if (kV.value() < 0) { + wpi::math::MathSharedStore::ReportError( + "kV must be a non-negative number, got {}!", kV.value()); + kV = units::unit_t{0}; + wpi::math::MathSharedStore::ReportWarning("kV defaulted to 0."); + } + if (kA.value() < 0) { + wpi::math::MathSharedStore::ReportError( + "kA must be a non-negative number, got {}!", kA.value()); + kA = units::unit_t{0}; + wpi::math::MathSharedStore::ReportWarning("kA defaulted to 0;"); + } + } /** * Calculates the feedforward from the gains and setpoints. @@ -170,9 +182,19 @@ class ElevatorFeedforward { return MaxAchievableAcceleration(-maxVoltage, velocity); } - units::volt_t kS{0}; - units::volt_t kG{0}; - units::unit_t kV{0}; - units::unit_t kA{0}; + /// The static gain. + const units::volt_t kS; + + /// The gravity gain. + const units::volt_t kG; + + /// The velocity gain. + const units::unit_t kV; + + /// The acceleration gain. + const units::unit_t kA; }; } // namespace frc + +#include "frc/controller/proto/ElevatorFeedforwardProto.h" +#include "frc/controller/struct/ElevatorFeedforwardStruct.h" diff --git a/wpimath/src/main/native/include/frc/controller/ImplicitModelFollower.h b/wpimath/src/main/native/include/frc/controller/ImplicitModelFollower.h index 3a1230d4bcf..f030d4898c9 100644 --- a/wpimath/src/main/native/include/frc/controller/ImplicitModelFollower.h +++ b/wpimath/src/main/native/include/frc/controller/ImplicitModelFollower.h @@ -24,6 +24,9 @@ namespace frc { * * For more on the underlying math, read appendix B.3 in * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. + * + * @tparam States Number of states. + * @tparam Inputs Number of inputs. */ template class ImplicitModelFollower { diff --git a/wpimath/src/main/native/include/frc/controller/LinearPlantInversionFeedforward.h b/wpimath/src/main/native/include/frc/controller/LinearPlantInversionFeedforward.h index 1d905e24ab2..fb46b030926 100644 --- a/wpimath/src/main/native/include/frc/controller/LinearPlantInversionFeedforward.h +++ b/wpimath/src/main/native/include/frc/controller/LinearPlantInversionFeedforward.h @@ -26,8 +26,8 @@ namespace frc { * For more on the underlying math, read * https://file.tavsys.net/control/controls-engineering-in-frc.pdf. * - * @tparam States The number of states. - * @tparam Inputs The number of inputs. + * @tparam States Number of states. + * @tparam Inputs Number of inputs. */ template class LinearPlantInversionFeedforward { @@ -38,7 +38,7 @@ class LinearPlantInversionFeedforward { /** * Constructs a feedforward with the given plant. * - * @tparam Outputs The number of outputs. + * @tparam Outputs Number of outputs. * @param plant The plant being controlled. * @param dt Discretization timestep. */ diff --git a/wpimath/src/main/native/include/frc/controller/LinearQuadraticRegulator.h b/wpimath/src/main/native/include/frc/controller/LinearQuadraticRegulator.h index 979e98a371f..8389a88a642 100644 --- a/wpimath/src/main/native/include/frc/controller/LinearQuadraticRegulator.h +++ b/wpimath/src/main/native/include/frc/controller/LinearQuadraticRegulator.h @@ -40,6 +40,7 @@ class LinearQuadraticRegulator { * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-intro.html#lqr-tuning * for how to select the tolerances. * + * @tparam Outputs Number of outputs. * @param plant The plant being controlled. * @param Qelems The maximum desired error tolerance for each state. * @param Relems The maximum desired control effort for each input. diff --git a/wpimath/src/main/native/include/frc/controller/PIDController.h b/wpimath/src/main/native/include/frc/controller/PIDController.h index 0d5b0a3f756..30ab8f07a99 100644 --- a/wpimath/src/main/native/include/frc/controller/PIDController.h +++ b/wpimath/src/main/native/include/frc/controller/PIDController.h @@ -25,11 +25,11 @@ class WPILIB_DLLEXPORT PIDController /** * Allocates a PIDController with the given constants for Kp, Ki, and Kd. * - * @param Kp The proportional coefficient. - * @param Ki The integral coefficient. - * @param Kd The derivative coefficient. + * @param Kp The proportional coefficient. Must be >= 0. + * @param Ki The integral coefficient. Must be >= 0. + * @param Kd The derivative coefficient. Must be >= 0. * @param period The period between controller updates in seconds. The - * default is 20 milliseconds. Must be non-zero and positive. + * default is 20 milliseconds. Must be positive. */ PIDController(double Kp, double Ki, double Kd, units::second_t period = 20_ms); @@ -46,30 +46,30 @@ class WPILIB_DLLEXPORT PIDController * * Sets the proportional, integral, and differential coefficients. * - * @param Kp Proportional coefficient - * @param Ki Integral coefficient - * @param Kd Differential coefficient + * @param Kp The proportional coefficient. Must be >= 0. + * @param Ki The integral coefficient. Must be >= 0. + * @param Kd The differential coefficient. Must be >= 0. */ void SetPID(double Kp, double Ki, double Kd); /** * Sets the proportional coefficient of the PID controller gain. * - * @param Kp proportional coefficient + * @param Kp The proportional coefficient. Must be >= 0. */ void SetP(double Kp); /** * Sets the integral coefficient of the PID controller gain. * - * @param Ki integral coefficient + * @param Ki The integral coefficient. Must be >= 0. */ void SetI(double Ki); /** * Sets the differential coefficient of the PID controller gain. * - * @param Kd differential coefficient + * @param Kd The differential coefficient. Must be >= 0. */ void SetD(double Kd); @@ -81,7 +81,8 @@ class WPILIB_DLLEXPORT PIDController * non-negative. Passing a value of zero will effectively disable integral * gain. Passing a value of infinity disables IZone functionality. * - * @param iZone Maximum magnitude of error to allow integral control. + * @param iZone Maximum magnitude of error to allow integral control. Must be + * >= 0. */ void SetIZone(double iZone); diff --git a/wpimath/src/main/native/include/frc/controller/ProfiledPIDController.h b/wpimath/src/main/native/include/frc/controller/ProfiledPIDController.h index 39dc3add2cd..72278affca8 100644 --- a/wpimath/src/main/native/include/frc/controller/ProfiledPIDController.h +++ b/wpimath/src/main/native/include/frc/controller/ProfiledPIDController.h @@ -49,12 +49,12 @@ class ProfiledPIDController * Kd. Users should call reset() when they first start running the controller * to avoid unwanted behavior. * - * @param Kp The proportional coefficient. - * @param Ki The integral coefficient. - * @param Kd The derivative coefficient. + * @param Kp The proportional coefficient. Must be >= 0. + * @param Ki The integral coefficient. Must be >= 0. + * @param Kd The derivative coefficient. Must be >= 0. * @param constraints Velocity and acceleration constraints for goal. * @param period The period between controller updates in seconds. The - * default is 20 milliseconds. + * default is 20 milliseconds. Must be positive. */ ProfiledPIDController(double Kp, double Ki, double Kd, Constraints constraints, units::second_t period = 20_ms) @@ -79,9 +79,9 @@ class ProfiledPIDController * * Sets the proportional, integral, and differential coefficients. * - * @param Kp Proportional coefficient - * @param Ki Integral coefficient - * @param Kd Differential coefficient + * @param Kp The proportional coefficient. Must be >= 0. + * @param Ki The integral coefficient. Must be >= 0. + * @param Kd The differential coefficient. Must be >= 0. */ void SetPID(double Kp, double Ki, double Kd) { m_controller.SetPID(Kp, Ki, Kd); @@ -90,21 +90,21 @@ class ProfiledPIDController /** * Sets the proportional coefficient of the PID controller gain. * - * @param Kp proportional coefficient + * @param Kp The proportional coefficient. Must be >= 0. */ void SetP(double Kp) { m_controller.SetP(Kp); } /** * Sets the integral coefficient of the PID controller gain. * - * @param Ki integral coefficient + * @param Ki The integral coefficient. Must be >= 0. */ void SetI(double Ki) { m_controller.SetI(Ki); } /** * Sets the differential coefficient of the PID controller gain. * - * @param Kd differential coefficient + * @param Kd The differential coefficient. Must be >= 0. */ void SetD(double Kd) { m_controller.SetD(Kd); } @@ -116,7 +116,8 @@ class ProfiledPIDController * non-negative. Passing a value of zero will effectively disable integral * gain. Passing a value of infinity disables IZone functionality. * - * @param iZone Maximum magnitude of error to allow integral control. + * @param iZone Maximum magnitude of error to allow integral control. Must be + * >= 0. */ void SetIZone(double iZone) { m_controller.SetIZone(iZone); } diff --git a/wpimath/src/main/native/include/frc/controller/RamseteController.h b/wpimath/src/main/native/include/frc/controller/RamseteController.h index d0311019c30..8d8ec3fdae3 100644 --- a/wpimath/src/main/native/include/frc/controller/RamseteController.h +++ b/wpimath/src/main/native/include/frc/controller/RamseteController.h @@ -56,14 +56,19 @@ class WPILIB_DLLEXPORT RamseteController { * convergence more aggressive like a proportional term. * @param zeta Tuning parameter (0 rad⁻¹ < zeta < 1 rad⁻¹) for which larger * values provide more damping in response. + * @deprecated Use LTVUnicycleController instead. */ + [[deprecated("Use LTVUnicycleController instead.")]] RamseteController(units::unit_t b, units::unit_t zeta); /** * Construct a Ramsete unicycle controller. The default arguments for * b and zeta of 2.0 rad²/m² and 0.7 rad⁻¹ have been well-tested to produce * desirable results. + * + * @deprecated Use LTVUnicycleController instead. */ + [[deprecated("Use LTVUnicycleController instead.")]] RamseteController(); /** diff --git a/wpimath/src/main/native/include/frc/controller/SimpleMotorFeedforward.h b/wpimath/src/main/native/include/frc/controller/SimpleMotorFeedforward.h index 86b40eab06d..cc31fc10582 100644 --- a/wpimath/src/main/native/include/frc/controller/SimpleMotorFeedforward.h +++ b/wpimath/src/main/native/include/frc/controller/SimpleMotorFeedforward.h @@ -11,6 +11,7 @@ #include "frc/system/plant/LinearSystemId.h" #include "units/time.h" #include "units/voltage.h" +#include "wpimath/MathShared.h" namespace frc { /** @@ -28,8 +29,6 @@ class SimpleMotorFeedforward { using ka_unit = units::compound_unit>; - constexpr SimpleMotorFeedforward() = default; - /** * Creates a new SimpleMotorFeedforward with the specified gains. * @@ -40,7 +39,20 @@ class SimpleMotorFeedforward { constexpr SimpleMotorFeedforward( units::volt_t kS, units::unit_t kV, units::unit_t kA = units::unit_t(0)) - : kS(kS), kV(kV), kA(kA) {} + : kS(kS), kV(kV), kA(kA) { + if (kV.value() < 0) { + wpi::math::MathSharedStore::ReportError( + "kV must be a non-negative number, got {}!", kV.value()); + kV = units::unit_t{0}; + wpi::math::MathSharedStore::ReportWarning("kV defaulted to 0."); + } + if (kA.value() < 0) { + wpi::math::MathSharedStore::ReportError( + "kA must be a non-negative number, got {}!", kA.value()); + kA = units::unit_t{0}; + wpi::math::MathSharedStore::ReportWarning("kA defaulted to 0;"); + } + } /** * Calculates the feedforward from the gains and setpoints. @@ -148,8 +160,13 @@ class SimpleMotorFeedforward { return MaxAchievableAcceleration(-maxVoltage, velocity); } - units::volt_t kS{0}; - units::unit_t kV{0}; - units::unit_t kA{0}; + /** The static gain. */ + const units::volt_t kS; + + /** The velocity gain. */ + const units::unit_t kV; + + /** The acceleration gain. */ + const units::unit_t kA; }; } // namespace frc diff --git a/wpimath/src/main/native/include/frc/controller/proto/ArmFeedforwardProto.h b/wpimath/src/main/native/include/frc/controller/proto/ArmFeedforwardProto.h new file mode 100644 index 00000000000..bc893aa8cb2 --- /dev/null +++ b/wpimath/src/main/native/include/frc/controller/proto/ArmFeedforwardProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/controller/ArmFeedforward.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::ArmFeedforward Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::ArmFeedforward& value); +}; diff --git a/wpimath/src/main/native/include/frc/controller/proto/DifferentialDriveWheelVoltagesProto.h b/wpimath/src/main/native/include/frc/controller/proto/DifferentialDriveWheelVoltagesProto.h new file mode 100644 index 00000000000..486fd177d5b --- /dev/null +++ b/wpimath/src/main/native/include/frc/controller/proto/DifferentialDriveWheelVoltagesProto.h @@ -0,0 +1,19 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/controller/DifferentialDriveWheelVoltages.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::DifferentialDriveWheelVoltages Unpack( + const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::DifferentialDriveWheelVoltages& value); +}; diff --git a/wpimath/src/main/native/include/frc/controller/proto/ElevatorFeedforwardProto.h b/wpimath/src/main/native/include/frc/controller/proto/ElevatorFeedforwardProto.h new file mode 100644 index 00000000000..377f62aaa3b --- /dev/null +++ b/wpimath/src/main/native/include/frc/controller/proto/ElevatorFeedforwardProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/controller/ElevatorFeedforward.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::ElevatorFeedforward Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::ElevatorFeedforward& value); +}; diff --git a/wpimath/src/main/native/include/frc/controller/struct/ArmFeedforwardStruct.h b/wpimath/src/main/native/include/frc/controller/struct/ArmFeedforwardStruct.h new file mode 100644 index 00000000000..cfc585cb320 --- /dev/null +++ b/wpimath/src/main/native/include/frc/controller/struct/ArmFeedforwardStruct.h @@ -0,0 +1,26 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/controller/ArmFeedforward.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:ArmFeedforward"; + } + static constexpr size_t GetSize() { return 32; } + static constexpr std::string_view GetSchema() { + return "double ks;double kg;double kv;double ka"; + } + + static frc::ArmFeedforward Unpack(std::span data); + static void Pack(std::span data, const frc::ArmFeedforward& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/controller/struct/DifferentialDriveWheelVoltagesStruct.h b/wpimath/src/main/native/include/frc/controller/struct/DifferentialDriveWheelVoltagesStruct.h new file mode 100644 index 00000000000..cb5311f691c --- /dev/null +++ b/wpimath/src/main/native/include/frc/controller/struct/DifferentialDriveWheelVoltagesStruct.h @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/controller/DifferentialDriveWheelVoltages.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:DifferentialDriveWheelVoltages"; + } + static constexpr size_t GetSize() { return 16; } + static constexpr std::string_view GetSchema() { + return "double left;double right"; + } + + static frc::DifferentialDriveWheelVoltages Unpack( + std::span data); + static void Pack(std::span data, + const frc::DifferentialDriveWheelVoltages& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/controller/struct/ElevatorFeedforwardStruct.h b/wpimath/src/main/native/include/frc/controller/struct/ElevatorFeedforwardStruct.h new file mode 100644 index 00000000000..fafb7d73ecc --- /dev/null +++ b/wpimath/src/main/native/include/frc/controller/struct/ElevatorFeedforwardStruct.h @@ -0,0 +1,27 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/controller/ElevatorFeedforward.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:ElevatorFeedforward"; + } + static constexpr size_t GetSize() { return 32; } + static constexpr std::string_view GetSchema() { + return "double ks;double kg;double kv;double ka"; + } + + static frc::ElevatorFeedforward Unpack(std::span data); + static void Pack(std::span data, + const frc::ElevatorFeedforward& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/estimator/AngleStatistics.h b/wpimath/src/main/native/include/frc/estimator/AngleStatistics.h index 026cc678812..de0de37e960 100644 --- a/wpimath/src/main/native/include/frc/estimator/AngleStatistics.h +++ b/wpimath/src/main/native/include/frc/estimator/AngleStatistics.h @@ -16,7 +16,7 @@ namespace frc { * Subtracts a and b while normalizing the resulting value in the selected row * as if it were an angle. * - * @tparam States The number of states. + * @tparam States Number of states. * @param a A vector to subtract from. * @param b A vector to subtract with. * @param angleStateIdx The row containing angles to be normalized. @@ -34,7 +34,7 @@ Vectord AngleResidual(const Vectord& a, * Returns a function that subtracts two vectors while normalizing the resulting * value in the selected row as if it were an angle. * - * @tparam States The number of states. + * @tparam States Number of states. * @param angleStateIdx The row containing angles to be normalized. */ template @@ -49,7 +49,7 @@ AngleResidual(int angleStateIdx) { * Adds a and b while normalizing the resulting value in the selected row as an * angle. * - * @tparam States The number of states. + * @tparam States Number of states. * @param a A vector to add with. * @param b A vector to add with. * @param angleStateIdx The row containing angles to be normalized. @@ -67,7 +67,7 @@ Vectord AngleAdd(const Vectord& a, const Vectord& b, * Returns a function that adds two vectors while normalizing the resulting * value in the selected row as an angle. * - * @tparam States The number of states. + * @tparam States Number of states. * @param angleStateIdx The row containing angles to be normalized. */ template @@ -82,7 +82,7 @@ AngleAdd(int angleStateIdx) { * * @tparam CovDim Dimension of covariance of sigma points after passing through * the transform. - * @tparam States The number of states. + * @tparam States Number of states. * @param sigmas Sigma points. * @param Wm Weights for the mean. * @param angleStatesIdx The row containing the angles. @@ -113,7 +113,7 @@ Vectord AngleMean(const Matrixd& sigmas, * * @tparam CovDim Dimension of covariance of sigma points after passing through * the transform. - * @tparam States The number of states. + * @tparam States Number of states. * @param angleStateIdx The row containing the angles. */ template diff --git a/wpimath/src/main/native/include/frc/estimator/ExtendedKalmanFilter.h b/wpimath/src/main/native/include/frc/estimator/ExtendedKalmanFilter.h index 32ed558f71b..68eb75b8818 100644 --- a/wpimath/src/main/native/include/frc/estimator/ExtendedKalmanFilter.h +++ b/wpimath/src/main/native/include/frc/estimator/ExtendedKalmanFilter.h @@ -33,9 +33,9 @@ namespace frc { * https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 * "Stochastic control theory". * - * @tparam States The number of states. - * @tparam Inputs The number of inputs. - * @tparam Outputs The number of outputs. + * @tparam States Number of states. + * @tparam Inputs Number of inputs. + * @tparam Outputs Number of outputs. */ template class ExtendedKalmanFilter { diff --git a/wpimath/src/main/native/include/frc/estimator/KalmanFilter.h b/wpimath/src/main/native/include/frc/estimator/KalmanFilter.h index f1434938482..56dce0c11ca 100644 --- a/wpimath/src/main/native/include/frc/estimator/KalmanFilter.h +++ b/wpimath/src/main/native/include/frc/estimator/KalmanFilter.h @@ -4,7 +4,6 @@ #pragma once -#include #include #include "frc/EigenCore.h" @@ -29,9 +28,9 @@ namespace frc { * https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 * "Stochastic control theory". * - * @tparam States The number of states. - * @tparam Inputs The number of inputs. - * @tparam Outputs The number of outputs. + * @tparam States Number of states. + * @tparam Inputs Number of inputs. + * @tparam Outputs Number of outputs. */ template class KalmanFilter { @@ -43,8 +42,10 @@ class KalmanFilter { using StateArray = wpi::array; using OutputArray = wpi::array; + using StateMatrix = Matrixd; + /** - * Constructs a state-space observer with the given plant. + * Constructs a Kalman filter with the given plant. * * See * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices @@ -60,21 +61,25 @@ class KalmanFilter { const StateArray& stateStdDevs, const OutputArray& measurementStdDevs, units::second_t dt); - KalmanFilter(KalmanFilter&&) = default; - KalmanFilter& operator=(KalmanFilter&&) = default; + /** + * Returns the error covariance matrix P. + */ + const StateMatrix& P() const { return m_P; } /** - * Returns the steady-state Kalman gain matrix K. + * Returns an element of the error covariance matrix P. + * + * @param i Row of P. + * @param j Column of P. */ - const Matrixd& K() const { return m_K; } + double P(int i, int j) const { return m_P(i, j); } /** - * Returns an element of the steady-state Kalman gain matrix K. + * Set the current error covariance matrix P. * - * @param i Row of K. - * @param j Column of K. + * @param P The error covariance matrix P. */ - double K(int i, int j) const { return m_K(i, j); } + void SetP(const StateMatrix& P) { m_P = P; } /** * Returns the state estimate x-hat. @@ -106,7 +111,10 @@ class KalmanFilter { /** * Resets the observer. */ - void Reset() { m_xHat.setZero(); } + void Reset() { + m_xHat.setZero(); + m_P = m_initP; + } /** * Project the model into the future with a new control input u. @@ -119,23 +127,34 @@ class KalmanFilter { /** * Correct the state estimate x-hat using the measurements in y. * - * @param u Same control input used in the last predict step. + * @param u Same control input used in the predict step. * @param y Measurement vector. */ - void Correct(const InputVector& u, const OutputVector& y); - - private: - LinearSystem* m_plant; + void Correct(const InputVector& u, const OutputVector& y) { + Correct(u, y, m_contR); + } /** - * The steady-state Kalman gain matrix. + * Correct the state estimate x-hat using the measurements in y. + * + * This is useful for when the measurement noise covariances vary. + * + * @param u Same control input used in the predict step. + * @param y Measurement vector. + * @param R Continuous measurement noise covariance matrix. */ - Matrixd m_K; + void Correct(const InputVector& u, const OutputVector& y, + const Matrixd& R); - /** - * The state estimate. - */ + private: + LinearSystem* m_plant; StateVector m_xHat; + StateMatrix m_P; + StateMatrix m_contQ; + Matrixd m_contR; + units::second_t m_dt; + + StateMatrix m_initP; }; extern template class EXPORT_TEMPLATE_DECLARE(WPILIB_DLLEXPORT) diff --git a/wpimath/src/main/native/include/frc/estimator/KalmanFilter.inc b/wpimath/src/main/native/include/frc/estimator/KalmanFilter.inc index 7506c0d7b78..cfb8bd9bf99 100644 --- a/wpimath/src/main/native/include/frc/estimator/KalmanFilter.inc +++ b/wpimath/src/main/native/include/frc/estimator/KalmanFilter.inc @@ -4,8 +4,6 @@ #pragma once -#include - #include #include #include @@ -15,6 +13,7 @@ #include "frc/DARE.h" #include "frc/StateSpaceUtil.h" #include "frc/estimator/KalmanFilter.h" +#include "frc/fmt/Eigen.h" #include "frc/system/Discretization.h" #include "wpimath/MathShared.h" @@ -27,14 +26,16 @@ KalmanFilter::KalmanFilter( units::second_t dt) { m_plant = &plant; - auto contQ = MakeCovMatrix(stateStdDevs); - auto contR = MakeCovMatrix(measurementStdDevs); + m_contQ = MakeCovMatrix(stateStdDevs); + m_contR = MakeCovMatrix(measurementStdDevs); + m_dt = dt; + // Find discrete A and Q Matrixd discA; Matrixd discQ; - DiscretizeAQ(plant.A(), contQ, dt, &discA, &discQ); + DiscretizeAQ(plant.A(), m_contQ, dt, &discA, &discQ); - auto discR = DiscretizeR(contR, dt); + Matrixd discR = DiscretizeR(m_contR, dt); const auto& C = plant.C(); @@ -48,11 +49,38 @@ KalmanFilter::KalmanFilter( throw std::invalid_argument(msg); } - Matrixd P = + m_initP = DARE(discA.transpose(), C.transpose(), discQ, discR); - // S = CPCᵀ + R - Matrixd S = C * P * C.transpose() + discR; + Reset(); +} + +template +void KalmanFilter::Predict(const InputVector& u, + units::second_t dt) { + // Find discrete A and Q + StateMatrix discA; + StateMatrix discQ; + DiscretizeAQ(m_plant->A(), m_contQ, dt, &discA, &discQ); + + m_xHat = m_plant->CalculateX(m_xHat, u, dt); + + // Pₖ₊₁⁻ = APₖ⁻Aᵀ + Q + m_P = discA * m_P * discA.transpose() + discQ; + + m_dt = dt; +} + +template +void KalmanFilter::Correct( + const InputVector& u, const OutputVector& y, + const Matrixd& R) { + const auto& C = m_plant->C(); + const auto& D = m_plant->D(); + + const Matrixd discR = DiscretizeR(R, m_dt); + + Matrixd S = C * m_P * C.transpose() + discR; // We want to put K = PCᵀS⁻¹ into Ax = b form so we can solve it more // efficiently. @@ -66,22 +94,17 @@ KalmanFilter::KalmanFilter( // // Kᵀ = Sᵀ.solve(CPᵀ) // K = (Sᵀ.solve(CPᵀ))ᵀ - m_K = S.transpose().ldlt().solve(C * P.transpose()).transpose(); + Matrixd K = + S.transpose().ldlt().solve(C * m_P.transpose()).transpose(); - Reset(); -} - -template -void KalmanFilter::Predict(const InputVector& u, - units::second_t dt) { - m_xHat = m_plant->CalculateX(m_xHat, u, dt); -} - -template -void KalmanFilter::Correct(const InputVector& u, - const OutputVector& y) { // x̂ₖ₊₁⁺ = x̂ₖ₊₁⁻ + K(y − (Cx̂ₖ₊₁⁻ + Duₖ₊₁)) - m_xHat += m_K * (y - (m_plant->C() * m_xHat + m_plant->D() * u)); + m_xHat += K * (y - (C * m_xHat + D * u)); + + // Pₖ₊₁⁺ = (I−Kₖ₊₁C)Pₖ₊₁⁻(I−Kₖ₊₁C)ᵀ + Kₖ₊₁RKₖ₊₁ᵀ + // Use Joseph form for numerical stability + m_P = (StateMatrix::Identity() - K * C) * m_P * + (StateMatrix::Identity() - K * C).transpose() + + K * discR * K.transpose(); } } // namespace frc diff --git a/wpimath/src/main/native/include/frc/estimator/KalmanFilterLatencyCompensator.h b/wpimath/src/main/native/include/frc/estimator/KalmanFilterLatencyCompensator.h index d6e41271c8b..b93d614f016 100644 --- a/wpimath/src/main/native/include/frc/estimator/KalmanFilterLatencyCompensator.h +++ b/wpimath/src/main/native/include/frc/estimator/KalmanFilterLatencyCompensator.h @@ -16,13 +16,28 @@ namespace frc { +/** + * This class incorporates time-delayed measurements into a Kalman filter's + * state estimate. + * + * @tparam States The number of states. + * @tparam Inputs The number of inputs. + * @tparam Outputs The number of outputs. + */ template class KalmanFilterLatencyCompensator { public: + /** + * This class contains all the information about our observer at a given time. + */ struct ObserverSnapshot { + /// The state estimate. Vectord xHat; + /// The square root error covariance. Matrixd squareRootErrorCovariances; + /// The inputs. Vectord inputs; + /// The local measurements. Vectord localMeasurements; ObserverSnapshot(const KalmanFilterType& observer, const Vectord& u, diff --git a/wpimath/src/main/native/include/frc/estimator/MerweScaledSigmaPoints.h b/wpimath/src/main/native/include/frc/estimator/MerweScaledSigmaPoints.h index b2e0e458ca3..6395d8d3f1e 100644 --- a/wpimath/src/main/native/include/frc/estimator/MerweScaledSigmaPoints.h +++ b/wpimath/src/main/native/include/frc/estimator/MerweScaledSigmaPoints.h @@ -21,8 +21,8 @@ namespace frc { * [1] R. Van der Merwe "Sigma-Point Kalman Filters for Probabilitic * Inference in Dynamic State-Space Models" (Doctoral dissertation) * - * @tparam States The dimensionality of the state. 2*States+1 weights will be - * generated. + * @tparam States The dimensionality of the state. 2 * States + 1 weights will + * be generated. */ template class MerweScaledSigmaPoints { diff --git a/wpimath/src/main/native/include/frc/estimator/PoseEstimator.h b/wpimath/src/main/native/include/frc/estimator/PoseEstimator.h index eb437a40f7e..342ed2529c9 100644 --- a/wpimath/src/main/native/include/frc/estimator/PoseEstimator.h +++ b/wpimath/src/main/native/include/frc/estimator/PoseEstimator.h @@ -4,6 +4,8 @@ #pragma once +#include + #include #include #include @@ -30,6 +32,9 @@ namespace frc { * * AddVisionMeasurement() can be called as infrequently as you want; if you * never call it, then this class will behave like regular encoder odometry. + * + * @tparam WheelSpeeds Wheel speeds type. + * @tparam WheelPositions Wheel positions type. */ template class WPILIB_DLLEXPORT PoseEstimator { @@ -86,6 +91,15 @@ class WPILIB_DLLEXPORT PoseEstimator { */ Pose2d GetEstimatedPosition() const; + /** + * Return the pose at a given timestamp, if the buffer is not empty. + * + * @param timestamp The pose's timestamp. + * @return The pose at the given timestamp (or std::nullopt if the buffer is + * empty). + */ + std::optional SampleAt(units::second_t timestamp) const; + /** * Adds a vision measurement to the Kalman Filter. This will correct * the odometry pose estimate while still accounting for measurement noise. diff --git a/wpimath/src/main/native/include/frc/estimator/PoseEstimator.inc b/wpimath/src/main/native/include/frc/estimator/PoseEstimator.inc index 79d71bcc566..43942cfbae2 100644 --- a/wpimath/src/main/native/include/frc/estimator/PoseEstimator.inc +++ b/wpimath/src/main/native/include/frc/estimator/PoseEstimator.inc @@ -57,6 +57,19 @@ Pose2d PoseEstimator::GetEstimatedPosition() return m_odometry.GetPose(); } +template +std::optional PoseEstimator::SampleAt( + units::second_t timestamp) const { + // TODO Replace with std::optional::transform() in C++23 + std::optional::InterpolationRecord> + sample = m_poseBuffer.Sample(timestamp); + if (sample) { + return sample->pose; + } else { + return std::nullopt; + } +} + template void PoseEstimator::AddVisionMeasurement( const Pose2d& visionRobotPose, units::second_t timestamp) { diff --git a/wpimath/src/main/native/include/frc/estimator/SteadyStateKalmanFilter.h b/wpimath/src/main/native/include/frc/estimator/SteadyStateKalmanFilter.h new file mode 100644 index 00000000000..64b1782b97c --- /dev/null +++ b/wpimath/src/main/native/include/frc/estimator/SteadyStateKalmanFilter.h @@ -0,0 +1,153 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/EigenCore.h" +#include "frc/system/LinearSystem.h" +#include "units/time.h" + +namespace frc { + +/** + * A Kalman filter combines predictions from a model and measurements to give an + * estimate of the true system state. This is useful because many states cannot + * be measured directly as a result of sensor noise, or because the state is + * "hidden". + * + * Kalman filters use a K gain matrix to determine whether to trust the model or + * measurements more. Kalman filter theory uses statistics to compute an optimal + * K gain which minimizes the sum of squares error in the state estimate. This K + * gain is used to correct the state estimate by some amount of the difference + * between the actual measurements and the measurements predicted by the model. + * + * This class assumes predict() and correct() are called in pairs, so the Kalman + * gain converges to a steady-state value. If they aren't, use KalmanFilter + * instead. + * + * For more on the underlying math, read + * https://file.tavsys.net/control/controls-engineering-in-frc.pdf chapter 9 + * "Stochastic control theory". + * + * @tparam States Number of states. + * @tparam Inputs Number of inputs. + * @tparam Outputs Number of outputs. + */ +template +class SteadyStateKalmanFilter { + public: + using StateVector = Vectord; + using InputVector = Vectord; + using OutputVector = Vectord; + + using StateArray = wpi::array; + using OutputArray = wpi::array; + + /** + * Constructs a staeady-state Kalman filter with the given plant. + * + * See + * https://docs.wpilib.org/en/stable/docs/software/advanced-controls/state-space/state-space-observers.html#process-and-measurement-noise-covariance-matrices + * for how to select the standard deviations. + * + * @param plant The plant used for the prediction step. + * @param stateStdDevs Standard deviations of model states. + * @param measurementStdDevs Standard deviations of measurements. + * @param dt Nominal discretization timestep. + * @throws std::invalid_argument If the system is unobservable. + */ + SteadyStateKalmanFilter(LinearSystem& plant, + const StateArray& stateStdDevs, + const OutputArray& measurementStdDevs, + units::second_t dt); + + SteadyStateKalmanFilter(SteadyStateKalmanFilter&&) = default; + SteadyStateKalmanFilter& operator=(SteadyStateKalmanFilter&&) = default; + + /** + * Returns the steady-state Kalman gain matrix K. + */ + const Matrixd& K() const { return m_K; } + + /** + * Returns an element of the steady-state Kalman gain matrix K. + * + * @param i Row of K. + * @param j Column of K. + */ + double K(int i, int j) const { return m_K(i, j); } + + /** + * Returns the state estimate x-hat. + */ + const StateVector& Xhat() const { return m_xHat; } + + /** + * Returns an element of the state estimate x-hat. + * + * @param i Row of x-hat. + */ + double Xhat(int i) const { return m_xHat(i); } + + /** + * Set initial state estimate x-hat. + * + * @param xHat The state estimate x-hat. + */ + void SetXhat(const StateVector& xHat) { m_xHat = xHat; } + + /** + * Set an element of the initial state estimate x-hat. + * + * @param i Row of x-hat. + * @param value Value for element of x-hat. + */ + void SetXhat(int i, double value) { m_xHat(i) = value; } + + /** + * Resets the observer. + */ + void Reset() { m_xHat.setZero(); } + + /** + * Project the model into the future with a new control input u. + * + * @param u New control input from controller. + * @param dt Timestep for prediction. + */ + void Predict(const InputVector& u, units::second_t dt); + + /** + * Correct the state estimate x-hat using the measurements in y. + * + * @param u Same control input used in the last predict step. + * @param y Measurement vector. + */ + void Correct(const InputVector& u, const OutputVector& y); + + private: + LinearSystem* m_plant; + + /** + * The steady-state Kalman gain matrix. + */ + Matrixd m_K; + + /** + * The state estimate. + */ + StateVector m_xHat; +}; + +extern template class EXPORT_TEMPLATE_DECLARE(WPILIB_DLLEXPORT) + SteadyStateKalmanFilter<1, 1, 1>; +extern template class EXPORT_TEMPLATE_DECLARE(WPILIB_DLLEXPORT) + SteadyStateKalmanFilter<2, 1, 1>; + +} // namespace frc + +#include "SteadyStateKalmanFilter.inc" diff --git a/wpimath/src/main/native/include/frc/estimator/SteadyStateKalmanFilter.inc b/wpimath/src/main/native/include/frc/estimator/SteadyStateKalmanFilter.inc new file mode 100644 index 00000000000..1f2f2a2ff65 --- /dev/null +++ b/wpimath/src/main/native/include/frc/estimator/SteadyStateKalmanFilter.inc @@ -0,0 +1,89 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include +#include + +#include + +#include "frc/DARE.h" +#include "frc/StateSpaceUtil.h" +#include "frc/estimator/SteadyStateKalmanFilter.h" +#include "frc/fmt/Eigen.h" +#include "frc/system/Discretization.h" +#include "wpimath/MathShared.h" + +namespace frc { + +template +SteadyStateKalmanFilter::SteadyStateKalmanFilter( + LinearSystem& plant, + const StateArray& stateStdDevs, const OutputArray& measurementStdDevs, + units::second_t dt) { + m_plant = &plant; + + auto contQ = MakeCovMatrix(stateStdDevs); + auto contR = MakeCovMatrix(measurementStdDevs); + + Matrixd discA; + Matrixd discQ; + DiscretizeAQ(plant.A(), contQ, dt, &discA, &discQ); + + auto discR = DiscretizeR(contR, dt); + + const auto& C = plant.C(); + + if (!IsDetectable(discA, C)) { + std::string msg = fmt::format( + "The system passed to the Kalman filter is " + "unobservable!\n\nA =\n{}\nC =\n{}\n", + discA, C); + + wpi::math::MathSharedStore::ReportError(msg); + throw std::invalid_argument(msg); + } + + Matrixd P = + DARE(discA.transpose(), C.transpose(), discQ, discR); + + // S = CPCᵀ + R + Matrixd S = C * P * C.transpose() + discR; + + // We want to put K = PCᵀS⁻¹ into Ax = b form so we can solve it more + // efficiently. + // + // K = PCᵀS⁻¹ + // KS = PCᵀ + // (KS)ᵀ = (PCᵀ)ᵀ + // SᵀKᵀ = CPᵀ + // + // The solution of Ax = b can be found via x = A.solve(b). + // + // Kᵀ = Sᵀ.solve(CPᵀ) + // K = (Sᵀ.solve(CPᵀ))ᵀ + m_K = S.transpose().ldlt().solve(C * P.transpose()).transpose(); + + Reset(); +} + +template +void SteadyStateKalmanFilter::Predict( + const InputVector& u, units::second_t dt) { + m_xHat = m_plant->CalculateX(m_xHat, u, dt); +} + +template +void SteadyStateKalmanFilter::Correct( + const InputVector& u, const OutputVector& y) { + const auto& C = m_plant->C(); + const auto& D = m_plant->D(); + + // x̂ₖ₊₁⁺ = x̂ₖ₊₁⁻ + K(y − (Cx̂ₖ₊₁⁻ + Duₖ₊₁)) + m_xHat += m_K * (y - (C * m_xHat + D * u)); +} + +} // namespace frc diff --git a/wpimath/src/main/native/include/frc/estimator/UnscentedKalmanFilter.h b/wpimath/src/main/native/include/frc/estimator/UnscentedKalmanFilter.h index 9526f0cb489..df68e151606 100644 --- a/wpimath/src/main/native/include/frc/estimator/UnscentedKalmanFilter.h +++ b/wpimath/src/main/native/include/frc/estimator/UnscentedKalmanFilter.h @@ -39,9 +39,9 @@ namespace frc { * (SR-UKF). For more information about the SR-UKF, see * https://www.researchgate.net/publication/3908304. * - * @tparam States The number of states. - * @tparam Inputs The number of inputs. - * @tparam Outputs The number of outputs. + * @tparam States Number of states. + * @tparam Inputs Number of inputs. + * @tparam Outputs Number of outputs. */ template class UnscentedKalmanFilter { diff --git a/wpimath/src/main/native/include/frc/filter/Debouncer.h b/wpimath/src/main/native/include/frc/filter/Debouncer.h index a929f37358a..9ab3e0e1680 100644 --- a/wpimath/src/main/native/include/frc/filter/Debouncer.h +++ b/wpimath/src/main/native/include/frc/filter/Debouncer.h @@ -17,7 +17,17 @@ namespace frc { */ class WPILIB_DLLEXPORT Debouncer { public: - enum DebounceType { kRising, kFalling, kBoth }; + /** + * Type of debouncing to perform. + */ + enum DebounceType { + /// Rising edge. + kRising, + /// Falling edge. + kFalling, + /// Both rising and falling edges. + kBoth + }; /** * Creates a new Debouncer. diff --git a/wpimath/src/main/native/include/frc/filter/LinearFilter.h b/wpimath/src/main/native/include/frc/filter/LinearFilter.h index fc558dfd588..3f5462d5947 100644 --- a/wpimath/src/main/native/include/frc/filter/LinearFilter.h +++ b/wpimath/src/main/native/include/frc/filter/LinearFilter.h @@ -271,6 +271,74 @@ class LinearFilter { std::fill(m_outputs.begin(), m_outputs.end(), T{0.0}); } + /** + * Resets the filter state, initializing internal buffers to the provided + * values. + * + * These are the expected lengths of the buffers, depending on what type of + * linear filter used: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    TypeInput Buffer SizeOutput Buffer Size
    Unspecifiedsize of {@code ffGains}size of {@code fbGains}
    Single Pole IIR11
    High-Pass21
    Moving Average{@code taps}0
    Finite Differencesize of {@code stencil}0
    Backward Finite Difference{@code Samples}0
    + * + * @param inputBuffer Values to initialize input buffer. + * @param outputBuffer Values to initialize output buffer. + * @throws std::runtime_error if size of inputBuffer or outputBuffer does not + * match the size of ffGains and fbGains provided in the constructor. + */ + void Reset(std::span inputBuffer, std::span outputBuffer) { + // Clear buffers + Reset(); + + if (inputBuffer.size() != m_inputGains.size() || + outputBuffer.size() != m_outputGains.size()) { + throw std::runtime_error( + "Incorrect length of inputBuffer or outputBuffer"); + } + + for (size_t i = 0; i < inputBuffer.size(); ++i) { + m_inputs.push_front(inputBuffer[i]); + } + for (size_t i = 0; i < outputBuffer.size(); ++i) { + m_outputs.push_front(outputBuffer[i]); + } + } + /** * Calculates the next value of the filter. * @@ -302,6 +370,13 @@ class LinearFilter { return retVal; } + /** + * Returns the last value calculated by the LinearFilter. + * + * @return The last value. + */ + T LastValue() const { return m_outputs.front(); } + private: wpi::circular_buffer m_inputs; wpi::circular_buffer m_outputs; diff --git a/wpimath/src/main/native/include/frc/filter/MedianFilter.h b/wpimath/src/main/native/include/frc/filter/MedianFilter.h index 40422a6d24a..4c714fb547e 100644 --- a/wpimath/src/main/native/include/frc/filter/MedianFilter.h +++ b/wpimath/src/main/native/include/frc/filter/MedianFilter.h @@ -61,6 +61,13 @@ class MedianFilter { } } + /** + * Returns the last value calculated by the MedianFilter. + * + * @return The last value. + */ + T LastValue() const { return m_valueBuffer.front(); } + /** * Resets the filter, clearing the window of all elements. */ diff --git a/wpimath/src/main/native/include/frc/filter/SlewRateLimiter.h b/wpimath/src/main/native/include/frc/filter/SlewRateLimiter.h index 17d0d219782..f04aac4855a 100644 --- a/wpimath/src/main/native/include/frc/filter/SlewRateLimiter.h +++ b/wpimath/src/main/native/include/frc/filter/SlewRateLimiter.h @@ -6,7 +6,6 @@ #include -#include #include #include "units/time.h" @@ -47,7 +46,7 @@ class SlewRateLimiter { m_negativeRateLimit{negativeRateLimit}, m_prevVal{initialValue}, m_prevTime{ - units::microsecond_t(wpi::math::MathSharedStore::GetTimestamp())} {} + units::microsecond_t{wpi::math::MathSharedStore::GetTimestamp()}} {} /** * Creates a new SlewRateLimiter with the given positive rate limit and @@ -75,6 +74,13 @@ class SlewRateLimiter { return m_prevVal; } + /** + * Returns the value last calculated by the SlewRateLimiter. + * + * @return The last value. + */ + Unit_t LastValue() const { return m_prevVal; } + /** * Resets the slew rate limiter to the specified value; ignores the rate limit * when doing so. diff --git a/wpimath/src/main/native/include/frc/fmt/Eigen.h b/wpimath/src/main/native/include/frc/fmt/Eigen.h index 2438b9f1de6..4f608553c3f 100644 --- a/wpimath/src/main/native/include/frc/fmt/Eigen.h +++ b/wpimath/src/main/native/include/frc/fmt/Eigen.h @@ -11,18 +11,20 @@ #include /** - * Formatter for classes derived from Eigen::MatrixBase or + * Formatter for classes derived from Eigen::DenseBase or * Eigen::SparseCompressedBase. */ template - requires std::derived_from> || + requires std::derived_from> || std::derived_from> struct fmt::formatter { - constexpr auto parse(fmt::format_parse_context& ctx) { + template + constexpr auto parse(ParseContext& ctx) { return m_underlying.parse(ctx); } - auto format(const Derived& mat, fmt::format_context& ctx) const { + template + auto format(const Derived& mat, FmtContext& ctx) const { auto out = ctx.out(); for (int row = 0; row < mat.rows(); ++row) { diff --git a/wpimath/src/main/native/include/frc/geometry/Pose2d.h b/wpimath/src/main/native/include/frc/geometry/Pose2d.h index 970f7929614..65a146c3dd7 100644 --- a/wpimath/src/main/native/include/frc/geometry/Pose2d.h +++ b/wpimath/src/main/native/include/frc/geometry/Pose2d.h @@ -9,8 +9,6 @@ #include #include -#include -#include #include "frc/geometry/Rotation2d.h" #include "frc/geometry/Transform2d.h" @@ -215,38 +213,6 @@ void from_json(const wpi::json& json, Pose2d& pose); } // namespace frc -template <> -struct wpi::Struct { - static constexpr std::string_view kTypeString = "struct:Pose2d"; - static constexpr size_t kSize = wpi::Struct::kSize + - wpi::Struct::kSize; - static constexpr std::string_view kSchema = - "Translation2d translation;Rotation2d rotation"; - static frc::Pose2d Unpack(std::span data) { - return {wpi::UnpackStruct(data), - wpi::UnpackStruct(data)}; - } - static void Pack(std::span data, const frc::Pose2d& value) { - wpi::PackStruct<0>(data, value.Translation()); - wpi::PackStruct(data, value.Rotation()); - } - static void ForEachNested( - std::invocable auto fn) { - wpi::ForEachStructSchema(fn); - wpi::ForEachStructSchema(fn); - } - - private: - static constexpr size_t kRotationOff = wpi::Struct::kSize; -}; - -static_assert(wpi::HasNestedStruct); - -template <> -struct WPILIB_DLLEXPORT wpi::Protobuf { - static google::protobuf::Message* New(google::protobuf::Arena* arena); - static frc::Pose2d Unpack(const google::protobuf::Message& msg); - static void Pack(google::protobuf::Message* msg, const frc::Pose2d& value); -}; - +#include "frc/geometry/proto/Pose2dProto.h" +#include "frc/geometry/struct/Pose2dStruct.h" #include "frc/geometry/Pose2d.inc" diff --git a/wpimath/src/main/native/include/frc/geometry/Pose2d.inc b/wpimath/src/main/native/include/frc/geometry/Pose2d.inc index 2764d16cbf8..559a0034e80 100644 --- a/wpimath/src/main/native/include/frc/geometry/Pose2d.inc +++ b/wpimath/src/main/native/include/frc/geometry/Pose2d.inc @@ -13,11 +13,11 @@ namespace frc { constexpr Pose2d::Pose2d(Translation2d translation, Rotation2d rotation) - : m_translation(std::move(translation)), m_rotation(std::move(rotation)) {} + : m_translation{std::move(translation)}, m_rotation{std::move(rotation)} {} constexpr Pose2d::Pose2d(units::meter_t x, units::meter_t y, Rotation2d rotation) - : m_translation(x, y), m_rotation(std::move(rotation)) {} + : m_translation{x, y}, m_rotation{std::move(rotation)} {} constexpr Pose2d Pose2d::operator+(const Transform2d& other) const { return TransformBy(other); diff --git a/wpimath/src/main/native/include/frc/geometry/Pose3d.h b/wpimath/src/main/native/include/frc/geometry/Pose3d.h index b5a0e031ba8..526dced399d 100644 --- a/wpimath/src/main/native/include/frc/geometry/Pose3d.h +++ b/wpimath/src/main/native/include/frc/geometry/Pose3d.h @@ -6,8 +6,6 @@ #include #include -#include -#include #include "frc/geometry/Pose2d.h" #include "frc/geometry/Rotation3d.h" @@ -217,36 +215,5 @@ void from_json(const wpi::json& json, Pose3d& pose); } // namespace frc -template <> -struct wpi::Struct { - static constexpr std::string_view kTypeString = "struct:Pose3d"; - static constexpr size_t kSize = wpi::Struct::kSize + - wpi::Struct::kSize; - static constexpr std::string_view kSchema = - "Translation3d translation;Rotation3d rotation"; - static frc::Pose3d Unpack(std::span data) { - return {wpi::UnpackStruct(data), - wpi::UnpackStruct(data)}; - } - static void Pack(std::span data, const frc::Pose3d& value) { - wpi::PackStruct<0>(data, value.Translation()); - wpi::PackStruct(data, value.Rotation()); - } - static void ForEachNested( - std::invocable auto fn) { - wpi::ForEachStructSchema(fn); - wpi::ForEachStructSchema(fn); - } - - private: - static constexpr size_t kRotationOff = wpi::Struct::kSize; -}; - -static_assert(wpi::HasNestedStruct); - -template <> -struct WPILIB_DLLEXPORT wpi::Protobuf { - static google::protobuf::Message* New(google::protobuf::Arena* arena); - static frc::Pose3d Unpack(const google::protobuf::Message& msg); - static void Pack(google::protobuf::Message* msg, const frc::Pose3d& value); -}; +#include "frc/geometry/proto/Pose3dProto.h" +#include "frc/geometry/struct/Pose3dStruct.h" diff --git a/wpimath/src/main/native/include/frc/geometry/Quaternion.h b/wpimath/src/main/native/include/frc/geometry/Quaternion.h index 63a3af2784d..4fe694cf25e 100644 --- a/wpimath/src/main/native/include/frc/geometry/Quaternion.h +++ b/wpimath/src/main/native/include/frc/geometry/Quaternion.h @@ -7,11 +7,12 @@ #include #include #include -#include -#include namespace frc { +/** + * Represents a quaternion. + */ class WPILIB_DLLEXPORT Quaternion { public: /** @@ -190,31 +191,5 @@ void from_json(const wpi::json& json, Quaternion& quaternion); } // namespace frc -template <> -struct wpi::Struct { - static constexpr std::string_view kTypeString = "struct:Quaternion"; - static constexpr size_t kSize = 32; - static constexpr std::string_view kSchema = - "double w;double x;double y;double z"; - static frc::Quaternion Unpack(std::span data) { - return {wpi::UnpackStruct(data), - wpi::UnpackStruct(data), - wpi::UnpackStruct(data), - wpi::UnpackStruct(data)}; - } - static void Pack(std::span data, const frc::Quaternion& value) { - wpi::PackStruct<0>(data, value.W()); - wpi::PackStruct<8>(data, value.X()); - wpi::PackStruct<16>(data, value.Y()); - wpi::PackStruct<24>(data, value.Z()); - } -}; - -template <> -struct WPILIB_DLLEXPORT wpi::Protobuf { - static constexpr std::string_view kTypeString = "proto:Quaternion"; - static google::protobuf::Message* New(google::protobuf::Arena* arena); - static frc::Quaternion Unpack(const google::protobuf::Message& msg); - static void Pack(google::protobuf::Message* msg, - const frc::Quaternion& value); -}; +#include "frc/geometry/proto/QuaternionProto.h" +#include "frc/geometry/struct/QuaternionStruct.h" diff --git a/wpimath/src/main/native/include/frc/geometry/Rotation2d.h b/wpimath/src/main/native/include/frc/geometry/Rotation2d.h index 96041a49799..6e9cd8e2a88 100644 --- a/wpimath/src/main/native/include/frc/geometry/Rotation2d.h +++ b/wpimath/src/main/native/include/frc/geometry/Rotation2d.h @@ -6,8 +6,6 @@ #include #include -#include -#include #include "units/angle.h" @@ -30,18 +28,11 @@ class WPILIB_DLLEXPORT Rotation2d { constexpr Rotation2d() = default; /** - * Constructs a Rotation2d with the given radian value. + * Constructs a Rotation2d with the given angle. * - * @param value The value of the angle in radians. + * @param value The value of the angle. */ - constexpr Rotation2d(units::radian_t value); // NOLINT - - /** - * Constructs a Rotation2d with the given degree value. - * - * @param value The value of the angle in degrees. - */ - constexpr Rotation2d(units::degree_t value); // NOLINT + constexpr Rotation2d(units::angle_unit auto value); // NOLINT /** * Constructs a Rotation2d with the given x and y (cosine and sine) @@ -178,25 +169,6 @@ void from_json(const wpi::json& json, Rotation2d& rotation); } // namespace frc -template <> -struct wpi::Struct { - static constexpr std::string_view kTypeString = "struct:Rotation2d"; - static constexpr size_t kSize = 8; - static constexpr std::string_view kSchema = "double value"; - static frc::Rotation2d Unpack(std::span data) { - return units::radian_t{wpi::UnpackStruct(data)}; - } - static void Pack(std::span data, const frc::Rotation2d& value) { - wpi::PackStruct(data, value.Radians().value()); - } -}; - -template <> -struct WPILIB_DLLEXPORT wpi::Protobuf { - static google::protobuf::Message* New(google::protobuf::Arena* arena); - static frc::Rotation2d Unpack(const google::protobuf::Message& msg); - static void Pack(google::protobuf::Message* msg, - const frc::Rotation2d& value); -}; - +#include "frc/geometry/proto/Rotation2dProto.h" +#include "frc/geometry/struct/Rotation2dStruct.h" #include "frc/geometry/Rotation2d.inc" diff --git a/wpimath/src/main/native/include/frc/geometry/Rotation2d.inc b/wpimath/src/main/native/include/frc/geometry/Rotation2d.inc index dbe9e3596e9..104b66b1605 100644 --- a/wpimath/src/main/native/include/frc/geometry/Rotation2d.inc +++ b/wpimath/src/main/native/include/frc/geometry/Rotation2d.inc @@ -4,27 +4,20 @@ #pragma once -#include +#include #include "frc/geometry/Rotation2d.h" -#include "gcem.hpp" #include "units/angle.h" namespace frc { -constexpr Rotation2d::Rotation2d(units::radian_t value) - : m_value(value), - m_cos(std::is_constant_evaluated() ? gcem::cos(value.to()) - : std::cos(value.to())), - m_sin(std::is_constant_evaluated() ? gcem::sin(value.to()) - : std::sin(value.to())) {} - -constexpr Rotation2d::Rotation2d(units::degree_t value) - : Rotation2d(units::radian_t{value}) {} +constexpr Rotation2d::Rotation2d(units::angle_unit auto value) + : m_value{value}, + m_cos{gcem::cos(value.template convert().value())}, + m_sin{gcem::sin(value.template convert().value())} {} constexpr Rotation2d::Rotation2d(double x, double y) { - double magnitude = - std::is_constant_evaluated() ? gcem::hypot(x, y) : std::hypot(x, y); + double magnitude = gcem::hypot(x, y); if (magnitude > 1e-6) { m_sin = y / magnitude; m_cos = x / magnitude; @@ -32,9 +25,7 @@ constexpr Rotation2d::Rotation2d(double x, double y) { m_sin = 0.0; m_cos = 1.0; } - m_value = - units::radian_t{std::is_constant_evaluated() ? gcem::atan2(m_sin, m_cos) - : std::atan2(m_sin, m_cos)}; + m_value = units::radian_t{gcem::atan2(m_sin, m_cos)}; } constexpr Rotation2d Rotation2d::operator-() const { @@ -42,7 +33,7 @@ constexpr Rotation2d Rotation2d::operator-() const { } constexpr Rotation2d Rotation2d::operator*(double scalar) const { - return Rotation2d(m_value * scalar); + return Rotation2d{m_value * scalar}; } constexpr Rotation2d Rotation2d::operator+(const Rotation2d& other) const { @@ -58,9 +49,7 @@ constexpr Rotation2d Rotation2d::operator/(double scalar) const { } constexpr bool Rotation2d::operator==(const Rotation2d& other) const { - return (std::is_constant_evaluated() - ? gcem::hypot(Cos() - other.Cos(), Sin() - other.Sin()) - : std::hypot(Cos() - other.Cos(), Sin() - other.Sin())) < 1E-9; + return gcem::hypot(Cos() - other.Cos(), Sin() - other.Sin()) < 1E-9; } constexpr Rotation2d Rotation2d::RotateBy(const Rotation2d& other) const { diff --git a/wpimath/src/main/native/include/frc/geometry/Rotation3d.h b/wpimath/src/main/native/include/frc/geometry/Rotation3d.h index 6d04715316e..bc01f2b8ee2 100644 --- a/wpimath/src/main/native/include/frc/geometry/Rotation3d.h +++ b/wpimath/src/main/native/include/frc/geometry/Rotation3d.h @@ -7,8 +7,6 @@ #include #include #include -#include -#include #include "frc/geometry/Quaternion.h" #include "frc/geometry/Rotation2d.h" @@ -22,7 +20,7 @@ namespace frc { class WPILIB_DLLEXPORT Rotation3d { public: /** - * Constructs a Rotation3d with a default angle of 0 degrees. + * Constructs a Rotation3d representing no rotation. */ Rotation3d() = default; @@ -197,30 +195,5 @@ void from_json(const wpi::json& json, Rotation3d& rotation); } // namespace frc -template <> -struct wpi::Struct { - static constexpr std::string_view kTypeString = "struct:Rotation3d"; - static constexpr size_t kSize = wpi::Struct::kSize; - static constexpr std::string_view kSchema = "Quaternion q"; - static frc::Rotation3d Unpack(std::span data) { - return frc::Rotation3d{wpi::UnpackStruct(data)}; - } - static void Pack(std::span data, - const frc::Rotation3d& value) { - wpi::PackStruct<0>(data, value.GetQuaternion()); - } - static void ForEachNested( - std::invocable auto fn) { - wpi::ForEachStructSchema(fn); - } -}; - -static_assert(wpi::HasNestedStruct); - -template <> -struct WPILIB_DLLEXPORT wpi::Protobuf { - static google::protobuf::Message* New(google::protobuf::Arena* arena); - static frc::Rotation3d Unpack(const google::protobuf::Message& msg); - static void Pack(google::protobuf::Message* msg, - const frc::Rotation3d& value); -}; +#include "frc/geometry/proto/Rotation3dProto.h" +#include "frc/geometry/struct/Rotation3dStruct.h" diff --git a/wpimath/src/main/native/include/frc/geometry/Transform2d.h b/wpimath/src/main/native/include/frc/geometry/Transform2d.h index 593dce03ab5..dccc0e1eeec 100644 --- a/wpimath/src/main/native/include/frc/geometry/Transform2d.h +++ b/wpimath/src/main/native/include/frc/geometry/Transform2d.h @@ -5,8 +5,6 @@ #pragma once #include -#include -#include #include "frc/geometry/Translation2d.h" @@ -126,40 +124,6 @@ class WPILIB_DLLEXPORT Transform2d { }; } // namespace frc -template <> -struct wpi::Struct { - static constexpr std::string_view kTypeString = "struct:Transform2d"; - static constexpr size_t kSize = wpi::Struct::kSize + - wpi::Struct::kSize; - static constexpr std::string_view kSchema = - "Translation2d translation;Rotation2d rotation"; - static frc::Transform2d Unpack(std::span data) { - return {wpi::UnpackStruct(data), - wpi::UnpackStruct(data)}; - } - static void Pack(std::span data, - const frc::Transform2d& value) { - wpi::PackStruct<0>(data, value.Translation()); - wpi::PackStruct(data, value.Rotation()); - } - static void ForEachNested( - std::invocable auto fn) { - wpi::ForEachStructSchema(fn); - wpi::ForEachStructSchema(fn); - } - - private: - static constexpr size_t kRotationOff = wpi::Struct::kSize; -}; - -static_assert(wpi::HasNestedStruct); - -template <> -struct WPILIB_DLLEXPORT wpi::Protobuf { - static google::protobuf::Message* New(google::protobuf::Arena* arena); - static frc::Transform2d Unpack(const google::protobuf::Message& msg); - static void Pack(google::protobuf::Message* msg, - const frc::Transform2d& value); -}; - +#include "frc/geometry/proto/Transform2dProto.h" +#include "frc/geometry/struct/Transform2dStruct.h" #include "frc/geometry/Transform2d.inc" diff --git a/wpimath/src/main/native/include/frc/geometry/Transform2d.inc b/wpimath/src/main/native/include/frc/geometry/Transform2d.inc index 862b8d5c600..cc925148d45 100644 --- a/wpimath/src/main/native/include/frc/geometry/Transform2d.inc +++ b/wpimath/src/main/native/include/frc/geometry/Transform2d.inc @@ -14,11 +14,11 @@ namespace frc { constexpr Transform2d::Transform2d(Translation2d translation, Rotation2d rotation) - : m_translation(std::move(translation)), m_rotation(std::move(rotation)) {} + : m_translation{std::move(translation)}, m_rotation{std::move(rotation)} {} constexpr Transform2d::Transform2d(units::meter_t x, units::meter_t y, Rotation2d rotation) - : m_translation(x, y), m_rotation(std::move(rotation)) {} + : m_translation{x, y}, m_rotation{std::move(rotation)} {} constexpr Transform2d Transform2d::Inverse() const { // We are rotating the difference between the translations diff --git a/wpimath/src/main/native/include/frc/geometry/Transform3d.h b/wpimath/src/main/native/include/frc/geometry/Transform3d.h index d5af97d4731..94ecfe37eda 100644 --- a/wpimath/src/main/native/include/frc/geometry/Transform3d.h +++ b/wpimath/src/main/native/include/frc/geometry/Transform3d.h @@ -5,8 +5,6 @@ #pragma once #include -#include -#include #include "frc/geometry/Translation3d.h" @@ -132,38 +130,5 @@ class WPILIB_DLLEXPORT Transform3d { }; } // namespace frc -template <> -struct wpi::Struct { - static constexpr std::string_view kTypeString = "struct:Transform3d"; - static constexpr size_t kSize = wpi::Struct::kSize + - wpi::Struct::kSize; - static constexpr std::string_view kSchema = - "Translation3d translation;Rotation3d rotation"; - static frc::Transform3d Unpack(std::span data) { - return {wpi::UnpackStruct(data), - wpi::UnpackStruct(data)}; - } - static void Pack(std::span data, - const frc::Transform3d& value) { - wpi::PackStruct<0>(data, value.Translation()); - wpi::PackStruct(data, value.Rotation()); - } - static void ForEachNested( - std::invocable auto fn) { - wpi::ForEachStructSchema(fn); - wpi::ForEachStructSchema(fn); - } - - private: - static constexpr size_t kRotationOff = wpi::Struct::kSize; -}; - -static_assert(wpi::HasNestedStruct); - -template <> -struct WPILIB_DLLEXPORT wpi::Protobuf { - static google::protobuf::Message* New(google::protobuf::Arena* arena); - static frc::Transform3d Unpack(const google::protobuf::Message& msg); - static void Pack(google::protobuf::Message* msg, - const frc::Transform3d& value); -}; +#include "frc/geometry/proto/Transform3dProto.h" +#include "frc/geometry/struct/Transform3dStruct.h" diff --git a/wpimath/src/main/native/include/frc/geometry/Translation2d.h b/wpimath/src/main/native/include/frc/geometry/Translation2d.h index 1568586163f..9d9a77c3bf2 100644 --- a/wpimath/src/main/native/include/frc/geometry/Translation2d.h +++ b/wpimath/src/main/native/include/frc/geometry/Translation2d.h @@ -7,10 +7,9 @@ #include #include +#include #include #include -#include -#include #include "frc/geometry/Rotation2d.h" #include "units/length.h" @@ -50,6 +49,14 @@ class WPILIB_DLLEXPORT Translation2d { */ constexpr Translation2d(units::meter_t distance, const Rotation2d& angle); + /** + * Constructs a Translation2d from the provided translation vector's X and Y + * components. The values are assumed to be in meters. + * + * @param vector The translation vector to represent. + */ + explicit Translation2d(const Eigen::Vector2d& vector); + /** * Calculates the distance between two translations in 2D space. * @@ -75,6 +82,13 @@ class WPILIB_DLLEXPORT Translation2d { */ constexpr units::meter_t Y() const { return m_y; } + /** + * Returns a vector representation of this translation. + * + * @return A Vector representation of this translation. + */ + constexpr Eigen::Vector2d ToVector() const; + /** * Returns the norm, or distance from the origin to the translation. * @@ -200,28 +214,6 @@ void from_json(const wpi::json& json, Translation2d& state); } // namespace frc -template <> -struct wpi::Struct { - static constexpr std::string_view kTypeString = "struct:Translation2d"; - static constexpr size_t kSize = 16; - static constexpr std::string_view kSchema = "double x;double y"; - static frc::Translation2d Unpack(std::span data) { - return {units::meter_t{wpi::UnpackStruct(data)}, - units::meter_t{wpi::UnpackStruct(data)}}; - } - static void Pack(std::span data, - const frc::Translation2d& value) { - wpi::PackStruct<0>(data, value.X().value()); - wpi::PackStruct<8>(data, value.Y().value()); - } -}; - -template <> -struct WPILIB_DLLEXPORT wpi::Protobuf { - static google::protobuf::Message* New(google::protobuf::Arena* arena); - static frc::Translation2d Unpack(const google::protobuf::Message& msg); - static void Pack(google::protobuf::Message* msg, - const frc::Translation2d& value); -}; - +#include "frc/geometry/proto/Translation2dProto.h" +#include "frc/geometry/struct/Translation2dStruct.h" #include "frc/geometry/Translation2d.inc" diff --git a/wpimath/src/main/native/include/frc/geometry/Translation2d.inc b/wpimath/src/main/native/include/frc/geometry/Translation2d.inc index 3be897fad6d..6b291e1f74c 100644 --- a/wpimath/src/main/native/include/frc/geometry/Translation2d.inc +++ b/wpimath/src/main/native/include/frc/geometry/Translation2d.inc @@ -10,11 +10,15 @@ namespace frc { constexpr Translation2d::Translation2d(units::meter_t x, units::meter_t y) - : m_x(x), m_y(y) {} + : m_x{x}, m_y{y} {} constexpr Translation2d::Translation2d(units::meter_t distance, const Rotation2d& angle) - : m_x(distance * angle.Cos()), m_y(distance * angle.Sin()) {} + : m_x{distance * angle.Cos()}, m_y{distance * angle.Sin()} {} + +constexpr Eigen::Vector2d Translation2d::ToVector() const { + return Eigen::Vector2d{{m_x.value(), m_y.value()}}; +} constexpr Rotation2d Translation2d::Angle() const { return Rotation2d{m_x.value(), m_y.value()}; diff --git a/wpimath/src/main/native/include/frc/geometry/Translation3d.h b/wpimath/src/main/native/include/frc/geometry/Translation3d.h index 47ba1f6bad5..b83b661fd98 100644 --- a/wpimath/src/main/native/include/frc/geometry/Translation3d.h +++ b/wpimath/src/main/native/include/frc/geometry/Translation3d.h @@ -4,10 +4,9 @@ #pragma once +#include #include #include -#include -#include #include "frc/geometry/Rotation3d.h" #include "frc/geometry/Translation2d.h" @@ -49,6 +48,14 @@ class WPILIB_DLLEXPORT Translation3d { */ Translation3d(units::meter_t distance, const Rotation3d& angle); + /** + * Constructs a Translation3d from the provided translation vector's X, Y, and + * Z components. The values are assumed to be in meters. + * + * @param vector The translation vector to represent. + */ + explicit Translation3d(const Eigen::Vector3d& vector); + /** * Calculates the distance between two translations in 3D space. * @@ -82,6 +89,13 @@ class WPILIB_DLLEXPORT Translation3d { */ constexpr units::meter_t Z() const { return m_z; } + /** + * Returns a vector representation of this translation. + * + * @return A Vector representation of this translation. + */ + constexpr Eigen::Vector3d ToVector() const; + /** * Returns the norm, or distance from the origin to the translation. * @@ -185,30 +199,6 @@ void from_json(const wpi::json& json, Translation3d& state); } // namespace frc -template <> -struct wpi::Struct { - static constexpr std::string_view kTypeString = "struct:Translation3d"; - static constexpr size_t kSize = 24; - static constexpr std::string_view kSchema = "double x;double y;double z"; - static frc::Translation3d Unpack(std::span data) { - return {units::meter_t{wpi::UnpackStruct(data)}, - units::meter_t{wpi::UnpackStruct(data)}, - units::meter_t{wpi::UnpackStruct(data)}}; - } - static void Pack(std::span data, - const frc::Translation3d& value) { - wpi::PackStruct<0>(data, value.X().value()); - wpi::PackStruct<8>(data, value.Y().value()); - wpi::PackStruct<16>(data, value.Z().value()); - } -}; - -template <> -struct WPILIB_DLLEXPORT wpi::Protobuf { - static google::protobuf::Message* New(google::protobuf::Arena* arena); - static frc::Translation3d Unpack(const google::protobuf::Message& msg); - static void Pack(google::protobuf::Message* msg, - const frc::Translation3d& value); -}; - +#include "frc/geometry/proto/Translation3dProto.h" +#include "frc/geometry/struct/Translation3dStruct.h" #include "frc/geometry/Translation3d.inc" diff --git a/wpimath/src/main/native/include/frc/geometry/Translation3d.inc b/wpimath/src/main/native/include/frc/geometry/Translation3d.inc index 8ab6e94c609..19268e6cee2 100644 --- a/wpimath/src/main/native/include/frc/geometry/Translation3d.inc +++ b/wpimath/src/main/native/include/frc/geometry/Translation3d.inc @@ -13,12 +13,16 @@ namespace frc { constexpr Translation3d::Translation3d(units::meter_t x, units::meter_t y, units::meter_t z) - : m_x(x), m_y(y), m_z(z) {} + : m_x{x}, m_y{y}, m_z{z} {} constexpr Translation2d Translation3d::ToTranslation2d() const { return Translation2d{m_x, m_y}; } +constexpr Eigen::Vector3d Translation3d::ToVector() const { + return Eigen::Vector3d{{m_x.value(), m_y.value(), m_z.value()}}; +} + constexpr Translation3d Translation3d::operator+( const Translation3d& other) const { return {X() + other.X(), Y() + other.Y(), Z() + other.Z()}; diff --git a/wpimath/src/main/native/include/frc/geometry/Twist2d.h b/wpimath/src/main/native/include/frc/geometry/Twist2d.h index 257f1b65e78..d13cc4ec80b 100644 --- a/wpimath/src/main/native/include/frc/geometry/Twist2d.h +++ b/wpimath/src/main/native/include/frc/geometry/Twist2d.h @@ -5,8 +5,6 @@ #pragma once #include -#include -#include #include "units/angle.h" #include "units/length.h" @@ -60,27 +58,5 @@ struct WPILIB_DLLEXPORT Twist2d { }; } // namespace frc -template <> -struct wpi::Struct { - static constexpr std::string_view kTypeString = "struct:Twist2d"; - static constexpr size_t kSize = 24; - static constexpr std::string_view kSchema = - "double dx;double dy;double dtheta"; - static frc::Twist2d Unpack(std::span data) { - return {units::meter_t{wpi::UnpackStruct(data)}, - units::meter_t{wpi::UnpackStruct(data)}, - units::radian_t{wpi::UnpackStruct(data)}}; - } - static void Pack(std::span data, const frc::Twist2d& value) { - wpi::PackStruct<0>(data, value.dx.value()); - wpi::PackStruct<8>(data, value.dy.value()); - wpi::PackStruct<16>(data, value.dtheta.value()); - } -}; - -template <> -struct WPILIB_DLLEXPORT wpi::Protobuf { - static google::protobuf::Message* New(google::protobuf::Arena* arena); - static frc::Twist2d Unpack(const google::protobuf::Message& msg); - static void Pack(google::protobuf::Message* msg, const frc::Twist2d& value); -}; +#include "frc/geometry/proto/Twist2dProto.h" +#include "frc/geometry/struct/Twist2dStruct.h" diff --git a/wpimath/src/main/native/include/frc/geometry/Twist3d.h b/wpimath/src/main/native/include/frc/geometry/Twist3d.h index 4d902dfcbba..3262367dc0f 100644 --- a/wpimath/src/main/native/include/frc/geometry/Twist3d.h +++ b/wpimath/src/main/native/include/frc/geometry/Twist3d.h @@ -5,8 +5,6 @@ #pragma once #include -#include -#include #include "frc/geometry/Rotation3d.h" #include "units/angle.h" @@ -80,34 +78,5 @@ struct WPILIB_DLLEXPORT Twist3d { }; } // namespace frc -template <> -struct wpi::Struct { - static constexpr std::string_view kTypeString = "struct:Twist3d"; - static constexpr size_t kSize = 48; - static constexpr std::string_view kSchema = - "double dx;double dy;double dz;double rx;double ry;double rz"; - static frc::Twist3d Unpack(std::span data) { - return {units::meter_t{wpi::UnpackStruct(data)}, - units::meter_t{wpi::UnpackStruct(data)}, - units::meter_t{wpi::UnpackStruct(data)}, - units::radian_t{wpi::UnpackStruct(data)}, - units::radian_t{wpi::UnpackStruct(data)}, - units::radian_t{wpi::UnpackStruct(data)}}; - } - static void Pack(std::span data, const frc::Twist3d& value) { - wpi::PackStruct<0>(data, value.dx.value()); - wpi::PackStruct<8>(data, value.dy.value()); - wpi::PackStruct<16>(data, value.dz.value()); - wpi::PackStruct<24>(data, value.rx.value()); - wpi::PackStruct<32>(data, value.ry.value()); - wpi::PackStruct<40>(data, value.rz.value()); - } -}; - -template <> -struct WPILIB_DLLEXPORT wpi::Protobuf { - static constexpr std::string_view kTypeString = "proto:Twist3d"; - static google::protobuf::Message* New(google::protobuf::Arena* arena); - static frc::Twist3d Unpack(const google::protobuf::Message& msg); - static void Pack(google::protobuf::Message* msg, const frc::Twist3d& value); -}; +#include "frc/geometry/proto/Twist3dProto.h" +#include "frc/geometry/struct/Twist3dStruct.h" diff --git a/wpimath/src/main/native/include/frc/geometry/proto/Pose2dProto.h b/wpimath/src/main/native/include/frc/geometry/proto/Pose2dProto.h new file mode 100644 index 00000000000..9934b4ae83d --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/proto/Pose2dProto.h @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Pose2d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Pose2d Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, const frc::Pose2d& value); +}; diff --git a/wpimath/src/main/native/include/frc/geometry/proto/Pose3dProto.h b/wpimath/src/main/native/include/frc/geometry/proto/Pose3dProto.h new file mode 100644 index 00000000000..9941568d258 --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/proto/Pose3dProto.h @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Pose3d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Pose3d Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, const frc::Pose3d& value); +}; diff --git a/wpimath/src/main/native/include/frc/geometry/proto/QuaternionProto.h b/wpimath/src/main/native/include/frc/geometry/proto/QuaternionProto.h new file mode 100644 index 00000000000..77f371d67e7 --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/proto/QuaternionProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Quaternion.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Quaternion Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::Quaternion& value); +}; diff --git a/wpimath/src/main/native/include/frc/geometry/proto/Rotation2dProto.h b/wpimath/src/main/native/include/frc/geometry/proto/Rotation2dProto.h new file mode 100644 index 00000000000..33c348e6fc3 --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/proto/Rotation2dProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Rotation2d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Rotation2d Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::Rotation2d& value); +}; diff --git a/wpimath/src/main/native/include/frc/geometry/proto/Rotation3dProto.h b/wpimath/src/main/native/include/frc/geometry/proto/Rotation3dProto.h new file mode 100644 index 00000000000..f6f5662357a --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/proto/Rotation3dProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Rotation3d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Rotation3d Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::Rotation3d& value); +}; diff --git a/wpimath/src/main/native/include/frc/geometry/proto/Transform2dProto.h b/wpimath/src/main/native/include/frc/geometry/proto/Transform2dProto.h new file mode 100644 index 00000000000..5ff19bd2268 --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/proto/Transform2dProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Transform2d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Transform2d Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::Transform2d& value); +}; diff --git a/wpimath/src/main/native/include/frc/geometry/proto/Transform3dProto.h b/wpimath/src/main/native/include/frc/geometry/proto/Transform3dProto.h new file mode 100644 index 00000000000..d27fb9a0b86 --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/proto/Transform3dProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Transform3d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Transform3d Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::Transform3d& value); +}; diff --git a/wpimath/src/main/native/include/frc/geometry/proto/Translation2dProto.h b/wpimath/src/main/native/include/frc/geometry/proto/Translation2dProto.h new file mode 100644 index 00000000000..6516fc8d88a --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/proto/Translation2dProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Translation2d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Translation2d Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::Translation2d& value); +}; diff --git a/wpimath/src/main/native/include/frc/geometry/proto/Translation3dProto.h b/wpimath/src/main/native/include/frc/geometry/proto/Translation3dProto.h new file mode 100644 index 00000000000..2d317fc5afb --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/proto/Translation3dProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Translation3d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Translation3d Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::Translation3d& value); +}; diff --git a/wpimath/src/main/native/include/frc/geometry/proto/Twist2dProto.h b/wpimath/src/main/native/include/frc/geometry/proto/Twist2dProto.h new file mode 100644 index 00000000000..328798e14cc --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/proto/Twist2dProto.h @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Twist2d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Twist2d Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, const frc::Twist2d& value); +}; diff --git a/wpimath/src/main/native/include/frc/geometry/proto/Twist3dProto.h b/wpimath/src/main/native/include/frc/geometry/proto/Twist3dProto.h new file mode 100644 index 00000000000..24f496935ed --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/proto/Twist3dProto.h @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Twist3d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Twist3d Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, const frc::Twist3d& value); +}; diff --git a/wpimath/src/main/native/include/frc/geometry/struct/Pose2dStruct.h b/wpimath/src/main/native/include/frc/geometry/struct/Pose2dStruct.h new file mode 100644 index 00000000000..66e3295f918 --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/struct/Pose2dStruct.h @@ -0,0 +1,33 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Pose2d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { return "struct:Pose2d"; } + static constexpr size_t GetSize() { + return wpi::GetStructSize() + + wpi::GetStructSize(); + } + static constexpr std::string_view GetSchema() { + return "Translation2d translation;Rotation2d rotation"; + } + + static frc::Pose2d Unpack(std::span data); + static void Pack(std::span data, const frc::Pose2d& value); + static void ForEachNested( + std::invocable auto fn) { + wpi::ForEachStructSchema(fn); + wpi::ForEachStructSchema(fn); + } +}; + +static_assert(wpi::StructSerializable); +static_assert(wpi::HasNestedStruct); diff --git a/wpimath/src/main/native/include/frc/geometry/struct/Pose3dStruct.h b/wpimath/src/main/native/include/frc/geometry/struct/Pose3dStruct.h new file mode 100644 index 00000000000..f47ffec964c --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/struct/Pose3dStruct.h @@ -0,0 +1,33 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Pose3d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { return "struct:Pose3d"; } + static constexpr size_t GetSize() { + return wpi::GetStructSize() + + wpi::GetStructSize(); + } + static constexpr std::string_view GetSchema() { + return "Translation3d translation;Rotation3d rotation"; + } + + static frc::Pose3d Unpack(std::span data); + static void Pack(std::span data, const frc::Pose3d& value); + static void ForEachNested( + std::invocable auto fn) { + wpi::ForEachStructSchema(fn); + wpi::ForEachStructSchema(fn); + } +}; + +static_assert(wpi::StructSerializable); +static_assert(wpi::HasNestedStruct); diff --git a/wpimath/src/main/native/include/frc/geometry/struct/QuaternionStruct.h b/wpimath/src/main/native/include/frc/geometry/struct/QuaternionStruct.h new file mode 100644 index 00000000000..80420c0774d --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/struct/QuaternionStruct.h @@ -0,0 +1,26 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Quaternion.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:Quaternion"; + } + static constexpr size_t GetSize() { return 32; } + static constexpr std::string_view GetSchema() { + return "double w;double x;double y;double z"; + } + + static frc::Quaternion Unpack(std::span data); + static void Pack(std::span data, const frc::Quaternion& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/geometry/struct/Rotation2dStruct.h b/wpimath/src/main/native/include/frc/geometry/struct/Rotation2dStruct.h new file mode 100644 index 00000000000..85b6ae51782 --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/struct/Rotation2dStruct.h @@ -0,0 +1,24 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Rotation2d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:Rotation2d"; + } + static constexpr size_t GetSize() { return 8; } + static constexpr std::string_view GetSchema() { return "double value"; } + + static frc::Rotation2d Unpack(std::span data); + static void Pack(std::span data, const frc::Rotation2d& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/geometry/struct/Rotation3dStruct.h b/wpimath/src/main/native/include/frc/geometry/struct/Rotation3dStruct.h new file mode 100644 index 00000000000..e94b75ee4be --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/struct/Rotation3dStruct.h @@ -0,0 +1,31 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Rotation3d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:Rotation3d"; + } + static constexpr size_t GetSize() { + return wpi::GetStructSize(); + } + static constexpr std::string_view GetSchema() { return "Quaternion q"; } + + static frc::Rotation3d Unpack(std::span data); + static void Pack(std::span data, const frc::Rotation3d& value); + static void ForEachNested( + std::invocable auto fn) { + wpi::ForEachStructSchema(fn); + } +}; + +static_assert(wpi::StructSerializable); +static_assert(wpi::HasNestedStruct); diff --git a/wpimath/src/main/native/include/frc/geometry/struct/Transform2dStruct.h b/wpimath/src/main/native/include/frc/geometry/struct/Transform2dStruct.h new file mode 100644 index 00000000000..28ef463ab14 --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/struct/Transform2dStruct.h @@ -0,0 +1,35 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Transform2d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:Transform2d"; + } + static constexpr size_t GetSize() { + return wpi::GetStructSize() + + wpi::GetStructSize(); + } + static constexpr std::string_view GetSchema() { + return "Translation2d translation;Rotation2d rotation"; + } + + static frc::Transform2d Unpack(std::span data); + static void Pack(std::span data, const frc::Transform2d& value); + static void ForEachNested( + std::invocable auto fn) { + wpi::ForEachStructSchema(fn); + wpi::ForEachStructSchema(fn); + } +}; + +static_assert(wpi::StructSerializable); +static_assert(wpi::HasNestedStruct); diff --git a/wpimath/src/main/native/include/frc/geometry/struct/Transform3dStruct.h b/wpimath/src/main/native/include/frc/geometry/struct/Transform3dStruct.h new file mode 100644 index 00000000000..e4e88bcf498 --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/struct/Transform3dStruct.h @@ -0,0 +1,35 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Transform3d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:Transform3d"; + } + static constexpr size_t GetSize() { + return wpi::GetStructSize() + + wpi::GetStructSize(); + } + static constexpr std::string_view GetSchema() { + return "Translation3d translation;Rotation3d rotation"; + } + + static frc::Transform3d Unpack(std::span data); + static void Pack(std::span data, const frc::Transform3d& value); + static void ForEachNested( + std::invocable auto fn) { + wpi::ForEachStructSchema(fn); + wpi::ForEachStructSchema(fn); + } +}; + +static_assert(wpi::StructSerializable); +static_assert(wpi::HasNestedStruct); diff --git a/wpimath/src/main/native/include/frc/geometry/struct/Translation2dStruct.h b/wpimath/src/main/native/include/frc/geometry/struct/Translation2dStruct.h new file mode 100644 index 00000000000..df12760f855 --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/struct/Translation2dStruct.h @@ -0,0 +1,24 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Translation2d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:Translation2d"; + } + static constexpr size_t GetSize() { return 16; } + static constexpr std::string_view GetSchema() { return "double x;double y"; } + + static frc::Translation2d Unpack(std::span data); + static void Pack(std::span data, const frc::Translation2d& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/geometry/struct/Translation3dStruct.h b/wpimath/src/main/native/include/frc/geometry/struct/Translation3dStruct.h new file mode 100644 index 00000000000..b61a8758c62 --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/struct/Translation3dStruct.h @@ -0,0 +1,26 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Translation3d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:Translation3d"; + } + static constexpr size_t GetSize() { return 24; } + static constexpr std::string_view GetSchema() { + return "double x;double y;double z"; + } + + static frc::Translation3d Unpack(std::span data); + static void Pack(std::span data, const frc::Translation3d& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/geometry/struct/Twist2dStruct.h b/wpimath/src/main/native/include/frc/geometry/struct/Twist2dStruct.h new file mode 100644 index 00000000000..86bb4ada36c --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/struct/Twist2dStruct.h @@ -0,0 +1,24 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Twist2d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { return "struct:Twist2d"; } + static constexpr size_t GetSize() { return 24; } + static constexpr std::string_view GetSchema() { + return "double dx;double dy;double dtheta"; + } + + static frc::Twist2d Unpack(std::span data); + static void Pack(std::span data, const frc::Twist2d& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/geometry/struct/Twist3dStruct.h b/wpimath/src/main/native/include/frc/geometry/struct/Twist3dStruct.h new file mode 100644 index 00000000000..a346a1ad801 --- /dev/null +++ b/wpimath/src/main/native/include/frc/geometry/struct/Twist3dStruct.h @@ -0,0 +1,24 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/geometry/Twist3d.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { return "struct:Twist3d"; } + static constexpr size_t GetSize() { return 48; } + static constexpr std::string_view GetSchema() { + return "double dx;double dy;double dz;double rx;double ry;double rz"; + } + + static frc::Twist3d Unpack(std::span data); + static void Pack(std::span data, const frc::Twist3d& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/interpolation/TimeInterpolatableBuffer.h b/wpimath/src/main/native/include/frc/interpolation/TimeInterpolatableBuffer.h index 9dd8e62890c..bfb1b548976 100644 --- a/wpimath/src/main/native/include/frc/interpolation/TimeInterpolatableBuffer.h +++ b/wpimath/src/main/native/include/frc/interpolation/TimeInterpolatableBuffer.h @@ -64,7 +64,7 @@ class TimeInterpolatableBuffer { * @param sample The sample object. */ void AddSample(units::second_t time, T sample) { - // Add the new state into the vector. + // Add the new state into the vector if (m_pastSnapshots.size() == 0 || time > m_pastSnapshots.back().first) { m_pastSnapshots.emplace_back(time, sample); } else { @@ -72,20 +72,17 @@ class TimeInterpolatableBuffer { m_pastSnapshots.begin(), m_pastSnapshots.end(), time, [](auto t, const auto& pair) { return t < pair.first; }); - // Don't access this before ensuring first_after isn't first. - auto last_not_greater_than = first_after - 1; - - if (first_after == m_pastSnapshots.begin() || - last_not_greater_than == m_pastSnapshots.begin() || - last_not_greater_than->first < time) { - // Two cases handled together: - // 1. All entries come after the sample - // 2. Some entries come before the sample, but none are recorded with - // the same time - m_pastSnapshots.insert(first_after, std::pair(time, sample)); + if (first_after == m_pastSnapshots.begin()) { + // All entries come after the sample + m_pastSnapshots.insert(first_after, std::pair{time, sample}); + } else if (auto last_not_greater_than = first_after - 1; + last_not_greater_than == m_pastSnapshots.begin() || + last_not_greater_than->first < time) { + // Some entries come before the sample, but none are recorded with the + // same time + m_pastSnapshots.insert(first_after, std::pair{time, sample}); } else { - // Final case: - // 3. An entry exists with the same recorded time. + // An entry exists with the same recorded time last_not_greater_than->second = sample; } } @@ -103,7 +100,7 @@ class TimeInterpolatableBuffer { * * @param time The time at which to sample the buffer. */ - std::optional Sample(units::second_t time) { + std::optional Sample(units::second_t time) const { if (m_pastSnapshots.empty()) { return {}; } diff --git a/wpimath/src/main/native/include/frc/kinematics/ChassisSpeeds.h b/wpimath/src/main/native/include/frc/kinematics/ChassisSpeeds.h index 93c9044dca6..d693b47068d 100644 --- a/wpimath/src/main/native/include/frc/kinematics/ChassisSpeeds.h +++ b/wpimath/src/main/native/include/frc/kinematics/ChassisSpeeds.h @@ -38,6 +38,17 @@ struct WPILIB_DLLEXPORT ChassisSpeeds { */ units::radians_per_second_t omega = 0_rad_per_s; + /** + * Creates a Twist2d from ChassisSpeeds. + * + * @param dt The duration of the timestep. + * + * @return Twist2d. + */ + Twist2d ToTwist2d(units::second_t dt) const { + return Twist2d{vx * dt, vy * dt, omega * dt}; + } + /** * Disretizes a continuous-time chassis speed. * @@ -61,8 +72,15 @@ struct WPILIB_DLLEXPORT ChassisSpeeds { units::meters_per_second_t vy, units::radians_per_second_t omega, units::second_t dt) { + // Construct the desired pose after a timestep, relative to the current + // pose. The desired pose has decoupled translation and rotation. Pose2d desiredDeltaPose{vx * dt, vy * dt, omega * dt}; + + // Find the chassis translation/rotation deltas in the robot frame that move + // the robot from its current pose to the desired pose auto twist = Pose2d{}.Log(desiredDeltaPose); + + // Turn the chassis translation/rotation deltas into average velocities return {twist.dx / dt, twist.dy / dt, twist.dtheta / dt}; } @@ -251,3 +269,6 @@ struct WPILIB_DLLEXPORT ChassisSpeeds { } }; } // namespace frc + +#include "frc/kinematics/proto/ChassisSpeedsProto.h" +#include "frc/kinematics/struct/ChassisSpeedsStruct.h" diff --git a/wpimath/src/main/native/include/frc/kinematics/DifferentialDriveKinematics.h b/wpimath/src/main/native/include/frc/kinematics/DifferentialDriveKinematics.h index 95f53fa3b98..0f0cff9faa6 100644 --- a/wpimath/src/main/native/include/frc/kinematics/DifferentialDriveKinematics.h +++ b/wpimath/src/main/native/include/frc/kinematics/DifferentialDriveKinematics.h @@ -88,6 +88,10 @@ class WPILIB_DLLEXPORT DifferentialDriveKinematics return ToTwist2d(end.left - start.left, end.right - start.right); } + /// Differential drive trackwidth. units::meter_t trackWidth; }; } // namespace frc + +#include "frc/kinematics/proto/DifferentialDriveKinematicsProto.h" +#include "frc/kinematics/struct/DifferentialDriveKinematicsStruct.h" diff --git a/wpimath/src/main/native/include/frc/kinematics/DifferentialDriveWheelPositions.h b/wpimath/src/main/native/include/frc/kinematics/DifferentialDriveWheelPositions.h index 4dddbeaf401..f22d6874f66 100644 --- a/wpimath/src/main/native/include/frc/kinematics/DifferentialDriveWheelPositions.h +++ b/wpimath/src/main/native/include/frc/kinematics/DifferentialDriveWheelPositions.h @@ -49,3 +49,6 @@ struct WPILIB_DLLEXPORT DifferentialDriveWheelPositions { } }; } // namespace frc + +#include "frc/kinematics/proto/DifferentialDriveWheelPositionsProto.h" +#include "frc/kinematics/struct/DifferentialDriveWheelPositionsStruct.h" diff --git a/wpimath/src/main/native/include/frc/kinematics/DifferentialDriveWheelSpeeds.h b/wpimath/src/main/native/include/frc/kinematics/DifferentialDriveWheelSpeeds.h index 9d9e705772d..676b8ad59c6 100644 --- a/wpimath/src/main/native/include/frc/kinematics/DifferentialDriveWheelSpeeds.h +++ b/wpimath/src/main/native/include/frc/kinematics/DifferentialDriveWheelSpeeds.h @@ -112,3 +112,6 @@ struct WPILIB_DLLEXPORT DifferentialDriveWheelSpeeds { } }; } // namespace frc + +#include "frc/kinematics/proto/DifferentialDriveWheelSpeedsProto.h" +#include "frc/kinematics/struct/DifferentialDriveWheelSpeedsStruct.h" diff --git a/wpimath/src/main/native/include/frc/kinematics/MecanumDriveKinematics.h b/wpimath/src/main/native/include/frc/kinematics/MecanumDriveKinematics.h index fe6eb5120a5..f5a53ca9531 100644 --- a/wpimath/src/main/native/include/frc/kinematics/MecanumDriveKinematics.h +++ b/wpimath/src/main/native/include/frc/kinematics/MecanumDriveKinematics.h @@ -138,6 +138,34 @@ class WPILIB_DLLEXPORT MecanumDriveKinematics */ Twist2d ToTwist2d(const MecanumDriveWheelPositions& wheelDeltas) const; + /** + * Returns the front-left wheel translation. + * + * @return The front-left wheel translation. + */ + const Translation2d& GetFrontLeft() const { return m_frontLeftWheel; } + + /** + * Returns the front-right wheel translation. + * + * @return The front-right wheel translation. + */ + const Translation2d& GetFrontRight() const { return m_frontRightWheel; } + + /** + * Returns the rear-left wheel translation. + * + * @return The rear-left wheel translation. + */ + const Translation2d& GetRearLeft() const { return m_rearLeftWheel; } + + /** + * Returns the rear-right wheel translation. + * + * @return The rear-right wheel translation. + */ + const Translation2d& GetRearRight() const { return m_rearRightWheel; } + private: mutable Matrixd<4, 3> m_inverseKinematics; Eigen::HouseholderQR> m_forwardKinematics; @@ -165,3 +193,6 @@ class WPILIB_DLLEXPORT MecanumDriveKinematics }; } // namespace frc + +#include "frc/kinematics/proto/MecanumDriveKinematicsProto.h" +#include "frc/kinematics/struct/MecanumDriveKinematicsStruct.h" diff --git a/wpimath/src/main/native/include/frc/kinematics/MecanumDriveWheelPositions.h b/wpimath/src/main/native/include/frc/kinematics/MecanumDriveWheelPositions.h index 76c8b9dd96d..77d79192b9d 100644 --- a/wpimath/src/main/native/include/frc/kinematics/MecanumDriveWheelPositions.h +++ b/wpimath/src/main/native/include/frc/kinematics/MecanumDriveWheelPositions.h @@ -60,3 +60,6 @@ struct WPILIB_DLLEXPORT MecanumDriveWheelPositions { } }; } // namespace frc + +#include "frc/kinematics/proto/MecanumDriveWheelPositionsProto.h" +#include "frc/kinematics/struct/MecanumDriveWheelPositionsStruct.h" diff --git a/wpimath/src/main/native/include/frc/kinematics/MecanumDriveWheelSpeeds.h b/wpimath/src/main/native/include/frc/kinematics/MecanumDriveWheelSpeeds.h index 80e84607ed7..5df198c8018 100644 --- a/wpimath/src/main/native/include/frc/kinematics/MecanumDriveWheelSpeeds.h +++ b/wpimath/src/main/native/include/frc/kinematics/MecanumDriveWheelSpeeds.h @@ -120,3 +120,6 @@ struct WPILIB_DLLEXPORT MecanumDriveWheelSpeeds { } }; } // namespace frc + +#include "frc/kinematics/proto/MecanumDriveWheelSpeedsProto.h" +#include "frc/kinematics/struct/MecanumDriveWheelSpeedsStruct.h" diff --git a/wpimath/src/main/native/include/frc/kinematics/Odometry.h b/wpimath/src/main/native/include/frc/kinematics/Odometry.h index 55c074c02fa..9e242e2586f 100644 --- a/wpimath/src/main/native/include/frc/kinematics/Odometry.h +++ b/wpimath/src/main/native/include/frc/kinematics/Odometry.h @@ -20,6 +20,9 @@ namespace frc { * Teams can use odometry during the autonomous period for complex tasks like * path following. Furthermore, odometry can be used for latency compensation * when using computer-vision systems. + * + * @tparam WheelSpeeds Wheel speeds type. + * @tparam WheelPositions Wheel positions type. */ template class WPILIB_DLLEXPORT Odometry { diff --git a/wpimath/src/main/native/include/frc/kinematics/SwerveDriveKinematics.inc b/wpimath/src/main/native/include/frc/kinematics/SwerveDriveKinematics.inc index db85d999e39..b9bf34016e3 100644 --- a/wpimath/src/main/native/include/frc/kinematics/SwerveDriveKinematics.inc +++ b/wpimath/src/main/native/include/frc/kinematics/SwerveDriveKinematics.inc @@ -166,7 +166,7 @@ void SwerveDriveKinematics::DesaturateWheelSpeeds( auto k = units::math::max(translationalK, rotationalK); auto scale = units::math::min(k * attainableMaxModuleSpeed / realMaxSpeed, - units::scalar_t(1)); + units::scalar_t{1}); for (auto& module : states) { module.speed = module.speed * scale; } diff --git a/wpimath/src/main/native/include/frc/kinematics/SwerveModulePosition.h b/wpimath/src/main/native/include/frc/kinematics/SwerveModulePosition.h index 93f7465a0a6..576bfcf00f9 100644 --- a/wpimath/src/main/native/include/frc/kinematics/SwerveModulePosition.h +++ b/wpimath/src/main/native/include/frc/kinematics/SwerveModulePosition.h @@ -42,3 +42,6 @@ struct WPILIB_DLLEXPORT SwerveModulePosition { } }; } // namespace frc + +#include "frc/kinematics/proto/SwerveModulePositionProto.h" +#include "frc/kinematics/struct/SwerveModulePositionStruct.h" diff --git a/wpimath/src/main/native/include/frc/kinematics/SwerveModuleState.h b/wpimath/src/main/native/include/frc/kinematics/SwerveModuleState.h index 2f95d9b3590..3060d35fc24 100644 --- a/wpimath/src/main/native/include/frc/kinematics/SwerveModuleState.h +++ b/wpimath/src/main/native/include/frc/kinematics/SwerveModuleState.h @@ -47,3 +47,6 @@ struct WPILIB_DLLEXPORT SwerveModuleState { const Rotation2d& currentAngle); }; } // namespace frc + +#include "frc/kinematics/proto/SwerveModuleStateProto.h" +#include "frc/kinematics/struct/SwerveModuleStateStruct.h" diff --git a/wpimath/src/main/native/include/frc/kinematics/proto/ChassisSpeedsProto.h b/wpimath/src/main/native/include/frc/kinematics/proto/ChassisSpeedsProto.h new file mode 100644 index 00000000000..cefc83f8db0 --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/proto/ChassisSpeedsProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/ChassisSpeeds.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::ChassisSpeeds Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::ChassisSpeeds& value); +}; diff --git a/wpimath/src/main/native/include/frc/kinematics/proto/DifferentialDriveKinematicsProto.h b/wpimath/src/main/native/include/frc/kinematics/proto/DifferentialDriveKinematicsProto.h new file mode 100644 index 00000000000..9108f33c9c6 --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/proto/DifferentialDriveKinematicsProto.h @@ -0,0 +1,19 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/DifferentialDriveKinematics.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::DifferentialDriveKinematics Unpack( + const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::DifferentialDriveKinematics& value); +}; diff --git a/wpimath/src/main/native/include/frc/kinematics/proto/DifferentialDriveWheelPositionsProto.h b/wpimath/src/main/native/include/frc/kinematics/proto/DifferentialDriveWheelPositionsProto.h new file mode 100644 index 00000000000..3cf44eaa40c --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/proto/DifferentialDriveWheelPositionsProto.h @@ -0,0 +1,19 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/DifferentialDriveWheelPositions.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::DifferentialDriveWheelPositions Unpack( + const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::DifferentialDriveWheelPositions& value); +}; diff --git a/wpimath/src/main/native/include/frc/kinematics/proto/DifferentialDriveWheelSpeedsProto.h b/wpimath/src/main/native/include/frc/kinematics/proto/DifferentialDriveWheelSpeedsProto.h new file mode 100644 index 00000000000..f310892538e --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/proto/DifferentialDriveWheelSpeedsProto.h @@ -0,0 +1,19 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/DifferentialDriveWheelSpeeds.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::DifferentialDriveWheelSpeeds Unpack( + const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::DifferentialDriveWheelSpeeds& value); +}; diff --git a/wpimath/src/main/native/include/frc/kinematics/proto/MecanumDriveKinematicsProto.h b/wpimath/src/main/native/include/frc/kinematics/proto/MecanumDriveKinematicsProto.h new file mode 100644 index 00000000000..16e828824f0 --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/proto/MecanumDriveKinematicsProto.h @@ -0,0 +1,19 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/MecanumDriveKinematics.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::MecanumDriveKinematics Unpack( + const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::MecanumDriveKinematics& value); +}; diff --git a/wpimath/src/main/native/include/frc/kinematics/proto/MecanumDriveWheelPositionsProto.h b/wpimath/src/main/native/include/frc/kinematics/proto/MecanumDriveWheelPositionsProto.h new file mode 100644 index 00000000000..a4b4bd6762f --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/proto/MecanumDriveWheelPositionsProto.h @@ -0,0 +1,19 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/MecanumDriveWheelPositions.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::MecanumDriveWheelPositions Unpack( + const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::MecanumDriveWheelPositions& value); +}; diff --git a/wpimath/src/main/native/include/frc/kinematics/proto/MecanumDriveWheelSpeedsProto.h b/wpimath/src/main/native/include/frc/kinematics/proto/MecanumDriveWheelSpeedsProto.h new file mode 100644 index 00000000000..4d099d3de16 --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/proto/MecanumDriveWheelSpeedsProto.h @@ -0,0 +1,19 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/MecanumDriveWheelSpeeds.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::MecanumDriveWheelSpeeds Unpack( + const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::MecanumDriveWheelSpeeds& value); +}; diff --git a/wpimath/src/main/native/include/frc/kinematics/proto/SwerveModulePositionProto.h b/wpimath/src/main/native/include/frc/kinematics/proto/SwerveModulePositionProto.h new file mode 100644 index 00000000000..3e864cbd95b --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/proto/SwerveModulePositionProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/SwerveModulePosition.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::SwerveModulePosition Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::SwerveModulePosition& value); +}; diff --git a/wpimath/src/main/native/include/frc/kinematics/proto/SwerveModuleStateProto.h b/wpimath/src/main/native/include/frc/kinematics/proto/SwerveModuleStateProto.h new file mode 100644 index 00000000000..3e7b3ec6e41 --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/proto/SwerveModuleStateProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/SwerveModuleState.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::SwerveModuleState Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::SwerveModuleState& value); +}; diff --git a/wpimath/src/main/native/include/frc/kinematics/struct/ChassisSpeedsStruct.h b/wpimath/src/main/native/include/frc/kinematics/struct/ChassisSpeedsStruct.h new file mode 100644 index 00000000000..8c65057da93 --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/struct/ChassisSpeedsStruct.h @@ -0,0 +1,26 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/ChassisSpeeds.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:ChassisSpeeds"; + } + static constexpr size_t GetSize() { return 24; } + static constexpr std::string_view GetSchema() { + return "double vx;double vy;double omega"; + } + + static frc::ChassisSpeeds Unpack(std::span data); + static void Pack(std::span data, const frc::ChassisSpeeds& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/kinematics/struct/DifferentialDriveKinematicsStruct.h b/wpimath/src/main/native/include/frc/kinematics/struct/DifferentialDriveKinematicsStruct.h new file mode 100644 index 00000000000..0acbc76e47c --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/struct/DifferentialDriveKinematicsStruct.h @@ -0,0 +1,25 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/DifferentialDriveKinematics.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:DifferentialDriveKinematics"; + } + static constexpr size_t GetSize() { return 8; } + static constexpr std::string_view GetSchema() { return "double track_width"; } + + static frc::DifferentialDriveKinematics Unpack(std::span data); + static void Pack(std::span data, + const frc::DifferentialDriveKinematics& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/kinematics/struct/DifferentialDriveWheelPositionsStruct.h b/wpimath/src/main/native/include/frc/kinematics/struct/DifferentialDriveWheelPositionsStruct.h new file mode 100644 index 00000000000..ef694bc37b4 --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/struct/DifferentialDriveWheelPositionsStruct.h @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/DifferentialDriveWheelPositions.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:DifferentialDriveWheelPositions"; + } + static constexpr size_t GetSize() { return 16; } + static constexpr std::string_view GetSchema() { + return "double left;double right"; + } + + static frc::DifferentialDriveWheelPositions Unpack( + std::span data); + static void Pack(std::span data, + const frc::DifferentialDriveWheelPositions& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/kinematics/struct/DifferentialDriveWheelSpeedsStruct.h b/wpimath/src/main/native/include/frc/kinematics/struct/DifferentialDriveWheelSpeedsStruct.h new file mode 100644 index 00000000000..12dc8431eb0 --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/struct/DifferentialDriveWheelSpeedsStruct.h @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/DifferentialDriveWheelSpeeds.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:DifferentialDriveWheelSpeeds"; + } + static constexpr size_t GetSize() { return 16; } + static constexpr std::string_view GetSchema() { + return "double left;double right"; + } + + static frc::DifferentialDriveWheelSpeeds Unpack( + std::span data); + static void Pack(std::span data, + const frc::DifferentialDriveWheelSpeeds& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/kinematics/struct/MecanumDriveKinematicsStruct.h b/wpimath/src/main/native/include/frc/kinematics/struct/MecanumDriveKinematicsStruct.h new file mode 100644 index 00000000000..a4fe3bddca0 --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/struct/MecanumDriveKinematicsStruct.h @@ -0,0 +1,35 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/MecanumDriveKinematics.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:MecanumDriveKinematics"; + } + static constexpr size_t GetSize() { + return 4 * wpi::GetStructSize(); + } + static constexpr std::string_view GetSchema() { + return "Translation2d front_left;Translation2d front_right;Translation2d " + "rear_left;Translation2d rear_right"; + } + + static frc::MecanumDriveKinematics Unpack(std::span data); + static void Pack(std::span data, + const frc::MecanumDriveKinematics& value); + static void ForEachNested( + std::invocable auto fn) { + wpi::ForEachStructSchema(fn); + } +}; + +static_assert(wpi::StructSerializable); +static_assert(wpi::HasNestedStruct); diff --git a/wpimath/src/main/native/include/frc/kinematics/struct/MecanumDriveWheelPositionsStruct.h b/wpimath/src/main/native/include/frc/kinematics/struct/MecanumDriveWheelPositionsStruct.h new file mode 100644 index 00000000000..87b5f386246 --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/struct/MecanumDriveWheelPositionsStruct.h @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/MecanumDriveWheelPositions.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:MecanumDriveWheelPositions"; + } + static constexpr size_t GetSize() { return 32; } + static constexpr std::string_view GetSchema() { + return "double front_left;double front_right;double rear_left;double " + "rear_right"; + } + + static frc::MecanumDriveWheelPositions Unpack(std::span data); + static void Pack(std::span data, + const frc::MecanumDriveWheelPositions& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/kinematics/struct/MecanumDriveWheelSpeedsStruct.h b/wpimath/src/main/native/include/frc/kinematics/struct/MecanumDriveWheelSpeedsStruct.h new file mode 100644 index 00000000000..28f28e8c229 --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/struct/MecanumDriveWheelSpeedsStruct.h @@ -0,0 +1,28 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/MecanumDriveWheelSpeeds.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:MecanumDriveWheelSpeeds"; + } + static constexpr size_t GetSize() { return 32; } + static constexpr std::string_view GetSchema() { + return "double front_left;double front_right;double rear_left;" + "double rear_right"; + } + + static frc::MecanumDriveWheelSpeeds Unpack(std::span data); + static void Pack(std::span data, + const frc::MecanumDriveWheelSpeeds& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/kinematics/struct/SwerveModulePositionStruct.h b/wpimath/src/main/native/include/frc/kinematics/struct/SwerveModulePositionStruct.h new file mode 100644 index 00000000000..ee58a2c7cdb --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/struct/SwerveModulePositionStruct.h @@ -0,0 +1,34 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/SwerveModulePosition.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:SwerveModulePosition"; + } + static constexpr size_t GetSize() { + return 8 + wpi::GetStructSize(); + } + static constexpr std::string_view GetSchema() { + return "double distance;Rotation2d angle"; + } + + static frc::SwerveModulePosition Unpack(std::span data); + static void Pack(std::span data, + const frc::SwerveModulePosition& value); + static void ForEachNested( + std::invocable auto fn) { + wpi::ForEachStructSchema(fn); + } +}; + +static_assert(wpi::StructSerializable); +static_assert(wpi::HasNestedStruct); diff --git a/wpimath/src/main/native/include/frc/kinematics/struct/SwerveModuleStateStruct.h b/wpimath/src/main/native/include/frc/kinematics/struct/SwerveModuleStateStruct.h new file mode 100644 index 00000000000..06885fed518 --- /dev/null +++ b/wpimath/src/main/native/include/frc/kinematics/struct/SwerveModuleStateStruct.h @@ -0,0 +1,34 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/kinematics/SwerveModuleState.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { + return "struct:SwerveModuleState"; + } + static constexpr size_t GetSize() { + return 8 + wpi::GetStructSize(); + } + static constexpr std::string_view GetSchema() { + return "double speed;Rotation2d angle"; + } + + static frc::SwerveModuleState Unpack(std::span data); + static void Pack(std::span data, + const frc::SwerveModuleState& value); + static void ForEachNested( + std::invocable auto fn) { + wpi::ForEachStructSchema(fn); + } +}; + +static_assert(wpi::StructSerializable); +static_assert(wpi::HasNestedStruct); diff --git a/wpimath/src/main/native/include/frc/optimization/SimulatedAnnealing.h b/wpimath/src/main/native/include/frc/optimization/SimulatedAnnealing.h new file mode 100644 index 00000000000..0a16dd963ad --- /dev/null +++ b/wpimath/src/main/native/include/frc/optimization/SimulatedAnnealing.h @@ -0,0 +1,101 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include +#include +#include + +namespace frc { + +/** + * An implementation of the Simulated Annealing stochastic nonlinear + * optimization method. + * + * Solving optimization problems involves tweaking decision variables to try to + * minimize some cost function. Simulated annealing is good for solving + * optimization problems with many local minima and a very large search space + * (it’s a heuristic solver rather than an exact solver like, say, SQP or + * interior-point method). Simulated annealing is a popular choice for solving + * the traveling salesman problem (see TravelingSalesman). + * + * @see https://en.wikipedia.org/wiki/Simulated_annealing + * @tparam State The type of the state to optimize. + */ +template +class SimulatedAnnealing { + public: + /** + * Constructor for Simulated Annealing that can be used for the same functions + * but with different initial states. + * + * @param initialTemperature The initial temperature. Higher temperatures make + * it more likely a worse state will be accepted during iteration, helping + * to avoid local minima. The temperature is decreased over time. + * @param neighbor Function that generates a random neighbor of the current + * state. + * @param cost Function that returns the scalar cost of a state. + */ + constexpr SimulatedAnnealing(double initialTemperature, + std::function neighbor, + std::function cost) + : m_initialTemperature{initialTemperature}, + m_neighbor{neighbor}, + m_cost{cost} {} + + /** + * Runs the Simulated Annealing algorithm. + * + * @param initialGuess The initial state. + * @param iterations Number of iterations to run the solver. + * @return The optimized state. + */ + State Solve(const State& initialGuess, int iterations) { + State minState = initialGuess; + double minCost = std::numeric_limits::infinity(); + + std::random_device rd; + std::mt19937 gen{rd()}; + std::uniform_real_distribution<> distr{0.0, 1.0}; + + State state = initialGuess; + double cost = m_cost(state); + + for (int i = 0; i < iterations; ++i) { + double temperature = m_initialTemperature / i; + + State proposedState = m_neighbor(state); + double proposedCost = m_cost(proposedState); + double deltaCost = proposedCost - cost; + + double acceptanceProbability = std::exp(-deltaCost / temperature); + + // If cost went down or random number exceeded acceptance probability, + // accept the proposed state + if (deltaCost < 0 || acceptanceProbability >= distr(gen)) { + state = proposedState; + cost = proposedCost; + } + + // If proposed cost is less than minimum, the proposed state becomes the + // new minimum + if (proposedCost < minCost) { + minState = proposedState; + minCost = proposedCost; + } + } + + return minState; + } + + private: + double m_initialTemperature; + std::function m_neighbor; + std::function m_cost; +}; + +} // namespace frc diff --git a/wpimath/src/main/native/include/frc/path/TravelingSalesman.h b/wpimath/src/main/native/include/frc/path/TravelingSalesman.h new file mode 100644 index 00000000000..d45f6203f8e --- /dev/null +++ b/wpimath/src/main/native/include/frc/path/TravelingSalesman.h @@ -0,0 +1,179 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include +#include +#include +#include + +#include + +#include "frc/EigenCore.h" +#include "frc/geometry/Pose2d.h" +#include "frc/optimization/SimulatedAnnealing.h" + +namespace frc { + +/** + * Given a list of poses, this class finds the shortest possible route that + * visits each pose exactly once and returns to the origin pose. + * + * @see https://en.wikipedia.org/wiki/Travelling_salesman_problem + */ +class TravelingSalesman { + public: + /** + * Constructs a traveling salesman problem solver with a cost function defined + * as the 2D distance between poses. + */ + constexpr TravelingSalesman() = default; + + /** + * Constructs a traveling salesman problem solver with a user-provided cost + * function. + * + * @param cost Function that returns the cost between two poses. The sum of + * the costs for every pair of poses is minimized. + */ + explicit TravelingSalesman(std::function cost) + : m_cost{std::move(cost)} {} + + /** + * Finds the path through every pose that minimizes the cost. The first pose + * in the returned array is the first pose that was passed in. + * + * This overload supports a statically-sized list of poses. + * + * @tparam Poses The length of the path and the number of poses. + * @param poses An array of Pose2ds the path must pass through. + * @param iterations The number of times the solver attempts to find a better + * random neighbor. + * @return The optimized path as an array of Pose2ds. + */ + template + wpi::array Solve(const wpi::array& poses, + int iterations) { + SimulatedAnnealing> solver{ + 1, &Neighbor, [&](const Vectord& state) { + // Total cost is sum of all costs between adjacent pairs in path + double sum = 0.0; + for (int i = 0; i < state.rows(); ++i) { + sum += + m_cost(poses[static_cast(state(i))], + poses[static_cast(state((i + 1) % poses.size()))]); + } + return sum; + }}; + + Eigen::Vector initial; + for (int i = 0; i < initial.rows(); ++i) { + initial(i) = i; + } + + auto indices = solver.Solve(initial, iterations); + + wpi::array solution{wpi::empty_array}; + for (size_t i = 0; i < poses.size(); ++i) { + solution[i] = poses[static_cast(indices[i])]; + } + + // Rotate solution list until solution[0] = poses[0] + std::rotate(solution.begin(), + std::find(solution.begin(), solution.end(), poses[0]), + solution.end()); + + return solution; + } + + /** + * Finds the path through every pose that minimizes the cost. The first pose + * in the returned array is the first pose that was passed in. + * + * This overload supports a dynamically-sized list of poses for Python to use. + * + * @param poses An array of Pose2ds the path must pass through. + * @param iterations The number of times the solver attempts to find a better + * random neighbor. + * @return The optimized path as an array of Pose2ds. + */ + std::vector Solve(std::span poses, int iterations) { + SimulatedAnnealing solver{ + 1.0, &Neighbor, [&](const Eigen::VectorXd& state) { + // Total cost is sum of all costs between adjacent pairs in path + double sum = 0.0; + for (int i = 0; i < state.rows(); ++i) { + sum += + m_cost(poses[static_cast(state(i))], + poses[static_cast(state((i + 1) % poses.size()))]); + } + return sum; + }}; + + Eigen::VectorXd initial{poses.size()}; + for (int i = 0; i < initial.rows(); ++i) { + initial(i) = i; + } + + auto indices = solver.Solve(initial, iterations); + + std::vector solution; + for (size_t i = 0; i < poses.size(); ++i) { + solution.emplace_back(poses[static_cast(indices[i])]); + } + + // Rotate solution list until solution[0] = poses[0] + std::rotate(solution.begin(), + std::find(solution.begin(), solution.end(), poses[0]), + solution.end()); + + return solution; + } + + private: + // Default cost is distance between poses + std::function m_cost = + [](const Pose2d& a, const Pose2d& b) -> double { + return units::math::hypot(a.X() - b.X(), a.Y() - b.Y()).value(); + }; + + /** + * A random neighbor is generated to try to replace the current one. + * + * @tparam Poses The length of the path and the number of poses. + * @param state A vector that is a list of indices that defines the path + * through the path array. + * @return Generates a random neighbor of the current state by flipping a + * random range in the path array. + */ + template + static Eigen::Vector Neighbor( + const Eigen::Vector& state) { + Eigen::Vector proposedState = state; + + std::random_device rd; + std::mt19937 gen{rd()}; + std::uniform_int_distribution<> distr{0, + static_cast(state.rows()) - 1}; + + int rangeStart = distr(gen); + int rangeEnd = distr(gen); + if (rangeEnd < rangeStart) { + std::swap(rangeStart, rangeEnd); + } + + for (int i = rangeStart; i <= (rangeStart + rangeEnd) / 2; ++i) { + double temp = proposedState(i, 0); + proposedState(i, 0) = state(rangeEnd - (i - rangeStart), 0); + proposedState(rangeEnd - (i - rangeStart), 0) = temp; + } + + return proposedState; + } +}; + +} // namespace frc diff --git a/wpimath/src/main/native/include/frc/spline/CubicHermiteSpline.h b/wpimath/src/main/native/include/frc/spline/CubicHermiteSpline.h index 1d6aaeb60e4..07cc13c9814 100644 --- a/wpimath/src/main/native/include/frc/spline/CubicHermiteSpline.h +++ b/wpimath/src/main/native/include/frc/spline/CubicHermiteSpline.h @@ -35,16 +35,36 @@ class WPILIB_DLLEXPORT CubicHermiteSpline : public Spline<3> { wpi::array yInitialControlVector, wpi::array yFinalControlVector); - protected: /** * Returns the coefficients matrix. * @return The coefficients matrix. */ Matrixd<6, 3 + 1> Coefficients() const override { return m_coefficients; } + /** + * Returns the initial control vector that created this spline. + * + * @return The initial control vector that created this spline. + */ + const ControlVector& GetInitialControlVector() const override { + return m_initialControlVector; + } + + /** + * Returns the final control vector that created this spline. + * + * @return The final control vector that created this spline. + */ + const ControlVector& GetFinalControlVector() const override { + return m_finalControlVector; + } + private: Matrixd<6, 4> m_coefficients = Matrixd<6, 4>::Zero(); + ControlVector m_initialControlVector; + ControlVector m_finalControlVector; + /** * Returns the hermite basis matrix for cubic hermite spline interpolation. * @return The hermite basis matrix for cubic hermite spline interpolation. diff --git a/wpimath/src/main/native/include/frc/spline/QuinticHermiteSpline.h b/wpimath/src/main/native/include/frc/spline/QuinticHermiteSpline.h index ad03a23919c..37513cc0643 100644 --- a/wpimath/src/main/native/include/frc/spline/QuinticHermiteSpline.h +++ b/wpimath/src/main/native/include/frc/spline/QuinticHermiteSpline.h @@ -35,16 +35,36 @@ class WPILIB_DLLEXPORT QuinticHermiteSpline : public Spline<5> { wpi::array yInitialControlVector, wpi::array yFinalControlVector); - protected: /** * Returns the coefficients matrix. * @return The coefficients matrix. */ Matrixd<6, 6> Coefficients() const override { return m_coefficients; } + /** + * Returns the initial control vector that created this spline. + * + * @return The initial control vector that created this spline. + */ + const ControlVector& GetInitialControlVector() const override { + return m_initialControlVector; + } + + /** + * Returns the final control vector that created this spline. + * + * @return The final control vector that created this spline. + */ + const ControlVector& GetFinalControlVector() const override { + return m_finalControlVector; + } + private: Matrixd<6, 6> m_coefficients = Matrixd<6, 6>::Zero(); + ControlVector m_initialControlVector; + ControlVector m_finalControlVector; + /** * Returns the hermite basis matrix for quintic hermite spline interpolation. * @return The hermite basis matrix for quintic hermite spline interpolation. diff --git a/wpimath/src/main/native/include/frc/spline/Spline.h b/wpimath/src/main/native/include/frc/spline/Spline.h index b5ff0242c18..257b167f38c 100644 --- a/wpimath/src/main/native/include/frc/spline/Spline.h +++ b/wpimath/src/main/native/include/frc/spline/Spline.h @@ -44,7 +44,10 @@ class Spline { * dimension. */ struct ControlVector { + /// The x components of the control vector. wpi::array x; + + /// The y components of the control vector. wpi::array y; }; @@ -94,7 +97,6 @@ class Spline { units::curvature_t{curvature}}; } - protected: /** * Returns the coefficients of the spline. * @@ -102,6 +104,21 @@ class Spline { */ virtual Matrixd<6, Degree + 1> Coefficients() const = 0; + /** + * Returns the initial control vector that created this spline. + * + * @return The initial control vector that created this spline. + */ + virtual const ControlVector& GetInitialControlVector() const = 0; + + /** + * Returns the final control vector that created this spline. + * + * @return The final control vector that created this spline. + */ + virtual const ControlVector& GetFinalControlVector() const = 0; + + protected: /** * Converts a Translation2d into a vector that is compatible with Eigen. * diff --git a/wpimath/src/main/native/include/frc/spline/SplineHelper.h b/wpimath/src/main/native/include/frc/spline/SplineHelper.h index 90b61078cf6..b023f12d736 100644 --- a/wpimath/src/main/native/include/frc/spline/SplineHelper.h +++ b/wpimath/src/main/native/include/frc/spline/SplineHelper.h @@ -77,6 +77,17 @@ class WPILIB_DLLEXPORT SplineHelper { static std::vector QuinticSplinesFromControlVectors( const std::vector::ControlVector>& controlVectors); + /** + * Optimizes the curvature of 2 or more quintic splines at knot points. + * Overall, this reduces the integral of the absolute value of the second + * derivative across the set of splines. + * + * @param splines A vector of un-optimized quintic splines. + * @return A vector of optimized quintic splines. + */ + static std::vector OptimizeCurvature( + const std::vector& splines); + private: static Spline<3>::ControlVector CubicControlVector(double scalar, const Pose2d& point) { diff --git a/wpimath/src/main/native/include/frc/system/LinearSystem.h b/wpimath/src/main/native/include/frc/system/LinearSystem.h index dff24338ac0..21a3783173a 100644 --- a/wpimath/src/main/native/include/frc/system/LinearSystem.h +++ b/wpimath/src/main/native/include/frc/system/LinearSystem.h @@ -5,9 +5,13 @@ #pragma once #include +#include #include #include +#include +#include + #include "frc/EigenCore.h" #include "frc/StateSpaceUtil.h" #include "frc/system/Discretization.h" @@ -164,6 +168,56 @@ class LinearSystem { return m_C * x + m_D * clampedU; } + /** + * Returns the LinearSystem with the outputs listed in outputIndices. + * + *

    This is used by state observers such as the Kalman Filter. + * + * @param outputIndices the list of output indices to include in the sliced + * system. + * @return the sliced LinearSystem with outputs set to row vectors of + * LinearSystem. + * @throws std::domain_error if any outputIndices are outside the range of + * system outputs. + * @throws std::domain_error if number of outputIndices exceeds the system + * outputs. + * @throws std::domain_error if duplication exists in outputIndices. + */ + template ... OutputIndices> + LinearSystem Slice( + OutputIndices... outputIndices) { + static_assert(sizeof...(OutputIndices) <= Outputs, + "More outputs requested than available. This is usually due " + "to model implementation errors."); + + wpi::for_each( + [](size_t i, const auto& elem) { + if (elem < 0 || elem >= Outputs) { + throw std::domain_error( + "Slice indices out of range. This is usually due to model " + "implementation errors."); + } + }, + outputIndices...); + + // Sort and deduplicate output indices + wpi::SmallVector outputIndicesArray{outputIndices...}; + std::sort(outputIndicesArray.begin(), outputIndicesArray.end()); + auto last = + std::unique(outputIndicesArray.begin(), outputIndicesArray.end()); + outputIndicesArray.erase(last, outputIndicesArray.end()); + + if (outputIndicesArray.size() != sizeof...(outputIndices)) { + throw std::domain_error( + "Duplicate indices exist. This is usually due to model " + "implementation errors."); + } + + return LinearSystem{ + m_A, m_B, m_C(outputIndicesArray, Eigen::placeholders::all), + m_D(outputIndicesArray, Eigen::placeholders::all)}; + } + private: /** * Continuous system matrix. diff --git a/wpimath/src/main/native/include/frc/system/plant/DCMotor.h b/wpimath/src/main/native/include/frc/system/plant/DCMotor.h index ad711ee3cfa..a2679452472 100644 --- a/wpimath/src/main/native/include/frc/system/plant/DCMotor.h +++ b/wpimath/src/main/native/include/frc/system/plant/DCMotor.h @@ -26,19 +26,28 @@ class WPILIB_DLLEXPORT DCMotor { units::unit_t>>; + /// Voltage at which the motor constants were measured. units::volt_t nominalVoltage; + + /// Torque when stalled. units::newton_meter_t stallTorque; + + /// Current draw when stalled. units::ampere_t stallCurrent; + + /// Current draw under no load. units::ampere_t freeCurrent; + + /// Angular velocity under no load. units::radians_per_second_t freeSpeed; - // Resistance of motor + /// Motor internal resistance. units::ohm_t R; - // Motor velocity constant + /// Motor velocity constant. radians_per_second_per_volt_t Kv; - // Torque constant + /// Motor torque constant. newton_meters_per_ampere_t Kt; /** @@ -239,3 +248,6 @@ class WPILIB_DLLEXPORT DCMotor { }; } // namespace frc + +#include "frc/system/plant/proto/DCMotorProto.h" +#include "frc/system/plant/struct/DCMotorStruct.h" diff --git a/wpimath/src/main/native/include/frc/system/plant/LinearSystemId.h b/wpimath/src/main/native/include/frc/system/plant/LinearSystemId.h index af9e799dea0..d149f8b65ac 100644 --- a/wpimath/src/main/native/include/frc/system/plant/LinearSystemId.h +++ b/wpimath/src/main/native/include/frc/system/plant/LinearSystemId.h @@ -20,6 +20,9 @@ #include "units/voltage.h" namespace frc { +/** + * Linear system ID utility functions. + */ class WPILIB_DLLEXPORT LinearSystemId { public: template @@ -41,7 +44,7 @@ class WPILIB_DLLEXPORT LinearSystemId { * @param gearing Gear ratio from motor to carriage. * @throws std::domain_error if mass <= 0, radius <= 0, or gearing <= 0. */ - static LinearSystem<2, 1, 1> ElevatorSystem(DCMotor motor, + static LinearSystem<2, 1, 2> ElevatorSystem(DCMotor motor, units::kilogram_t mass, units::meter_t radius, double gearing); @@ -56,7 +59,7 @@ class WPILIB_DLLEXPORT LinearSystemId { * @param gearing Gear ratio from motor to arm. * @throws std::domain_error if J <= 0 or gearing <= 0. */ - static LinearSystem<2, 1, 1> SingleJointedArmSystem( + static LinearSystem<2, 1, 2> SingleJointedArmSystem( DCMotor motor, units::kilogram_square_meter_t J, double gearing); /** @@ -76,7 +79,9 @@ class WPILIB_DLLEXPORT LinearSystemId { * * @param kV The velocity gain, in volts/(unit/sec). * @param kA The acceleration gain, in volts/(unit/sec²). - * @throws std::domain_error if kV <= 0 or kA <= 0. + * @throws std::domain_error if kV < 0 or kA <= 0. + * @see https://github.com/wpilibsuite/sysid */ template requires std::same_as || @@ -84,8 +89,8 @@ class WPILIB_DLLEXPORT LinearSystemId { static LinearSystem<1, 1, 1> IdentifyVelocitySystem( decltype(1_V / Velocity_t(1)) kV, decltype(1_V / Acceleration_t(1)) kA) { - if (kV <= decltype(kV){0}) { - throw std::domain_error("Kv must be greater than zero."); + if (kV < decltype(kV){0}) { + throw std::domain_error("Kv must be greater than or equal to zero."); } if (kA <= decltype(kA){0}) { throw std::domain_error("Ka must be greater than zero."); @@ -117,7 +122,9 @@ class WPILIB_DLLEXPORT LinearSystemId { * @param kV The velocity gain, in volts/(unit/sec). * @param kA The acceleration gain, in volts/(unit/sec²). * - * @throws std::domain_error if kV <= 0 or kA <= 0. + * @throws std::domain_error if kV < 0 or kA <= 0. + * @see https://github.com/wpilibsuite/sysid */ template requires std::same_as || @@ -125,8 +132,8 @@ class WPILIB_DLLEXPORT LinearSystemId { static LinearSystem<2, 1, 1> IdentifyPositionSystem( decltype(1_V / Velocity_t(1)) kV, decltype(1_V / Acceleration_t(1)) kA) { - if (kV <= decltype(kV){0}) { - throw std::domain_error("Kv must be greater than zero."); + if (kV < decltype(kV){0}) { + throw std::domain_error("Kv must be greater than or equal to zero."); } if (kA <= decltype(kA){0}) { throw std::domain_error("Ka must be greater than zero."); @@ -159,6 +166,8 @@ class WPILIB_DLLEXPORT LinearSystemId { * second squared). * @throws domain_error if kVLinear <= 0, kALinear <= 0, kVAngular <= 0, * or kAAngular <= 0. + * @see https://github.com/wpilibsuite/sysid */ static LinearSystem<2, 2, 2> IdentifyDrivetrainSystem( decltype(1_V / 1_mps) kVLinear, decltype(1_V / 1_mps_sq) kALinear, @@ -186,6 +195,8 @@ class WPILIB_DLLEXPORT LinearSystemId { * right wheels, in meters. * @throws domain_error if kVLinear <= 0, kALinear <= 0, kVAngular <= 0, * kAAngular <= 0, or trackwidth <= 0. + * @see https://github.com/wpilibsuite/sysid */ static LinearSystem<2, 2, 2> IdentifyDrivetrainSystem( decltype(1_V / 1_mps) kVLinear, decltype(1_V / 1_mps_sq) kALinear, @@ -215,6 +226,8 @@ class WPILIB_DLLEXPORT LinearSystemId { * @param J the moment of inertia J of the DC motor. * @param gearing Gear ratio from motor to output. * @throws std::domain_error if J <= 0 or gearing <= 0. + * @see https://github.com/wpilibsuite/sysid */ static LinearSystem<2, 1, 2> DCMotorSystem(DCMotor motor, units::kilogram_square_meter_t J, @@ -238,7 +251,7 @@ class WPILIB_DLLEXPORT LinearSystemId { * @param kV The velocity gain, in volts/(unit/sec). * @param kA The acceleration gain, in volts/(unit/sec²). * - * @throws std::domain_error if kV <= 0 or kA <= 0. + * @throws std::domain_error if kV < 0 or kA <= 0. */ template requires std::same_as || @@ -246,8 +259,8 @@ class WPILIB_DLLEXPORT LinearSystemId { static LinearSystem<2, 1, 2> DCMotorSystem( decltype(1_V / Velocity_t(1)) kV, decltype(1_V / Acceleration_t(1)) kA) { - if (kV <= decltype(kV){0}) { - throw std::domain_error("Kv must be greater than zero."); + if (kV < decltype(kV){0}) { + throw std::domain_error("Kv must be greater than or equal to zero."); } if (kA <= decltype(kA){0}) { throw std::domain_error("Ka must be greater than zero."); diff --git a/wpimath/src/main/native/include/frc/system/plant/proto/DCMotorProto.h b/wpimath/src/main/native/include/frc/system/plant/proto/DCMotorProto.h new file mode 100644 index 00000000000..acae1db6d3c --- /dev/null +++ b/wpimath/src/main/native/include/frc/system/plant/proto/DCMotorProto.h @@ -0,0 +1,17 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/system/plant/DCMotor.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::DCMotor Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, const frc::DCMotor& value); +}; diff --git a/wpimath/src/main/native/include/frc/system/plant/struct/DCMotorStruct.h b/wpimath/src/main/native/include/frc/system/plant/struct/DCMotorStruct.h new file mode 100644 index 00000000000..22a6405d9a6 --- /dev/null +++ b/wpimath/src/main/native/include/frc/system/plant/struct/DCMotorStruct.h @@ -0,0 +1,26 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/system/plant/DCMotor.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Struct { + static constexpr std::string_view GetTypeString() { return "struct:DCMotor"; } + static constexpr size_t GetSize() { return 40; } + static constexpr std::string_view GetSchema() { + return "double nominal_voltage;double stall_torque;double " + "stall_current;double " + "free_current;double free_speed"; + } + + static frc::DCMotor Unpack(std::span data); + static void Pack(std::span data, const frc::DCMotor& value); +}; + +static_assert(wpi::StructSerializable); diff --git a/wpimath/src/main/native/include/frc/trajectory/ExponentialProfile.h b/wpimath/src/main/native/include/frc/trajectory/ExponentialProfile.h index f45987b7d0c..9f836c10363 100644 --- a/wpimath/src/main/native/include/frc/trajectory/ExponentialProfile.h +++ b/wpimath/src/main/native/include/frc/trajectory/ExponentialProfile.h @@ -55,38 +55,82 @@ class ExponentialProfile { using KA = units::compound_unit>; using kA_t = units::unit_t; + /** + * Profile timing. + */ + class ProfileTiming { + public: + /// Profile inflection time. + units::second_t inflectionTime; + + /// Total profile time. + units::second_t totalTime; + + /** + * Decides if the profile is finished by time t. + * + * @param t The time since the beginning of the profile. + * @return if the profile is finished at time t. + */ + bool IsFinished(const units::second_t& t) const { return t >= totalTime; } + }; + + /** + * Profile constraints. + */ class Constraints { public: + /** + * Constructs constraints for an ExponentialProfile. + * + * @param maxInput maximum unsigned input voltage + * @param A The State-Space 1x1 system matrix. + * @param B The State-Space 1x1 input matrix. + */ Constraints(Input_t maxInput, A_t A, B_t B) : maxInput{maxInput}, A{A}, B{B} {} + + /** + * Constructs constraints for an ExponentialProfile from characteristics. + * + * @param maxInput maximum unsigned input voltage + * @param kV The velocity gain. + * @param kA The acceleration gain. + */ Constraints(Input_t maxInput, kV_t kV, kA_t kA) : maxInput{maxInput}, A{-kV / kA}, B{1 / kA} {} + + /** + * Computes the max achievable velocity for an Exponential Profile. + * + * @return The seady-state velocity achieved by this profile. + */ Velocity_t MaxVelocity() const { return -maxInput * B / A; } + /// Maximum unsigned input voltage. Input_t maxInput{0}; + + /// The State-Space 1x1 system matrix. A_t A{0}; + + /// The State-Space 1x1 input matrix. B_t B{0}; }; + /** Profile state. */ class State { public: + /// The position at this state. Distance_t position{0}; - Velocity_t velocity{0}; - bool operator==(const State&) const = default; - }; - class ProfileTiming { - public: - units::second_t inflectionTime; - units::second_t totalTime; + /// The velocity at this state. + Velocity_t velocity{0}; - bool IsFinished(const units::second_t& time) const { - return time > totalTime; - } + bool operator==(const State&) const = default; }; /** - * Construct a ExponentialProfile. + * Constructs a ExponentialProfile. * * @param constraints The constraints on the profile, like maximum input. */ @@ -98,41 +142,72 @@ class ExponentialProfile { ExponentialProfile& operator=(ExponentialProfile&&) = default; /** - * Calculate the correct position and velocity for the profile at a time t - * where the current state is at time t = 0. + * Calculates the position and velocity for the profile at a time t where the + * current state is at time t = 0. + * + * @param t How long to advance from the current state toward the desired + * state. + * @param current The current state. + * @param goal The desired state when the profile is complete. + * @return The position and velocity of the profile at time t. */ State Calculate(const units::second_t& t, const State& current, const State& goal) const; /** - * Calculate the point after which the fastest way to reach the goal state is + * Calculates the point after which the fastest way to reach the goal state is * to apply input in the opposite direction. + * + * @param current The current state. + * @param goal The desired state when the profile is complete. + * @return The position and velocity of the profile at the inflection point. */ State CalculateInflectionPoint(const State& current, const State& goal) const; /** - * Calculate the time it will take for this profile to reach the goal state. + * Calculates the time it will take for this profile to reach the goal state. + * + * @param current The current state. + * @param goal The desired state when the profile is complete. + * @return The total duration of this profile. */ units::second_t TimeLeftUntil(const State& current, const State& goal) const; /** - * Calculate the time it will take for this profile to reach the inflection + * Calculates the time it will take for this profile to reach the inflection * point, and the time it will take for this profile to reach the goal state. + * + * @param current The current state. + * @param goal The desired state when the profile is complete. + * @return The timing information for this profile. */ ProfileTiming CalculateProfileTiming(const State& current, const State& goal) const; private: /** - * Calculate the point after which the fastest way to reach the goal state is + * Calculates the point after which the fastest way to reach the goal state is * to apply input in the opposite direction. + * + * @param current The current state. + * @param goal The desired state when the profile is complete. + * @param input The signed input applied to this profile from the current + * state. + * @return The position and velocity of the profile at the inflection point. */ State CalculateInflectionPoint(const State& current, const State& goal, const Input_t& input) const; /** - * Calculate the time it will take for this profile to reach the inflection + * Calculates the time it will take for this profile to reach the inflection * point, and the time it will take for this profile to reach the goal state. + * + * @param current The current state. + * @param inflectionPoint The inflection point of this profile. + * @param goal The desired state when the profile is complete. + * @param input The signed input applied to this profile from the current + * state. + * @return The timing information for this profile. */ ProfileTiming CalculateProfileTiming(const State& current, const State& inflectionPoint, @@ -140,40 +215,70 @@ class ExponentialProfile { const Input_t& input) const; /** - * Calculate the velocity reached after t seconds when applying an input from + * Calculates the position reached after t seconds when applying an input from * the initial state. + * + * @param t The time since the initial state. + * @param input The signed input applied to this profile from the initial + * state. + * @param initial The initial state. + * @return The distance travelled by this profile. */ - Velocity_t ComputeVelocityFromTime(const units::second_t& time, + Distance_t ComputeDistanceFromTime(const units::second_t& time, const Input_t& input, const State& initial) const; /** - * Calculate the position reached after t seconds when applying an input from + * Calculates the velocity reached after t seconds when applying an input from * the initial state. + * + * @param t The time since the initial state. + * @param input The signed input applied to this profile from the initial + * state. + * @param initial The initial state. + * @return The distance travelled by this profile. */ - Distance_t ComputeDistanceFromTime(const units::second_t& time, + Velocity_t ComputeVelocityFromTime(const units::second_t& time, const Input_t& input, const State& initial) const; /** - * Calculate the distance reached at the same time as the given velocity when + * Calculates the time required to reach a specified velocity given the + * initial velocity. + * + * @param velocity The goal velocity. + * @param input The signed input applied to this profile from the initial + * state. + * @param initial The initial velocity. + * @return The time required to reach the goal velocity. + */ + units::second_t ComputeTimeFromVelocity(const Velocity_t& velocity, + const Input_t& input, + const Velocity_t& initial) const; + + /** + * Calculates the distance reached at the same time as the given velocity when * applying the given input from the initial state. + * + * @param velocity The velocity reached by this profile + * @param input The signed input applied to this profile from the initial + * state. + * @param initial The initial state. + * @return The distance reached when the given velocity is reached. */ Distance_t ComputeDistanceFromVelocity(const Velocity_t& velocity, const Input_t& input, const State& initial) const; /** - * Calculate the time required to reach a specified velocity given the initial - * velocity. - */ - units::second_t ComputeTimeFromVelocity(const Velocity_t& velocity, - const Input_t& input, - const Velocity_t& initial) const; - - /** - * Calculate the velocity at which input should be reversed in order to reach + * Calculates the velocity at which input should be reversed in order to reach * the goal state from the current state. + * + * @param input The signed input applied to this profile from the current + * state. + * @param current The current state. + * @param goal The goal state. + * @return The inflection velocity. */ Velocity_t SolveForInflectionVelocity(const Input_t& input, const State& current, @@ -182,8 +287,11 @@ class ExponentialProfile { /** * Returns true if the profile should be inverted. * - *

    The profile is inverted if we should first apply negative input in order - * to reach the goal state. + * The profile is inverted if we should first apply negative input in order to + * reach the goal state. + * + * @param current The initial state (usually the current state). + * @param goal The desired state when the profile is complete. */ bool ShouldFlipInput(const State& current, const State& goal) const; diff --git a/wpimath/src/main/native/include/frc/trajectory/ExponentialProfile.inc b/wpimath/src/main/native/include/frc/trajectory/ExponentialProfile.inc index ded52452e53..f8fd5f0ac5a 100644 --- a/wpimath/src/main/native/include/frc/trajectory/ExponentialProfile.inc +++ b/wpimath/src/main/native/include/frc/trajectory/ExponentialProfile.inc @@ -50,23 +50,6 @@ ExponentialProfile::CalculateInflectionPoint( return CalculateInflectionPoint(current, goal, u); } -template -typename ExponentialProfile::State -ExponentialProfile::CalculateInflectionPoint( - const State& current, const State& goal, const Input_t& input) const { - auto u = input; - - if (current == goal) { - return current; - } - - auto inflectionVelocity = SolveForInflectionVelocity(u, current, goal); - auto inflectionPosition = - ComputeDistanceFromVelocity(inflectionVelocity, -u, goal); - - return {inflectionPosition, inflectionVelocity}; -} - template units::second_t ExponentialProfile::TimeLeftUntil( const State& current, const State& goal) const { @@ -86,6 +69,23 @@ ExponentialProfile::CalculateProfileTiming( return CalculateProfileTiming(current, inflectionPoint, goal, u); } +template +typename ExponentialProfile::State +ExponentialProfile::CalculateInflectionPoint( + const State& current, const State& goal, const Input_t& input) const { + auto u = input; + + if (current == goal) { + return current; + } + + auto inflectionVelocity = SolveForInflectionVelocity(u, current, goal); + auto inflectionPosition = + ComputeDistanceFromVelocity(inflectionVelocity, -u, goal); + + return {inflectionPosition, inflectionVelocity}; +} + template typename ExponentialProfile::ProfileTiming ExponentialProfile::CalculateProfileTiming( diff --git a/wpimath/src/main/native/include/frc/trajectory/Trajectory.h b/wpimath/src/main/native/include/frc/trajectory/Trajectory.h index ca97593a1ad..753bf9e2d14 100644 --- a/wpimath/src/main/native/include/frc/trajectory/Trajectory.h +++ b/wpimath/src/main/native/include/frc/trajectory/Trajectory.h @@ -28,19 +28,19 @@ class WPILIB_DLLEXPORT Trajectory { * Represents one point on the trajectory. */ struct WPILIB_DLLEXPORT State { - // The time elapsed since the beginning of the trajectory. + /// The time elapsed since the beginning of the trajectory. units::second_t t = 0_s; - // The speed at that point of the trajectory. + /// The speed at that point of the trajectory. units::meters_per_second_t velocity = 0_mps; - // The acceleration at that point of the trajectory. + /// The acceleration at that point of the trajectory. units::meters_per_second_squared_t acceleration = 0_mps_sq; - // The pose at that point of the trajectory. + /// The pose at that point of the trajectory. Pose2d pose; - // The curvature at that point of the trajectory. + /// The curvature at that point of the trajectory. units::curvature_t curvature{0.0}; /** @@ -145,3 +145,6 @@ WPILIB_DLLEXPORT void from_json(const wpi::json& json, Trajectory::State& state); } // namespace frc + +#include "frc/trajectory/proto/TrajectoryProto.h" +#include "frc/trajectory/proto/TrajectoryStateProto.h" diff --git a/wpimath/src/main/native/include/frc/trajectory/TrajectoryUtil.h b/wpimath/src/main/native/include/frc/trajectory/TrajectoryUtil.h index 3ba882f1ac6..48a0a49a9bf 100644 --- a/wpimath/src/main/native/include/frc/trajectory/TrajectoryUtil.h +++ b/wpimath/src/main/native/include/frc/trajectory/TrajectoryUtil.h @@ -12,6 +12,9 @@ #include "frc/trajectory/Trajectory.h" namespace frc { +/** + * Trajectory utilities. + */ class WPILIB_DLLEXPORT TrajectoryUtil { public: TrajectoryUtil() = delete; diff --git a/wpimath/src/main/native/include/frc/trajectory/TrapezoidProfile.h b/wpimath/src/main/native/include/frc/trajectory/TrapezoidProfile.h index 18002462a03..90c5cd973fe 100644 --- a/wpimath/src/main/native/include/frc/trajectory/TrapezoidProfile.h +++ b/wpimath/src/main/native/include/frc/trajectory/TrapezoidProfile.h @@ -4,8 +4,6 @@ #pragma once -#include - #include "units/time.h" #include "wpimath/MathShared.h" @@ -52,61 +50,70 @@ class TrapezoidProfile { units::compound_unit>; using Acceleration_t = units::unit_t; + /** + * Profile constraints. + */ class Constraints { public: + /// Maximum velocity. + Velocity_t maxVelocity{0}; + + /// Maximum acceleration. + Acceleration_t maxAcceleration{0}; + + /** + * Default constructor. + */ Constraints() { wpi::math::MathSharedStore::ReportUsage( wpi::math::MathUsageId::kTrajectory_TrapezoidProfile, 1); } - Constraints(Velocity_t maxVelocity_, Acceleration_t maxAcceleration_) - : maxVelocity{maxVelocity_}, maxAcceleration{maxAcceleration_} { + + /** + * Constructs constraints for a Trapezoid Profile. + * + * @param maxVelocity Maximum velocity. + * @param maxAcceleration Maximum acceleration. + */ + Constraints(Velocity_t maxVelocity, Acceleration_t maxAcceleration) + : maxVelocity{maxVelocity}, maxAcceleration{maxAcceleration} { wpi::math::MathSharedStore::ReportUsage( wpi::math::MathUsageId::kTrajectory_TrapezoidProfile, 1); } - Velocity_t maxVelocity{0}; - Acceleration_t maxAcceleration{0}; }; + /** + * Profile state. + */ class State { public: + /// The position at this state. Distance_t position{0}; + + /// The velocity at this state. Velocity_t velocity{0}; + bool operator==(const State&) const = default; }; /** - * Construct a TrapezoidProfile. + * Constructs a TrapezoidProfile. * * @param constraints The constraints on the profile, like maximum velocity. */ TrapezoidProfile(Constraints constraints); // NOLINT - - /** - * Construct a TrapezoidProfile. - * - * @param constraints The constraints on the profile, like maximum velocity. - * @param goal The desired state when the profile is complete. - * @param initial The initial state (usually the current state). - * @deprecated Pass the desired and current state into calculate instead of - * constructing a new TrapezoidProfile with the desired and current state - */ - WPI_DEPRECATED( - "Pass the desired and current state into calculate instead of " - "constructing a new TrapezoidProfile with the desired and current " - "state") - TrapezoidProfile(Constraints constraints, State goal, - State initial = State{Distance_t{0}, Velocity_t{0}}); - TrapezoidProfile(const TrapezoidProfile&) = default; TrapezoidProfile& operator=(const TrapezoidProfile&) = default; TrapezoidProfile(TrapezoidProfile&&) = default; TrapezoidProfile& operator=(TrapezoidProfile&&) = default; /** - * Calculate the correct position and velocity for the profile at a time t - * where the beginning of the profile was at time t = 0. + * Calculates the position and velocity for the profile at a time t where the + * current state is at time t = 0. * - * @param t The time since the beginning of the profile. + * @param t How long to advance from the current state toward the desired + * state. + * @return The position and velocity of the profile at time t. * @deprecated Pass the desired and current state into calculate instead of * constructing a new TrapezoidProfile with the desired and current state */ @@ -117,12 +124,14 @@ class TrapezoidProfile { State Calculate(units::second_t t) const; /** - * Calculate the correct position and velocity for the profile at a time t - * where the beginning of the profile was at time t = 0. + * Calculates the position and velocity for the profile at a time t where the + * current state is at time t = 0. * - * @param t The time since the beginning of the profile. - * @param current The initial state (usually the current state). - * @param goal The desired state when the profile is complete. + * @param t How long to advance from the current state toward the desired + * state. + * @param current The current state. + * @param goal The desired state when the profile is complete. + * @return The position and velocity of the profile at time t. */ State Calculate(units::second_t t, State current, State goal); @@ -130,21 +139,25 @@ class TrapezoidProfile { * Returns the time left until a target distance in the profile is reached. * * @param target The target distance. + * @return The time left until a target distance in the profile is reached. */ units::second_t TimeLeftUntil(Distance_t target) const; /** * Returns the total time the profile takes to reach the goal. + * + * @return The total time the profile takes to reach the goal. */ units::second_t TotalTime() const { return m_endDeccel; } /** * Returns true if the profile has reached the goal. * - * The profile has reached the goal if the time since the profile started - * has exceeded the profile's total time. + * The profile has reached the goal if the time since the profile started has + * exceeded the profile's total time. * * @param t The time since the beginning of the profile. + * @return True if the profile has reached the goal. */ bool IsFinished(units::second_t t) const { return t >= TotalTime(); } @@ -155,7 +168,7 @@ class TrapezoidProfile { * The profile is inverted if goal position is less than the initial position. * * @param initial The initial state (usually the current state). - * @param goal The desired state when the profile is complete. + * @param goal The desired state when the profile is complete. */ static bool ShouldFlipAcceleration(const State& initial, const State& goal) { return initial.position > goal.position; @@ -174,8 +187,6 @@ class TrapezoidProfile { Constraints m_constraints; State m_current; - State m_goal; // TODO: remove - bool m_newAPI; // TODO: remove units::second_t m_endAccel; units::second_t m_endFullSpeed; diff --git a/wpimath/src/main/native/include/frc/trajectory/TrapezoidProfile.inc b/wpimath/src/main/native/include/frc/trajectory/TrapezoidProfile.inc index c970a791d57..75e76d9eeed 100644 --- a/wpimath/src/main/native/include/frc/trajectory/TrapezoidProfile.inc +++ b/wpimath/src/main/native/include/frc/trajectory/TrapezoidProfile.inc @@ -12,89 +12,8 @@ namespace frc { template TrapezoidProfile::TrapezoidProfile(Constraints constraints) - : m_constraints(constraints), m_newAPI(true) {} + : m_constraints(constraints) {} -template -TrapezoidProfile::TrapezoidProfile(Constraints constraints, - State goal, State initial) - : m_direction{ShouldFlipAcceleration(initial, goal) ? -1 : 1}, - m_constraints(constraints), - m_current(Direct(initial)), - m_goal(Direct(goal)), - m_newAPI(false) { - if (m_current.velocity > m_constraints.maxVelocity) { - m_current.velocity = m_constraints.maxVelocity; - } - - // Deal with a possibly truncated motion profile (with nonzero initial or - // final velocity) by calculating the parameters as if the profile began and - // ended at zero velocity - units::second_t cutoffBegin = - m_current.velocity / m_constraints.maxAcceleration; - Distance_t cutoffDistBegin = - cutoffBegin * cutoffBegin * m_constraints.maxAcceleration / 2.0; - - units::second_t cutoffEnd = m_goal.velocity / m_constraints.maxAcceleration; - Distance_t cutoffDistEnd = - cutoffEnd * cutoffEnd * m_constraints.maxAcceleration / 2.0; - - // Now we can calculate the parameters as if it was a full trapezoid instead - // of a truncated one - - Distance_t fullTrapezoidDist = - cutoffDistBegin + (m_goal.position - m_current.position) + cutoffDistEnd; - units::second_t accelerationTime = - m_constraints.maxVelocity / m_constraints.maxAcceleration; - - Distance_t fullSpeedDist = - fullTrapezoidDist - - accelerationTime * accelerationTime * m_constraints.maxAcceleration; - - // Handle the case where the profile never reaches full speed - if (fullSpeedDist < Distance_t{0}) { - accelerationTime = - units::math::sqrt(fullTrapezoidDist / m_constraints.maxAcceleration); - fullSpeedDist = Distance_t{0}; - } - - m_endAccel = accelerationTime - cutoffBegin; - m_endFullSpeed = m_endAccel + fullSpeedDist / m_constraints.maxVelocity; - m_endDeccel = m_endFullSpeed + accelerationTime - cutoffEnd; -} - -template -typename TrapezoidProfile::State -TrapezoidProfile::Calculate(units::second_t t) const { - if (m_newAPI) { - throw std::runtime_error( - "Cannot use new constructor with deprecated Calculate()"); - } - State result = m_current; - - if (t < m_endAccel) { - result.velocity += t * m_constraints.maxAcceleration; - result.position += - (m_current.velocity + t * m_constraints.maxAcceleration / 2.0) * t; - } else if (t < m_endFullSpeed) { - result.velocity = m_constraints.maxVelocity; - result.position += (m_current.velocity + - m_endAccel * m_constraints.maxAcceleration / 2.0) * - m_endAccel + - m_constraints.maxVelocity * (t - m_endAccel); - } else if (t <= m_endDeccel) { - result.velocity = - m_goal.velocity + (m_endDeccel - t) * m_constraints.maxAcceleration; - units::second_t timeLeft = m_endDeccel - t; - result.position = - m_goal.position - - (m_goal.velocity + timeLeft * m_constraints.maxAcceleration / 2.0) * - timeLeft; - } else { - result = m_goal; - } - - return Direct(result); -} template typename TrapezoidProfile::State TrapezoidProfile::Calculate(units::second_t t, State current, diff --git a/wpimath/src/main/native/include/frc/trajectory/proto/TrajectoryProto.h b/wpimath/src/main/native/include/frc/trajectory/proto/TrajectoryProto.h new file mode 100644 index 00000000000..4b485b2a922 --- /dev/null +++ b/wpimath/src/main/native/include/frc/trajectory/proto/TrajectoryProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/trajectory/Trajectory.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Trajectory Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::Trajectory& value); +}; diff --git a/wpimath/src/main/native/include/frc/trajectory/proto/TrajectoryStateProto.h b/wpimath/src/main/native/include/frc/trajectory/proto/TrajectoryStateProto.h new file mode 100644 index 00000000000..150837b8d3e --- /dev/null +++ b/wpimath/src/main/native/include/frc/trajectory/proto/TrajectoryStateProto.h @@ -0,0 +1,18 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#pragma once + +#include +#include + +#include "frc/trajectory/Trajectory.h" + +template <> +struct WPILIB_DLLEXPORT wpi::Protobuf { + static google::protobuf::Message* New(google::protobuf::Arena* arena); + static frc::Trajectory::State Unpack(const google::protobuf::Message& msg); + static void Pack(google::protobuf::Message* msg, + const frc::Trajectory::State& value); +}; diff --git a/wpimath/src/main/native/include/units/base.h b/wpimath/src/main/native/include/units/base.h index 34cd59e4198..e7333a91ee4 100644 --- a/wpimath/src/main/native/include/units/base.h +++ b/wpimath/src/main/native/include/units/base.h @@ -53,7 +53,6 @@ #if !defined(_MSC_VER) || _MSC_VER > 1800 # define UNIT_HAS_LITERAL_SUPPORT -# define UNIT_HAS_VARIADIC_TEMPLATE_SUPPORT #endif #ifndef UNIT_LIB_DEFAULT_TYPE @@ -82,6 +81,8 @@ #include #endif +#include + //------------------------------ // STRING FORMATTER //------------------------------ @@ -358,25 +359,14 @@ template<> inline constexpr const char* abbreviation(const namespaceName::nameSi /** @endcond */\ } -#if defined(UNIT_HAS_VARIADIC_TEMPLATE_SUPPORT) #define UNIT_ADD_IS_UNIT_CATEGORY_TRAIT(unitCategory)\ namespace traits\ {\ template struct is_ ## unitCategory ## _unit : std::integral_constant>::value...>::value> {};\ template inline constexpr bool is_ ## unitCategory ## _unit_v = is_ ## unitCategory ## _unit::value;\ - } -#else -#define UNIT_ADD_IS_UNIT_CATEGORY_TRAIT(unitCategory)\ - namespace traits\ - {\ - template\ - struct is_ ## unitCategory ## _unit : std::integral_constant::type>::value &&\ - units::traits::detail::is_ ## unitCategory ## _unit_impl::type>::value &&\ - units::traits::detail::is_ ## unitCategory ## _unit_impl::type>::value>{};\ - template\ - inline constexpr bool is_ ## unitCategory ## _unit_v = is_ ## unitCategory ## _unit::value;\ - } -#endif + }\ + template \ + concept unitCategory ## _unit = traits::is_ ## unitCategory ## _unit_v; #define UNIT_ADD_CATEGORY_TRAIT(unitCategory)\ UNIT_ADD_CATEGORY_TRAIT_DETAIL(unitCategory)\ @@ -2815,10 +2805,10 @@ namespace units * @returns new unit_t, raised to the given exponent */ template::value, int>> - inline auto pow(const UnitType& value) noexcept -> unit_t::unit_type>::type, typename units::traits::unit_t_traits::underlying_type, linear_scale> + inline constexpr auto pow(const UnitType& value) noexcept -> unit_t::unit_type>::type, typename units::traits::unit_t_traits::underlying_type, linear_scale> { return unit_t::unit_type>::type, typename units::traits::unit_t_traits::underlying_type, linear_scale> - (std::pow(value(), power)); + (gcem::pow(value(), power)); } /** diff --git a/wpimath/src/main/native/include/units/formatter.h b/wpimath/src/main/native/include/units/formatter.h index 1c17b0a1856..e7f69910a0f 100644 --- a/wpimath/src/main/native/include/units/formatter.h +++ b/wpimath/src/main/native/include/units/formatter.h @@ -20,7 +20,8 @@ template struct fmt::formatter>> { - constexpr auto parse(fmt::format_parse_context& ctx) { + template + constexpr auto parse(ParseContext& ctx) { return m_underlying.parse(ctx); } @@ -30,7 +31,8 @@ struct fmt::formatter + auto format(const Unit& obj, FmtContext& ctx) const { using Units = typename Unit::unit_type; using BaseUnits = units::unit, diff --git a/wpimath/src/main/native/include/units/math.h b/wpimath/src/main/native/include/units/math.h index 995335bbb59..a5cf357b5f0 100644 --- a/wpimath/src/main/native/include/units/math.h +++ b/wpimath/src/main/native/include/units/math.h @@ -28,6 +28,8 @@ #include +#include + #include "units/angle.h" #include "units/base.h" #include "units/dimensionless.h" @@ -58,12 +60,12 @@ namespace units::math { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -dimensionless::scalar_t cos(const AngleUnit angle) noexcept { +constexpr dimensionless::scalar_t cos(const AngleUnit angle) noexcept { static_assert( traits::is_angle_unit::value, "Type `AngleUnit` must be a unit of angle derived from `unit_t`."); return dimensionless::scalar_t( - std::cos(angle.template convert()())); + gcem::cos(angle.template convert()())); } #endif @@ -78,12 +80,12 @@ dimensionless::scalar_t cos(const AngleUnit angle) noexcept { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -dimensionless::scalar_t sin(const AngleUnit angle) noexcept { +constexpr dimensionless::scalar_t sin(const AngleUnit angle) noexcept { static_assert( traits::is_angle_unit::value, "Type `AngleUnit` must be a unit of angle derived from `unit_t`."); return dimensionless::scalar_t( - std::sin(angle.template convert()())); + gcem::sin(angle.template convert()())); } #endif /** @@ -97,12 +99,12 @@ dimensionless::scalar_t sin(const AngleUnit angle) noexcept { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -dimensionless::scalar_t tan(const AngleUnit angle) noexcept { +constexpr dimensionless::scalar_t tan(const AngleUnit angle) noexcept { static_assert( traits::is_angle_unit::value, "Type `AngleUnit` must be a unit of angle derived from `unit_t`."); return dimensionless::scalar_t( - std::tan(angle.template convert()())); + gcem::tan(angle.template convert()())); } #endif @@ -116,11 +118,11 @@ dimensionless::scalar_t tan(const AngleUnit angle) noexcept { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -angle::radian_t acos(const ScalarUnit x) noexcept { +constexpr angle::radian_t acos(const ScalarUnit x) noexcept { static_assert( traits::is_dimensionless_unit::value, "Type `ScalarUnit` must be a dimensionless unit derived from `unit_t`."); - return angle::radian_t(std::acos(x())); + return angle::radian_t(gcem::acos(x())); } #endif @@ -134,11 +136,11 @@ angle::radian_t acos(const ScalarUnit x) noexcept { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -angle::radian_t asin(const ScalarUnit x) noexcept { +constexpr angle::radian_t asin(const ScalarUnit x) noexcept { static_assert( traits::is_dimensionless_unit::value, "Type `ScalarUnit` must be a dimensionless unit derived from `unit_t`."); - return angle::radian_t(std::asin(x())); + return angle::radian_t(gcem::asin(x())); } #endif @@ -156,11 +158,11 @@ angle::radian_t asin(const ScalarUnit x) noexcept { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -angle::radian_t atan(const ScalarUnit x) noexcept { +constexpr angle::radian_t atan(const ScalarUnit x) noexcept { static_assert( traits::is_dimensionless_unit::value, "Type `ScalarUnit` must be a dimensionless unit derived from `unit_t`."); - return angle::radian_t(std::atan(x())); + return angle::radian_t(gcem::atan(x())); } #endif @@ -176,15 +178,15 @@ angle::radian_t atan(const ScalarUnit x) noexcept { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -angle::radian_t atan2(const Y y, const X x) noexcept { +constexpr angle::radian_t atan2(const Y y, const X x) noexcept { static_assert(traits::is_dimensionless_unit::value, "The quantity y/x must yield a dimensionless ratio."); // X and Y could be different length units, so normalize them return angle::radian_t( - std::atan2(y.template convert< - typename units::traits::unit_t_traits::unit_type>()(), - x())); + gcem::atan2(y.template convert< + typename units::traits::unit_t_traits::unit_type>()(), + x())); } #endif @@ -203,12 +205,12 @@ angle::radian_t atan2(const Y y, const X x) noexcept { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -dimensionless::scalar_t cosh(const AngleUnit angle) noexcept { +constexpr dimensionless::scalar_t cosh(const AngleUnit angle) noexcept { static_assert( traits::is_angle_unit::value, "Type `AngleUnit` must be a unit of angle derived from `unit_t`."); return dimensionless::scalar_t( - std::cosh(angle.template convert()())); + gcem::cosh(angle.template convert()())); } #endif @@ -223,12 +225,12 @@ dimensionless::scalar_t cosh(const AngleUnit angle) noexcept { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -dimensionless::scalar_t sinh(const AngleUnit angle) noexcept { +constexpr dimensionless::scalar_t sinh(const AngleUnit angle) noexcept { static_assert( traits::is_angle_unit::value, "Type `AngleUnit` must be a unit of angle derived from `unit_t`."); return dimensionless::scalar_t( - std::sinh(angle.template convert()())); + gcem::sinh(angle.template convert()())); } #endif @@ -243,12 +245,12 @@ dimensionless::scalar_t sinh(const AngleUnit angle) noexcept { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -dimensionless::scalar_t tanh(const AngleUnit angle) noexcept { +constexpr dimensionless::scalar_t tanh(const AngleUnit angle) noexcept { static_assert( traits::is_angle_unit::value, "Type `AngleUnit` must be a unit of angle derived from `unit_t`."); return dimensionless::scalar_t( - std::tanh(angle.template convert()())); + gcem::tanh(angle.template convert()())); } #endif @@ -264,11 +266,11 @@ dimensionless::scalar_t tanh(const AngleUnit angle) noexcept { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -angle::radian_t acosh(const ScalarUnit x) noexcept { +constexpr angle::radian_t acosh(const ScalarUnit x) noexcept { static_assert( traits::is_dimensionless_unit::value, "Type `ScalarUnit` must be a dimensionless unit derived from `unit_t`."); - return angle::radian_t(std::acosh(x())); + return angle::radian_t(gcem::acosh(x())); } #endif @@ -281,11 +283,11 @@ angle::radian_t acosh(const ScalarUnit x) noexcept { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -angle::radian_t asinh(const ScalarUnit x) noexcept { +constexpr angle::radian_t asinh(const ScalarUnit x) noexcept { static_assert( traits::is_dimensionless_unit::value, "Type `ScalarUnit` must be a dimensionless unit derived from `unit_t`."); - return angle::radian_t(std::asinh(x())); + return angle::radian_t(gcem::asinh(x())); } #endif @@ -300,11 +302,11 @@ angle::radian_t asinh(const ScalarUnit x) noexcept { */ #if !defined(DISABLE_PREDEFINED_UNITS) || defined(ENABLE_PREDEFINED_ANGLE_UNITS) template -angle::radian_t atanh(const ScalarUnit x) noexcept { +constexpr angle::radian_t atanh(const ScalarUnit x) noexcept { static_assert( traits::is_dimensionless_unit::value, "Type `ScalarUnit` must be a dimensionless unit derived from `unit_t`."); - return angle::radian_t(std::atanh(x())); + return angle::radian_t(gcem::atanh(x())); } #endif @@ -329,11 +331,11 @@ angle::radian_t atanh(const ScalarUnit x) noexcept { * error occurs. */ template -dimensionless::scalar_t exp(const ScalarUnit x) noexcept { +constexpr dimensionless::scalar_t exp(const ScalarUnit x) noexcept { static_assert( traits::is_dimensionless_unit::value, "Type `ScalarUnit` must be a dimensionless unit derived from `unit_t`."); - return dimensionless::scalar_t(std::exp(x())); + return dimensionless::scalar_t(gcem::exp(x())); } /** @@ -346,11 +348,11 @@ dimensionless::scalar_t exp(const ScalarUnit x) noexcept { * @returns Natural logarithm of x. */ template -dimensionless::scalar_t log(const ScalarUnit x) noexcept { +constexpr dimensionless::scalar_t log(const ScalarUnit x) noexcept { static_assert( traits::is_dimensionless_unit::value, "Type `ScalarUnit` must be a dimensionless unit derived from `unit_t`."); - return dimensionless::scalar_t(std::log(x())); + return dimensionless::scalar_t(gcem::log(x())); } /** @@ -362,11 +364,11 @@ dimensionless::scalar_t log(const ScalarUnit x) noexcept { * @returns Common logarithm of x. */ template -dimensionless::scalar_t log10(const ScalarUnit x) noexcept { +constexpr dimensionless::scalar_t log10(const ScalarUnit x) noexcept { static_assert( traits::is_dimensionless_unit::value, "Type `ScalarUnit` must be a dimensionless unit derived from `unit_t`."); - return dimensionless::scalar_t(std::log10(x())); + return dimensionless::scalar_t(gcem::log10(x())); } /** @@ -417,11 +419,11 @@ dimensionless::scalar_t exp2(const ScalarUnit x) noexcept { * @returns e raised to the power of x, minus one. */ template -dimensionless::scalar_t expm1(const ScalarUnit x) noexcept { +constexpr dimensionless::scalar_t expm1(const ScalarUnit x) noexcept { static_assert( traits::is_dimensionless_unit::value, "Type `ScalarUnit` must be a dimensionless unit derived from `unit_t`."); - return dimensionless::scalar_t(std::expm1(x())); + return dimensionless::scalar_t(gcem::expm1(x())); } /** @@ -434,11 +436,11 @@ dimensionless::scalar_t expm1(const ScalarUnit x) noexcept { * @returns The natural logarithm of (1+x). */ template -dimensionless::scalar_t log1p(const ScalarUnit x) noexcept { +constexpr dimensionless::scalar_t log1p(const ScalarUnit x) noexcept { static_assert( traits::is_dimensionless_unit::value, "Type `ScalarUnit` must be a dimensionless unit derived from `unit_t`."); - return dimensionless::scalar_t(std::log1p(x())); + return dimensionless::scalar_t(gcem::log1p(x())); } /** @@ -450,11 +452,11 @@ dimensionless::scalar_t log1p(const ScalarUnit x) noexcept { * @returns The binary logarithm of x: log2x. */ template -dimensionless::scalar_t log2(const ScalarUnit x) noexcept { +constexpr dimensionless::scalar_t log2(const ScalarUnit x) noexcept { static_assert( traits::is_dimensionless_unit::value, "Type `ScalarUnit` must be a dimensionless unit derived from `unit_t`."); - return dimensionless::scalar_t(std::log2(x())); + return dimensionless::scalar_t(gcem::log2(x())); } //---------------------------------- @@ -480,14 +482,15 @@ dimensionless::scalar_t log2(const ScalarUnit x) noexcept { template < class UnitType, std::enable_if_t::value, int> = 0> -inline auto sqrt(const UnitType& value) noexcept -> unit_t< - square_root::unit_type>, - typename units::traits::unit_t_traits::underlying_type, - linear_scale> { +inline constexpr auto sqrt(const UnitType& value) noexcept + -> unit_t< + square_root::unit_type>, + typename units::traits::unit_t_traits::underlying_type, + linear_scale> { return unit_t< square_root::unit_type>, typename units::traits::unit_t_traits::underlying_type, - linear_scale>(std::sqrt(value())); + linear_scale>(gcem::sqrt(value())); } /** @@ -502,10 +505,10 @@ template ::value, int> = 0> -inline UnitTypeLhs hypot(const UnitTypeLhs& x, const UnitTypeRhs& y) { +inline constexpr UnitTypeLhs hypot(const UnitTypeLhs& x, const UnitTypeRhs& y) { static_assert(traits::is_convertible_unit_t::value, "Parameters of hypot() function are not compatible units."); - return UnitTypeLhs(std::hypot( + return UnitTypeLhs(gcem::hypot( x(), y.template convert< typename units::traits::unit_t_traits::unit_type>()())); @@ -525,8 +528,8 @@ inline UnitTypeLhs hypot(const UnitTypeLhs& x, const UnitTypeRhs& y) { */ template ::value>> -UnitType ceil(const UnitType x) noexcept { - return UnitType(std::ceil(x())); +constexpr UnitType ceil(const UnitType x) noexcept { + return UnitType(gcem::ceil(x())); } /** @@ -539,8 +542,8 @@ UnitType ceil(const UnitType x) noexcept { */ template ::value>> -UnitType floor(const UnitType x) noexcept { - return UnitType(std::floor(x())); +constexpr UnitType floor(const UnitType x) noexcept { + return UnitType(gcem::floor(x())); } /** @@ -555,10 +558,11 @@ UnitType floor(const UnitType x) noexcept { template ::value && traits::is_unit_t::value>> -UnitTypeLhs fmod(const UnitTypeLhs numer, const UnitTypeRhs denom) noexcept { +constexpr UnitTypeLhs fmod(const UnitTypeLhs numer, + const UnitTypeRhs denom) noexcept { static_assert(traits::is_convertible_unit_t::value, "Parameters of fmod() function are not compatible units."); - return UnitTypeLhs(std::fmod( + return UnitTypeLhs(gcem::fmod( numer(), denom.template convert< typename units::traits::unit_t_traits::unit_type>()())); @@ -574,8 +578,8 @@ UnitTypeLhs fmod(const UnitTypeLhs numer, const UnitTypeRhs denom) noexcept { */ template ::value>> -UnitType trunc(const UnitType x) noexcept { - return UnitType(std::trunc(x())); +constexpr UnitType trunc(const UnitType x) noexcept { + return UnitType(gcem::trunc(x())); } /** @@ -588,8 +592,8 @@ UnitType trunc(const UnitType x) noexcept { */ template ::value>> -UnitType round(const UnitType x) noexcept { - return UnitType(std::round(x())); +constexpr UnitType round(const UnitType x) noexcept { + return UnitType(gcem::round(x())); } //---------------------------------- @@ -608,17 +612,18 @@ UnitType round(const UnitType x) noexcept { template ::value && traits::is_unit_t::value>> -UnitTypeLhs copysign(const UnitTypeLhs x, const UnitTypeRhs y) noexcept { - return UnitTypeLhs(std::copysign( +constexpr UnitTypeLhs copysign(const UnitTypeLhs x, + const UnitTypeRhs y) noexcept { + return UnitTypeLhs(gcem::copysign( x(), y())); // no need for conversion to get the correct sign. } /// Overload to copy the sign from a raw double template ::value>> -UnitTypeLhs copysign(const UnitTypeLhs x, - const UNIT_LIB_DEFAULT_TYPE y) noexcept { - return UnitTypeLhs(std::copysign(x(), y)); +constexpr UnitTypeLhs copysign(const UnitTypeLhs x, + const UNIT_LIB_DEFAULT_TYPE y) noexcept { + return UnitTypeLhs(gcem::copysign(x(), y)); } //---------------------------------- @@ -660,10 +665,10 @@ UnitTypeLhs fdim(const UnitTypeLhs x, const UnitTypeRhs y) noexcept { template ::value && traits::is_unit_t::value>> -UnitTypeLhs fmax(const UnitTypeLhs x, const UnitTypeRhs y) noexcept { +constexpr UnitTypeLhs fmax(const UnitTypeLhs x, const UnitTypeRhs y) noexcept { static_assert(traits::is_convertible_unit_t::value, "Parameters of fmax() function are not compatible units."); - return UnitTypeLhs(std::fmax( + return UnitTypeLhs(gcem::max( x(), y.template convert< typename units::traits::unit_t_traits::unit_type>()())); @@ -683,10 +688,10 @@ UnitTypeLhs fmax(const UnitTypeLhs x, const UnitTypeRhs y) noexcept { template ::value && traits::is_unit_t::value>> -UnitTypeLhs fmin(const UnitTypeLhs x, const UnitTypeRhs y) noexcept { +constexpr UnitTypeLhs fmin(const UnitTypeLhs x, const UnitTypeRhs y) noexcept { static_assert(traits::is_convertible_unit_t::value, "Parameters of fmin() function are not compatible units."); - return UnitTypeLhs(std::fmin( + return UnitTypeLhs(gcem::min( x(), y.template convert< typename units::traits::unit_t_traits::unit_type>()())); @@ -705,8 +710,8 @@ UnitTypeLhs fmin(const UnitTypeLhs x, const UnitTypeRhs y) noexcept { */ template ::value>> -UnitType fabs(const UnitType x) noexcept { - return UnitType(std::fabs(x())); +constexpr UnitType fabs(const UnitType x) noexcept { + return UnitType(gcem::abs(x())); } /** @@ -718,8 +723,8 @@ UnitType fabs(const UnitType x) noexcept { */ template ::value>> -UnitType abs(const UnitType x) noexcept { - return UnitType(std::fabs(x())); +constexpr UnitType abs(const UnitType x) noexcept { + return UnitType(gcem::abs(x())); } /** @@ -737,8 +742,8 @@ template ::value && traits::is_unit_t::value && traits::is_unit_t::value>> -auto fma(const UnitTypeLhs x, const UnitMultiply y, const UnitAdd z) noexcept - -> decltype(x * y) { +auto fma(const UnitTypeLhs x, const UnitMultiply y, + const UnitAdd z) noexcept -> decltype(x * y) { using resultType = decltype(x * y); static_assert( traits::is_convertible_unit_t< diff --git a/wpimath/src/main/native/thirdparty/eigen/include/.clang-format b/wpimath/src/main/native/thirdparty/eigen/include/.clang-format new file mode 100644 index 00000000000..28251c665a2 --- /dev/null +++ b/wpimath/src/main/native/thirdparty/eigen/include/.clang-format @@ -0,0 +1,12 @@ +--- +Language: Cpp +BasedOnStyle: Google +ColumnLimit: 120 +SortIncludes: false +AttributeMacros: +- EIGEN_STRONG_INLINE +- EIGEN_ALWAYS_INLINE +- EIGEN_DEVICE_FUNC +- EIGEN_DONT_INLINE +- EIGEN_DEPRECATED +- EIGEN_UNUSED diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Cholesky b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Cholesky index ef249de7bc7..c3bf8452837 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Cholesky +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Cholesky @@ -14,32 +14,30 @@ #include "src/Core/util/DisableStupidWarnings.h" /** \defgroup Cholesky_Module Cholesky module - * - * - * - * This module provides two variants of the Cholesky decomposition for selfadjoint (hermitian) matrices. - * Those decompositions are also accessible via the following methods: - * - MatrixBase::llt() - * - MatrixBase::ldlt() - * - SelfAdjointView::llt() - * - SelfAdjointView::ldlt() - * - * \code - * #include - * \endcode - */ + * + * + * + * This module provides two variants of the Cholesky decomposition for selfadjoint (hermitian) matrices. + * Those decompositions are also accessible via the following methods: + * - MatrixBase::llt() + * - MatrixBase::ldlt() + * - SelfAdjointView::llt() + * - SelfAdjointView::ldlt() + * + * \code + * #include + * \endcode + */ +// IWYU pragma: begin_exports #include "src/Cholesky/LLT.h" #include "src/Cholesky/LDLT.h" #ifdef EIGEN_USE_LAPACKE -#ifdef EIGEN_USE_MKL -// #include "mkl_lapacke.h" -#else -// #include "src/misc/lapacke.h" -#endif +// #include "src/misc/lapacke_helpers.h" // #include "src/Cholesky/LLT_LAPACKE.h" #endif +// IWYU pragma: end_exports #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_CHOLESKY_MODULE_H +#endif // EIGEN_CHOLESKY_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Core b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Core index fd5e098cb75..fdd4472c390 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Core +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Core @@ -8,8 +8,8 @@ // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -#ifndef EIGEN_CORE_H -#define EIGEN_CORE_H +#ifndef EIGEN_CORE_MODULE_H +#define EIGEN_CORE_MODULE_H // first thing Eigen does: stop the compiler from reporting useless warnings. #include "src/Core/util/DisableStupidWarnings.h" @@ -24,27 +24,25 @@ // We need cuda_runtime.h/hip_runtime.h to ensure that // the EIGEN_USING_STD macro works properly on the device side #if defined(EIGEN_CUDACC) - #include +#include #elif defined(EIGEN_HIPCC) - #include +#include #endif - #ifdef EIGEN_EXCEPTIONS - #include +#include #endif -// Disable the ipa-cp-clone optimization flag with MinGW 6.x or newer (enabled by default with -O3) +// Disable the ipa-cp-clone optimization flag with MinGW 6.x or older (enabled by default with -O3) // See http://eigen.tuxfamily.org/bz/show_bug.cgi?id=556 for details. -#if EIGEN_COMP_MINGW && EIGEN_GNUC_AT_LEAST(4,6) && EIGEN_GNUC_AT_MOST(5,5) - #pragma GCC optimize ("-fno-ipa-cp-clone") +#if EIGEN_COMP_MINGW && EIGEN_GNUC_STRICT_LESS_THAN(6, 0, 0) +#pragma GCC optimize("-fno-ipa-cp-clone") #endif // Prevent ICC from specializing std::complex operators that silently fail // on device. This allows us to use our own device-compatible specializations // instead. -#if defined(EIGEN_COMP_ICC) && defined(EIGEN_GPU_COMPILE_PHASE) \ - && !defined(_OVERRIDE_COMPLEX_SPECIALIZATION_) +#if EIGEN_COMP_ICC && defined(EIGEN_GPU_COMPILE_PHASE) && !defined(_OVERRIDE_COMPLEX_SPECIALIZATION_) #define _OVERRIDE_COMPLEX_SPECIALIZATION_ 1 #endif #include @@ -53,20 +51,20 @@ // and inclusion of their respective header files // #include "src/Core/util/MKL_support.h" - #if defined(EIGEN_HAS_CUDA_FP16) || defined(EIGEN_HAS_HIP_FP16) - #define EIGEN_HAS_GPU_FP16 +#define EIGEN_HAS_GPU_FP16 #endif #if defined(EIGEN_HAS_CUDA_BF16) || defined(EIGEN_HAS_HIP_BF16) - #define EIGEN_HAS_GPU_BF16 +#define EIGEN_HAS_GPU_BF16 #endif #if (defined _OPENMP) && (!defined EIGEN_DONT_PARALLELIZE) - #define EIGEN_HAS_OPENMP +#define EIGEN_HAS_OPENMP #endif #ifdef EIGEN_HAS_OPENMP +#include #include #endif @@ -81,27 +79,23 @@ #include #include #include -#include #include -#include #ifndef EIGEN_NO_IO - #include +#include +#include #endif #include #include #include -#include // for CHAR_BIT +#include // for CHAR_BIT // for min/max: #include -#if EIGEN_HAS_CXX11 #include -#endif +#include // for std::is_nothrow_move_assignable -#ifdef EIGEN_INCLUDE_TYPE_TRAITS #include -#endif // for outputting debug info #ifdef EIGEN_DEBUG_ASSIGN @@ -109,31 +103,33 @@ #endif // required for __cpuid, needs to be included after cmath -#if EIGEN_COMP_MSVC && EIGEN_ARCH_i386_OR_x86_64 && !EIGEN_OS_WINCE - #include +// also required for _BitScanReverse on Windows on ARM +#if EIGEN_COMP_MSVC && (EIGEN_ARCH_i386_OR_x86_64 || EIGEN_ARCH_ARM64) && !EIGEN_OS_WINCE +#include #endif #if defined(EIGEN_USE_SYCL) - #undef min - #undef max - #undef isnan - #undef isinf - #undef isfinite - #include - #include - #include - #include - #include - #ifndef EIGEN_SYCL_LOCAL_THREAD_DIM0 - #define EIGEN_SYCL_LOCAL_THREAD_DIM0 16 - #endif - #ifndef EIGEN_SYCL_LOCAL_THREAD_DIM1 - #define EIGEN_SYCL_LOCAL_THREAD_DIM1 16 - #endif -#endif - - -#if defined EIGEN2_SUPPORT_STAGE40_FULL_EIGEN3_STRICTNESS || defined EIGEN2_SUPPORT_STAGE30_FULL_EIGEN3_API || defined EIGEN2_SUPPORT_STAGE20_RESOLVE_API_CONFLICTS || defined EIGEN2_SUPPORT_STAGE10_FULL_EIGEN2_API || defined EIGEN2_SUPPORT +#undef min +#undef max +#undef isnan +#undef isinf +#undef isfinite +#include +#include +#include +#include +#include +#ifndef EIGEN_SYCL_LOCAL_THREAD_DIM0 +#define EIGEN_SYCL_LOCAL_THREAD_DIM0 16 +#endif +#ifndef EIGEN_SYCL_LOCAL_THREAD_DIM1 +#define EIGEN_SYCL_LOCAL_THREAD_DIM1 16 +#endif +#endif + +#if defined EIGEN2_SUPPORT_STAGE40_FULL_EIGEN3_STRICTNESS || defined EIGEN2_SUPPORT_STAGE30_FULL_EIGEN3_API || \ + defined EIGEN2_SUPPORT_STAGE20_RESOLVE_API_CONFLICTS || defined EIGEN2_SUPPORT_STAGE10_FULL_EIGEN2_API || \ + defined EIGEN2_SUPPORT // This will generate an error message: #error Eigen2-support is only available up to version 3.2. Please go to "http://eigen.tuxfamily.org/index.php?title=Eigen2" for further information #endif @@ -146,102 +142,121 @@ using std::size_t; // gcc 4.6.0 wants std:: for ptrdiff_t using std::ptrdiff_t; -} +} // namespace Eigen /** \defgroup Core_Module Core module - * This is the main module of Eigen providing dense matrix and vector support - * (both fixed and dynamic size) with all the features corresponding to a BLAS library - * and much more... - * - * \code - * #include - * \endcode - */ + * This is the main module of Eigen providing dense matrix and vector support + * (both fixed and dynamic size) with all the features corresponding to a BLAS library + * and much more... + * + * \code + * #include + * \endcode + */ + +#ifdef EIGEN_USE_LAPACKE +#ifdef EIGEN_USE_MKL +// #include "mkl_lapacke.h" +#else +// #include "src/misc/lapacke.h" +#endif +#endif +// IWYU pragma: begin_exports #include "src/Core/util/Constants.h" #include "src/Core/util/Meta.h" +#include "src/Core/util/Assert.h" #include "src/Core/util/ForwardDeclarations.h" #include "src/Core/util/StaticAssert.h" #include "src/Core/util/XprHelper.h" #include "src/Core/util/Memory.h" #include "src/Core/util/IntegralConstant.h" +#include "src/Core/util/Serializer.h" #include "src/Core/util/SymbolicIndex.h" +#include "src/Core/util/EmulateArray.h" +#include "src/Core/util/MoreMeta.h" #include "src/Core/NumTraits.h" #include "src/Core/MathFunctions.h" +#include "src/Core/RandomImpl.h" #include "src/Core/GenericPacketMath.h" #include "src/Core/MathFunctionsImpl.h" #include "src/Core/arch/Default/ConjHelper.h" // Generic half float support #include "src/Core/arch/Default/Half.h" #include "src/Core/arch/Default/BFloat16.h" -#include "src/Core/arch/Default/TypeCasting.h" #include "src/Core/arch/Default/GenericPacketMathFunctionsFwd.h" #if defined EIGEN_VECTORIZE_AVX512 - #include "src/Core/arch/SSE/PacketMath.h" - #include "src/Core/arch/SSE/TypeCasting.h" - #include "src/Core/arch/SSE/Complex.h" - #include "src/Core/arch/AVX/PacketMath.h" - #include "src/Core/arch/AVX/TypeCasting.h" - #include "src/Core/arch/AVX/Complex.h" - // #include "src/Core/arch/AVX512/PacketMath.h" - // #include "src/Core/arch/AVX512/TypeCasting.h" - // #include "src/Core/arch/AVX512/Complex.h" - #include "src/Core/arch/SSE/MathFunctions.h" - #include "src/Core/arch/AVX/MathFunctions.h" - // #include "src/Core/arch/AVX512/MathFunctions.h" +#if defined EIGEN_VECTORIZE_AVX512FP16 +// #include "src/Core/arch/AVX512/PacketMathFP16.h" +#endif +#include "src/Core/arch/SSE/PacketMath.h" +#include "src/Core/arch/SSE/TypeCasting.h" +#include "src/Core/arch/SSE/Complex.h" +#include "src/Core/arch/AVX/PacketMath.h" +#include "src/Core/arch/AVX/TypeCasting.h" +#include "src/Core/arch/AVX/Complex.h" +// #include "src/Core/arch/AVX512/PacketMath.h" +// #include "src/Core/arch/AVX512/TypeCasting.h" +// #include "src/Core/arch/AVX512/Complex.h" +#include "src/Core/arch/SSE/MathFunctions.h" +#include "src/Core/arch/AVX/MathFunctions.h" +// #include "src/Core/arch/AVX512/MathFunctions.h" +// #include "src/Core/arch/AVX512/TrsmKernel.h" #elif defined EIGEN_VECTORIZE_AVX - // Use AVX for floats and doubles, SSE for integers - #include "src/Core/arch/SSE/PacketMath.h" - #include "src/Core/arch/SSE/TypeCasting.h" - #include "src/Core/arch/SSE/Complex.h" - #include "src/Core/arch/AVX/PacketMath.h" - #include "src/Core/arch/AVX/TypeCasting.h" - #include "src/Core/arch/AVX/Complex.h" - #include "src/Core/arch/SSE/MathFunctions.h" - #include "src/Core/arch/AVX/MathFunctions.h" + // Use AVX for floats and doubles, SSE for integers +#include "src/Core/arch/SSE/PacketMath.h" +#include "src/Core/arch/SSE/TypeCasting.h" +#include "src/Core/arch/SSE/Complex.h" +#include "src/Core/arch/AVX/PacketMath.h" +#include "src/Core/arch/AVX/TypeCasting.h" +#include "src/Core/arch/AVX/Complex.h" +#include "src/Core/arch/SSE/MathFunctions.h" +#include "src/Core/arch/AVX/MathFunctions.h" #elif defined EIGEN_VECTORIZE_SSE - #include "src/Core/arch/SSE/PacketMath.h" - #include "src/Core/arch/SSE/TypeCasting.h" - #include "src/Core/arch/SSE/MathFunctions.h" - #include "src/Core/arch/SSE/Complex.h" +#include "src/Core/arch/SSE/PacketMath.h" +#include "src/Core/arch/SSE/TypeCasting.h" +#include "src/Core/arch/SSE/MathFunctions.h" +#include "src/Core/arch/SSE/Complex.h" #elif defined(EIGEN_VECTORIZE_ALTIVEC) || defined(EIGEN_VECTORIZE_VSX) - // #include "src/Core/arch/AltiVec/PacketMath.h" - // #include "src/Core/arch/AltiVec/MathFunctions.h" - // #include "src/Core/arch/AltiVec/Complex.h" +// #include "src/Core/arch/AltiVec/PacketMath.h" +// #include "src/Core/arch/AltiVec/TypeCasting.h" +// #include "src/Core/arch/AltiVec/MathFunctions.h" +// #include "src/Core/arch/AltiVec/Complex.h" #elif defined EIGEN_VECTORIZE_NEON - #include "src/Core/arch/NEON/PacketMath.h" - #include "src/Core/arch/NEON/TypeCasting.h" - #include "src/Core/arch/NEON/MathFunctions.h" - #include "src/Core/arch/NEON/Complex.h" +#include "src/Core/arch/NEON/PacketMath.h" +#include "src/Core/arch/NEON/TypeCasting.h" +#include "src/Core/arch/NEON/MathFunctions.h" +#include "src/Core/arch/NEON/Complex.h" #elif defined EIGEN_VECTORIZE_SVE - // #include "src/Core/arch/SVE/PacketMath.h" - // #include "src/Core/arch/SVE/TypeCasting.h" - // #include "src/Core/arch/SVE/MathFunctions.h" +// #include "src/Core/arch/SVE/PacketMath.h" +// #include "src/Core/arch/SVE/TypeCasting.h" +// #include "src/Core/arch/SVE/MathFunctions.h" #elif defined EIGEN_VECTORIZE_ZVECTOR - // #include "src/Core/arch/ZVector/PacketMath.h" - // #include "src/Core/arch/ZVector/MathFunctions.h" - // #include "src/Core/arch/ZVector/Complex.h" +// #include "src/Core/arch/ZVector/PacketMath.h" +// #include "src/Core/arch/ZVector/MathFunctions.h" +// #include "src/Core/arch/ZVector/Complex.h" #elif defined EIGEN_VECTORIZE_MSA - // #include "src/Core/arch/MSA/PacketMath.h" - // #include "src/Core/arch/MSA/MathFunctions.h" - // #include "src/Core/arch/MSA/Complex.h" +// #include "src/Core/arch/MSA/PacketMath.h" +// #include "src/Core/arch/MSA/MathFunctions.h" +// #include "src/Core/arch/MSA/Complex.h" +#elif defined EIGEN_VECTORIZE_HVX +// #include "src/Core/arch/HVX/PacketMath.h" #endif #if defined EIGEN_VECTORIZE_GPU - // #include "src/Core/arch/GPU/PacketMath.h" - // #include "src/Core/arch/GPU/MathFunctions.h" - // #include "src/Core/arch/GPU/TypeCasting.h" +// #include "src/Core/arch/GPU/PacketMath.h" +// #include "src/Core/arch/GPU/MathFunctions.h" +// #include "src/Core/arch/GPU/TypeCasting.h" #endif #if defined(EIGEN_USE_SYCL) - // #include "src/Core/arch/SYCL/SyclMemoryModel.h" - // #include "src/Core/arch/SYCL/InteropHeaders.h" +// #include "src/Core/arch/SYCL/InteropHeaders.h" #if !defined(EIGEN_DONT_VECTORIZE_SYCL) - // #include "src/Core/arch/SYCL/PacketMath.h" - // #include "src/Core/arch/SYCL/MathFunctions.h" - // #include "src/Core/arch/SYCL/TypeCasting.h" +// #include "src/Core/arch/SYCL/PacketMath.h" +// #include "src/Core/arch/SYCL/MathFunctions.h" +// #include "src/Core/arch/SYCL/TypeCasting.h" #endif #endif @@ -256,17 +271,21 @@ using std::ptrdiff_t; #include "src/Core/functors/StlFunctors.h" #include "src/Core/functors/AssignmentFunctors.h" -// Specialized functors to enable the processing of complex numbers -// on CUDA devices -#ifdef EIGEN_CUDACC -// #include "src/Core/arch/CUDA/Complex.h" +// Specialized functors for GPU. +#ifdef EIGEN_GPUCC +// #include "src/Core/arch/GPU/Complex.h" +#endif + +// Specializations of vectorized activation functions for NEON. +#ifdef EIGEN_VECTORIZE_NEON +#include "src/Core/arch/NEON/UnaryFunctors.h" #endif #include "src/Core/util/IndexedViewHelper.h" #include "src/Core/util/ReshapedHelper.h" #include "src/Core/ArithmeticSequence.h" #ifndef EIGEN_NO_IO - #include "src/Core/IO.h" +#include "src/Core/IO.h" #endif #include "src/Core/DenseCoeffsBase.h" #include "src/Core/DenseBase.h" @@ -277,9 +296,9 @@ using std::ptrdiff_t; #include "src/Core/CoreEvaluators.h" #include "src/Core/AssignEvaluator.h" -#ifndef EIGEN_PARSED_BY_DOXYGEN // work around Doxygen bug triggered by Assign.h r814874 - // at least confirmed with Doxygen 1.5.5 and 1.5.6 - #include "src/Core/Assign.h" +#ifndef EIGEN_PARSED_BY_DOXYGEN // work around Doxygen bug triggered by Assign.h r814874 + // at least confirmed with Doxygen 1.5.5 and 1.5.6 +#include "src/Core/Assign.h" #endif #include "src/Core/ArrayBase.h" @@ -314,6 +333,7 @@ using std::ptrdiff_t; #include "src/Core/DiagonalMatrix.h" #include "src/Core/Diagonal.h" #include "src/Core/DiagonalProduct.h" +#include "src/Core/SkewSymmetricMatrix3.h" #include "src/Core/Redux.h" #include "src/Core/Visitor.h" #include "src/Core/Fuzzy.h" @@ -328,6 +348,9 @@ using std::ptrdiff_t; #include "src/Core/TriangularMatrix.h" #include "src/Core/SelfAdjointView.h" #include "src/Core/products/GeneralBlockPanelKernel.h" +#ifdef EIGEN_GEMM_THREADPOOL +// #include "ThreadPool" +#endif #include "src/Core/products/Parallelizer.h" #include "src/Core/ProductEvaluators.h" #include "src/Core/products/GeneralMatrixVector.h" @@ -346,13 +369,16 @@ using std::ptrdiff_t; #include "src/Core/CoreIterators.h" #include "src/Core/ConditionEstimator.h" -#if defined(EIGEN_VECTORIZE_ALTIVEC) || defined(EIGEN_VECTORIZE_VSX) - // #include "src/Core/arch/AltiVec/MatrixProduct.h" +#if defined(EIGEN_VECTORIZE_VSX) +// #include "src/Core/arch/AltiVec/MatrixProduct.h" #elif defined EIGEN_VECTORIZE_NEON - #include "src/Core/arch/NEON/GeneralBlockPanelKernel.h" +#include "src/Core/arch/NEON/GeneralBlockPanelKernel.h" +#endif + +#if defined(EIGEN_VECTORIZE_AVX512) +// #include "src/Core/arch/AVX512/GemmKernel.h" #endif -#include "src/Core/BooleanRedux.h" #include "src/Core/Select.h" #include "src/Core/VectorwiseOp.h" #include "src/Core/PartialReduxEvaluator.h" @@ -371,14 +397,15 @@ using std::ptrdiff_t; // #include "src/Core/products/TriangularMatrixMatrix_BLAS.h" // #include "src/Core/products/TriangularMatrixVector_BLAS.h" // #include "src/Core/products/TriangularSolverMatrix_BLAS.h" -#endif // EIGEN_USE_BLAS +#endif // EIGEN_USE_BLAS #ifdef EIGEN_USE_MKL_VML // #include "src/Core/Assign_MKL.h" #endif #include "src/Core/GlobalFunctions.h" +// IWYU pragma: end_exports #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_CORE_H +#endif // EIGEN_CORE_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Eigenvalues b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Eigenvalues index c6defe34a4d..51438ef365b 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Eigenvalues +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Eigenvalues @@ -19,20 +19,22 @@ #include "src/Core/util/DisableStupidWarnings.h" /** \defgroup Eigenvalues_Module Eigenvalues module - * - * - * - * This module mainly provides various eigenvalue solvers. - * This module also provides some MatrixBase methods, including: - * - MatrixBase::eigenvalues(), - * - MatrixBase::operatorNorm() - * - * \code - * #include - * \endcode - */ + * + * + * + * This module mainly provides various eigenvalue solvers. + * This module also provides some MatrixBase methods, including: + * - MatrixBase::eigenvalues(), + * - MatrixBase::operatorNorm() + * + * \code + * #include + * \endcode + */ #include "src/misc/RealSvd2x2.h" + +// IWYU pragma: begin_exports #include "src/Eigenvalues/Tridiagonalization.h" #include "src/Eigenvalues/RealSchur.h" #include "src/Eigenvalues/EigenSolver.h" @@ -54,7 +56,8 @@ // #include "src/Eigenvalues/ComplexSchur_LAPACKE.h" // #include "src/Eigenvalues/SelfAdjointEigenSolver_LAPACKE.h" #endif +// IWYU pragma: end_exports #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_EIGENVALUES_MODULE_H +#endif // EIGEN_EIGENVALUES_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Householder b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Householder index f2fa79969c9..5070e070e67 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Householder +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Householder @@ -13,17 +13,19 @@ #include "src/Core/util/DisableStupidWarnings.h" /** \defgroup Householder_Module Householder module - * This module provides Householder transformations. - * - * \code - * #include - * \endcode - */ + * This module provides Householder transformations. + * + * \code + * #include + * \endcode + */ +// IWYU pragma: begin_exports #include "src/Householder/Householder.h" #include "src/Householder/HouseholderSequence.h" #include "src/Householder/BlockHouseholder.h" +// IWYU pragma: end_exports #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_HOUSEHOLDER_MODULE_H +#endif // EIGEN_HOUSEHOLDER_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/IterativeLinearSolvers b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/IterativeLinearSolvers index 957d5750b2c..fe5159e9f88 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/IterativeLinearSolvers +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/IterativeLinearSolvers @@ -13,10 +13,11 @@ #include "src/Core/util/DisableStupidWarnings.h" -/** +/** * \defgroup IterativeLinearSolvers_Module IterativeLinearSolvers module * - * This module currently provides iterative methods to solve problems of the form \c A \c x = \c b, where \c A is a squared matrix, usually very large and sparse. + * This module currently provides iterative methods to solve problems of the form \c A \c x = \c b, where \c A is a + squared matrix, usually very large and sparse. * Those solvers are accessible via the following classes: * - ConjugateGradient for selfadjoint (hermitian) matrices, * - LeastSquaresConjugateGradient for rectangular least-square problems, @@ -27,13 +28,15 @@ * - DiagonalPreconditioner - also called Jacobi preconditioner, work very well on diagonal dominant matrices. * - IncompleteLUT - incomplete LU factorization with dual thresholding * - * Such problems can also be solved using the direct sparse decomposition modules: SparseCholesky, CholmodSupport, UmfPackSupport, SuperLUSupport. + * Such problems can also be solved using the direct sparse decomposition modules: SparseCholesky, CholmodSupport, + UmfPackSupport, SuperLUSupport, AccelerateSupport. * \code #include \endcode */ +// IWYU pragma: begin_exports #include "src/IterativeLinearSolvers/SolveWithGuess.h" #include "src/IterativeLinearSolvers/IterativeSolverBase.h" #include "src/IterativeLinearSolvers/BasicPreconditioners.h" @@ -42,7 +45,8 @@ #include "src/IterativeLinearSolvers/BiCGSTAB.h" #include "src/IterativeLinearSolvers/IncompleteLUT.h" #include "src/IterativeLinearSolvers/IncompleteCholesky.h" +// IWYU pragma: end_exports #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_ITERATIVELINEARSOLVERS_MODULE_H +#endif // EIGEN_ITERATIVELINEARSOLVERS_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Jacobi b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Jacobi index 43edc7a1946..31eb36a79f6 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Jacobi +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/Jacobi @@ -13,20 +13,21 @@ #include "src/Core/util/DisableStupidWarnings.h" /** \defgroup Jacobi_Module Jacobi module - * This module provides Jacobi and Givens rotations. - * - * \code - * #include - * \endcode - * - * In addition to listed classes, it defines the two following MatrixBase methods to apply a Jacobi or Givens rotation: - * - MatrixBase::applyOnTheLeft() - * - MatrixBase::applyOnTheRight(). - */ - + * This module provides Jacobi and Givens rotations. + * + * \code + * #include + * \endcode + * + * In addition to listed classes, it defines the two following MatrixBase methods to apply a Jacobi or Givens rotation: + * - MatrixBase::applyOnTheLeft() + * - MatrixBase::applyOnTheRight(). + */ + +// IWYU pragma: begin_exports #include "src/Jacobi/Jacobi.h" +// IWYU pragma: end_exports #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_JACOBI_MODULE_H - +#endif // EIGEN_JACOBI_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/LU b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/LU index a1b5d462f7e..e58e895d3f3 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/LU +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/LU @@ -13,35 +13,34 @@ #include "src/Core/util/DisableStupidWarnings.h" /** \defgroup LU_Module LU module - * This module includes %LU decomposition and related notions such as matrix inversion and determinant. - * This module defines the following MatrixBase methods: - * - MatrixBase::inverse() - * - MatrixBase::determinant() - * - * \code - * #include - * \endcode - */ + * This module includes %LU decomposition and related notions such as matrix inversion and determinant. + * This module defines the following MatrixBase methods: + * - MatrixBase::inverse() + * - MatrixBase::determinant() + * + * \code + * #include + * \endcode + */ #include "src/misc/Kernel.h" #include "src/misc/Image.h" + +// IWYU pragma: begin_exports #include "src/LU/FullPivLU.h" #include "src/LU/PartialPivLU.h" #ifdef EIGEN_USE_LAPACKE -#ifdef EIGEN_USE_MKL -// #include "mkl_lapacke.h" -#else -// #include "src/misc/lapacke.h" -#endif +// #include "src/misc/lapacke_helpers.h" // #include "src/LU/PartialPivLU_LAPACKE.h" #endif #include "src/LU/Determinant.h" #include "src/LU/InverseImpl.h" #if defined EIGEN_VECTORIZE_SSE || defined EIGEN_VECTORIZE_NEON - #include "src/LU/arch/InverseSize4.h" +#include "src/LU/arch/InverseSize4.h" #endif +// IWYU pragma: end_exports #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_LU_MODULE_H +#endif // EIGEN_LU_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/OrderingMethods b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/OrderingMethods index 29691a62b44..921b8a01ae6 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/OrderingMethods +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/OrderingMethods @@ -12,59 +12,62 @@ #include "src/Core/util/DisableStupidWarnings.h" -/** - * \defgroup OrderingMethods_Module OrderingMethods module - * - * This module is currently for internal use only - * - * It defines various built-in and external ordering methods for sparse matrices. - * They are typically used to reduce the number of elements during - * the sparse matrix decomposition (LLT, LU, QR). - * Precisely, in a preprocessing step, a permutation matrix P is computed using - * those ordering methods and applied to the columns of the matrix. - * Using for instance the sparse Cholesky decomposition, it is expected that - * the nonzeros elements in LLT(A*P) will be much smaller than that in LLT(A). - * - * - * Usage : - * \code - * #include - * \endcode - * - * A simple usage is as a template parameter in the sparse decomposition classes : - * - * \code - * SparseLU > solver; - * \endcode - * - * \code - * SparseQR > solver; - * \endcode - * - * It is possible as well to call directly a particular ordering method for your own purpose, - * \code - * AMDOrdering ordering; - * PermutationMatrix perm; - * SparseMatrix A; - * //Fill the matrix ... - * - * ordering(A, perm); // Call AMD - * \endcode - * - * \note Some of these methods (like AMD or METIS), need the sparsity pattern - * of the input matrix to be symmetric. When the matrix is structurally unsymmetric, - * Eigen computes internally the pattern of \f$A^T*A\f$ before calling the method. - * If your matrix is already symmetric (at leat in structure), you can avoid that - * by calling the method with a SelfAdjointView type. - * - * \code - * // Call the ordering on the pattern of the lower triangular matrix A - * ordering(A.selfadjointView(), perm); - * \endcode - */ +/** + * \defgroup OrderingMethods_Module OrderingMethods module + * + * This module is currently for internal use only + * + * It defines various built-in and external ordering methods for sparse matrices. + * They are typically used to reduce the number of elements during + * the sparse matrix decomposition (LLT, LU, QR). + * Precisely, in a preprocessing step, a permutation matrix P is computed using + * those ordering methods and applied to the columns of the matrix. + * Using for instance the sparse Cholesky decomposition, it is expected that + * the nonzeros elements in LLT(A*P) will be much smaller than that in LLT(A). + * + * + * Usage : + * \code + * #include + * \endcode + * + * A simple usage is as a template parameter in the sparse decomposition classes : + * + * \code + * SparseLU > solver; + * \endcode + * + * \code + * SparseQR > solver; + * \endcode + * + * It is possible as well to call directly a particular ordering method for your own purpose, + * \code + * AMDOrdering ordering; + * PermutationMatrix perm; + * SparseMatrix A; + * //Fill the matrix ... + * + * ordering(A, perm); // Call AMD + * \endcode + * + * \note Some of these methods (like AMD or METIS), need the sparsity pattern + * of the input matrix to be symmetric. When the matrix is structurally unsymmetric, + * Eigen computes internally the pattern of \f$A^T*A\f$ before calling the method. + * If your matrix is already symmetric (at leat in structure), you can avoid that + * by calling the method with a SelfAdjointView type. + * + * \code + * // Call the ordering on the pattern of the lower triangular matrix A + * ordering(A.selfadjointView(), perm); + * \endcode + */ +// IWYU pragma: begin_exports #include "src/OrderingMethods/Amd.h" #include "src/OrderingMethods/Ordering.h" +// IWYU pragma: end_exports + #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_ORDERINGMETHODS_MODULE_H +#endif // EIGEN_ORDERINGMETHODS_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/QR b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/QR index 42a3fa819b5..9392ecbe89e 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/QR +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/QR @@ -17,34 +17,32 @@ #include "src/Core/util/DisableStupidWarnings.h" /** \defgroup QR_Module QR module - * - * - * - * This module provides various QR decompositions - * This module also provides some MatrixBase methods, including: - * - MatrixBase::householderQr() - * - MatrixBase::colPivHouseholderQr() - * - MatrixBase::fullPivHouseholderQr() - * - * \code - * #include - * \endcode - */ - + * + * + * + * This module provides various QR decompositions + * This module also provides some MatrixBase methods, including: + * - MatrixBase::householderQr() + * - MatrixBase::colPivHouseholderQr() + * - MatrixBase::fullPivHouseholderQr() + * + * \code + * #include + * \endcode + */ + +// IWYU pragma: begin_exports #include "src/QR/HouseholderQR.h" #include "src/QR/FullPivHouseholderQR.h" #include "src/QR/ColPivHouseholderQR.h" #include "src/QR/CompleteOrthogonalDecomposition.h" #ifdef EIGEN_USE_LAPACKE -#ifdef EIGEN_USE_MKL -// #include "mkl_lapacke.h" -#else -// #include "src/misc/lapacke.h" -#endif +// #include "src/misc/lapacke_helpers.h" // #include "src/QR/HouseholderQR_LAPACKE.h" // #include "src/QR/ColPivHouseholderQR_LAPACKE.h" #endif +// IWYU pragma: end_exports #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_QR_MODULE_H +#endif // EIGEN_QR_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SVD b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SVD index 4441a38ef85..66a7678ee7e 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SVD +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SVD @@ -15,36 +15,42 @@ #include "src/Core/util/DisableStupidWarnings.h" /** \defgroup SVD_Module SVD module - * - * - * - * This module provides SVD decomposition for matrices (both real and complex). - * Two decomposition algorithms are provided: - * - JacobiSVD implementing two-sided Jacobi iterations is numerically very accurate, fast for small matrices, but very slow for larger ones. - * - BDCSVD implementing a recursive divide & conquer strategy on top of an upper-bidiagonalization which remains fast for large problems. - * These decompositions are accessible via the respective classes and following MatrixBase methods: - * - MatrixBase::jacobiSvd() - * - MatrixBase::bdcSvd() - * - * \code - * #include - * \endcode - */ + * + * + * + * This module provides SVD decomposition for matrices (both real and complex). + * Two decomposition algorithms are provided: + * - JacobiSVD implementing two-sided Jacobi iterations is numerically very accurate, fast for small matrices, but very + * slow for larger ones. + * - BDCSVD implementing a recursive divide & conquer strategy on top of an upper-bidiagonalization which remains fast + * for large problems. These decompositions are accessible via the respective classes and following MatrixBase methods: + * - MatrixBase::jacobiSvd() + * - MatrixBase::bdcSvd() + * + * \code + * #include + * \endcode + */ +// IWYU pragma: begin_exports #include "src/misc/RealSvd2x2.h" #include "src/SVD/UpperBidiagonalization.h" #include "src/SVD/SVDBase.h" #include "src/SVD/JacobiSVD.h" #include "src/SVD/BDCSVD.h" -#if defined(EIGEN_USE_LAPACKE) && !defined(EIGEN_USE_LAPACKE_STRICT) +#ifdef EIGEN_USE_LAPACKE #ifdef EIGEN_USE_MKL // #include "mkl_lapacke.h" #else // #include "src/misc/lapacke.h" #endif +#ifndef EIGEN_USE_LAPACKE_STRICT // #include "src/SVD/JacobiSVD_LAPACKE.h" #endif +// #include "src/SVD/BDCSVD_LAPACKE.h" +#endif +// IWYU pragma: end_exports #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_SVD_MODULE_H +#endif // EIGEN_SVD_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseCholesky b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseCholesky index d2b1f1276da..6abdcd6601c 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseCholesky +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseCholesky @@ -15,23 +15,26 @@ #include "src/Core/util/DisableStupidWarnings.h" -/** - * \defgroup SparseCholesky_Module SparseCholesky module - * - * This module currently provides two variants of the direct sparse Cholesky decomposition for selfadjoint (hermitian) matrices. - * Those decompositions are accessible via the following classes: - * - SimplicialLLt, - * - SimplicialLDLt - * - * Such problems can also be solved using the ConjugateGradient solver from the IterativeLinearSolvers module. - * - * \code - * #include - * \endcode - */ +/** + * \defgroup SparseCholesky_Module SparseCholesky module + * + * This module currently provides two variants of the direct sparse Cholesky decomposition for selfadjoint (hermitian) + * matrices. Those decompositions are accessible via the following classes: + * - SimplicialLLt, + * - SimplicialLDLt + * + * Such problems can also be solved using the ConjugateGradient solver from the IterativeLinearSolvers module. + * + * \code + * #include + * \endcode + */ +// IWYU pragma: begin_exports #include "src/SparseCholesky/SimplicialCholesky.h" #include "src/SparseCholesky/SimplicialCholesky_impl.h" +// IWYU pragma: end_exports + #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_SPARSECHOLESKY_MODULE_H +#endif // EIGEN_SPARSECHOLESKY_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseCore b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseCore index 76966c4c4cb..56a9401af34 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseCore +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseCore @@ -17,22 +17,24 @@ #include #include #include +#include -/** - * \defgroup SparseCore_Module SparseCore module - * - * This module provides a sparse matrix representation, and basic associated matrix manipulations - * and operations. - * - * See the \ref TutorialSparse "Sparse tutorial" - * - * \code - * #include - * \endcode - * - * This module depends on: Core. - */ +/** + * \defgroup SparseCore_Module SparseCore module + * + * This module provides a sparse matrix representation, and basic associated matrix manipulations + * and operations. + * + * See the \ref TutorialSparse "Sparse tutorial" + * + * \code + * #include + * \endcode + * + * This module depends on: Core. + */ +// IWYU pragma: begin_exports #include "src/SparseCore/SparseUtil.h" #include "src/SparseCore/SparseMatrixBase.h" #include "src/SparseCore/SparseAssign.h" @@ -41,7 +43,6 @@ #include "src/SparseCore/SparseCompressedBase.h" #include "src/SparseCore/SparseMatrix.h" #include "src/SparseCore/SparseMap.h" -#include "src/SparseCore/MappedSparseMatrix.h" #include "src/SparseCore/SparseVector.h" #include "src/SparseCore/SparseRef.h" #include "src/SparseCore/SparseCwiseUnaryOp.h" @@ -62,8 +63,8 @@ #include "src/SparseCore/SparsePermutation.h" #include "src/SparseCore/SparseFuzzy.h" #include "src/SparseCore/SparseSolverBase.h" +// IWYU pragma: end_exports #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_SPARSECORE_MODULE_H - +#endif // EIGEN_SPARSECORE_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseLU b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseLU index 37c4a5c5a8b..6faf1306943 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseLU +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseLU @@ -13,20 +13,19 @@ #include "SparseCore" -/** - * \defgroup SparseLU_Module SparseLU module - * This module defines a supernodal factorization of general sparse matrices. - * The code is fully optimized for supernode-panel updates with specialized kernels. - * Please, see the documentation of the SparseLU class for more details. - */ +/** + * \defgroup SparseLU_Module SparseLU module + * This module defines a supernodal factorization of general sparse matrices. + * The code is fully optimized for supernode-panel updates with specialized kernels. + * Please, see the documentation of the SparseLU class for more details. + */ // Ordering interface #include "OrderingMethods" #include "src/Core/util/DisableStupidWarnings.h" -#include "src/SparseLU/SparseLU_gemm_kernel.h" - +// IWYU pragma: begin_exports #include "src/SparseLU/SparseLU_Structs.h" #include "src/SparseLU/SparseLU_SupernodalMatrix.h" #include "src/SparseLU/SparseLUImpl.h" @@ -44,7 +43,8 @@ #include "src/SparseLU/SparseLU_pruneL.h" #include "src/SparseLU/SparseLU_Utils.h" #include "src/SparseLU/SparseLU.h" +// IWYU pragma: end_exports #include "src/Core/util/ReenableStupidWarnings.h" -#endif // EIGEN_SPARSELU_MODULE_H +#endif // EIGEN_SPARSELU_MODULE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseQR b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseQR index f5fc5fa7fee..b4f1cad6bbb 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseQR +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/SparseQR @@ -13,23 +13,25 @@ #include "src/Core/util/DisableStupidWarnings.h" /** \defgroup SparseQR_Module SparseQR module - * \brief Provides QR decomposition for sparse matrices - * - * This module provides a simplicial version of the left-looking Sparse QR decomposition. - * The columns of the input matrix should be reordered to limit the fill-in during the - * decomposition. Built-in methods (COLAMD, AMD) or external methods (METIS) can be used to this end. - * See the \link OrderingMethods_Module OrderingMethods\endlink module for the list - * of built-in and external ordering methods. - * - * \code - * #include - * \endcode - * - * - */ + * \brief Provides QR decomposition for sparse matrices + * + * This module provides a simplicial version of the left-looking Sparse QR decomposition. + * The columns of the input matrix should be reordered to limit the fill-in during the + * decomposition. Built-in methods (COLAMD, AMD) or external methods (METIS) can be used to this end. + * See the \link OrderingMethods_Module OrderingMethods\endlink module for the list + * of built-in and external ordering methods. + * + * \code + * #include + * \endcode + * + * + */ +// IWYU pragma: begin_exports #include "src/SparseCore/SparseColEtree.h" #include "src/SparseQR/SparseQR.h" +// IWYU pragma: end_exports #include "src/Core/util/ReenableStupidWarnings.h" diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Cholesky/InternalHeaderCheck.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Cholesky/InternalHeaderCheck.h new file mode 100644 index 00000000000..5de2b219b3f --- /dev/null +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Cholesky/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_CHOLESKY_MODULE_H +#error "Please include Eigen/Cholesky instead of including headers inside the src directory directly." +#endif diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Cholesky/LDLT.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Cholesky/LDLT.h index 1013ca045df..5d52ab20f64 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Cholesky/LDLT.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Cholesky/LDLT.h @@ -13,335 +13,314 @@ #ifndef EIGEN_LDLT_H #define EIGEN_LDLT_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { - template struct traits > - : traits<_MatrixType> - { - typedef MatrixXpr XprKind; - typedef SolverStorage StorageKind; - typedef int StorageIndex; - enum { Flags = 0 }; - }; +template +struct traits > : traits { + typedef MatrixXpr XprKind; + typedef SolverStorage StorageKind; + typedef int StorageIndex; + enum { Flags = 0 }; +}; - template struct LDLT_Traits; +template +struct LDLT_Traits; - // PositiveSemiDef means positive semi-definite and non-zero; same for NegativeSemiDef - enum SignMatrix { PositiveSemiDef, NegativeSemiDef, ZeroSign, Indefinite }; -} +// PositiveSemiDef means positive semi-definite and non-zero; same for NegativeSemiDef +enum SignMatrix { PositiveSemiDef, NegativeSemiDef, ZeroSign, Indefinite }; +} // namespace internal /** \ingroup Cholesky_Module - * - * \class LDLT - * - * \brief Robust Cholesky decomposition of a matrix with pivoting - * - * \tparam _MatrixType the type of the matrix of which to compute the LDL^T Cholesky decomposition - * \tparam _UpLo the triangular part that will be used for the decompositon: Lower (default) or Upper. - * The other triangular part won't be read. - * - * Perform a robust Cholesky decomposition of a positive semidefinite or negative semidefinite - * matrix \f$ A \f$ such that \f$ A = P^TLDL^*P \f$, where P is a permutation matrix, L - * is lower triangular with a unit diagonal and D is a diagonal matrix. - * - * The decomposition uses pivoting to ensure stability, so that D will have - * zeros in the bottom right rank(A) - n submatrix. Avoiding the square root - * on D also stabilizes the computation. - * - * Remember that Cholesky decompositions are not rank-revealing. Also, do not use a Cholesky - * decomposition to determine whether a system of equations has a solution. - * - * This class supports the \link InplaceDecomposition inplace decomposition \endlink mechanism. - * - * \sa MatrixBase::ldlt(), SelfAdjointView::ldlt(), class LLT - */ -template class LDLT - : public SolverBase > -{ - public: - typedef _MatrixType MatrixType; - typedef SolverBase Base; - friend class SolverBase; - - EIGEN_GENERIC_PUBLIC_INTERFACE(LDLT) - enum { - MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, - MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime, - UpLo = _UpLo - }; - typedef Matrix TmpMatrixType; - - typedef Transpositions TranspositionType; - typedef PermutationMatrix PermutationType; - - typedef internal::LDLT_Traits Traits; - - /** \brief Default Constructor. - * - * The default constructor is useful in cases in which the user intends to - * perform decompositions via LDLT::compute(const MatrixType&). - */ - LDLT() - : m_matrix(), - m_transpositions(), - m_sign(internal::ZeroSign), - m_isInitialized(false) - {} - - /** \brief Default Constructor with memory preallocation - * - * Like the default constructor but with preallocation of the internal data - * according to the specified problem \a size. - * \sa LDLT() - */ - explicit LDLT(Index size) + * + * \class LDLT + * + * \brief Robust Cholesky decomposition of a matrix with pivoting + * + * \tparam MatrixType_ the type of the matrix of which to compute the LDL^T Cholesky decomposition + * \tparam UpLo_ the triangular part that will be used for the decomposition: Lower (default) or Upper. + * The other triangular part won't be read. + * + * Perform a robust Cholesky decomposition of a positive semidefinite or negative semidefinite + * matrix \f$ A \f$ such that \f$ A = P^TLDL^*P \f$, where P is a permutation matrix, L + * is lower triangular with a unit diagonal and D is a diagonal matrix. + * + * The decomposition uses pivoting to ensure stability, so that D will have + * zeros in the bottom right rank(A) - n submatrix. Avoiding the square root + * on D also stabilizes the computation. + * + * Remember that Cholesky decompositions are not rank-revealing. Also, do not use a Cholesky + * decomposition to determine whether a system of equations has a solution. + * + * This class supports the \link InplaceDecomposition inplace decomposition \endlink mechanism. + * + * \sa MatrixBase::ldlt(), SelfAdjointView::ldlt(), class LLT + */ +template +class LDLT : public SolverBase > { + public: + typedef MatrixType_ MatrixType; + typedef SolverBase Base; + friend class SolverBase; + + EIGEN_GENERIC_PUBLIC_INTERFACE(LDLT) + enum { + MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime, + UpLo = UpLo_ + }; + typedef Matrix TmpMatrixType; + + typedef Transpositions TranspositionType; + typedef PermutationMatrix PermutationType; + + typedef internal::LDLT_Traits Traits; + + /** \brief Default Constructor. + * + * The default constructor is useful in cases in which the user intends to + * perform decompositions via LDLT::compute(const MatrixType&). + */ + LDLT() : m_matrix(), m_transpositions(), m_sign(internal::ZeroSign), m_isInitialized(false) {} + + /** \brief Default Constructor with memory preallocation + * + * Like the default constructor but with preallocation of the internal data + * according to the specified problem \a size. + * \sa LDLT() + */ + explicit LDLT(Index size) : m_matrix(size, size), m_transpositions(size), m_temporary(size), m_sign(internal::ZeroSign), - m_isInitialized(false) - {} - - /** \brief Constructor with decomposition - * - * This calculates the decomposition for the input \a matrix. - * - * \sa LDLT(Index size) - */ - template - explicit LDLT(const EigenBase& matrix) + m_isInitialized(false) {} + + /** \brief Constructor with decomposition + * + * This calculates the decomposition for the input \a matrix. + * + * \sa LDLT(Index size) + */ + template + explicit LDLT(const EigenBase& matrix) : m_matrix(matrix.rows(), matrix.cols()), m_transpositions(matrix.rows()), m_temporary(matrix.rows()), m_sign(internal::ZeroSign), - m_isInitialized(false) - { - compute(matrix.derived()); - } + m_isInitialized(false) { + compute(matrix.derived()); + } - /** \brief Constructs a LDLT factorization from a given matrix - * - * This overloaded constructor is provided for \link InplaceDecomposition inplace decomposition \endlink when \c MatrixType is a Eigen::Ref. - * - * \sa LDLT(const EigenBase&) - */ - template - explicit LDLT(EigenBase& matrix) + /** \brief Constructs a LDLT factorization from a given matrix + * + * This overloaded constructor is provided for \link InplaceDecomposition inplace decomposition \endlink when \c + * MatrixType is a Eigen::Ref. + * + * \sa LDLT(const EigenBase&) + */ + template + explicit LDLT(EigenBase& matrix) : m_matrix(matrix.derived()), m_transpositions(matrix.rows()), m_temporary(matrix.rows()), m_sign(internal::ZeroSign), - m_isInitialized(false) - { - compute(matrix.derived()); - } + m_isInitialized(false) { + compute(matrix.derived()); + } - /** Clear any existing decomposition - * \sa rankUpdate(w,sigma) - */ - void setZero() - { - m_isInitialized = false; - } + /** Clear any existing decomposition + * \sa rankUpdate(w,sigma) + */ + void setZero() { m_isInitialized = false; } - /** \returns a view of the upper triangular matrix U */ - inline typename Traits::MatrixU matrixU() const - { - eigen_assert(m_isInitialized && "LDLT is not initialized."); - return Traits::getU(m_matrix); - } + /** \returns a view of the upper triangular matrix U */ + inline typename Traits::MatrixU matrixU() const { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return Traits::getU(m_matrix); + } - /** \returns a view of the lower triangular matrix L */ - inline typename Traits::MatrixL matrixL() const - { - eigen_assert(m_isInitialized && "LDLT is not initialized."); - return Traits::getL(m_matrix); - } + /** \returns a view of the lower triangular matrix L */ + inline typename Traits::MatrixL matrixL() const { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return Traits::getL(m_matrix); + } - /** \returns the permutation matrix P as a transposition sequence. - */ - inline const TranspositionType& transpositionsP() const - { - eigen_assert(m_isInitialized && "LDLT is not initialized."); - return m_transpositions; - } + /** \returns the permutation matrix P as a transposition sequence. + */ + inline const TranspositionType& transpositionsP() const { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return m_transpositions; + } - /** \returns the coefficients of the diagonal matrix D */ - inline Diagonal vectorD() const - { - eigen_assert(m_isInitialized && "LDLT is not initialized."); - return m_matrix.diagonal(); - } + /** \returns the coefficients of the diagonal matrix D */ + inline Diagonal vectorD() const { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return m_matrix.diagonal(); + } - /** \returns true if the matrix is positive (semidefinite) */ - inline bool isPositive() const - { - eigen_assert(m_isInitialized && "LDLT is not initialized."); - return m_sign == internal::PositiveSemiDef || m_sign == internal::ZeroSign; - } + /** \returns true if the matrix is positive (semidefinite) */ + inline bool isPositive() const { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return m_sign == internal::PositiveSemiDef || m_sign == internal::ZeroSign; + } - /** \returns true if the matrix is negative (semidefinite) */ - inline bool isNegative(void) const - { - eigen_assert(m_isInitialized && "LDLT is not initialized."); - return m_sign == internal::NegativeSemiDef || m_sign == internal::ZeroSign; - } + /** \returns true if the matrix is negative (semidefinite) */ + inline bool isNegative(void) const { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return m_sign == internal::NegativeSemiDef || m_sign == internal::ZeroSign; + } - #ifdef EIGEN_PARSED_BY_DOXYGEN - /** \returns a solution x of \f$ A x = b \f$ using the current decomposition of A. - * - * This function also supports in-place solves using the syntax x = decompositionObject.solve(x) . - * - * \note_about_checking_solutions - * - * More precisely, this method solves \f$ A x = b \f$ using the decomposition \f$ A = P^T L D L^* P \f$ - * by solving the systems \f$ P^T y_1 = b \f$, \f$ L y_2 = y_1 \f$, \f$ D y_3 = y_2 \f$, - * \f$ L^* y_4 = y_3 \f$ and \f$ P x = y_4 \f$ in succession. If the matrix \f$ A \f$ is singular, then - * \f$ D \f$ will also be singular (all the other matrices are invertible). In that case, the - * least-square solution of \f$ D y_3 = y_2 \f$ is computed. This does not mean that this function - * computes the least-square solution of \f$ A x = b \f$ if \f$ A \f$ is singular. - * - * \sa MatrixBase::ldlt(), SelfAdjointView::ldlt() - */ - template - inline const Solve - solve(const MatrixBase& b) const; - #endif - - template - bool solveInPlace(MatrixBase &bAndX) const; - - template - LDLT& compute(const EigenBase& matrix); - - /** \returns an estimate of the reciprocal condition number of the matrix of - * which \c *this is the LDLT decomposition. - */ - RealScalar rcond() const - { - eigen_assert(m_isInitialized && "LDLT is not initialized."); - return internal::rcond_estimate_helper(m_l1_norm, *this); - } +#ifdef EIGEN_PARSED_BY_DOXYGEN + /** \returns a solution x of \f$ A x = b \f$ using the current decomposition of A. + * + * This function also supports in-place solves using the syntax x = decompositionObject.solve(x) . + * + * \note_about_checking_solutions + * + * More precisely, this method solves \f$ A x = b \f$ using the decomposition \f$ A = P^T L D L^* P \f$ + * by solving the systems \f$ P^T y_1 = b \f$, \f$ L y_2 = y_1 \f$, \f$ D y_3 = y_2 \f$, + * \f$ L^* y_4 = y_3 \f$ and \f$ P x = y_4 \f$ in succession. If the matrix \f$ A \f$ is singular, then + * \f$ D \f$ will also be singular (all the other matrices are invertible). In that case, the + * least-square solution of \f$ D y_3 = y_2 \f$ is computed. This does not mean that this function + * computes the least-square solution of \f$ A x = b \f$ if \f$ A \f$ is singular. + * + * \sa MatrixBase::ldlt(), SelfAdjointView::ldlt() + */ + template + inline const Solve solve(const MatrixBase& b) const; +#endif - template - LDLT& rankUpdate(const MatrixBase& w, const RealScalar& alpha=1); - - /** \returns the internal LDLT decomposition matrix - * - * TODO: document the storage layout - */ - inline const MatrixType& matrixLDLT() const - { - eigen_assert(m_isInitialized && "LDLT is not initialized."); - return m_matrix; - } + template + bool solveInPlace(MatrixBase& bAndX) const; - MatrixType reconstructedMatrix() const; - - /** \returns the adjoint of \c *this, that is, a const reference to the decomposition itself as the underlying matrix is self-adjoint. - * - * This method is provided for compatibility with other matrix decompositions, thus enabling generic code such as: - * \code x = decomposition.adjoint().solve(b) \endcode - */ - const LDLT& adjoint() const { return *this; }; - - EIGEN_DEVICE_FUNC inline EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_matrix.rows(); } - EIGEN_DEVICE_FUNC inline EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_matrix.cols(); } - - /** \brief Reports whether previous computation was successful. - * - * \returns \c Success if computation was successful, - * \c NumericalIssue if the factorization failed because of a zero pivot. - */ - ComputationInfo info() const - { - eigen_assert(m_isInitialized && "LDLT is not initialized."); - return m_info; - } + template + LDLT& compute(const EigenBase& matrix); - #ifndef EIGEN_PARSED_BY_DOXYGEN - template - void _solve_impl(const RhsType &rhs, DstType &dst) const; + /** \returns an estimate of the reciprocal condition number of the matrix of + * which \c *this is the LDLT decomposition. + */ + RealScalar rcond() const { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return internal::rcond_estimate_helper(m_l1_norm, *this); + } - template - void _solve_impl_transposed(const RhsType &rhs, DstType &dst) const; - #endif + template + LDLT& rankUpdate(const MatrixBase& w, const RealScalar& alpha = 1); - protected: + /** \returns the internal LDLT decomposition matrix + * + * TODO: document the storage layout + */ + inline const MatrixType& matrixLDLT() const { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return m_matrix; + } - static void check_template_parameters() - { - EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar); - } + MatrixType reconstructedMatrix() const; + + /** \returns the adjoint of \c *this, that is, a const reference to the decomposition itself as the underlying matrix + * is self-adjoint. + * + * This method is provided for compatibility with other matrix decompositions, thus enabling generic code such as: + * \code x = decomposition.adjoint().solve(b) \endcode + */ + const LDLT& adjoint() const { return *this; } + + EIGEN_DEVICE_FUNC inline EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_matrix.rows(); } + EIGEN_DEVICE_FUNC inline EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_matrix.cols(); } + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was successful, + * \c NumericalIssue if the factorization failed because of a zero pivot. + */ + ComputationInfo info() const { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return m_info; + } + +#ifndef EIGEN_PARSED_BY_DOXYGEN + template + void _solve_impl(const RhsType& rhs, DstType& dst) const; + + template + void _solve_impl_transposed(const RhsType& rhs, DstType& dst) const; +#endif - /** \internal - * Used to compute and store the Cholesky decomposition A = L D L^* = U^* D U. - * The strict upper part is used during the decomposition, the strict lower - * part correspond to the coefficients of L (its diagonal is equal to 1 and - * is not stored), and the diagonal entries correspond to D. - */ - MatrixType m_matrix; - RealScalar m_l1_norm; - TranspositionType m_transpositions; - TmpMatrixType m_temporary; - internal::SignMatrix m_sign; - bool m_isInitialized; - ComputationInfo m_info; + protected: + EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar) + + /** \internal + * Used to compute and store the Cholesky decomposition A = L D L^* = U^* D U. + * The strict upper part is used during the decomposition, the strict lower + * part correspond to the coefficients of L (its diagonal is equal to 1 and + * is not stored), and the diagonal entries correspond to D. + */ + MatrixType m_matrix; + RealScalar m_l1_norm; + TranspositionType m_transpositions; + TmpMatrixType m_temporary; + internal::SignMatrix m_sign; + bool m_isInitialized; + ComputationInfo m_info; }; namespace internal { -template struct ldlt_inplace; +template +struct ldlt_inplace; -template<> struct ldlt_inplace -{ - template - static bool unblocked(MatrixType& mat, TranspositionType& transpositions, Workspace& temp, SignMatrix& sign) - { +template <> +struct ldlt_inplace { + template + static bool unblocked(MatrixType& mat, TranspositionType& transpositions, Workspace& temp, SignMatrix& sign) { using std::abs; typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; typedef typename TranspositionType::StorageIndex IndexType; - eigen_assert(mat.rows()==mat.cols()); + eigen_assert(mat.rows() == mat.cols()); const Index size = mat.rows(); bool found_zero_pivot = false; bool ret = true; - if (size <= 1) - { + if (size <= 1) { transpositions.setIdentity(); - if(size==0) sign = ZeroSign; - else if (numext::real(mat.coeff(0,0)) > static_cast(0) ) sign = PositiveSemiDef; - else if (numext::real(mat.coeff(0,0)) < static_cast(0)) sign = NegativeSemiDef; - else sign = ZeroSign; + if (size == 0) + sign = ZeroSign; + else if (numext::real(mat.coeff(0, 0)) > static_cast(0)) + sign = PositiveSemiDef; + else if (numext::real(mat.coeff(0, 0)) < static_cast(0)) + sign = NegativeSemiDef; + else + sign = ZeroSign; return true; } - for (Index k = 0; k < size; ++k) - { + for (Index k = 0; k < size; ++k) { // Find largest diagonal element Index index_of_biggest_in_corner; - mat.diagonal().tail(size-k).cwiseAbs().maxCoeff(&index_of_biggest_in_corner); + mat.diagonal().tail(size - k).cwiseAbs().maxCoeff(&index_of_biggest_in_corner); index_of_biggest_in_corner += k; transpositions.coeffRef(k) = IndexType(index_of_biggest_in_corner); - if(k != index_of_biggest_in_corner) - { + if (k != index_of_biggest_in_corner) { // apply the transposition while taking care to consider only // the lower triangular part - Index s = size-index_of_biggest_in_corner-1; // trailing size after the biggest element + Index s = size - index_of_biggest_in_corner - 1; // trailing size after the biggest element mat.row(k).head(k).swap(mat.row(index_of_biggest_in_corner).head(k)); mat.col(k).tail(s).swap(mat.col(index_of_biggest_in_corner).tail(s)); - std::swap(mat.coeffRef(k,k),mat.coeffRef(index_of_biggest_in_corner,index_of_biggest_in_corner)); - for(Index i=k+1;i::IsComplex) - mat.coeffRef(index_of_biggest_in_corner,k) = numext::conj(mat.coeff(index_of_biggest_in_corner,k)); + if (NumTraits::IsComplex) + mat.coeffRef(index_of_biggest_in_corner, k) = numext::conj(mat.coeff(index_of_biggest_in_corner, k)); } // partition the matrix: @@ -349,53 +328,53 @@ template<> struct ldlt_inplace // lu = A10 | A11 | - // A20 | A21 | A22 Index rs = size - k - 1; - Block A21(mat,k+1,k,rs,1); - Block A10(mat,k,0,1,k); - Block A20(mat,k+1,0,rs,k); + Block A21(mat, k + 1, k, rs, 1); + Block A10(mat, k, 0, 1, k); + Block A20(mat, k + 1, 0, rs, k); - if(k>0) - { + if (k > 0) { temp.head(k) = mat.diagonal().real().head(k).asDiagonal() * A10.adjoint(); - mat.coeffRef(k,k) -= (A10 * temp.head(k)).value(); - if(rs>0) - A21.noalias() -= A20 * temp.head(k); + mat.coeffRef(k, k) -= (A10 * temp.head(k)).value(); + if (rs > 0) A21.noalias() -= A20 * temp.head(k); } // In some previous versions of Eigen (e.g., 3.2.1), the scaling was omitted if the pivot // was smaller than the cutoff value. However, since LDLT is not rank-revealing // we should only make sure that we do not introduce INF or NaN values. // Remark that LAPACK also uses 0 as the cutoff value. - RealScalar realAkk = numext::real(mat.coeffRef(k,k)); + RealScalar realAkk = numext::real(mat.coeffRef(k, k)); bool pivot_is_valid = (abs(realAkk) > RealScalar(0)); - if(k==0 && !pivot_is_valid) - { + if (k == 0 && !pivot_is_valid) { // The entire diagonal is zero, there is nothing more to do // except filling the transpositions, and checking whether the matrix is zero. sign = ZeroSign; - for(Index j = 0; j0) && pivot_is_valid) + if ((rs > 0) && pivot_is_valid) A21 /= realAkk; - else if(rs>0) - ret = ret && (A21.array()==Scalar(0)).all(); + else if (rs > 0) + ret = ret && (A21.array() == Scalar(0)).all(); - if(found_zero_pivot && pivot_is_valid) ret = false; // factorization failed - else if(!pivot_is_valid) found_zero_pivot = true; + if (found_zero_pivot && pivot_is_valid) + ret = false; // factorization failed + else if (!pivot_is_valid) + found_zero_pivot = true; if (sign == PositiveSemiDef) { if (realAkk < static_cast(0)) sign = Indefinite; } else if (sign == NegativeSemiDef) { if (realAkk > static_cast(0)) sign = Indefinite; } else if (sign == ZeroSign) { - if (realAkk > static_cast(0)) sign = PositiveSemiDef; - else if (realAkk < static_cast(0)) sign = NegativeSemiDef; + if (realAkk > static_cast(0)) + sign = PositiveSemiDef; + else if (realAkk < static_cast(0)) + sign = NegativeSemiDef; } } @@ -409,98 +388,91 @@ template<> struct ldlt_inplace // original matrix is not of full rank. // Here only rank-1 updates are implemented, to reduce the // requirement for intermediate storage and improve accuracy - template - static bool updateInPlace(MatrixType& mat, MatrixBase& w, const typename MatrixType::RealScalar& sigma=1) - { + template + static bool updateInPlace(MatrixType& mat, MatrixBase& w, + const typename MatrixType::RealScalar& sigma = 1) { using numext::isfinite; typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; const Index size = mat.rows(); - eigen_assert(mat.cols() == size && w.size()==size); + eigen_assert(mat.cols() == size && w.size() == size); RealScalar alpha = 1; // Apply the update - for (Index j = 0; j < size; j++) - { + for (Index j = 0; j < size; j++) { // Check for termination due to an original decomposition of low-rank - if (!(isfinite)(alpha)) - break; + if (!(isfinite)(alpha)) break; // Update the diagonal terms - RealScalar dj = numext::real(mat.coeff(j,j)); + RealScalar dj = numext::real(mat.coeff(j, j)); Scalar wj = w.coeff(j); - RealScalar swj2 = sigma*numext::abs2(wj); - RealScalar gamma = dj*alpha + swj2; - - mat.coeffRef(j,j) += swj2/alpha; - alpha += swj2/dj; + RealScalar swj2 = sigma * numext::abs2(wj); + RealScalar gamma = dj * alpha + swj2; + mat.coeffRef(j, j) += swj2 / alpha; + alpha += swj2 / dj; // Update the terms of L - Index rs = size-j-1; + Index rs = size - j - 1; w.tail(rs) -= wj * mat.col(j).tail(rs); - if(gamma != 0) - mat.col(j).tail(rs) += (sigma*numext::conj(wj)/gamma)*w.tail(rs); + if (!numext::is_exactly_zero(gamma)) mat.col(j).tail(rs) += (sigma * numext::conj(wj) / gamma) * w.tail(rs); } return true; } - template - static bool update(MatrixType& mat, const TranspositionType& transpositions, Workspace& tmp, const WType& w, const typename MatrixType::RealScalar& sigma=1) - { + template + static bool update(MatrixType& mat, const TranspositionType& transpositions, Workspace& tmp, const WType& w, + const typename MatrixType::RealScalar& sigma = 1) { // Apply the permutation to the input w tmp = transpositions * w; - return ldlt_inplace::updateInPlace(mat,tmp,sigma); + return ldlt_inplace::updateInPlace(mat, tmp, sigma); } }; -template<> struct ldlt_inplace -{ - template - static EIGEN_STRONG_INLINE bool unblocked(MatrixType& mat, TranspositionType& transpositions, Workspace& temp, SignMatrix& sign) - { +template <> +struct ldlt_inplace { + template + static EIGEN_STRONG_INLINE bool unblocked(MatrixType& mat, TranspositionType& transpositions, Workspace& temp, + SignMatrix& sign) { Transpose matt(mat); return ldlt_inplace::unblocked(matt, transpositions, temp, sign); } - template - static EIGEN_STRONG_INLINE bool update(MatrixType& mat, TranspositionType& transpositions, Workspace& tmp, WType& w, const typename MatrixType::RealScalar& sigma=1) - { + template + static EIGEN_STRONG_INLINE bool update(MatrixType& mat, TranspositionType& transpositions, Workspace& tmp, WType& w, + const typename MatrixType::RealScalar& sigma = 1) { Transpose matt(mat); return ldlt_inplace::update(matt, transpositions, tmp, w.conjugate(), sigma); } }; -template struct LDLT_Traits -{ +template +struct LDLT_Traits { typedef const TriangularView MatrixL; typedef const TriangularView MatrixU; static inline MatrixL getL(const MatrixType& m) { return MatrixL(m); } static inline MatrixU getU(const MatrixType& m) { return MatrixU(m.adjoint()); } }; -template struct LDLT_Traits -{ +template +struct LDLT_Traits { typedef const TriangularView MatrixL; typedef const TriangularView MatrixU; static inline MatrixL getL(const MatrixType& m) { return MatrixL(m.adjoint()); } static inline MatrixU getU(const MatrixType& m) { return MatrixU(m); } }; -} // end namespace internal +} // end namespace internal /** Compute / recompute the LDLT decomposition A = L D L^* = U^* D U of \a matrix - */ -template -template -LDLT& LDLT::compute(const EigenBase& a) -{ - check_template_parameters(); - - eigen_assert(a.rows()==a.cols()); + */ +template +template +LDLT& LDLT::compute(const EigenBase& a) { + eigen_assert(a.rows() == a.cols()); const Index size = a.rows(); m_matrix = a.derived(); @@ -510,12 +482,13 @@ LDLT& LDLT::compute(const EigenBase() + m_matrix.row(col).head(col).template lpNorm<1>(); + if (UpLo_ == Lower) + abs_col_sum = + m_matrix.col(col).tail(size - col).template lpNorm<1>() + m_matrix.row(col).head(col).template lpNorm<1>(); else - abs_col_sum = m_matrix.col(col).head(col).template lpNorm<1>() + m_matrix.row(col).tail(size - col).template lpNorm<1>(); - if (abs_col_sum > m_l1_norm) - m_l1_norm = abs_col_sum; + abs_col_sum = + m_matrix.col(col).head(col).template lpNorm<1>() + m_matrix.row(col).tail(size - col).template lpNorm<1>(); + if (abs_col_sum > m_l1_norm) m_l1_norm = abs_col_sum; } m_transpositions.resize(size); @@ -523,7 +496,8 @@ LDLT& LDLT::compute(const EigenBase::unblocked(m_matrix, m_transpositions, m_temporary, m_sign) ? Success : NumericalIssue; + m_info = internal::ldlt_inplace::unblocked(m_matrix, m_transpositions, m_temporary, m_sign) ? Success + : NumericalIssue; m_isInitialized = true; return *this; @@ -531,28 +505,24 @@ LDLT& LDLT::compute(const EigenBase -template -LDLT& LDLT::rankUpdate(const MatrixBase& w, const typename LDLT::RealScalar& sigma) -{ + * \param sigma a scalar, +1 for updates and -1 for "downdates," which correspond to removing previously-added column + * vectors. Optional; default value is +1. \sa setZero() + */ +template +template +LDLT& LDLT::rankUpdate( + const MatrixBase& w, const typename LDLT::RealScalar& sigma) { typedef typename TranspositionType::StorageIndex IndexType; const Index size = w.rows(); - if (m_isInitialized) - { - eigen_assert(m_matrix.rows()==size); - } - else - { - m_matrix.resize(size,size); + if (m_isInitialized) { + eigen_assert(m_matrix.rows() == size); + } else { + m_matrix.resize(size, size); m_matrix.setZero(); m_transpositions.resize(size); - for (Index i = 0; i < size; i++) - m_transpositions.coeffRef(i) = IndexType(i); + for (Index i = 0; i < size; i++) m_transpositions.coeffRef(i) = IndexType(i); m_temporary.resize(size); - m_sign = sigma>=0 ? internal::PositiveSemiDef : internal::NegativeSemiDef; + m_sign = sigma >= 0 ? internal::PositiveSemiDef : internal::NegativeSemiDef; m_isInitialized = true; } @@ -562,17 +532,15 @@ LDLT& LDLT::rankUpdate(const MatrixBase -template -void LDLT<_MatrixType,_UpLo>::_solve_impl(const RhsType &rhs, DstType &dst) const -{ +template +template +void LDLT::_solve_impl(const RhsType& rhs, DstType& dst) const { _solve_impl_transposed(rhs, dst); } -template -template -void LDLT<_MatrixType,_UpLo>::_solve_impl_transposed(const RhsType &rhs, DstType &dst) const -{ +template +template +void LDLT::_solve_impl_transposed(const RhsType& rhs, DstType& dst) const { // dst = P b dst = m_transpositions * rhs; @@ -587,15 +555,13 @@ void LDLT<_MatrixType,_UpLo>::_solve_impl_transposed(const RhsType &rhs, DstType const typename Diagonal::RealReturnType vecD(vectorD()); // In some previous versions, tolerance was set to the max of 1/highest (or rather numeric_limits::min()) // and the maximal diagonal entry * epsilon as motivated by LAPACK's xGELSS: - // RealScalar tolerance = numext::maxi(vecD.array().abs().maxCoeff() * NumTraits::epsilon(),RealScalar(1) / NumTraits::highest()); - // However, LDLT is not rank revealing, and so adjusting the tolerance wrt to the highest - // diagonal element is not well justified and leads to numerical issues in some cases. - // Moreover, Lapack's xSYTRS routines use 0 for the tolerance. - // Using numeric_limits::min() gives us more robustness to denormals. + // RealScalar tolerance = numext::maxi(vecD.array().abs().maxCoeff() * NumTraits::epsilon(),RealScalar(1) + // / NumTraits::highest()); However, LDLT is not rank revealing, and so adjusting the tolerance wrt to the + // highest diagonal element is not well justified and leads to numerical issues in some cases. Moreover, Lapack's + // xSYTRS routines use 0 for the tolerance. Using numeric_limits::min() gives us more robustness to denormals. RealScalar tolerance = (std::numeric_limits::min)(); - for (Index i = 0; i < vecD.size(); ++i) - { - if(abs(vecD(i)) > tolerance) + for (Index i = 0; i < vecD.size(); ++i) { + if (abs(vecD(i)) > tolerance) dst.row(i) /= vecD(i); else dst.row(i).setZero(); @@ -612,22 +578,21 @@ void LDLT<_MatrixType,_UpLo>::_solve_impl_transposed(const RhsType &rhs, DstType #endif /** \internal use x = ldlt_object.solve(x); - * - * This is the \em in-place version of solve(). - * - * \param bAndX represents both the right-hand side matrix b and result x. - * - * \returns true always! If you need to check for existence of solutions, use another decomposition like LU, QR, or SVD. - * - * This version avoids a copy when the right hand side matrix b is not - * needed anymore. - * - * \sa LDLT::solve(), MatrixBase::ldlt() - */ -template -template -bool LDLT::solveInPlace(MatrixBase &bAndX) const -{ + * + * This is the \em in-place version of solve(). + * + * \param bAndX represents both the right-hand side matrix b and result x. + * + * \returns true always! If you need to check for existence of solutions, use another decomposition like LU, QR, or SVD. + * + * This version avoids a copy when the right hand side matrix b is not + * needed anymore. + * + * \sa LDLT::solve(), MatrixBase::ldlt() + */ +template +template +bool LDLT::solveInPlace(MatrixBase& bAndX) const { eigen_assert(m_isInitialized && "LDLT is not initialized."); eigen_assert(m_matrix.rows() == bAndX.rows()); @@ -639,12 +604,11 @@ bool LDLT::solveInPlace(MatrixBase &bAndX) const /** \returns the matrix represented by the decomposition, * i.e., it returns the product: P^T L D L^* P. * This function is provided for debug purpose. */ -template -MatrixType LDLT::reconstructedMatrix() const -{ +template +MatrixType LDLT::reconstructedMatrix() const { eigen_assert(m_isInitialized && "LDLT is not initialized."); const Index size = m_matrix.rows(); - MatrixType res(size,size); + MatrixType res(size, size); // P res.setIdentity(); @@ -662,27 +626,24 @@ MatrixType LDLT::reconstructedMatrix() const } /** \cholesky_module - * \returns the Cholesky decomposition with full pivoting without square root of \c *this - * \sa MatrixBase::ldlt() - */ -template + * \returns the Cholesky decomposition with full pivoting without square root of \c *this + * \sa MatrixBase::ldlt() + */ +template inline const LDLT::PlainObject, UpLo> -SelfAdjointView::ldlt() const -{ - return LDLT(m_matrix); +SelfAdjointView::ldlt() const { + return LDLT(m_matrix); } /** \cholesky_module - * \returns the Cholesky decomposition with full pivoting without square root of \c *this - * \sa SelfAdjointView::ldlt() - */ -template -inline const LDLT::PlainObject> -MatrixBase::ldlt() const -{ + * \returns the Cholesky decomposition with full pivoting without square root of \c *this + * \sa SelfAdjointView::ldlt() + */ +template +inline const LDLT::PlainObject> MatrixBase::ldlt() const { return LDLT(derived()); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_LDLT_H +#endif // EIGEN_LDLT_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Cholesky/LLT.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Cholesky/LLT.h index 8c9b2b39879..01b44769a26 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Cholesky/LLT.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Cholesky/LLT.h @@ -10,446 +10,410 @@ #ifndef EIGEN_LLT_H #define EIGEN_LLT_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { -namespace internal{ +namespace internal { -template struct traits > - : traits<_MatrixType> -{ +template +struct traits > : traits { typedef MatrixXpr XprKind; typedef SolverStorage StorageKind; typedef int StorageIndex; enum { Flags = 0 }; }; -template struct LLT_Traits; -} +template +struct LLT_Traits; +} // namespace internal /** \ingroup Cholesky_Module - * - * \class LLT - * - * \brief Standard Cholesky decomposition (LL^T) of a matrix and associated features - * - * \tparam _MatrixType the type of the matrix of which we are computing the LL^T Cholesky decomposition - * \tparam _UpLo the triangular part that will be used for the decompositon: Lower (default) or Upper. - * The other triangular part won't be read. - * - * This class performs a LL^T Cholesky decomposition of a symmetric, positive definite - * matrix A such that A = LL^* = U^*U, where L is lower triangular. - * - * While the Cholesky decomposition is particularly useful to solve selfadjoint problems like D^*D x = b, - * for that purpose, we recommend the Cholesky decomposition without square root which is more stable - * and even faster. Nevertheless, this standard Cholesky decomposition remains useful in many other - * situations like generalised eigen problems with hermitian matrices. - * - * Remember that Cholesky decompositions are not rank-revealing. This LLT decomposition is only stable on positive definite matrices, - * use LDLT instead for the semidefinite case. Also, do not use a Cholesky decomposition to determine whether a system of equations - * has a solution. - * - * Example: \include LLT_example.cpp - * Output: \verbinclude LLT_example.out - * - * \b Performance: for best performance, it is recommended to use a column-major storage format - * with the Lower triangular part (the default), or, equivalently, a row-major storage format - * with the Upper triangular part. Otherwise, you might get a 20% slowdown for the full factorization - * step, and rank-updates can be up to 3 times slower. - * - * This class supports the \link InplaceDecomposition inplace decomposition \endlink mechanism. - * - * Note that during the decomposition, only the lower (or upper, as defined by _UpLo) triangular part of A is considered. - * Therefore, the strict lower part does not have to store correct values. - * - * \sa MatrixBase::llt(), SelfAdjointView::llt(), class LDLT - */ -template class LLT - : public SolverBase > -{ - public: - typedef _MatrixType MatrixType; - typedef SolverBase Base; - friend class SolverBase; - - EIGEN_GENERIC_PUBLIC_INTERFACE(LLT) - enum { - MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime - }; - - enum { - PacketSize = internal::packet_traits::size, - AlignmentMask = int(PacketSize)-1, - UpLo = _UpLo - }; - - typedef internal::LLT_Traits Traits; - - /** - * \brief Default Constructor. - * - * The default constructor is useful in cases in which the user intends to - * perform decompositions via LLT::compute(const MatrixType&). - */ - LLT() : m_matrix(), m_isInitialized(false) {} - - /** \brief Default Constructor with memory preallocation - * - * Like the default constructor but with preallocation of the internal data - * according to the specified problem \a size. - * \sa LLT() - */ - explicit LLT(Index size) : m_matrix(size, size), - m_isInitialized(false) {} - - template - explicit LLT(const EigenBase& matrix) - : m_matrix(matrix.rows(), matrix.cols()), - m_isInitialized(false) - { - compute(matrix.derived()); - } + * + * \class LLT + * + * \brief Standard Cholesky decomposition (LL^T) of a matrix and associated features + * + * \tparam MatrixType_ the type of the matrix of which we are computing the LL^T Cholesky decomposition + * \tparam UpLo_ the triangular part that will be used for the decomposition: Lower (default) or Upper. + * The other triangular part won't be read. + * + * This class performs a LL^T Cholesky decomposition of a symmetric, positive definite + * matrix A such that A = LL^* = U^*U, where L is lower triangular. + * + * While the Cholesky decomposition is particularly useful to solve selfadjoint problems like D^*D x = b, + * for that purpose, we recommend the Cholesky decomposition without square root which is more stable + * and even faster. Nevertheless, this standard Cholesky decomposition remains useful in many other + * situations like generalised eigen problems with hermitian matrices. + * + * Remember that Cholesky decompositions are not rank-revealing. This LLT decomposition is only stable on positive + * definite matrices, use LDLT instead for the semidefinite case. Also, do not use a Cholesky decomposition to determine + * whether a system of equations has a solution. + * + * Example: \include LLT_example.cpp + * Output: \verbinclude LLT_example.out + * + * \b Performance: for best performance, it is recommended to use a column-major storage format + * with the Lower triangular part (the default), or, equivalently, a row-major storage format + * with the Upper triangular part. Otherwise, you might get a 20% slowdown for the full factorization + * step, and rank-updates can be up to 3 times slower. + * + * This class supports the \link InplaceDecomposition inplace decomposition \endlink mechanism. + * + * Note that during the decomposition, only the lower (or upper, as defined by UpLo_) triangular part of A is + * considered. Therefore, the strict lower part does not have to store correct values. + * + * \sa MatrixBase::llt(), SelfAdjointView::llt(), class LDLT + */ +template +class LLT : public SolverBase > { + public: + typedef MatrixType_ MatrixType; + typedef SolverBase Base; + friend class SolverBase; + + EIGEN_GENERIC_PUBLIC_INTERFACE(LLT) + enum { MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime }; + + enum { PacketSize = internal::packet_traits::size, AlignmentMask = int(PacketSize) - 1, UpLo = UpLo_ }; + + typedef internal::LLT_Traits Traits; + + /** + * \brief Default Constructor. + * + * The default constructor is useful in cases in which the user intends to + * perform decompositions via LLT::compute(const MatrixType&). + */ + LLT() : m_matrix(), m_isInitialized(false) {} + + /** \brief Default Constructor with memory preallocation + * + * Like the default constructor but with preallocation of the internal data + * according to the specified problem \a size. + * \sa LLT() + */ + explicit LLT(Index size) : m_matrix(size, size), m_isInitialized(false) {} + + template + explicit LLT(const EigenBase& matrix) : m_matrix(matrix.rows(), matrix.cols()), m_isInitialized(false) { + compute(matrix.derived()); + } - /** \brief Constructs a LLT factorization from a given matrix - * - * This overloaded constructor is provided for \link InplaceDecomposition inplace decomposition \endlink when - * \c MatrixType is a Eigen::Ref. - * - * \sa LLT(const EigenBase&) - */ - template - explicit LLT(EigenBase& matrix) - : m_matrix(matrix.derived()), - m_isInitialized(false) - { - compute(matrix.derived()); - } + /** \brief Constructs a LLT factorization from a given matrix + * + * This overloaded constructor is provided for \link InplaceDecomposition inplace decomposition \endlink when + * \c MatrixType is a Eigen::Ref. + * + * \sa LLT(const EigenBase&) + */ + template + explicit LLT(EigenBase& matrix) : m_matrix(matrix.derived()), m_isInitialized(false) { + compute(matrix.derived()); + } - /** \returns a view of the upper triangular matrix U */ - inline typename Traits::MatrixU matrixU() const - { - eigen_assert(m_isInitialized && "LLT is not initialized."); - return Traits::getU(m_matrix); - } + /** \returns a view of the upper triangular matrix U */ + inline typename Traits::MatrixU matrixU() const { + eigen_assert(m_isInitialized && "LLT is not initialized."); + return Traits::getU(m_matrix); + } - /** \returns a view of the lower triangular matrix L */ - inline typename Traits::MatrixL matrixL() const - { - eigen_assert(m_isInitialized && "LLT is not initialized."); - return Traits::getL(m_matrix); - } + /** \returns a view of the lower triangular matrix L */ + inline typename Traits::MatrixL matrixL() const { + eigen_assert(m_isInitialized && "LLT is not initialized."); + return Traits::getL(m_matrix); + } - #ifdef EIGEN_PARSED_BY_DOXYGEN - /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A. - * - * Since this LLT class assumes anyway that the matrix A is invertible, the solution - * theoretically exists and is unique regardless of b. - * - * Example: \include LLT_solve.cpp - * Output: \verbinclude LLT_solve.out - * - * \sa solveInPlace(), MatrixBase::llt(), SelfAdjointView::llt() - */ - template - inline const Solve - solve(const MatrixBase& b) const; - #endif - - template - void solveInPlace(const MatrixBase &bAndX) const; - - template - LLT& compute(const EigenBase& matrix); - - /** \returns an estimate of the reciprocal condition number of the matrix of - * which \c *this is the Cholesky decomposition. - */ - RealScalar rcond() const - { - eigen_assert(m_isInitialized && "LLT is not initialized."); - eigen_assert(m_info == Success && "LLT failed because matrix appears to be negative"); - return internal::rcond_estimate_helper(m_l1_norm, *this); - } +#ifdef EIGEN_PARSED_BY_DOXYGEN + /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A. + * + * Since this LLT class assumes anyway that the matrix A is invertible, the solution + * theoretically exists and is unique regardless of b. + * + * Example: \include LLT_solve.cpp + * Output: \verbinclude LLT_solve.out + * + * \sa solveInPlace(), MatrixBase::llt(), SelfAdjointView::llt() + */ + template + inline const Solve solve(const MatrixBase& b) const; +#endif - /** \returns the LLT decomposition matrix - * - * TODO: document the storage layout - */ - inline const MatrixType& matrixLLT() const - { - eigen_assert(m_isInitialized && "LLT is not initialized."); - return m_matrix; - } + template + void solveInPlace(const MatrixBase& bAndX) const; - MatrixType reconstructedMatrix() const; + template + LLT& compute(const EigenBase& matrix); + /** \returns an estimate of the reciprocal condition number of the matrix of + * which \c *this is the Cholesky decomposition. + */ + RealScalar rcond() const { + eigen_assert(m_isInitialized && "LLT is not initialized."); + eigen_assert(m_info == Success && "LLT failed because matrix appears to be negative"); + return internal::rcond_estimate_helper(m_l1_norm, *this); + } - /** \brief Reports whether previous computation was successful. - * - * \returns \c Success if computation was successful, - * \c NumericalIssue if the matrix.appears not to be positive definite. - */ - ComputationInfo info() const - { - eigen_assert(m_isInitialized && "LLT is not initialized."); - return m_info; - } + /** \returns the LLT decomposition matrix + * + * TODO: document the storage layout + */ + inline const MatrixType& matrixLLT() const { + eigen_assert(m_isInitialized && "LLT is not initialized."); + return m_matrix; + } - /** \returns the adjoint of \c *this, that is, a const reference to the decomposition itself as the underlying matrix is self-adjoint. - * - * This method is provided for compatibility with other matrix decompositions, thus enabling generic code such as: - * \code x = decomposition.adjoint().solve(b) \endcode - */ - const LLT& adjoint() const EIGEN_NOEXCEPT { return *this; }; + MatrixType reconstructedMatrix() const; - inline EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_matrix.rows(); } - inline EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_matrix.cols(); } + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was successful, + * \c NumericalIssue if the matrix.appears not to be positive definite. + */ + ComputationInfo info() const { + eigen_assert(m_isInitialized && "LLT is not initialized."); + return m_info; + } - template - LLT & rankUpdate(const VectorType& vec, const RealScalar& sigma = 1); + /** \returns the adjoint of \c *this, that is, a const reference to the decomposition itself as the underlying matrix + * is self-adjoint. + * + * This method is provided for compatibility with other matrix decompositions, thus enabling generic code such as: + * \code x = decomposition.adjoint().solve(b) \endcode + */ + const LLT& adjoint() const EIGEN_NOEXCEPT { return *this; } - #ifndef EIGEN_PARSED_BY_DOXYGEN - template - void _solve_impl(const RhsType &rhs, DstType &dst) const; + inline EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_matrix.rows(); } + inline EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_matrix.cols(); } - template - void _solve_impl_transposed(const RhsType &rhs, DstType &dst) const; - #endif + template + LLT& rankUpdate(const VectorType& vec, const RealScalar& sigma = 1); - protected: +#ifndef EIGEN_PARSED_BY_DOXYGEN + template + void _solve_impl(const RhsType& rhs, DstType& dst) const; - static void check_template_parameters() - { - EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar); - } + template + void _solve_impl_transposed(const RhsType& rhs, DstType& dst) const; +#endif - /** \internal - * Used to compute and store L - * The strict upper part is not used and even not initialized. - */ - MatrixType m_matrix; - RealScalar m_l1_norm; - bool m_isInitialized; - ComputationInfo m_info; + protected: + EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar) + + /** \internal + * Used to compute and store L + * The strict upper part is not used and even not initialized. + */ + MatrixType m_matrix; + RealScalar m_l1_norm; + bool m_isInitialized; + ComputationInfo m_info; }; namespace internal { -template struct llt_inplace; +template +struct llt_inplace; -template -static Index llt_rank_update_lower(MatrixType& mat, const VectorType& vec, const typename MatrixType::RealScalar& sigma) -{ +template +static Index llt_rank_update_lower(MatrixType& mat, const VectorType& vec, + const typename MatrixType::RealScalar& sigma) { using std::sqrt; typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; typedef typename MatrixType::ColXpr ColXpr; - typedef typename internal::remove_all::type ColXprCleaned; + typedef internal::remove_all_t ColXprCleaned; typedef typename ColXprCleaned::SegmentReturnType ColXprSegment; - typedef Matrix TempVectorType; + typedef Matrix TempVectorType; typedef typename TempVectorType::SegmentReturnType TempVecSegment; Index n = mat.cols(); - eigen_assert(mat.rows()==n && vec.size()==n); + eigen_assert(mat.rows() == n && vec.size() == n); TempVectorType temp; - if(sigma>0) - { + if (sigma > 0) { // This version is based on Givens rotations. // It is faster than the other one below, but only works for updates, // i.e., for sigma > 0 temp = sqrt(sigma) * vec; - for(Index i=0; i g; - g.makeGivens(mat(i,i), -temp(i), &mat(i,i)); + g.makeGivens(mat(i, i), -temp(i), &mat(i, i)); - Index rs = n-i-1; - if(rs>0) - { + Index rs = n - i - 1; + if (rs > 0) { ColXprSegment x(mat.col(i).tail(rs)); TempVecSegment y(temp.tail(rs)); apply_rotation_in_the_plane(x, y, g); } } - } - else - { + } else { temp = vec; RealScalar beta = 1; - for(Index j=0; j struct llt_inplace -{ +template +struct llt_inplace { typedef typename NumTraits::Real RealScalar; - template - static Index unblocked(MatrixType& mat) - { + template + static Index unblocked(MatrixType& mat) { using std::sqrt; - eigen_assert(mat.rows()==mat.cols()); + eigen_assert(mat.rows() == mat.cols()); const Index size = mat.rows(); - for(Index k = 0; k < size; ++k) - { - Index rs = size-k-1; // remaining size - - Block A21(mat,k+1,k,rs,1); - Block A10(mat,k,0,1,k); - Block A20(mat,k+1,0,rs,k); - - RealScalar x = numext::real(mat.coeff(k,k)); - if (k>0) x -= A10.squaredNorm(); - if (x<=RealScalar(0)) - return k; - mat.coeffRef(k,k) = x = sqrt(x); - if (k>0 && rs>0) A21.noalias() -= A20 * A10.adjoint(); - if (rs>0) A21 /= x; + for (Index k = 0; k < size; ++k) { + Index rs = size - k - 1; // remaining size + + Block A21(mat, k + 1, k, rs, 1); + Block A10(mat, k, 0, 1, k); + Block A20(mat, k + 1, 0, rs, k); + + RealScalar x = numext::real(mat.coeff(k, k)); + if (k > 0) x -= A10.squaredNorm(); + if (x <= RealScalar(0)) return k; + mat.coeffRef(k, k) = x = sqrt(x); + if (k > 0 && rs > 0) A21.noalias() -= A20 * A10.adjoint(); + if (rs > 0) A21 /= x; } return -1; } - template - static Index blocked(MatrixType& m) - { - eigen_assert(m.rows()==m.cols()); + template + static Index blocked(MatrixType& m) { + eigen_assert(m.rows() == m.cols()); Index size = m.rows(); - if(size<32) - return unblocked(m); + if (size < 32) return unblocked(m); - Index blockSize = size/8; - blockSize = (blockSize/16)*16; - blockSize = (std::min)((std::max)(blockSize,Index(8)), Index(128)); + Index blockSize = size / 8; + blockSize = (blockSize / 16) * 16; + blockSize = (std::min)((std::max)(blockSize, Index(8)), Index(128)); - for (Index k=0; k A11(m,k, k, bs,bs); - Block A21(m,k+bs,k, rs,bs); - Block A22(m,k+bs,k+bs,rs,rs); + Block A11(m, k, k, bs, bs); + Block A21(m, k + bs, k, rs, bs); + Block A22(m, k + bs, k + bs, rs, rs); Index ret; - if((ret=unblocked(A11))>=0) return k+ret; - if(rs>0) A11.adjoint().template triangularView().template solveInPlace(A21); - if(rs>0) A22.template selfadjointView().rankUpdate(A21,typename NumTraits::Literal(-1)); // bottleneck + if ((ret = unblocked(A11)) >= 0) return k + ret; + if (rs > 0) A11.adjoint().template triangularView().template solveInPlace(A21); + if (rs > 0) + A22.template selfadjointView().rankUpdate(A21, + typename NumTraits::Literal(-1)); // bottleneck } return -1; } - template - static Index rankUpdate(MatrixType& mat, const VectorType& vec, const RealScalar& sigma) - { + template + static Index rankUpdate(MatrixType& mat, const VectorType& vec, const RealScalar& sigma) { return Eigen::internal::llt_rank_update_lower(mat, vec, sigma); } }; -template struct llt_inplace -{ +template +struct llt_inplace { typedef typename NumTraits::Real RealScalar; - template - static EIGEN_STRONG_INLINE Index unblocked(MatrixType& mat) - { + template + static EIGEN_STRONG_INLINE Index unblocked(MatrixType& mat) { Transpose matt(mat); return llt_inplace::unblocked(matt); } - template - static EIGEN_STRONG_INLINE Index blocked(MatrixType& mat) - { + template + static EIGEN_STRONG_INLINE Index blocked(MatrixType& mat) { Transpose matt(mat); return llt_inplace::blocked(matt); } - template - static Index rankUpdate(MatrixType& mat, const VectorType& vec, const RealScalar& sigma) - { + template + static Index rankUpdate(MatrixType& mat, const VectorType& vec, const RealScalar& sigma) { Transpose matt(mat); return llt_inplace::rankUpdate(matt, vec.conjugate(), sigma); } }; -template struct LLT_Traits -{ +template +struct LLT_Traits { typedef const TriangularView MatrixL; typedef const TriangularView MatrixU; static inline MatrixL getL(const MatrixType& m) { return MatrixL(m); } static inline MatrixU getU(const MatrixType& m) { return MatrixU(m.adjoint()); } - static bool inplace_decomposition(MatrixType& m) - { return llt_inplace::blocked(m)==-1; } + static bool inplace_decomposition(MatrixType& m) { + return llt_inplace::blocked(m) == -1; + } }; -template struct LLT_Traits -{ +template +struct LLT_Traits { typedef const TriangularView MatrixL; typedef const TriangularView MatrixU; static inline MatrixL getL(const MatrixType& m) { return MatrixL(m.adjoint()); } static inline MatrixU getU(const MatrixType& m) { return MatrixU(m); } - static bool inplace_decomposition(MatrixType& m) - { return llt_inplace::blocked(m)==-1; } + static bool inplace_decomposition(MatrixType& m) { + return llt_inplace::blocked(m) == -1; + } }; -} // end namespace internal +} // end namespace internal /** Computes / recomputes the Cholesky decomposition A = LL^* = U^*U of \a matrix - * - * \returns a reference to *this - * - * Example: \include TutorialLinAlgComputeTwice.cpp - * Output: \verbinclude TutorialLinAlgComputeTwice.out - */ -template -template -LLT& LLT::compute(const EigenBase& a) -{ - check_template_parameters(); - - eigen_assert(a.rows()==a.cols()); + * + * \returns a reference to *this + * + * Example: \include TutorialLinAlgComputeTwice.cpp + * Output: \verbinclude TutorialLinAlgComputeTwice.out + */ +template +template +LLT& LLT::compute(const EigenBase& a) { + eigen_assert(a.rows() == a.cols()); const Index size = a.rows(); m_matrix.resize(size, size); - if (!internal::is_same_dense(m_matrix, a.derived())) - m_matrix = a.derived(); + if (!internal::is_same_dense(m_matrix, a.derived())) m_matrix = a.derived(); // Compute matrix L1 norm = max abs column sum. m_l1_norm = RealScalar(0); // TODO move this code to SelfAdjointView for (Index col = 0; col < size; ++col) { RealScalar abs_col_sum; - if (_UpLo == Lower) - abs_col_sum = m_matrix.col(col).tail(size - col).template lpNorm<1>() + m_matrix.row(col).head(col).template lpNorm<1>(); + if (UpLo_ == Lower) + abs_col_sum = + m_matrix.col(col).tail(size - col).template lpNorm<1>() + m_matrix.row(col).head(col).template lpNorm<1>(); else - abs_col_sum = m_matrix.col(col).head(col).template lpNorm<1>() + m_matrix.row(col).tail(size - col).template lpNorm<1>(); - if (abs_col_sum > m_l1_norm) - m_l1_norm = abs_col_sum; + abs_col_sum = + m_matrix.col(col).head(col).template lpNorm<1>() + m_matrix.row(col).tail(size - col).template lpNorm<1>(); + if (abs_col_sum > m_l1_norm) m_l1_norm = abs_col_sum; } m_isInitialized = true; @@ -460,18 +424,17 @@ LLT& LLT::compute(const EigenBase } /** Performs a rank one update (or dowdate) of the current decomposition. - * If A = LL^* before the rank one update, - * then after it we have LL^* = A + sigma * v v^* where \a v must be a vector - * of same dimension. - */ -template -template -LLT<_MatrixType,_UpLo> & LLT<_MatrixType,_UpLo>::rankUpdate(const VectorType& v, const RealScalar& sigma) -{ + * If A = LL^* before the rank one update, + * then after it we have LL^* = A + sigma * v v^* where \a v must be a vector + * of same dimension. + */ +template +template +LLT& LLT::rankUpdate(const VectorType& v, const RealScalar& sigma) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(VectorType); - eigen_assert(v.size()==m_matrix.cols()); + eigen_assert(v.size() == m_matrix.cols()); eigen_assert(m_isInitialized); - if(internal::llt_inplace::rankUpdate(m_matrix,v,sigma)>=0) + if (internal::llt_inplace::rankUpdate(m_matrix, v, sigma) >= 0) m_info = NumericalIssue; else m_info = Success; @@ -480,43 +443,40 @@ LLT<_MatrixType,_UpLo> & LLT<_MatrixType,_UpLo>::rankUpdate(const VectorType& v, } #ifndef EIGEN_PARSED_BY_DOXYGEN -template -template -void LLT<_MatrixType,_UpLo>::_solve_impl(const RhsType &rhs, DstType &dst) const -{ +template +template +void LLT::_solve_impl(const RhsType& rhs, DstType& dst) const { _solve_impl_transposed(rhs, dst); } -template -template -void LLT<_MatrixType,_UpLo>::_solve_impl_transposed(const RhsType &rhs, DstType &dst) const -{ - dst = rhs; +template +template +void LLT::_solve_impl_transposed(const RhsType& rhs, DstType& dst) const { + dst = rhs; - matrixL().template conjugateIf().solveInPlace(dst); - matrixU().template conjugateIf().solveInPlace(dst); + matrixL().template conjugateIf().solveInPlace(dst); + matrixU().template conjugateIf().solveInPlace(dst); } #endif /** \internal use x = llt_object.solve(x); - * - * This is the \em in-place version of solve(). - * - * \param bAndX represents both the right-hand side matrix b and result x. - * - * This version avoids a copy when the right hand side matrix b is not needed anymore. - * - * \warning The parameter is only marked 'const' to make the C++ compiler accept a temporary expression here. - * This function will const_cast it, so constness isn't honored here. - * - * \sa LLT::solve(), MatrixBase::llt() - */ -template -template -void LLT::solveInPlace(const MatrixBase &bAndX) const -{ + * + * This is the \em in-place version of solve(). + * + * \param bAndX represents both the right-hand side matrix b and result x. + * + * This version avoids a copy when the right hand side matrix b is not needed anymore. + * + * \warning The parameter is only marked 'const' to make the C++ compiler accept a temporary expression here. + * This function will const_cast it, so constness isn't honored here. + * + * \sa LLT::solve(), MatrixBase::llt() + */ +template +template +void LLT::solveInPlace(const MatrixBase& bAndX) const { eigen_assert(m_isInitialized && "LLT is not initialized."); - eigen_assert(m_matrix.rows()==bAndX.rows()); + eigen_assert(m_matrix.rows() == bAndX.rows()); matrixL().solveInPlace(bAndX); matrixU().solveInPlace(bAndX); } @@ -524,35 +484,31 @@ void LLT::solveInPlace(const MatrixBase &bAndX) const /** \returns the matrix represented by the decomposition, * i.e., it returns the product: L L^*. * This function is provided for debug purpose. */ -template -MatrixType LLT::reconstructedMatrix() const -{ +template +MatrixType LLT::reconstructedMatrix() const { eigen_assert(m_isInitialized && "LLT is not initialized."); return matrixL() * matrixL().adjoint().toDenseMatrix(); } /** \cholesky_module - * \returns the LLT decomposition of \c *this - * \sa SelfAdjointView::llt() - */ -template -inline const LLT::PlainObject> -MatrixBase::llt() const -{ + * \returns the LLT decomposition of \c *this + * \sa SelfAdjointView::llt() + */ +template +inline const LLT::PlainObject> MatrixBase::llt() const { return LLT(derived()); } /** \cholesky_module - * \returns the LLT decomposition of \c *this - * \sa SelfAdjointView::llt() - */ -template -inline const LLT::PlainObject, UpLo> -SelfAdjointView::llt() const -{ - return LLT(m_matrix); + * \returns the LLT decomposition of \c *this + * \sa SelfAdjointView::llt() + */ +template +inline const LLT::PlainObject, UpLo> SelfAdjointView::llt() + const { + return LLT(m_matrix); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_LLT_H +#endif // EIGEN_LLT_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ArithmeticSequence.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ArithmeticSequence.h index b6200fac1b0..ae6373dda2d 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ArithmeticSequence.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ArithmeticSequence.h @@ -10,374 +10,202 @@ #ifndef EIGEN_ARITHMETIC_SEQUENCE_H #define EIGEN_ARITHMETIC_SEQUENCE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -#if (!EIGEN_HAS_CXX11) || !((!EIGEN_COMP_GNUC) || EIGEN_COMP_GNUC>=48) -template struct aseq_negate {}; - -template<> struct aseq_negate { - typedef Index type; -}; - -template struct aseq_negate > { - typedef FixedInt<-N> type; -}; - -// Compilation error in the following case: -template<> struct aseq_negate > {}; - -template::value, - bool SizeIsSymbolic =symbolic::is_symbolic::value> -struct aseq_reverse_first_type { - typedef Index type; -}; - -template -struct aseq_reverse_first_type { - typedef symbolic::AddExpr > >, - symbolic::ValueExpr > - > type; -}; - -template -struct aseq_reverse_first_type_aux { - typedef Index type; -}; - -template -struct aseq_reverse_first_type_aux::type> { - typedef FixedInt<(SizeType::value-1)*IncrType::value> type; -}; - -template -struct aseq_reverse_first_type { - typedef typename aseq_reverse_first_type_aux::type Aux; - typedef symbolic::AddExpr > type; -}; - -template -struct aseq_reverse_first_type { - typedef symbolic::AddExpr > >, - symbolic::ValueExpr >, - symbolic::ValueExpr<> > type; -}; -#endif - // Helper to cleanup the type of the increment: -template struct cleanup_seq_incr { - typedef typename cleanup_index_type::type type; +template +struct cleanup_seq_incr { + typedef typename cleanup_index_type::type type; }; -} +} // namespace internal //-------------------------------------------------------------------------------- // seq(first,last,incr) and seqN(first,size,incr) //-------------------------------------------------------------------------------- -template > +template > class ArithmeticSequence; -template +template ArithmeticSequence::type, typename internal::cleanup_index_type::type, - typename internal::cleanup_seq_incr::type > + typename internal::cleanup_seq_incr::type> seqN(FirstType first, SizeType size, IncrType incr); /** \class ArithmeticSequence - * \ingroup Core_Module - * - * This class represents an arithmetic progression \f$ a_0, a_1, a_2, ..., a_{n-1}\f$ defined by - * its \em first value \f$ a_0 \f$, its \em size (aka length) \em n, and the \em increment (aka stride) - * that is equal to \f$ a_{i+1}-a_{i}\f$ for any \em i. - * - * It is internally used as the return type of the Eigen::seq and Eigen::seqN functions, and as the input arguments - * of DenseBase::operator()(const RowIndices&, const ColIndices&), and most of the time this is the - * only way it is used. - * - * \tparam FirstType type of the first element, usually an Index, - * but internally it can be a symbolic expression - * \tparam SizeType type representing the size of the sequence, usually an Index - * or a compile time integral constant. Internally, it can also be a symbolic expression - * \tparam IncrType type of the increment, can be a runtime Index, or a compile time integral constant (default is compile-time 1) - * - * \sa Eigen::seq, Eigen::seqN, DenseBase::operator()(const RowIndices&, const ColIndices&), class IndexedView - */ -template -class ArithmeticSequence -{ -public: - ArithmeticSequence(FirstType first, SizeType size) : m_first(first), m_size(size) {} - ArithmeticSequence(FirstType first, SizeType size, IncrType incr) : m_first(first), m_size(size), m_incr(incr) {} + * \ingroup Core_Module + * + * This class represents an arithmetic progression \f$ a_0, a_1, a_2, ..., a_{n-1}\f$ defined by + * its \em first value \f$ a_0 \f$, its \em size (aka length) \em n, and the \em increment (aka stride) + * that is equal to \f$ a_{i+1}-a_{i}\f$ for any \em i. + * + * It is internally used as the return type of the Eigen::seq and Eigen::seqN functions, and as the input arguments + * of DenseBase::operator()(const RowIndices&, const ColIndices&), and most of the time this is the + * only way it is used. + * + * \tparam FirstType type of the first element, usually an Index, + * but internally it can be a symbolic expression + * \tparam SizeType type representing the size of the sequence, usually an Index + * or a compile time integral constant. Internally, it can also be a symbolic expression + * \tparam IncrType type of the increment, can be a runtime Index, or a compile time integral constant (default is + * compile-time 1) + * + * \sa Eigen::seq, Eigen::seqN, DenseBase::operator()(const RowIndices&, const ColIndices&), class IndexedView + */ +template +class ArithmeticSequence { + public: + constexpr ArithmeticSequence() = default; + constexpr ArithmeticSequence(FirstType first, SizeType size) : m_first(first), m_size(size) {} + constexpr ArithmeticSequence(FirstType first, SizeType size, IncrType incr) + : m_first(first), m_size(size), m_incr(incr) {} enum { - SizeAtCompileTime = internal::get_fixed_value::value, - IncrAtCompileTime = internal::get_fixed_value::value + // SizeAtCompileTime = internal::get_fixed_value::value, + IncrAtCompileTime = internal::get_fixed_value::value }; /** \returns the size, i.e., number of elements, of the sequence */ - Index size() const { return m_size; } + constexpr Index size() const { return m_size; } /** \returns the first element \f$ a_0 \f$ in the sequence */ - Index first() const { return m_first; } + constexpr Index first() const { return m_first; } /** \returns the value \f$ a_i \f$ at index \a i in the sequence. */ - Index operator[](Index i) const { return m_first + i * m_incr; } + constexpr Index operator[](Index i) const { return m_first + i * m_incr; } - const FirstType& firstObject() const { return m_first; } - const SizeType& sizeObject() const { return m_size; } - const IncrType& incrObject() const { return m_incr; } + constexpr const FirstType& firstObject() const { return m_first; } + constexpr const SizeType& sizeObject() const { return m_size; } + constexpr const IncrType& incrObject() const { return m_incr; } -protected: + protected: FirstType m_first; - SizeType m_size; - IncrType m_incr; - -public: + SizeType m_size; + IncrType m_incr; -#if EIGEN_HAS_CXX11 && ((!EIGEN_COMP_GNUC) || EIGEN_COMP_GNUC>=48) - auto reverse() const -> decltype(Eigen::seqN(m_first+(m_size+fix<-1>())*m_incr,m_size,-m_incr)) { - return seqN(m_first+(m_size+fix<-1>())*m_incr,m_size,-m_incr); - } -#else -protected: - typedef typename internal::aseq_negate::type ReverseIncrType; - typedef typename internal::aseq_reverse_first_type::type ReverseFirstType; -public: - ArithmeticSequence - reverse() const { - return seqN(m_first+(m_size+fix<-1>())*m_incr,m_size,-m_incr); + public: + constexpr auto reverse() const -> decltype(Eigen::seqN(m_first + (m_size + fix<-1>()) * m_incr, m_size, -m_incr)) { + return seqN(m_first + (m_size + fix<-1>()) * m_incr, m_size, -m_incr); } -#endif }; /** \returns an ArithmeticSequence starting at \a first, of length \a size, and increment \a incr - * - * \sa seqN(FirstType,SizeType), seq(FirstType,LastType,IncrType) */ -template -ArithmeticSequence::type,typename internal::cleanup_index_type::type,typename internal::cleanup_seq_incr::type > -seqN(FirstType first, SizeType size, IncrType incr) { - return ArithmeticSequence::type,typename internal::cleanup_index_type::type,typename internal::cleanup_seq_incr::type>(first,size,incr); + * + * \sa seqN(FirstType,SizeType), seq(FirstType,LastType,IncrType) */ +template +ArithmeticSequence::type, + typename internal::cleanup_index_type::type, + typename internal::cleanup_seq_incr::type> +seqN(FirstType first, SizeType size, IncrType incr) { + return ArithmeticSequence::type, + typename internal::cleanup_index_type::type, + typename internal::cleanup_seq_incr::type>(first, size, incr); } /** \returns an ArithmeticSequence starting at \a first, of length \a size, and unit increment - * - * \sa seqN(FirstType,SizeType,IncrType), seq(FirstType,LastType) */ -template -ArithmeticSequence::type,typename internal::cleanup_index_type::type > -seqN(FirstType first, SizeType size) { - return ArithmeticSequence::type,typename internal::cleanup_index_type::type>(first,size); + * + * \sa seqN(FirstType,SizeType,IncrType), seq(FirstType,LastType) */ +template +ArithmeticSequence::type, + typename internal::cleanup_index_type::type> +seqN(FirstType first, SizeType size) { + return ArithmeticSequence::type, + typename internal::cleanup_index_type::type>(first, size); } #ifdef EIGEN_PARSED_BY_DOXYGEN -/** \returns an ArithmeticSequence starting at \a f, up (or down) to \a l, and with positive (or negative) increment \a incr - * - * It is essentially an alias to: - * \code - * seqN(f, (l-f+incr)/incr, incr); - * \endcode - * - * \sa seqN(FirstType,SizeType,IncrType), seq(FirstType,LastType) - */ -template +/** \returns an ArithmeticSequence starting at \a f, up (or down) to \a l, and with positive (or negative) increment \a + * incr + * + * It is essentially an alias to: + * \code + * seqN(f, (l-f+incr)/incr, incr); + * \endcode + * + * \sa seqN(FirstType,SizeType,IncrType), seq(FirstType,LastType) + */ +template auto seq(FirstType f, LastType l, IncrType incr); /** \returns an ArithmeticSequence starting at \a f, up (or down) to \a l, and unit increment - * - * It is essentially an alias to: - * \code - * seqN(f,l-f+1); - * \endcode - * - * \sa seqN(FirstType,SizeType), seq(FirstType,LastType,IncrType) - */ -template + * + * It is essentially an alias to: + * \code + * seqN(f,l-f+1); + * \endcode + * + * \sa seqN(FirstType,SizeType), seq(FirstType,LastType,IncrType) + */ +template auto seq(FirstType f, LastType l); -#else // EIGEN_PARSED_BY_DOXYGEN +#else // EIGEN_PARSED_BY_DOXYGEN -#if EIGEN_HAS_CXX11 -template -auto seq(FirstType f, LastType l) -> decltype(seqN(typename internal::cleanup_index_type::type(f), - ( typename internal::cleanup_index_type::type(l) - - typename internal::cleanup_index_type::type(f)+fix<1>()))) -{ +template +auto seq(FirstType f, LastType l) + -> decltype(seqN(typename internal::cleanup_index_type::type(f), + (typename internal::cleanup_index_type::type(l) - + typename internal::cleanup_index_type::type(f) + fix<1>()))) { return seqN(typename internal::cleanup_index_type::type(f), - (typename internal::cleanup_index_type::type(l) - -typename internal::cleanup_index_type::type(f)+fix<1>())); + (typename internal::cleanup_index_type::type(l) - + typename internal::cleanup_index_type::type(f) + fix<1>())); } -template +template auto seq(FirstType f, LastType l, IncrType incr) - -> decltype(seqN(typename internal::cleanup_index_type::type(f), - ( typename internal::cleanup_index_type::type(l) - - typename internal::cleanup_index_type::type(f)+typename internal::cleanup_seq_incr::type(incr) - ) / typename internal::cleanup_seq_incr::type(incr), - typename internal::cleanup_seq_incr::type(incr))) -{ + -> decltype(seqN(typename internal::cleanup_index_type::type(f), + (typename internal::cleanup_index_type::type(l) - + typename internal::cleanup_index_type::type(f) + + typename internal::cleanup_seq_incr::type(incr)) / + typename internal::cleanup_seq_incr::type(incr), + typename internal::cleanup_seq_incr::type(incr))) { typedef typename internal::cleanup_seq_incr::type CleanedIncrType; return seqN(typename internal::cleanup_index_type::type(f), - ( typename internal::cleanup_index_type::type(l) - -typename internal::cleanup_index_type::type(f)+CleanedIncrType(incr)) / CleanedIncrType(incr), + (typename internal::cleanup_index_type::type(l) - + typename internal::cleanup_index_type::type(f) + CleanedIncrType(incr)) / + CleanedIncrType(incr), CleanedIncrType(incr)); } -#else // EIGEN_HAS_CXX11 +#endif // EIGEN_PARSED_BY_DOXYGEN -template -typename internal::enable_if::value || symbolic::is_symbolic::value), - ArithmeticSequence::type,Index> >::type -seq(FirstType f, LastType l) -{ - return seqN(typename internal::cleanup_index_type::type(f), - Index((typename internal::cleanup_index_type::type(l)-typename internal::cleanup_index_type::type(f)+fix<1>()))); -} +namespace placeholders { -template -typename internal::enable_if::value, - ArithmeticSequence,symbolic::ValueExpr<> >, - symbolic::ValueExpr > > > >::type -seq(const symbolic::BaseExpr &f, LastType l) -{ - return seqN(f.derived(),(typename internal::cleanup_index_type::type(l)-f.derived()+fix<1>())); -} - -template -typename internal::enable_if::value, - ArithmeticSequence::type, - symbolic::AddExpr >, - symbolic::ValueExpr > > > >::type -seq(FirstType f, const symbolic::BaseExpr &l) -{ - return seqN(typename internal::cleanup_index_type::type(f),(l.derived()-typename internal::cleanup_index_type::type(f)+fix<1>())); -} - -template -ArithmeticSequence >,symbolic::ValueExpr > > > -seq(const symbolic::BaseExpr &f, const symbolic::BaseExpr &l) -{ - return seqN(f.derived(),(l.derived()-f.derived()+fix<1>())); -} - - -template -typename internal::enable_if::value || symbolic::is_symbolic::value), - ArithmeticSequence::type,Index,typename internal::cleanup_seq_incr::type> >::type -seq(FirstType f, LastType l, IncrType incr) -{ - typedef typename internal::cleanup_seq_incr::type CleanedIncrType; - return seqN(typename internal::cleanup_index_type::type(f), - Index((typename internal::cleanup_index_type::type(l)-typename internal::cleanup_index_type::type(f)+CleanedIncrType(incr))/CleanedIncrType(incr)), incr); -} - -template -typename internal::enable_if::value, - ArithmeticSequence, - symbolic::ValueExpr<> >, - symbolic::ValueExpr::type> >, - symbolic::ValueExpr::type> >, - typename internal::cleanup_seq_incr::type> >::type -seq(const symbolic::BaseExpr &f, LastType l, IncrType incr) -{ - typedef typename internal::cleanup_seq_incr::type CleanedIncrType; - return seqN(f.derived(),(typename internal::cleanup_index_type::type(l)-f.derived()+CleanedIncrType(incr))/CleanedIncrType(incr), incr); -} - -template -typename internal::enable_if::value, - ArithmeticSequence::type, - symbolic::QuotientExpr >, - symbolic::ValueExpr::type> >, - symbolic::ValueExpr::type> >, - typename internal::cleanup_seq_incr::type> >::type -seq(FirstType f, const symbolic::BaseExpr &l, IncrType incr) -{ - typedef typename internal::cleanup_seq_incr::type CleanedIncrType; - return seqN(typename internal::cleanup_index_type::type(f), - (l.derived()-typename internal::cleanup_index_type::type(f)+CleanedIncrType(incr))/CleanedIncrType(incr), incr); -} - -template -ArithmeticSequence >, - symbolic::ValueExpr::type> >, - symbolic::ValueExpr::type> >, - typename internal::cleanup_seq_incr::type> -seq(const symbolic::BaseExpr &f, const symbolic::BaseExpr &l, IncrType incr) -{ - typedef typename internal::cleanup_seq_incr::type CleanedIncrType; - return seqN(f.derived(),(l.derived()-f.derived()+CleanedIncrType(incr))/CleanedIncrType(incr), incr); -} -#endif // EIGEN_HAS_CXX11 - -#endif // EIGEN_PARSED_BY_DOXYGEN - - -#if EIGEN_HAS_CXX11 || defined(EIGEN_PARSED_BY_DOXYGEN) /** \cpp11 - * \returns a symbolic ArithmeticSequence representing the last \a size elements with increment \a incr. - * - * It is a shortcut for: \code seqN(last-(size-fix<1>)*incr, size, incr) \endcode - * - * \sa lastN(SizeType), seqN(FirstType,SizeType), seq(FirstType,LastType,IncrType) */ -template + * \returns a symbolic ArithmeticSequence representing the last \a size elements with increment \a incr. + * + * It is a shortcut for: \code seqN(last-(size-fix<1>)*incr, size, incr) \endcode + * + * \sa lastN(SizeType), seqN(FirstType,SizeType), seq(FirstType,LastType,IncrType) */ +template auto lastN(SizeType size, IncrType incr) --> decltype(seqN(Eigen::last-(size-fix<1>())*incr, size, incr)) -{ - return seqN(Eigen::last-(size-fix<1>())*incr, size, incr); + -> decltype(seqN(Eigen::placeholders::last - (size - fix<1>()) * incr, size, incr)) { + return seqN(Eigen::placeholders::last - (size - fix<1>()) * incr, size, incr); } /** \cpp11 - * \returns a symbolic ArithmeticSequence representing the last \a size elements with a unit increment. - * - * It is a shortcut for: \code seq(last+fix<1>-size, last) \endcode - * - * \sa lastN(SizeType,IncrType, seqN(FirstType,SizeType), seq(FirstType,LastType) */ -template -auto lastN(SizeType size) --> decltype(seqN(Eigen::last+fix<1>()-size, size)) -{ - return seqN(Eigen::last+fix<1>()-size, size); + * \returns a symbolic ArithmeticSequence representing the last \a size elements with a unit increment. + * + * It is a shortcut for: \code seq(last+fix<1>-size, last) \endcode + * + * \sa lastN(SizeType,IncrType, seqN(FirstType,SizeType), seq(FirstType,LastType) */ +template +auto lastN(SizeType size) -> decltype(seqN(Eigen::placeholders::last + fix<1>() - size, size)) { + return seqN(Eigen::placeholders::last + fix<1>() - size, size); } -#endif - -namespace internal { - -// Convert a symbolic span into a usable one (i.e., remove last/end "keywords") -template -struct make_size_type { - typedef typename internal::conditional::value, Index, T>::type type; -}; -template -struct IndexedViewCompatibleType, XprSize> { - typedef ArithmeticSequence::type,IncrType> type; -}; - -template -ArithmeticSequence::type,IncrType> -makeIndexedViewCompatible(const ArithmeticSequence& ids, Index size,SpecializedType) { - return ArithmeticSequence::type,IncrType>( - eval_expr_given_size(ids.firstObject(),size),eval_expr_given_size(ids.sizeObject(),size),ids.incrObject()); -} - -template -struct get_compile_time_incr > { - enum { value = get_fixed_value::value }; -}; - -} // end namespace internal +} // namespace placeholders /** \namespace Eigen::indexing * \ingroup Core_Module - * + * * The sole purpose of this namespace is to be able to import all functions * and symbols that are expected to be used within operator() for indexing * and slicing. If you already imported the whole Eigen namespace: @@ -387,27 +215,25 @@ struct get_compile_time_incr > { * \code using namespace Eigen::indexing; \endcode * is equivalent to: * \code - using Eigen::all; + using Eigen::fix; using Eigen::seq; using Eigen::seqN; - using Eigen::lastN; // c++11 only - using Eigen::last; - using Eigen::lastp1; - using Eigen::fix; + using Eigen::placeholders::all; + using Eigen::placeholders::last; + using Eigen::placeholders::lastN; // c++11 only + using Eigen::placeholders::lastp1; \endcode */ namespace indexing { - using Eigen::all; - using Eigen::seq; - using Eigen::seqN; - #if EIGEN_HAS_CXX11 - using Eigen::lastN; - #endif - using Eigen::last; - using Eigen::lastp1; - using Eigen::fix; -} - -} // end namespace Eigen - -#endif // EIGEN_ARITHMETIC_SEQUENCE_H +using Eigen::fix; +using Eigen::seq; +using Eigen::seqN; +using Eigen::placeholders::all; +using Eigen::placeholders::last; +using Eigen::placeholders::lastN; +using Eigen::placeholders::lastp1; +} // namespace indexing + +} // end namespace Eigen + +#endif // EIGEN_ARITHMETIC_SEQUENCE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Array.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Array.h index 20c789b10c7..29c968210f3 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Array.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Array.h @@ -10,376 +10,330 @@ #ifndef EIGEN_ARRAY_H #define EIGEN_ARRAY_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > : traits > -{ +template +struct traits> + : traits> { typedef ArrayXpr XprKind; - typedef ArrayBase > XprBase; + typedef ArrayBase> XprBase; }; -} +} // namespace internal /** \class Array - * \ingroup Core_Module - * - * \brief General-purpose arrays with easy API for coefficient-wise operations - * - * The %Array class is very similar to the Matrix class. It provides - * general-purpose one- and two-dimensional arrays. The difference between the - * %Array and the %Matrix class is primarily in the API: the API for the - * %Array class provides easy access to coefficient-wise operations, while the - * API for the %Matrix class provides easy access to linear-algebra - * operations. - * - * See documentation of class Matrix for detailed information on the template parameters - * storage layout. - * - * This class can be extended with the help of the plugin mechanism described on the page - * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_ARRAY_PLUGIN. - * - * \sa \blank \ref TutorialArrayClass, \ref TopicClassHierarchy - */ -template -class Array - : public PlainObjectBase > -{ - public: - - typedef PlainObjectBase Base; - EIGEN_DENSE_PUBLIC_INTERFACE(Array) - - enum { Options = _Options }; - typedef typename Base::PlainObject PlainObject; - - protected: - template - friend struct internal::conservative_resize_like_impl; - - using Base::m_storage; - - public: - - using Base::base; - using Base::coeff; - using Base::coeffRef; - - /** - * The usage of - * using Base::operator=; - * fails on MSVC. Since the code below is working with GCC and MSVC, we skipped - * the usage of 'using'. This should be done only for operator=. - */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Array& operator=(const EigenBase &other) - { - return Base::operator=(other); - } - - /** Set all the entries to \a value. - * \sa DenseBase::setConstant(), DenseBase::fill() - */ - /* This overload is needed because the usage of - * using Base::operator=; - * fails on MSVC. Since the code below is working with GCC and MSVC, we skipped - * the usage of 'using'. This should be done only for operator=. - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Array& operator=(const Scalar &value) - { - Base::setConstant(value); - return *this; - } - - /** Copies the value of the expression \a other into \c *this with automatic resizing. - * - * *this might be resized to match the dimensions of \a other. If *this was a null matrix (not already initialized), - * it will be initialized. - * - * Note that copying a row-vector into a vector (and conversely) is allowed. - * The resizing, if any, is then done in the appropriate way so that row-vectors - * remain row-vectors and vectors remain vectors. - */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Array& operator=(const DenseBase& other) - { - return Base::_set(other); - } - - /** This is a special case of the templated operator=. Its purpose is to - * prevent a default operator= from hiding the templated operator=. - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Array& operator=(const Array& other) - { - return Base::_set(other); - } - - /** Default constructor. - * - * For fixed-size matrices, does nothing. - * - * For dynamic-size matrices, creates an empty matrix of size 0. Does not allocate any array. Such a matrix - * is called a null matrix. This constructor is the unique way to create null matrices: resizing - * a matrix to 0 is not supported. - * - * \sa resize(Index,Index) - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Array() : Base() - { - Base::_check_template_params(); - EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED - } + * \ingroup Core_Module + * + * \brief General-purpose arrays with easy API for coefficient-wise operations + * + * The %Array class is very similar to the Matrix class. It provides + * general-purpose one- and two-dimensional arrays. The difference between the + * %Array and the %Matrix class is primarily in the API: the API for the + * %Array class provides easy access to coefficient-wise operations, while the + * API for the %Matrix class provides easy access to linear-algebra + * operations. + * + * See documentation of class Matrix for detailed information on the template parameters + * storage layout. + * + * This class can be extended with the help of the plugin mechanism described on the page + * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_ARRAY_PLUGIN. + * + * \sa \blank \ref TutorialArrayClass, \ref TopicClassHierarchy + */ +template +class Array : public PlainObjectBase> { + public: + typedef PlainObjectBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Array) + + enum { Options = Options_ }; + typedef typename Base::PlainObject PlainObject; + + protected: + template + friend struct internal::conservative_resize_like_impl; + + using Base::m_storage; + + public: + using Base::base; + using Base::coeff; + using Base::coeffRef; + + /** + * The usage of + * using Base::operator=; + * fails on MSVC. Since the code below is working with GCC and MSVC, we skipped + * the usage of 'using'. This should be done only for operator=. + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Array& operator=(const EigenBase& other) { + return Base::operator=(other); + } + + /** Set all the entries to \a value. + * \sa DenseBase::setConstant(), DenseBase::fill() + */ + /* This overload is needed because the usage of + * using Base::operator=; + * fails on MSVC. Since the code below is working with GCC and MSVC, we skipped + * the usage of 'using'. This should be done only for operator=. + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Array& operator=(const Scalar& value) { + Base::setConstant(value); + return *this; + } + + /** Copies the value of the expression \a other into \c *this with automatic resizing. + * + * *this might be resized to match the dimensions of \a other. If *this was a null matrix (not already initialized), + * it will be initialized. + * + * Note that copying a row-vector into a vector (and conversely) is allowed. + * The resizing, if any, is then done in the appropriate way so that row-vectors + * remain row-vectors and vectors remain vectors. + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Array& operator=(const DenseBase& other) { + return Base::_set(other); + } + + /** This is a special case of the templated operator=. Its purpose is to + * prevent a default operator= from hiding the templated operator=. + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Array& operator=(const Array& other) { return Base::_set(other); } + + /** Default constructor. + * + * For fixed-size matrices, does nothing. + * + * For dynamic-size matrices, creates an empty matrix of size 0. Does not allocate any array. Such a matrix + * is called a null matrix. This constructor is the unique way to create null matrices: resizing + * a matrix to 0 is not supported. + * + * \sa resize(Index,Index) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Array() : Base() { EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED } #ifndef EIGEN_PARSED_BY_DOXYGEN - // FIXME is it still needed ?? - /** \internal */ - EIGEN_DEVICE_FUNC - Array(internal::constructor_without_unaligned_array_assert) - : Base(internal::constructor_without_unaligned_array_assert()) - { - Base::_check_template_params(); - EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED - } -#endif - -#if EIGEN_HAS_RVALUE_REFERENCES - EIGEN_DEVICE_FUNC - Array(Array&& other) EIGEN_NOEXCEPT_IF(std::is_nothrow_move_constructible::value) - : Base(std::move(other)) - { - Base::_check_template_params(); - } - EIGEN_DEVICE_FUNC - Array& operator=(Array&& other) EIGEN_NOEXCEPT_IF(std::is_nothrow_move_assignable::value) - { - Base::operator=(std::move(other)); - return *this; - } + // FIXME is it still needed ?? + /** \internal */ + EIGEN_DEVICE_FUNC Array(internal::constructor_without_unaligned_array_assert) + : Base(internal::constructor_without_unaligned_array_assert()){EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED} #endif - #if EIGEN_HAS_CXX11 - /** \copydoc PlainObjectBase(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) - * - * Example: \include Array_variadic_ctor_cxx11.cpp - * Output: \verbinclude Array_variadic_ctor_cxx11.out - * - * \sa Array(const std::initializer_list>&) - * \sa Array(const Scalar&), Array(const Scalar&,const Scalar&) - */ - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) + EIGEN_DEVICE_FUNC Array(Array && other) EIGEN_NOEXCEPT_IF(std::is_nothrow_move_constructible::value) + : Base(std::move(other)) { + } + EIGEN_DEVICE_FUNC Array& operator=(Array&& other) EIGEN_NOEXCEPT_IF(std::is_nothrow_move_assignable::value) { + Base::operator=(std::move(other)); + return *this; + } + + /** \copydoc PlainObjectBase(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const + * ArgTypes&... args) + * + * Example: \include Array_variadic_ctor_cxx11.cpp + * Output: \verbinclude Array_variadic_ctor_cxx11.out + * + * \sa Array(const std::initializer_list>&) + * \sa Array(const Scalar&), Array(const Scalar&,const Scalar&) + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, + const ArgTypes&... args) : Base(a0, a1, a2, a3, args...) {} - /** \brief Constructs an array and initializes it from the coefficients given as initializer-lists grouped by row. \cpp11 - * - * In the general case, the constructor takes a list of rows, each row being represented as a list of coefficients: - * - * Example: \include Array_initializer_list_23_cxx11.cpp - * Output: \verbinclude Array_initializer_list_23_cxx11.out - * - * Each of the inner initializer lists must contain the exact same number of elements, otherwise an assertion is triggered. - * - * In the case of a compile-time column 1D array, implicit transposition from a single row is allowed. - * Therefore Array{{1,2,3,4,5}} is legal and the more verbose syntax - * Array{{1},{2},{3},{4},{5}} can be avoided: - * - * Example: \include Array_initializer_list_vector_cxx11.cpp - * Output: \verbinclude Array_initializer_list_vector_cxx11.out - * - * In the case of fixed-sized arrays, the initializer list sizes must exactly match the array sizes, - * and implicit transposition is allowed for compile-time 1D arrays only. - * - * \sa Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Array(const std::initializer_list>& list) : Base(list) {} - #endif // end EIGEN_HAS_CXX11 - - #ifndef EIGEN_PARSED_BY_DOXYGEN - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE explicit Array(const T& x) - { - Base::_check_template_params(); - Base::template _init1(x); - } - - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Array(const T0& val0, const T1& val1) - { - Base::_check_template_params(); - this->template _init2(val0, val1); - } - - #else - /** \brief Constructs a fixed-sized array initialized with coefficients starting at \a data */ - EIGEN_DEVICE_FUNC explicit Array(const Scalar *data); - /** Constructs a vector or row-vector with given dimension. \only_for_vectors - * - * Note that this is only useful for dynamic-size vectors. For fixed-size vectors, - * it is redundant to pass the dimension here, so it makes more sense to use the default - * constructor Array() instead. - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE explicit Array(Index dim); - /** constructs an initialized 1x1 Array with the given coefficient - * \sa const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args */ - Array(const Scalar& value); - /** constructs an uninitialized array with \a rows rows and \a cols columns. - * - * This is useful for dynamic-size arrays. For fixed-size arrays, - * it is redundant to pass these parameters, so one should use the default constructor - * Array() instead. */ - Array(Index rows, Index cols); - /** constructs an initialized 2D vector with given coefficients - * \sa Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) */ - Array(const Scalar& val0, const Scalar& val1); - #endif // end EIGEN_PARSED_BY_DOXYGEN - - /** constructs an initialized 3D vector with given coefficients - * \sa Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Array(const Scalar& val0, const Scalar& val1, const Scalar& val2) - { - Base::_check_template_params(); - EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Array, 3) - m_storage.data()[0] = val0; - m_storage.data()[1] = val1; - m_storage.data()[2] = val2; - } - /** constructs an initialized 4D vector with given coefficients - * \sa Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Array(const Scalar& val0, const Scalar& val1, const Scalar& val2, const Scalar& val3) - { - Base::_check_template_params(); - EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Array, 4) - m_storage.data()[0] = val0; - m_storage.data()[1] = val1; - m_storage.data()[2] = val2; - m_storage.data()[3] = val3; - } - - /** Copy constructor */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Array(const Array& other) - : Base(other) - { } - - private: - struct PrivateType {}; - public: - - /** \sa MatrixBase::operator=(const EigenBase&) */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Array(const EigenBase &other, - typename internal::enable_if::value, - PrivateType>::type = PrivateType()) - : Base(other.derived()) - { } - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index innerStride() const EIGEN_NOEXCEPT{ return 1; } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outerStride() const EIGEN_NOEXCEPT { return this->innerSize(); } - - #ifdef EIGEN_ARRAY_PLUGIN - #include EIGEN_ARRAY_PLUGIN - #endif - - private: - - template - friend struct internal::matrix_swap_impl; + /** \brief Constructs an array and initializes it from the coefficients given as initializer-lists grouped by row. + * \cpp11 + * + * In the general case, the constructor takes a list of rows, each row being represented as a list of coefficients: + * + * Example: \include Array_initializer_list_23_cxx11.cpp + * Output: \verbinclude Array_initializer_list_23_cxx11.out + * + * Each of the inner initializer lists must contain the exact same number of elements, otherwise an assertion is + * triggered. + * + * In the case of a compile-time column 1D array, implicit transposition from a single row is allowed. + * Therefore Array{{1,2,3,4,5}} is legal and the more verbose syntax + * Array{{1},{2},{3},{4},{5}} can be avoided: + * + * Example: \include Array_initializer_list_vector_cxx11.cpp + * Output: \verbinclude Array_initializer_list_vector_cxx11.out + * + * In the case of fixed-sized arrays, the initializer list sizes must exactly match the array sizes, + * and implicit transposition is allowed for compile-time 1D arrays only. + * + * \sa Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr Array( + const std::initializer_list>& list) + : Base(list) {} + +#ifndef EIGEN_PARSED_BY_DOXYGEN + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit Array(const T& x) { + Base::template _init1(x); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Array(const T0& val0, const T1& val1) { + this->template _init2(val0, val1); + } + +#else + /** \brief Constructs a fixed-sized array initialized with coefficients starting at \a data */ + EIGEN_DEVICE_FUNC explicit Array(const Scalar* data); + /** Constructs a vector or row-vector with given dimension. \only_for_vectors + * + * Note that this is only useful for dynamic-size vectors. For fixed-size vectors, + * it is redundant to pass the dimension here, so it makes more sense to use the default + * constructor Array() instead. + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit Array(Index dim); + /** constructs an initialized 1x1 Array with the given coefficient + * \sa const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args */ + Array(const Scalar& value); + /** constructs an uninitialized array with \a rows rows and \a cols columns. + * + * This is useful for dynamic-size arrays. For fixed-size arrays, + * it is redundant to pass these parameters, so one should use the default constructor + * Array() instead. */ + Array(Index rows, Index cols); + /** constructs an initialized 2D vector with given coefficients + * \sa Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) */ + Array(const Scalar& val0, const Scalar& val1); +#endif // end EIGEN_PARSED_BY_DOXYGEN + + /** constructs an initialized 3D vector with given coefficients + * \sa Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Array(const Scalar& val0, const Scalar& val1, const Scalar& val2) { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Array, 3) + m_storage.data()[0] = val0; + m_storage.data()[1] = val1; + m_storage.data()[2] = val2; + } + /** constructs an initialized 4D vector with given coefficients + * \sa Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Array(const Scalar& val0, const Scalar& val1, const Scalar& val2, + const Scalar& val3) { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Array, 4) + m_storage.data()[0] = val0; + m_storage.data()[1] = val1; + m_storage.data()[2] = val2; + m_storage.data()[3] = val3; + } + + /** Copy constructor */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Array(const Array& other) : Base(other) {} + + private: + struct PrivateType {}; + + public: + /** \sa MatrixBase::operator=(const EigenBase&) */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Array( + const EigenBase& other, + std::enable_if_t::value, PrivateType> = + PrivateType()) + : Base(other.derived()) {} + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const EIGEN_NOEXCEPT { return 1; } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const EIGEN_NOEXCEPT { return this->innerSize(); } + +#ifdef EIGEN_ARRAY_PLUGIN +#include EIGEN_ARRAY_PLUGIN +#endif + + private: + template + friend struct internal::matrix_swap_impl; }; /** \defgroup arraytypedefs Global array typedefs - * \ingroup Core_Module - * - * %Eigen defines several typedef shortcuts for most common 1D and 2D array types. - * - * The general patterns are the following: - * - * \c ArrayRowsColsType where \c Rows and \c Cols can be \c 2,\c 3,\c 4 for fixed size square matrices or \c X for dynamic size, - * and where \c Type can be \c i for integer, \c f for float, \c d for double, \c cf for complex float, \c cd - * for complex double. - * - * For example, \c Array33d is a fixed-size 3x3 array type of doubles, and \c ArrayXXf is a dynamic-size matrix of floats. - * - * There are also \c ArraySizeType which are self-explanatory. For example, \c Array4cf is - * a fixed-size 1D array of 4 complex floats. - * - * With \cpp11, template alias are also defined for common sizes. - * They follow the same pattern as above except that the scalar type suffix is replaced by a - * template parameter, i.e.: - * - `ArrayRowsCols` where `Rows` and `Cols` can be \c 2,\c 3,\c 4, or \c X for fixed or dynamic size. - * - `ArraySize` where `Size` can be \c 2,\c 3,\c 4 or \c X for fixed or dynamic size 1D arrays. - * - * \sa class Array - */ - -#define EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, Size, SizeSuffix) \ -/** \ingroup arraytypedefs */ \ -typedef Array Array##SizeSuffix##SizeSuffix##TypeSuffix; \ -/** \ingroup arraytypedefs */ \ -typedef Array Array##SizeSuffix##TypeSuffix; - -#define EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, Size) \ -/** \ingroup arraytypedefs */ \ -typedef Array Array##Size##X##TypeSuffix; \ -/** \ingroup arraytypedefs */ \ -typedef Array Array##X##Size##TypeSuffix; + * \ingroup Core_Module + * + * %Eigen defines several typedef shortcuts for most common 1D and 2D array types. + * + * The general patterns are the following: + * + * \c ArrayRowsColsType where \c Rows and \c Cols can be \c 2,\c 3,\c 4 for fixed size square matrices or \c X for + * dynamic size, and where \c Type can be \c i for integer, \c f for float, \c d for double, \c cf for complex float, \c + * cd for complex double. + * + * For example, \c Array33d is a fixed-size 3x3 array type of doubles, and \c ArrayXXf is a dynamic-size matrix of + * floats. + * + * There are also \c ArraySizeType which are self-explanatory. For example, \c Array4cf is + * a fixed-size 1D array of 4 complex floats. + * + * With \cpp11, template alias are also defined for common sizes. + * They follow the same pattern as above except that the scalar type suffix is replaced by a + * template parameter, i.e.: + * - `ArrayRowsCols` where `Rows` and `Cols` can be \c 2,\c 3,\c 4, or \c X for fixed or dynamic size. + * - `ArraySize` where `Size` can be \c 2,\c 3,\c 4 or \c X for fixed or dynamic size 1D arrays. + * + * \sa class Array + */ + +#define EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, Size, SizeSuffix) \ + /** \ingroup arraytypedefs */ \ + typedef Array Array##SizeSuffix##SizeSuffix##TypeSuffix; \ + /** \ingroup arraytypedefs */ \ + typedef Array Array##SizeSuffix##TypeSuffix; + +#define EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, Size) \ + /** \ingroup arraytypedefs */ \ + typedef Array Array##Size##X##TypeSuffix; \ + /** \ingroup arraytypedefs */ \ + typedef Array Array##X##Size##TypeSuffix; #define EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(Type, TypeSuffix) \ -EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, 2, 2) \ -EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, 3, 3) \ -EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, 4, 4) \ -EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, Dynamic, X) \ -EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, 2) \ -EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, 3) \ -EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, 4) - -EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(int, i) -EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(float, f) -EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(double, d) -EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(std::complex, cf) + EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, 2, 2) \ + EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, 3, 3) \ + EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, 4, 4) \ + EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, Dynamic, X) \ + EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, 2) \ + EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, 3) \ + EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, 4) + +EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(int, i) +EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(float, f) +EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(double, d) +EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(std::complex, cf) EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(std::complex, cd) #undef EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES #undef EIGEN_MAKE_ARRAY_TYPEDEFS #undef EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS -#if EIGEN_HAS_CXX11 - -#define EIGEN_MAKE_ARRAY_TYPEDEFS(Size, SizeSuffix) \ -/** \ingroup arraytypedefs */ \ -/** \brief \cpp11 */ \ -template \ -using Array##SizeSuffix##SizeSuffix = Array; \ -/** \ingroup arraytypedefs */ \ -/** \brief \cpp11 */ \ -template \ -using Array##SizeSuffix = Array; - -#define EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Size) \ -/** \ingroup arraytypedefs */ \ -/** \brief \cpp11 */ \ -template \ -using Array##Size##X = Array; \ -/** \ingroup arraytypedefs */ \ -/** \brief \cpp11 */ \ -template \ -using Array##X##Size = Array; +#define EIGEN_MAKE_ARRAY_TYPEDEFS(Size, SizeSuffix) \ + /** \ingroup arraytypedefs */ \ + /** \brief \cpp11 */ \ + template \ + using Array##SizeSuffix##SizeSuffix = Array; \ + /** \ingroup arraytypedefs */ \ + /** \brief \cpp11 */ \ + template \ + using Array##SizeSuffix = Array; + +#define EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Size) \ + /** \ingroup arraytypedefs */ \ + /** \brief \cpp11 */ \ + template \ + using Array##Size##X = Array; \ + /** \ingroup arraytypedefs */ \ + /** \brief \cpp11 */ \ + template \ + using Array##X##Size = Array; EIGEN_MAKE_ARRAY_TYPEDEFS(2, 2) EIGEN_MAKE_ARRAY_TYPEDEFS(3, 3) @@ -392,26 +346,24 @@ EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(4) #undef EIGEN_MAKE_ARRAY_TYPEDEFS #undef EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS -#endif // EIGEN_HAS_CXX11 - #define EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, SizeSuffix) \ -using Eigen::Matrix##SizeSuffix##TypeSuffix; \ -using Eigen::Vector##SizeSuffix##TypeSuffix; \ -using Eigen::RowVector##SizeSuffix##TypeSuffix; - -#define EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(TypeSuffix) \ -EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 2) \ -EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 3) \ -EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 4) \ -EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, X) \ - -#define EIGEN_USING_ARRAY_TYPEDEFS \ -EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(i) \ -EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(f) \ -EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(d) \ -EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(cf) \ -EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(cd) - -} // end namespace Eigen - -#endif // EIGEN_ARRAY_H + using Eigen::Matrix##SizeSuffix##TypeSuffix; \ + using Eigen::Vector##SizeSuffix##TypeSuffix; \ + using Eigen::RowVector##SizeSuffix##TypeSuffix; + +#define EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(TypeSuffix) \ + EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 2) \ + EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 3) \ + EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 4) \ + EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, X) + +#define EIGEN_USING_ARRAY_TYPEDEFS \ + EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(i) \ + EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(f) \ + EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(d) \ + EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(cf) \ + EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(cd) + +} // end namespace Eigen + +#endif // EIGEN_ARRAY_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ArrayBase.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ArrayBase.h index ea3dd1c3b38..6237df454be 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ArrayBase.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ArrayBase.h @@ -10,217 +10,213 @@ #ifndef EIGEN_ARRAYBASE_H #define EIGEN_ARRAYBASE_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" -template class MatrixWrapper; +namespace Eigen { + +template +class MatrixWrapper; /** \class ArrayBase - * \ingroup Core_Module - * - * \brief Base class for all 1D and 2D array, and related expressions - * - * An array is similar to a dense vector or matrix. While matrices are mathematical - * objects with well defined linear algebra operators, an array is just a collection - * of scalar values arranged in a one or two dimensionnal fashion. As the main consequence, - * all operations applied to an array are performed coefficient wise. Furthermore, - * arrays support scalar math functions of the c++ standard library (e.g., std::sin(x)), and convenient - * constructors allowing to easily write generic code working for both scalar values - * and arrays. - * - * This class is the base that is inherited by all array expression types. - * - * \tparam Derived is the derived type, e.g., an array or an expression type. - * - * This class can be extended with the help of the plugin mechanism described on the page - * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_ARRAYBASE_PLUGIN. - * - * \sa class MatrixBase, \ref TopicClassHierarchy - */ -template class ArrayBase - : public DenseBase -{ - public: + * \ingroup Core_Module + * + * \brief Base class for all 1D and 2D array, and related expressions + * + * An array is similar to a dense vector or matrix. While matrices are mathematical + * objects with well defined linear algebra operators, an array is just a collection + * of scalar values arranged in a one or two dimensional fashion. As the main consequence, + * all operations applied to an array are performed coefficient wise. Furthermore, + * arrays support scalar math functions of the c++ standard library (e.g., std::sin(x)), and convenient + * constructors allowing to easily write generic code working for both scalar values + * and arrays. + * + * This class is the base that is inherited by all array expression types. + * + * \tparam Derived is the derived type, e.g., an array or an expression type. + * + * This class can be extended with the help of the plugin mechanism described on the page + * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_ARRAYBASE_PLUGIN. + * + * \sa class MatrixBase, \ref TopicClassHierarchy + */ +template +class ArrayBase : public DenseBase { + public: #ifndef EIGEN_PARSED_BY_DOXYGEN - /** The base class for a given storage type. */ - typedef ArrayBase StorageBaseType; - - typedef ArrayBase Eigen_BaseClassForSpecializationOfGlobalMathFuncImpl; - - typedef typename internal::traits::StorageKind StorageKind; - typedef typename internal::traits::Scalar Scalar; - typedef typename internal::packet_traits::type PacketScalar; - typedef typename NumTraits::Real RealScalar; - - typedef DenseBase Base; - using Base::RowsAtCompileTime; - using Base::ColsAtCompileTime; - using Base::SizeAtCompileTime; - using Base::MaxRowsAtCompileTime; - using Base::MaxColsAtCompileTime; - using Base::MaxSizeAtCompileTime; - using Base::IsVectorAtCompileTime; - using Base::Flags; - - using Base::derived; - using Base::const_cast_derived; - using Base::rows; - using Base::cols; - using Base::size; - using Base::coeff; - using Base::coeffRef; - using Base::lazyAssign; - using Base::operator-; - using Base::operator=; - using Base::operator+=; - using Base::operator-=; - using Base::operator*=; - using Base::operator/=; - - typedef typename Base::CoeffReturnType CoeffReturnType; - -#endif // not EIGEN_PARSED_BY_DOXYGEN + /** The base class for a given storage type. */ + typedef ArrayBase StorageBaseType; + + typedef ArrayBase Eigen_BaseClassForSpecializationOfGlobalMathFuncImpl; + + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::packet_traits::type PacketScalar; + typedef typename NumTraits::Real RealScalar; + + typedef DenseBase Base; + using Base::ColsAtCompileTime; + using Base::Flags; + using Base::IsVectorAtCompileTime; + using Base::MaxColsAtCompileTime; + using Base::MaxRowsAtCompileTime; + using Base::MaxSizeAtCompileTime; + using Base::RowsAtCompileTime; + using Base::SizeAtCompileTime; + + using Base::coeff; + using Base::coeffRef; + using Base::cols; + using Base::const_cast_derived; + using Base::derived; + using Base::lazyAssign; + using Base::rows; + using Base::size; + using Base::operator-; + using Base::operator=; + using Base::operator+=; + using Base::operator-=; + using Base::operator*=; + using Base::operator/=; + + typedef typename Base::CoeffReturnType CoeffReturnType; + +#endif // not EIGEN_PARSED_BY_DOXYGEN #ifndef EIGEN_PARSED_BY_DOXYGEN - typedef typename Base::PlainObject PlainObject; + typedef typename Base::PlainObject PlainObject; - /** \internal Represents a matrix with all coefficients equal to one another*/ - typedef CwiseNullaryOp,PlainObject> ConstantReturnType; -#endif // not EIGEN_PARSED_BY_DOXYGEN + /** \internal Represents a matrix with all coefficients equal to one another*/ + typedef CwiseNullaryOp, PlainObject> ConstantReturnType; +#endif // not EIGEN_PARSED_BY_DOXYGEN #define EIGEN_CURRENT_STORAGE_BASE_CLASS Eigen::ArrayBase -#define EIGEN_DOC_UNARY_ADDONS(X,Y) -# include "../plugins/MatrixCwiseUnaryOps.h" -# include "../plugins/ArrayCwiseUnaryOps.h" -# include "../plugins/CommonCwiseBinaryOps.h" -# include "../plugins/MatrixCwiseBinaryOps.h" -# include "../plugins/ArrayCwiseBinaryOps.h" -# ifdef EIGEN_ARRAYBASE_PLUGIN -# include EIGEN_ARRAYBASE_PLUGIN -# endif +#define EIGEN_DOC_UNARY_ADDONS(X, Y) +#include "../plugins/MatrixCwiseUnaryOps.inc" +#include "../plugins/ArrayCwiseUnaryOps.inc" +#include "../plugins/CommonCwiseBinaryOps.inc" +#include "../plugins/MatrixCwiseBinaryOps.inc" +#include "../plugins/ArrayCwiseBinaryOps.inc" +#ifdef EIGEN_ARRAYBASE_PLUGIN +#include EIGEN_ARRAYBASE_PLUGIN +#endif #undef EIGEN_CURRENT_STORAGE_BASE_CLASS #undef EIGEN_DOC_UNARY_ADDONS - /** Special case of the template operator=, in order to prevent the compiler - * from generating a default operator= (issue hit with g++ 4.1) - */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator=(const ArrayBase& other) - { - internal::call_assignment(derived(), other.derived()); - return derived(); - } - - /** Set all the entries to \a value. - * \sa DenseBase::setConstant(), DenseBase::fill() */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator=(const Scalar &value) - { Base::setConstant(value); return derived(); } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator+=(const Scalar& scalar); - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator-=(const Scalar& scalar); - - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator+=(const ArrayBase& other); - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator-=(const ArrayBase& other); - - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator*=(const ArrayBase& other); - - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator/=(const ArrayBase& other); - - public: - EIGEN_DEVICE_FUNC - ArrayBase& array() { return *this; } - EIGEN_DEVICE_FUNC - const ArrayBase& array() const { return *this; } - - /** \returns an \link Eigen::MatrixBase Matrix \endlink expression of this array - * \sa MatrixBase::array() */ - EIGEN_DEVICE_FUNC - MatrixWrapper matrix() { return MatrixWrapper(derived()); } - EIGEN_DEVICE_FUNC - const MatrixWrapper matrix() const { return MatrixWrapper(derived()); } - -// template -// inline void evalTo(Dest& dst) const { dst = matrix(); } - - protected: - EIGEN_DEFAULT_COPY_CONSTRUCTOR(ArrayBase) - EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(ArrayBase) - - private: - explicit ArrayBase(Index); - ArrayBase(Index,Index); - template explicit ArrayBase(const ArrayBase&); - protected: - // mixing arrays and matrices is not legal - template Derived& operator+=(const MatrixBase& ) - {EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;} - // mixing arrays and matrices is not legal - template Derived& operator-=(const MatrixBase& ) - {EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;} + /** Special case of the template operator=, in order to prevent the compiler + * from generating a default operator= (issue hit with g++ 4.1) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator=(const ArrayBase& other) { + internal::call_assignment(derived(), other.derived()); + return derived(); + } + + /** Set all the entries to \a value. + * \sa DenseBase::setConstant(), DenseBase::fill() */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator=(const Scalar& value) { + Base::setConstant(value); + return derived(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator+=(const Scalar& scalar); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator-=(const Scalar& scalar); + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator+=(const ArrayBase& other); + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator-=(const ArrayBase& other); + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator*=(const ArrayBase& other); + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator/=(const ArrayBase& other); + + public: + EIGEN_DEVICE_FUNC ArrayBase& array() { return *this; } + EIGEN_DEVICE_FUNC const ArrayBase& array() const { return *this; } + + /** \returns an \link Eigen::MatrixBase Matrix \endlink expression of this array + * \sa MatrixBase::array() */ + EIGEN_DEVICE_FUNC MatrixWrapper matrix() { return MatrixWrapper(derived()); } + EIGEN_DEVICE_FUNC const MatrixWrapper matrix() const { + return MatrixWrapper(derived()); + } + + // template + // inline void evalTo(Dest& dst) const { dst = matrix(); } + + protected: + EIGEN_DEFAULT_COPY_CONSTRUCTOR(ArrayBase) + EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(ArrayBase) + + private: + explicit ArrayBase(Index); + ArrayBase(Index, Index); + template + explicit ArrayBase(const ArrayBase&); + + protected: + // mixing arrays and matrices is not legal + template + Derived& operator+=(const MatrixBase&) { + EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar)) == -1, + YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); + return *this; + } + // mixing arrays and matrices is not legal + template + Derived& operator-=(const MatrixBase&) { + EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar)) == -1, + YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); + return *this; + } }; /** replaces \c *this by \c *this - \a other. - * - * \returns a reference to \c *this - */ -template -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived & -ArrayBase::operator-=(const ArrayBase &other) -{ - call_assignment(derived(), other.derived(), internal::sub_assign_op()); + * + * \returns a reference to \c *this + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& ArrayBase::operator-=(const ArrayBase& other) { + call_assignment(derived(), other.derived(), internal::sub_assign_op()); return derived(); } /** replaces \c *this by \c *this + \a other. - * - * \returns a reference to \c *this - */ -template -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived & -ArrayBase::operator+=(const ArrayBase& other) -{ - call_assignment(derived(), other.derived(), internal::add_assign_op()); + * + * \returns a reference to \c *this + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& ArrayBase::operator+=(const ArrayBase& other) { + call_assignment(derived(), other.derived(), internal::add_assign_op()); return derived(); } /** replaces \c *this by \c *this * \a other coefficient wise. - * - * \returns a reference to \c *this - */ -template -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived & -ArrayBase::operator*=(const ArrayBase& other) -{ - call_assignment(derived(), other.derived(), internal::mul_assign_op()); + * + * \returns a reference to \c *this + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& ArrayBase::operator*=(const ArrayBase& other) { + call_assignment(derived(), other.derived(), internal::mul_assign_op()); return derived(); } /** replaces \c *this by \c *this / \a other coefficient wise. - * - * \returns a reference to \c *this - */ -template -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived & -ArrayBase::operator/=(const ArrayBase& other) -{ - call_assignment(derived(), other.derived(), internal::div_assign_op()); + * + * \returns a reference to \c *this + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& ArrayBase::operator/=(const ArrayBase& other) { + call_assignment(derived(), other.derived(), internal::div_assign_op()); return derived(); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_ARRAYBASE_H +#endif // EIGEN_ARRAYBASE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ArrayWrapper.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ArrayWrapper.h index 2e9555b5374..b45395d7a03 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ArrayWrapper.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ArrayWrapper.h @@ -10,200 +10,164 @@ #ifndef EIGEN_ARRAYWRAPPER_H #define EIGEN_ARRAYWRAPPER_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { /** \class ArrayWrapper - * \ingroup Core_Module - * - * \brief Expression of a mathematical vector or matrix as an array object - * - * This class is the return type of MatrixBase::array(), and most of the time - * this is the only way it is use. - * - * \sa MatrixBase::array(), class MatrixWrapper - */ + * \ingroup Core_Module + * + * \brief Expression of a mathematical vector or matrix as an array object + * + * This class is the return type of MatrixBase::array(), and most of the time + * this is the only way it is use. + * + * \sa MatrixBase::array(), class MatrixWrapper + */ namespace internal { -template -struct traits > - : public traits::type > -{ +template +struct traits > : public traits > { typedef ArrayXpr XprKind; // Let's remove NestByRefBit enum { - Flags0 = traits::type >::Flags, + Flags0 = traits >::Flags, LvalueBitFlag = is_lvalue::value ? LvalueBit : 0, Flags = (Flags0 & ~(NestByRefBit | LvalueBit)) | LvalueBitFlag }; }; -} - -template -class ArrayWrapper : public ArrayBase > -{ - public: - typedef ArrayBase Base; - EIGEN_DENSE_PUBLIC_INTERFACE(ArrayWrapper) - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(ArrayWrapper) - typedef typename internal::remove_all::type NestedExpression; - - typedef typename internal::conditional< - internal::is_lvalue::value, - Scalar, - const Scalar - >::type ScalarWithConstIfNotLvalue; - - typedef typename internal::ref_selector::non_const_type NestedExpressionType; - - using Base::coeffRef; - - EIGEN_DEVICE_FUNC - explicit EIGEN_STRONG_INLINE ArrayWrapper(ExpressionType& matrix) : m_expression(matrix) {} - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rows() const EIGEN_NOEXCEPT { return m_expression.rows(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index cols() const EIGEN_NOEXCEPT { return m_expression.cols(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outerStride() const EIGEN_NOEXCEPT { return m_expression.outerStride(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index innerStride() const EIGEN_NOEXCEPT { return m_expression.innerStride(); } - - EIGEN_DEVICE_FUNC - inline ScalarWithConstIfNotLvalue* data() { return m_expression.data(); } - EIGEN_DEVICE_FUNC - inline const Scalar* data() const { return m_expression.data(); } - - EIGEN_DEVICE_FUNC - inline const Scalar& coeffRef(Index rowId, Index colId) const - { - return m_expression.coeffRef(rowId, colId); - } - - EIGEN_DEVICE_FUNC - inline const Scalar& coeffRef(Index index) const - { - return m_expression.coeffRef(index); - } - - template - EIGEN_DEVICE_FUNC - inline void evalTo(Dest& dst) const { dst = m_expression; } - - EIGEN_DEVICE_FUNC - const typename internal::remove_all::type& - nestedExpression() const - { - return m_expression; - } - - /** Forwards the resizing request to the nested expression - * \sa DenseBase::resize(Index) */ - EIGEN_DEVICE_FUNC - void resize(Index newSize) { m_expression.resize(newSize); } - /** Forwards the resizing request to the nested expression - * \sa DenseBase::resize(Index,Index)*/ - EIGEN_DEVICE_FUNC - void resize(Index rows, Index cols) { m_expression.resize(rows,cols); } - - protected: - NestedExpressionType m_expression; +} // namespace internal + +template +class ArrayWrapper : public ArrayBase > { + public: + typedef ArrayBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(ArrayWrapper) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(ArrayWrapper) + typedef internal::remove_all_t NestedExpression; + + typedef std::conditional_t::value, Scalar, const Scalar> + ScalarWithConstIfNotLvalue; + + typedef typename internal::ref_selector::non_const_type NestedExpressionType; + + using Base::coeffRef; + + EIGEN_DEVICE_FUNC explicit EIGEN_STRONG_INLINE ArrayWrapper(ExpressionType& matrix) : m_expression(matrix) {} + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { return m_expression.rows(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return m_expression.cols(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const EIGEN_NOEXCEPT { + return m_expression.outerStride(); + } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const EIGEN_NOEXCEPT { + return m_expression.innerStride(); + } + + EIGEN_DEVICE_FUNC inline ScalarWithConstIfNotLvalue* data() { return m_expression.data(); } + EIGEN_DEVICE_FUNC inline const Scalar* data() const { return m_expression.data(); } + + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index rowId, Index colId) const { + return m_expression.coeffRef(rowId, colId); + } + + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index index) const { return m_expression.coeffRef(index); } + + template + EIGEN_DEVICE_FUNC inline void evalTo(Dest& dst) const { + dst = m_expression; + } + + EIGEN_DEVICE_FUNC const internal::remove_all_t& nestedExpression() const { + return m_expression; + } + + /** Forwards the resizing request to the nested expression + * \sa DenseBase::resize(Index) */ + EIGEN_DEVICE_FUNC void resize(Index newSize) { m_expression.resize(newSize); } + /** Forwards the resizing request to the nested expression + * \sa DenseBase::resize(Index,Index)*/ + EIGEN_DEVICE_FUNC void resize(Index rows, Index cols) { m_expression.resize(rows, cols); } + + protected: + NestedExpressionType m_expression; }; /** \class MatrixWrapper - * \ingroup Core_Module - * - * \brief Expression of an array as a mathematical vector or matrix - * - * This class is the return type of ArrayBase::matrix(), and most of the time - * this is the only way it is use. - * - * \sa MatrixBase::matrix(), class ArrayWrapper - */ + * \ingroup Core_Module + * + * \brief Expression of an array as a mathematical vector or matrix + * + * This class is the return type of ArrayBase::matrix(), and most of the time + * this is the only way it is use. + * + * \sa MatrixBase::matrix(), class ArrayWrapper + */ namespace internal { -template -struct traits > - : public traits::type > -{ +template +struct traits > : public traits > { typedef MatrixXpr XprKind; // Let's remove NestByRefBit enum { - Flags0 = traits::type >::Flags, + Flags0 = traits >::Flags, LvalueBitFlag = is_lvalue::value ? LvalueBit : 0, Flags = (Flags0 & ~(NestByRefBit | LvalueBit)) | LvalueBitFlag }; }; -} - -template -class MatrixWrapper : public MatrixBase > -{ - public: - typedef MatrixBase > Base; - EIGEN_DENSE_PUBLIC_INTERFACE(MatrixWrapper) - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(MatrixWrapper) - typedef typename internal::remove_all::type NestedExpression; - - typedef typename internal::conditional< - internal::is_lvalue::value, - Scalar, - const Scalar - >::type ScalarWithConstIfNotLvalue; - - typedef typename internal::ref_selector::non_const_type NestedExpressionType; - - using Base::coeffRef; - - EIGEN_DEVICE_FUNC - explicit inline MatrixWrapper(ExpressionType& matrix) : m_expression(matrix) {} - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rows() const EIGEN_NOEXCEPT { return m_expression.rows(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index cols() const EIGEN_NOEXCEPT { return m_expression.cols(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outerStride() const EIGEN_NOEXCEPT { return m_expression.outerStride(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index innerStride() const EIGEN_NOEXCEPT { return m_expression.innerStride(); } - - EIGEN_DEVICE_FUNC - inline ScalarWithConstIfNotLvalue* data() { return m_expression.data(); } - EIGEN_DEVICE_FUNC - inline const Scalar* data() const { return m_expression.data(); } - - EIGEN_DEVICE_FUNC - inline const Scalar& coeffRef(Index rowId, Index colId) const - { - return m_expression.derived().coeffRef(rowId, colId); - } - - EIGEN_DEVICE_FUNC - inline const Scalar& coeffRef(Index index) const - { - return m_expression.coeffRef(index); - } - - EIGEN_DEVICE_FUNC - const typename internal::remove_all::type& - nestedExpression() const - { - return m_expression; - } - - /** Forwards the resizing request to the nested expression - * \sa DenseBase::resize(Index) */ - EIGEN_DEVICE_FUNC - void resize(Index newSize) { m_expression.resize(newSize); } - /** Forwards the resizing request to the nested expression - * \sa DenseBase::resize(Index,Index)*/ - EIGEN_DEVICE_FUNC - void resize(Index rows, Index cols) { m_expression.resize(rows,cols); } - - protected: - NestedExpressionType m_expression; +} // namespace internal + +template +class MatrixWrapper : public MatrixBase > { + public: + typedef MatrixBase > Base; + EIGEN_DENSE_PUBLIC_INTERFACE(MatrixWrapper) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(MatrixWrapper) + typedef internal::remove_all_t NestedExpression; + + typedef std::conditional_t::value, Scalar, const Scalar> + ScalarWithConstIfNotLvalue; + + typedef typename internal::ref_selector::non_const_type NestedExpressionType; + + using Base::coeffRef; + + EIGEN_DEVICE_FUNC explicit inline MatrixWrapper(ExpressionType& matrix) : m_expression(matrix) {} + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { return m_expression.rows(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return m_expression.cols(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const EIGEN_NOEXCEPT { + return m_expression.outerStride(); + } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const EIGEN_NOEXCEPT { + return m_expression.innerStride(); + } + + EIGEN_DEVICE_FUNC inline ScalarWithConstIfNotLvalue* data() { return m_expression.data(); } + EIGEN_DEVICE_FUNC inline const Scalar* data() const { return m_expression.data(); } + + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index rowId, Index colId) const { + return m_expression.derived().coeffRef(rowId, colId); + } + + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index index) const { return m_expression.coeffRef(index); } + + EIGEN_DEVICE_FUNC const internal::remove_all_t& nestedExpression() const { + return m_expression; + } + + /** Forwards the resizing request to the nested expression + * \sa DenseBase::resize(Index) */ + EIGEN_DEVICE_FUNC void resize(Index newSize) { m_expression.resize(newSize); } + /** Forwards the resizing request to the nested expression + * \sa DenseBase::resize(Index,Index)*/ + EIGEN_DEVICE_FUNC void resize(Index rows, Index cols) { m_expression.resize(rows, cols); } + + protected: + NestedExpressionType m_expression; }; -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_ARRAYWRAPPER_H +#endif // EIGEN_ARRAYWRAPPER_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Assign.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Assign.h index 655412efd7f..4b30f7bb626 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Assign.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Assign.h @@ -12,79 +12,69 @@ #ifndef EIGEN_ASSIGN_H #define EIGEN_ASSIGN_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { -template -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase - ::lazyAssign(const DenseBase& other) -{ - enum{ - SameType = internal::is_same::value - }; +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::lazyAssign(const DenseBase& other) { + enum { SameType = internal::is_same::value }; EIGEN_STATIC_ASSERT_LVALUE(Derived) - EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Derived,OtherDerived) - EIGEN_STATIC_ASSERT(SameType,YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY) + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Derived, OtherDerived) + EIGEN_STATIC_ASSERT( + SameType, + YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY) eigen_assert(rows() == other.rows() && cols() == other.cols()); - internal::call_assignment_no_alias(derived(),other.derived()); - + internal::call_assignment_no_alias(derived(), other.derived()); + return derived(); } -template -template -EIGEN_DEVICE_FUNC -EIGEN_STRONG_INLINE Derived& DenseBase::operator=(const DenseBase& other) -{ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::operator=(const DenseBase& other) { internal::call_assignment(derived(), other.derived()); return derived(); } -template -EIGEN_DEVICE_FUNC -EIGEN_STRONG_INLINE Derived& DenseBase::operator=(const DenseBase& other) -{ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::operator=(const DenseBase& other) { internal::call_assignment(derived(), other.derived()); return derived(); } -template -EIGEN_DEVICE_FUNC -EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const MatrixBase& other) -{ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const MatrixBase& other) { internal::call_assignment(derived(), other.derived()); return derived(); } -template +template template -EIGEN_DEVICE_FUNC -EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const DenseBase& other) -{ +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const DenseBase& other) { internal::call_assignment(derived(), other.derived()); return derived(); } -template +template template -EIGEN_DEVICE_FUNC -EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const EigenBase& other) -{ +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const EigenBase& other) { internal::call_assignment(derived(), other.derived()); return derived(); } -template -template -EIGEN_DEVICE_FUNC -EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const ReturnByValue& other) -{ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::operator=( + const ReturnByValue& other) { other.derived().evalTo(derived()); return derived(); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_ASSIGN_H +#endif // EIGEN_ASSIGN_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/AssignEvaluator.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/AssignEvaluator.h index 7d76f0c256f..f7f0b238b8c 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/AssignEvaluator.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/AssignEvaluator.h @@ -12,6 +12,9 @@ #ifndef EIGEN_ASSIGN_EVALUATOR_H #define EIGEN_ASSIGN_EVALUATOR_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { // This implementation is based on Assign.h @@ -19,143 +22,140 @@ namespace Eigen { namespace internal { /*************************************************************************** -* Part 1 : the logic deciding a strategy for traversal and unrolling * -***************************************************************************/ + * Part 1 : the logic deciding a strategy for traversal and unrolling * + ***************************************************************************/ // copy_using_evaluator_traits is based on assign_traits template -struct copy_using_evaluator_traits -{ +struct copy_using_evaluator_traits { typedef typename DstEvaluator::XprType Dst; typedef typename Dst::Scalar DstScalar; - enum { - DstFlags = DstEvaluator::Flags, - SrcFlags = SrcEvaluator::Flags - }; + enum { DstFlags = DstEvaluator::Flags, SrcFlags = SrcEvaluator::Flags }; -public: + public: enum { DstAlignment = DstEvaluator::Alignment, SrcAlignment = SrcEvaluator::Alignment, DstHasDirectAccess = (DstFlags & DirectAccessBit) == DirectAccessBit, - JointAlignment = EIGEN_PLAIN_ENUM_MIN(DstAlignment,SrcAlignment) + JointAlignment = plain_enum_min(DstAlignment, SrcAlignment) }; -private: + private: enum { InnerSize = int(Dst::IsVectorAtCompileTime) ? int(Dst::SizeAtCompileTime) - : int(DstFlags)&RowMajorBit ? int(Dst::ColsAtCompileTime) - : int(Dst::RowsAtCompileTime), + : int(DstFlags) & RowMajorBit ? int(Dst::ColsAtCompileTime) + : int(Dst::RowsAtCompileTime), InnerMaxSize = int(Dst::IsVectorAtCompileTime) ? int(Dst::MaxSizeAtCompileTime) - : int(DstFlags)&RowMajorBit ? int(Dst::MaxColsAtCompileTime) - : int(Dst::MaxRowsAtCompileTime), - RestrictedInnerSize = EIGEN_SIZE_MIN_PREFER_FIXED(InnerSize,MaxPacketSize), - RestrictedLinearSize = EIGEN_SIZE_MIN_PREFER_FIXED(Dst::SizeAtCompileTime,MaxPacketSize), + : int(DstFlags) & RowMajorBit ? int(Dst::MaxColsAtCompileTime) + : int(Dst::MaxRowsAtCompileTime), + RestrictedInnerSize = min_size_prefer_fixed(InnerSize, MaxPacketSize), + RestrictedLinearSize = min_size_prefer_fixed(Dst::SizeAtCompileTime, MaxPacketSize), OuterStride = int(outer_stride_at_compile_time::ret), MaxSizeAtCompileTime = Dst::SizeAtCompileTime }; // TODO distinguish between linear traversal and inner-traversals - typedef typename find_best_packet::type LinearPacketType; - typedef typename find_best_packet::type InnerPacketType; + typedef typename find_best_packet::type LinearPacketType; + typedef typename find_best_packet::type InnerPacketType; enum { LinearPacketSize = unpacket_traits::size, InnerPacketSize = unpacket_traits::size }; -public: + public: enum { LinearRequiredAlignment = unpacket_traits::alignment, InnerRequiredAlignment = unpacket_traits::alignment }; -private: + private: enum { - DstIsRowMajor = DstFlags&RowMajorBit, - SrcIsRowMajor = SrcFlags&RowMajorBit, + DstIsRowMajor = DstFlags & RowMajorBit, + SrcIsRowMajor = SrcFlags & RowMajorBit, StorageOrdersAgree = (int(DstIsRowMajor) == int(SrcIsRowMajor)), - MightVectorize = bool(StorageOrdersAgree) - && (int(DstFlags) & int(SrcFlags) & ActualPacketAccessBit) - && bool(functor_traits::PacketAccess), - MayInnerVectorize = MightVectorize - && int(InnerSize)!=Dynamic && int(InnerSize)%int(InnerPacketSize)==0 - && int(OuterStride)!=Dynamic && int(OuterStride)%int(InnerPacketSize)==0 - && (EIGEN_UNALIGNED_VECTORIZE || int(JointAlignment)>=int(InnerRequiredAlignment)), + MightVectorize = bool(StorageOrdersAgree) && (int(DstFlags) & int(SrcFlags) & ActualPacketAccessBit) && + bool(functor_traits::PacketAccess), + MayInnerVectorize = MightVectorize && int(InnerSize) != Dynamic && int(InnerSize) % int(InnerPacketSize) == 0 && + int(OuterStride) != Dynamic && int(OuterStride) % int(InnerPacketSize) == 0 && + (EIGEN_UNALIGNED_VECTORIZE || int(JointAlignment) >= int(InnerRequiredAlignment)), MayLinearize = bool(StorageOrdersAgree) && (int(DstFlags) & int(SrcFlags) & LinearAccessBit), - MayLinearVectorize = bool(MightVectorize) && bool(MayLinearize) && bool(DstHasDirectAccess) - && (EIGEN_UNALIGNED_VECTORIZE || (int(DstAlignment)>=int(LinearRequiredAlignment)) || MaxSizeAtCompileTime == Dynamic), - /* If the destination isn't aligned, we have to do runtime checks and we don't unroll, - so it's only good for large enough sizes. */ - MaySliceVectorize = bool(MightVectorize) && bool(DstHasDirectAccess) - && (int(InnerMaxSize)==Dynamic || int(InnerMaxSize)>=(EIGEN_UNALIGNED_VECTORIZE?InnerPacketSize:(3*InnerPacketSize))) - /* slice vectorization can be slow, so we only want it if the slices are big, which is - indicated by InnerMaxSize rather than InnerSize, think of the case of a dynamic block - in a fixed-size matrix - However, with EIGEN_UNALIGNED_VECTORIZE and unrolling, slice vectorization is still worth it */ + MayLinearVectorize = bool(MightVectorize) && bool(MayLinearize) && bool(DstHasDirectAccess) && + (EIGEN_UNALIGNED_VECTORIZE || (int(DstAlignment) >= int(LinearRequiredAlignment)) || + MaxSizeAtCompileTime == Dynamic), + /* If the destination isn't aligned, we have to do runtime checks and we don't unroll, + so it's only good for large enough sizes. */ + MaySliceVectorize = bool(MightVectorize) && bool(DstHasDirectAccess) && + (int(InnerMaxSize) == Dynamic || + int(InnerMaxSize) >= (EIGEN_UNALIGNED_VECTORIZE ? InnerPacketSize : (3 * InnerPacketSize))) + /* slice vectorization can be slow, so we only want it if the slices are big, which is + indicated by InnerMaxSize rather than InnerSize, think of the case of a dynamic block + in a fixed-size matrix + However, with EIGEN_UNALIGNED_VECTORIZE and unrolling, slice vectorization is still worth it */ }; -public: + public: enum { - Traversal = int(Dst::SizeAtCompileTime) == 0 ? int(AllAtOnceTraversal) // If compile-size is zero, traversing will fail at compile-time. - : (int(MayLinearVectorize) && (LinearPacketSize>InnerPacketSize)) ? int(LinearVectorizedTraversal) - : int(MayInnerVectorize) ? int(InnerVectorizedTraversal) - : int(MayLinearVectorize) ? int(LinearVectorizedTraversal) - : int(MaySliceVectorize) ? int(SliceVectorizedTraversal) - : int(MayLinearize) ? int(LinearTraversal) - : int(DefaultTraversal), - Vectorized = int(Traversal) == InnerVectorizedTraversal - || int(Traversal) == LinearVectorizedTraversal - || int(Traversal) == SliceVectorizedTraversal + Traversal = int(Dst::SizeAtCompileTime) == 0 + ? int(AllAtOnceTraversal) // If compile-size is zero, traversing will fail at compile-time. + : (int(MayLinearVectorize) && (LinearPacketSize > InnerPacketSize)) ? int(LinearVectorizedTraversal) + : int(MayInnerVectorize) ? int(InnerVectorizedTraversal) + : int(MayLinearVectorize) ? int(LinearVectorizedTraversal) + : int(MaySliceVectorize) ? int(SliceVectorizedTraversal) + : int(MayLinearize) ? int(LinearTraversal) + : int(DefaultTraversal), + Vectorized = int(Traversal) == InnerVectorizedTraversal || int(Traversal) == LinearVectorizedTraversal || + int(Traversal) == SliceVectorizedTraversal }; - typedef typename conditional::type PacketType; + typedef std::conditional_t PacketType; -private: + private: enum { - ActualPacketSize = int(Traversal)==LinearVectorizedTraversal ? LinearPacketSize - : Vectorized ? InnerPacketSize - : 1, - UnrollingLimit = EIGEN_UNROLLING_LIMIT * ActualPacketSize, - MayUnrollCompletely = int(Dst::SizeAtCompileTime) != Dynamic - && int(Dst::SizeAtCompileTime) * (int(DstEvaluator::CoeffReadCost)+int(SrcEvaluator::CoeffReadCost)) <= int(UnrollingLimit), - MayUnrollInner = int(InnerSize) != Dynamic - && int(InnerSize) * (int(DstEvaluator::CoeffReadCost)+int(SrcEvaluator::CoeffReadCost)) <= int(UnrollingLimit) + ActualPacketSize = int(Traversal) == LinearVectorizedTraversal ? LinearPacketSize + : Vectorized ? InnerPacketSize + : 1, + UnrollingLimit = EIGEN_UNROLLING_LIMIT * ActualPacketSize, + MayUnrollCompletely = + int(Dst::SizeAtCompileTime) != Dynamic && + int(Dst::SizeAtCompileTime) * (int(DstEvaluator::CoeffReadCost) + int(SrcEvaluator::CoeffReadCost)) <= + int(UnrollingLimit), + MayUnrollInner = + int(InnerSize) != Dynamic && + int(InnerSize) * (int(DstEvaluator::CoeffReadCost) + int(SrcEvaluator::CoeffReadCost)) <= int(UnrollingLimit) }; -public: + public: enum { Unrolling = (int(Traversal) == int(InnerVectorizedTraversal) || int(Traversal) == int(DefaultTraversal)) - ? ( - int(MayUnrollCompletely) ? int(CompleteUnrolling) - : int(MayUnrollInner) ? int(InnerUnrolling) - : int(NoUnrolling) - ) - : int(Traversal) == int(LinearVectorizedTraversal) - ? ( bool(MayUnrollCompletely) && ( EIGEN_UNALIGNED_VECTORIZE || (int(DstAlignment)>=int(LinearRequiredAlignment))) - ? int(CompleteUnrolling) - : int(NoUnrolling) ) - : int(Traversal) == int(LinearTraversal) - ? ( bool(MayUnrollCompletely) ? int(CompleteUnrolling) - : int(NoUnrolling) ) + ? (int(MayUnrollCompletely) ? int(CompleteUnrolling) + : int(MayUnrollInner) ? int(InnerUnrolling) + : int(NoUnrolling)) + : int(Traversal) == int(LinearVectorizedTraversal) + ? (bool(MayUnrollCompletely) && + (EIGEN_UNALIGNED_VECTORIZE || (int(DstAlignment) >= int(LinearRequiredAlignment))) + ? int(CompleteUnrolling) + : int(NoUnrolling)) + : int(Traversal) == int(LinearTraversal) + ? (bool(MayUnrollCompletely) ? int(CompleteUnrolling) : int(NoUnrolling)) #if EIGEN_UNALIGNED_VECTORIZE - : int(Traversal) == int(SliceVectorizedTraversal) - ? ( bool(MayUnrollInner) ? int(InnerUnrolling) - : int(NoUnrolling) ) + : int(Traversal) == int(SliceVectorizedTraversal) + ? (bool(MayUnrollInner) ? int(InnerUnrolling) : int(NoUnrolling)) #endif - : int(NoUnrolling) + : int(NoUnrolling) }; #ifdef EIGEN_DEBUG_ASSIGN - static void debug() - { + static void debug() { std::cerr << "DstXpr: " << typeid(typename DstEvaluator::XprType).name() << std::endl; std::cerr << "SrcXpr: " << typeid(typename SrcEvaluator::XprType).name() << std::endl; std::cerr.setf(std::ios::hex, std::ios::basefield); - std::cerr << "DstFlags" << " = " << DstFlags << " (" << demangle_flags(DstFlags) << " )" << std::endl; - std::cerr << "SrcFlags" << " = " << SrcFlags << " (" << demangle_flags(SrcFlags) << " )" << std::endl; + std::cerr << "DstFlags" + << " = " << DstFlags << " (" << demangle_flags(DstFlags) << " )" << std::endl; + std::cerr << "SrcFlags" + << " = " << SrcFlags << " (" << demangle_flags(SrcFlags) << " )" << std::endl; std::cerr.unsetf(std::ios::hex); EIGEN_DEBUG_VAR(DstAlignment) EIGEN_DEBUG_VAR(SrcAlignment) @@ -173,95 +173,84 @@ struct copy_using_evaluator_traits EIGEN_DEBUG_VAR(MayInnerVectorize) EIGEN_DEBUG_VAR(MayLinearVectorize) EIGEN_DEBUG_VAR(MaySliceVectorize) - std::cerr << "Traversal" << " = " << Traversal << " (" << demangle_traversal(Traversal) << ")" << std::endl; + std::cerr << "Traversal" + << " = " << Traversal << " (" << demangle_traversal(Traversal) << ")" << std::endl; EIGEN_DEBUG_VAR(SrcEvaluator::CoeffReadCost) EIGEN_DEBUG_VAR(DstEvaluator::CoeffReadCost) EIGEN_DEBUG_VAR(Dst::SizeAtCompileTime) EIGEN_DEBUG_VAR(UnrollingLimit) EIGEN_DEBUG_VAR(MayUnrollCompletely) EIGEN_DEBUG_VAR(MayUnrollInner) - std::cerr << "Unrolling" << " = " << Unrolling << " (" << demangle_unrolling(Unrolling) << ")" << std::endl; + std::cerr << "Unrolling" + << " = " << Unrolling << " (" << demangle_unrolling(Unrolling) << ")" << std::endl; std::cerr << std::endl; } #endif }; /*************************************************************************** -* Part 2 : meta-unrollers -***************************************************************************/ + * Part 2 : meta-unrollers + ***************************************************************************/ /************************ *** Default traversal *** ************************/ -template -struct copy_using_evaluator_DefaultTraversal_CompleteUnrolling -{ +template +struct copy_using_evaluator_DefaultTraversal_CompleteUnrolling { // FIXME: this is not very clean, perhaps this information should be provided by the kernel? typedef typename Kernel::DstEvaluatorType DstEvaluatorType; typedef typename DstEvaluatorType::XprType DstXprType; - enum { - outer = Index / DstXprType::InnerSizeAtCompileTime, - inner = Index % DstXprType::InnerSizeAtCompileTime - }; + enum { outer = Index / DstXprType::InnerSizeAtCompileTime, inner = Index % DstXprType::InnerSizeAtCompileTime }; - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel& kernel) { kernel.assignCoeffByOuterInner(outer, inner); - copy_using_evaluator_DefaultTraversal_CompleteUnrolling::run(kernel); + copy_using_evaluator_DefaultTraversal_CompleteUnrolling::run(kernel); } }; -template -struct copy_using_evaluator_DefaultTraversal_CompleteUnrolling -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&) { } +template +struct copy_using_evaluator_DefaultTraversal_CompleteUnrolling { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void run(Kernel&) {} }; -template -struct copy_using_evaluator_DefaultTraversal_InnerUnrolling -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel, Index outer) - { +template +struct copy_using_evaluator_DefaultTraversal_InnerUnrolling { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel& kernel, Index outer) { kernel.assignCoeffByOuterInner(outer, Index_); - copy_using_evaluator_DefaultTraversal_InnerUnrolling::run(kernel, outer); + copy_using_evaluator_DefaultTraversal_InnerUnrolling::run(kernel, outer); } }; -template -struct copy_using_evaluator_DefaultTraversal_InnerUnrolling -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&, Index) { } +template +struct copy_using_evaluator_DefaultTraversal_InnerUnrolling { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&, Index) {} }; /*********************** *** Linear traversal *** ***********************/ -template -struct copy_using_evaluator_LinearTraversal_CompleteUnrolling -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel& kernel) - { +template +struct copy_using_evaluator_LinearTraversal_CompleteUnrolling { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel& kernel) { kernel.assignCoeff(Index); - copy_using_evaluator_LinearTraversal_CompleteUnrolling::run(kernel); + copy_using_evaluator_LinearTraversal_CompleteUnrolling::run(kernel); } }; -template -struct copy_using_evaluator_LinearTraversal_CompleteUnrolling -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&) { } +template +struct copy_using_evaluator_LinearTraversal_CompleteUnrolling { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&) {} }; /************************** *** Inner vectorization *** **************************/ -template -struct copy_using_evaluator_innervec_CompleteUnrolling -{ +template +struct copy_using_evaluator_innervec_CompleteUnrolling { // FIXME: this is not very clean, perhaps this information should be provided by the kernel? typedef typename Kernel::DstEvaluatorType DstEvaluatorType; typedef typename DstEvaluatorType::XprType DstXprType; @@ -274,47 +263,42 @@ struct copy_using_evaluator_innervec_CompleteUnrolling DstAlignment = Kernel::AssignmentTraits::DstAlignment }; - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel& kernel) { kernel.template assignPacketByOuterInner(outer, inner); enum { NextIndex = Index + unpacket_traits::size }; copy_using_evaluator_innervec_CompleteUnrolling::run(kernel); } }; -template -struct copy_using_evaluator_innervec_CompleteUnrolling -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&) { } +template +struct copy_using_evaluator_innervec_CompleteUnrolling { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void run(Kernel&) {} }; -template -struct copy_using_evaluator_innervec_InnerUnrolling -{ +template +struct copy_using_evaluator_innervec_InnerUnrolling { typedef typename Kernel::PacketType PacketType; - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel, Index outer) - { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel& kernel, Index outer) { kernel.template assignPacketByOuterInner(outer, Index_); enum { NextIndex = Index_ + unpacket_traits::size }; - copy_using_evaluator_innervec_InnerUnrolling::run(kernel, outer); + copy_using_evaluator_innervec_InnerUnrolling::run(kernel, + outer); } }; -template -struct copy_using_evaluator_innervec_InnerUnrolling -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &, Index) { } +template +struct copy_using_evaluator_innervec_InnerUnrolling { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&, Index) {} }; /*************************************************************************** -* Part 3 : implementation of all cases -***************************************************************************/ + * Part 3 : implementation of all cases + ***************************************************************************/ // dense_assignment_loop is based on assign_impl -template +template struct dense_assignment_loop; /************************ @@ -322,14 +306,11 @@ struct dense_assignment_loop; ************************/ // Zero-sized assignment is a no-op. -template -struct dense_assignment_loop -{ - EIGEN_DEVICE_FUNC static void EIGEN_STRONG_INLINE run(Kernel& /*kernel*/) - { - typedef typename Kernel::DstEvaluatorType::XprType DstXprType; - EIGEN_STATIC_ASSERT(int(DstXprType::SizeAtCompileTime) == 0, - EIGEN_INTERNAL_ERROR_PLEASE_FILE_A_BUG_REPORT) +template +struct dense_assignment_loop { + EIGEN_DEVICE_FUNC static void EIGEN_STRONG_INLINE EIGEN_CONSTEXPR run(Kernel& /*kernel*/) { + EIGEN_STATIC_ASSERT(int(Kernel::DstEvaluatorType::XprType::SizeAtCompileTime) == 0, + EIGEN_INTERNAL_ERROR_PLEASE_FILE_A_BUG_REPORT) } }; @@ -337,39 +318,34 @@ struct dense_assignment_loop *** Default traversal *** ************************/ -template -struct dense_assignment_loop -{ - EIGEN_DEVICE_FUNC static void EIGEN_STRONG_INLINE run(Kernel &kernel) - { - for(Index outer = 0; outer < kernel.outerSize(); ++outer) { - for(Index inner = 0; inner < kernel.innerSize(); ++inner) { +template +struct dense_assignment_loop { + EIGEN_DEVICE_FUNC static void EIGEN_STRONG_INLINE run(Kernel& kernel) { + for (Index outer = 0; outer < kernel.outerSize(); ++outer) { + for (Index inner = 0; inner < kernel.innerSize(); ++inner) { kernel.assignCoeffByOuterInner(outer, inner); } } } }; -template -struct dense_assignment_loop -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { +template +struct dense_assignment_loop { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel& kernel) { typedef typename Kernel::DstEvaluatorType::XprType DstXprType; copy_using_evaluator_DefaultTraversal_CompleteUnrolling::run(kernel); } }; -template -struct dense_assignment_loop -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { +template +struct dense_assignment_loop { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel& kernel) { typedef typename Kernel::DstEvaluatorType::XprType DstXprType; const Index outerSize = kernel.outerSize(); - for(Index outer = 0; outer < outerSize; ++outer) - copy_using_evaluator_DefaultTraversal_InnerUnrolling::run(kernel, outer); + for (Index outer = 0; outer < outerSize; ++outer) + copy_using_evaluator_DefaultTraversal_InnerUnrolling::run(kernel, + outer); } }; @@ -377,83 +353,95 @@ struct dense_assignment_loop *** Linear vectorization *** ***************************/ - // The goal of unaligned_dense_assignment_loop is simply to factorize the handling // of the non vectorizable beginning and ending parts template -struct unaligned_dense_assignment_loop -{ +struct unaligned_dense_assignment_loop { // if IsAligned = true, then do nothing template - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&, Index, Index) {} + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void run(Kernel&, Index, Index) {} }; template <> -struct unaligned_dense_assignment_loop -{ +struct unaligned_dense_assignment_loop { // MSVC must not inline this functions. If it does, it fails to optimize the // packet access path. // FIXME check which version exhibits this issue #if EIGEN_COMP_MSVC template - static EIGEN_DONT_INLINE void run(Kernel &kernel, - Index start, - Index end) + static EIGEN_DONT_INLINE void run(Kernel& kernel, Index start, Index end) #else template - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel, - Index start, - Index end) + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void run(Kernel& kernel, Index start, Index end) #endif { - for (Index index = start; index < end; ++index) - kernel.assignCoeff(index); + for (Index index = start; index < end; ++index) kernel.assignCoeff(index); } }; -template -struct dense_assignment_loop -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { +template +struct copy_using_evaluator_linearvec_CompleteUnrolling { + // FIXME: this is not very clean, perhaps this information should be provided by the kernel? + typedef typename Kernel::DstEvaluatorType DstEvaluatorType; + typedef typename DstEvaluatorType::XprType DstXprType; + typedef typename Kernel::PacketType PacketType; + + enum { SrcAlignment = Kernel::AssignmentTraits::SrcAlignment, DstAlignment = Kernel::AssignmentTraits::DstAlignment }; + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel& kernel) { + kernel.template assignPacket(Index); + enum { NextIndex = Index + unpacket_traits::size }; + copy_using_evaluator_linearvec_CompleteUnrolling::run(kernel); + } +}; + +template +struct copy_using_evaluator_linearvec_CompleteUnrolling { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void run(Kernel&) {} +}; + +template +struct dense_assignment_loop { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void run(Kernel& kernel) { const Index size = kernel.size(); typedef typename Kernel::Scalar Scalar; typedef typename Kernel::PacketType PacketType; enum { requestedAlignment = Kernel::AssignmentTraits::LinearRequiredAlignment, packetSize = unpacket_traits::size, - dstIsAligned = int(Kernel::AssignmentTraits::DstAlignment)>=int(requestedAlignment), + dstIsAligned = int(Kernel::AssignmentTraits::DstAlignment) >= int(requestedAlignment), dstAlignment = packet_traits::AlignedOnScalar ? int(requestedAlignment) : int(Kernel::AssignmentTraits::DstAlignment), srcAlignment = Kernel::AssignmentTraits::JointAlignment }; - const Index alignedStart = dstIsAligned ? 0 : internal::first_aligned(kernel.dstDataPtr(), size); - const Index alignedEnd = alignedStart + ((size-alignedStart)/packetSize)*packetSize; + const Index alignedStart = + dstIsAligned ? 0 : internal::first_aligned(kernel.dstDataPtr(), size); + const Index alignedEnd = alignedStart + ((size - alignedStart) / packetSize) * packetSize; - unaligned_dense_assignment_loop::run(kernel, 0, alignedStart); + unaligned_dense_assignment_loop::run(kernel, 0, alignedStart); - for(Index index = alignedStart; index < alignedEnd; index += packetSize) + for (Index index = alignedStart; index < alignedEnd; index += packetSize) kernel.template assignPacket(index); unaligned_dense_assignment_loop<>::run(kernel, alignedEnd, size); } }; -template -struct dense_assignment_loop -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { +template +struct dense_assignment_loop { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void run(Kernel& kernel) { typedef typename Kernel::DstEvaluatorType::XprType DstXprType; typedef typename Kernel::PacketType PacketType; - enum { size = DstXprType::SizeAtCompileTime, - packetSize =unpacket_traits::size, - alignedSize = (int(size)/packetSize)*packetSize }; + enum { + size = DstXprType::SizeAtCompileTime, + packetSize = unpacket_traits::size, + alignedSize = (int(size) / packetSize) * packetSize + }; - copy_using_evaluator_innervec_CompleteUnrolling::run(kernel); - copy_using_evaluator_DefaultTraversal_CompleteUnrolling::run(kernel); + copy_using_evaluator_linearvec_CompleteUnrolling::run(kernel); + copy_using_evaluator_LinearTraversal_CompleteUnrolling::run(kernel); } }; @@ -461,46 +449,37 @@ struct dense_assignment_loop -struct dense_assignment_loop -{ +template +struct dense_assignment_loop { typedef typename Kernel::PacketType PacketType; - enum { - SrcAlignment = Kernel::AssignmentTraits::SrcAlignment, - DstAlignment = Kernel::AssignmentTraits::DstAlignment - }; - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { + enum { SrcAlignment = Kernel::AssignmentTraits::SrcAlignment, DstAlignment = Kernel::AssignmentTraits::DstAlignment }; + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void run(Kernel& kernel) { const Index innerSize = kernel.innerSize(); const Index outerSize = kernel.outerSize(); const Index packetSize = unpacket_traits::size; - for(Index outer = 0; outer < outerSize; ++outer) - for(Index inner = 0; inner < innerSize; inner+=packetSize) + for (Index outer = 0; outer < outerSize; ++outer) + for (Index inner = 0; inner < innerSize; inner += packetSize) kernel.template assignPacketByOuterInner(outer, inner); } }; -template -struct dense_assignment_loop -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { +template +struct dense_assignment_loop { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel& kernel) { typedef typename Kernel::DstEvaluatorType::XprType DstXprType; copy_using_evaluator_innervec_CompleteUnrolling::run(kernel); } }; -template -struct dense_assignment_loop -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { +template +struct dense_assignment_loop { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel& kernel) { typedef typename Kernel::DstEvaluatorType::XprType DstXprType; typedef typename Kernel::AssignmentTraits Traits; const Index outerSize = kernel.outerSize(); - for(Index outer = 0; outer < outerSize; ++outer) - copy_using_evaluator_innervec_InnerUnrolling::run(kernel, outer); + for (Index outer = 0; outer < outerSize; ++outer) + copy_using_evaluator_innervec_InnerUnrolling::run(kernel, outer); } }; @@ -508,22 +487,17 @@ struct dense_assignment_loop *** Linear traversal *** ***********************/ -template -struct dense_assignment_loop -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { +template +struct dense_assignment_loop { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void run(Kernel& kernel) { const Index size = kernel.size(); - for(Index i = 0; i < size; ++i) - kernel.assignCoeff(i); + for (Index i = 0; i < size; ++i) kernel.assignCoeff(i); } }; -template -struct dense_assignment_loop -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { +template +struct dense_assignment_loop { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void run(Kernel& kernel) { typedef typename Kernel::DstEvaluatorType::XprType DstXprType; copy_using_evaluator_LinearTraversal_CompleteUnrolling::run(kernel); } @@ -533,69 +507,63 @@ struct dense_assignment_loop *** Slice vectorization *** ***************************/ -template -struct dense_assignment_loop -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { +template +struct dense_assignment_loop { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void run(Kernel& kernel) { typedef typename Kernel::Scalar Scalar; typedef typename Kernel::PacketType PacketType; enum { packetSize = unpacket_traits::size, requestedAlignment = int(Kernel::AssignmentTraits::InnerRequiredAlignment), - alignable = packet_traits::AlignedOnScalar || int(Kernel::AssignmentTraits::DstAlignment)>=sizeof(Scalar), - dstIsAligned = int(Kernel::AssignmentTraits::DstAlignment)>=int(requestedAlignment), - dstAlignment = alignable ? int(requestedAlignment) - : int(Kernel::AssignmentTraits::DstAlignment) + alignable = + packet_traits::AlignedOnScalar || int(Kernel::AssignmentTraits::DstAlignment) >= sizeof(Scalar), + dstIsAligned = int(Kernel::AssignmentTraits::DstAlignment) >= int(requestedAlignment), + dstAlignment = alignable ? int(requestedAlignment) : int(Kernel::AssignmentTraits::DstAlignment) }; - const Scalar *dst_ptr = kernel.dstDataPtr(); - if((!bool(dstIsAligned)) && (UIntPtr(dst_ptr) % sizeof(Scalar))>0) - { + const Scalar* dst_ptr = kernel.dstDataPtr(); + if ((!bool(dstIsAligned)) && (std::uintptr_t(dst_ptr) % sizeof(Scalar)) > 0) { // the pointer is not aligned-on scalar, so alignment is not possible - return dense_assignment_loop::run(kernel); + return dense_assignment_loop::run(kernel); } const Index packetAlignedMask = packetSize - 1; const Index innerSize = kernel.innerSize(); const Index outerSize = kernel.outerSize(); const Index alignedStep = alignable ? (packetSize - kernel.outerStride() % packetSize) & packetAlignedMask : 0; - Index alignedStart = ((!alignable) || bool(dstIsAligned)) ? 0 : internal::first_aligned(dst_ptr, innerSize); + Index alignedStart = + ((!alignable) || bool(dstIsAligned)) ? 0 : internal::first_aligned(dst_ptr, innerSize); - for(Index outer = 0; outer < outerSize; ++outer) - { - const Index alignedEnd = alignedStart + ((innerSize-alignedStart) & ~packetAlignedMask); + for (Index outer = 0; outer < outerSize; ++outer) { + const Index alignedEnd = alignedStart + ((innerSize - alignedStart) & ~packetAlignedMask); // do the non-vectorizable part of the assignment - for(Index inner = 0; inner(outer, inner); // do the non-vectorizable part of the assignment - for(Index inner = alignedEnd; inner -struct dense_assignment_loop -{ - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) - { +template +struct dense_assignment_loop { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void run(Kernel& kernel) { typedef typename Kernel::DstEvaluatorType::XprType DstXprType; typedef typename Kernel::PacketType PacketType; - enum { innerSize = DstXprType::InnerSizeAtCompileTime, - packetSize =unpacket_traits::size, - vectorizableSize = (int(innerSize) / int(packetSize)) * int(packetSize), - size = DstXprType::SizeAtCompileTime }; + enum { + innerSize = DstXprType::InnerSizeAtCompileTime, + packetSize = unpacket_traits::size, + vectorizableSize = (int(innerSize) / int(packetSize)) * int(packetSize), + size = DstXprType::SizeAtCompileTime + }; - for(Index outer = 0; outer < kernel.outerSize(); ++outer) - { + for (Index outer = 0; outer < kernel.outerSize(); ++outer) { copy_using_evaluator_innervec_InnerUnrolling::run(kernel, outer); copy_using_evaluator_DefaultTraversal_InnerUnrolling::run(kernel, outer); } @@ -603,10 +571,9 @@ struct dense_assignment_loop }; #endif - /*************************************************************************** -* Part 4 : Generic dense assignment kernel -***************************************************************************/ + * Part 4 : Generic dense assignment kernel + ***************************************************************************/ // This class generalize the assignment of a coefficient (or packet) from one dense evaluator // to another dense writable evaluator. @@ -614,28 +581,26 @@ struct dense_assignment_loop // This abstraction level permits to keep the evaluation loops as simple and as generic as possible. // One can customize the assignment using this generic dense_assignment_kernel with different // functors, or by completely overloading it, by-passing a functor. -template -class generic_dense_assignment_kernel -{ -protected: +template +class generic_dense_assignment_kernel { + protected: typedef typename DstEvaluatorTypeT::XprType DstXprType; typedef typename SrcEvaluatorTypeT::XprType SrcXprType; -public: + public: typedef DstEvaluatorTypeT DstEvaluatorType; typedef SrcEvaluatorTypeT SrcEvaluatorType; typedef typename DstEvaluatorType::Scalar Scalar; typedef copy_using_evaluator_traits AssignmentTraits; typedef typename AssignmentTraits::PacketType PacketType; - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - generic_dense_assignment_kernel(DstEvaluatorType &dst, const SrcEvaluatorType &src, const Functor &func, DstXprType& dstExpr) - : m_dst(dst), m_src(src), m_functor(func), m_dstExpr(dstExpr) - { - #ifdef EIGEN_DEBUG_ASSIGN + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE generic_dense_assignment_kernel(DstEvaluatorType& dst, + const SrcEvaluatorType& src, + const Functor& func, DstXprType& dstExpr) + : m_dst(dst), m_src(src), m_functor(func), m_dstExpr(dstExpr) { +#ifdef EIGEN_DEBUG_ASSIGN AssignmentTraits::debug(); - #endif +#endif } EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index size() const EIGEN_NOEXCEPT { return m_dstExpr.size(); } @@ -649,73 +614,62 @@ class generic_dense_assignment_kernel EIGEN_DEVICE_FUNC const SrcEvaluatorType& srcEvaluator() const EIGEN_NOEXCEPT { return m_src; } /// Assign src(row,col) to dst(row,col) through the assignment functor. - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignCoeff(Index row, Index col) - { - m_functor.assignCoeff(m_dst.coeffRef(row,col), m_src.coeff(row,col)); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignCoeff(Index row, Index col) { + m_functor.assignCoeff(m_dst.coeffRef(row, col), m_src.coeff(row, col)); } /// \sa assignCoeff(Index,Index) - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignCoeff(Index index) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignCoeff(Index index) { m_functor.assignCoeff(m_dst.coeffRef(index), m_src.coeff(index)); } /// \sa assignCoeff(Index,Index) - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignCoeffByOuterInner(Index outer, Index inner) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignCoeffByOuterInner(Index outer, Index inner) { Index row = rowIndexByOuterInner(outer, inner); Index col = colIndexByOuterInner(outer, inner); assignCoeff(row, col); } - - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignPacket(Index row, Index col) - { - m_functor.template assignPacket(&m_dst.coeffRef(row,col), m_src.template packet(row,col)); + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignPacket(Index row, Index col) { + m_functor.template assignPacket(&m_dst.coeffRef(row, col), + m_src.template packet(row, col)); } - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignPacket(Index index) - { - m_functor.template assignPacket(&m_dst.coeffRef(index), m_src.template packet(index)); + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignPacket(Index index) { + m_functor.template assignPacket(&m_dst.coeffRef(index), m_src.template packet(index)); } - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignPacketByOuterInner(Index outer, Index inner) - { + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignPacketByOuterInner(Index outer, Index inner) { Index row = rowIndexByOuterInner(outer, inner); Index col = colIndexByOuterInner(outer, inner); - assignPacket(row, col); + assignPacket(row, col); } - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Index rowIndexByOuterInner(Index outer, Index inner) - { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Index rowIndexByOuterInner(Index outer, Index inner) { typedef typename DstEvaluatorType::ExpressionTraits Traits; - return int(Traits::RowsAtCompileTime) == 1 ? 0 - : int(Traits::ColsAtCompileTime) == 1 ? inner - : int(DstEvaluatorType::Flags)&RowMajorBit ? outer - : inner; + return int(Traits::RowsAtCompileTime) == 1 ? 0 + : int(Traits::ColsAtCompileTime) == 1 ? inner + : int(DstEvaluatorType::Flags) & RowMajorBit ? outer + : inner; } - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Index colIndexByOuterInner(Index outer, Index inner) - { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Index colIndexByOuterInner(Index outer, Index inner) { typedef typename DstEvaluatorType::ExpressionTraits Traits; - return int(Traits::ColsAtCompileTime) == 1 ? 0 - : int(Traits::RowsAtCompileTime) == 1 ? inner - : int(DstEvaluatorType::Flags)&RowMajorBit ? inner - : outer; + return int(Traits::ColsAtCompileTime) == 1 ? 0 + : int(Traits::RowsAtCompileTime) == 1 ? inner + : int(DstEvaluatorType::Flags) & RowMajorBit ? inner + : outer; } - EIGEN_DEVICE_FUNC const Scalar* dstDataPtr() const - { - return m_dstExpr.data(); - } + EIGEN_DEVICE_FUNC const Scalar* dstDataPtr() const { return m_dstExpr.data(); } -protected: + protected: DstEvaluatorType& m_dst; const SrcEvaluatorType& m_src; - const Functor &m_functor; + const Functor& m_functor; // TODO find a way to avoid the needs of the original expression DstXprType& m_dstExpr; }; @@ -724,50 +678,48 @@ class generic_dense_assignment_kernel // PacketSize used is no larger than 4, thereby increasing the chance that vectorized instructions will be used // when computing the product. -template -class restricted_packet_dense_assignment_kernel : public generic_dense_assignment_kernel -{ -protected: +template +class restricted_packet_dense_assignment_kernel + : public generic_dense_assignment_kernel { + protected: typedef generic_dense_assignment_kernel Base; + public: - typedef typename Base::Scalar Scalar; - typedef typename Base::DstXprType DstXprType; - typedef copy_using_evaluator_traits AssignmentTraits; - typedef typename AssignmentTraits::PacketType PacketType; + typedef typename Base::Scalar Scalar; + typedef typename Base::DstXprType DstXprType; + typedef copy_using_evaluator_traits AssignmentTraits; + typedef typename AssignmentTraits::PacketType PacketType; - EIGEN_DEVICE_FUNC restricted_packet_dense_assignment_kernel(DstEvaluatorTypeT &dst, const SrcEvaluatorTypeT &src, const Functor &func, DstXprType& dstExpr) - : Base(dst, src, func, dstExpr) - { - } - }; + EIGEN_DEVICE_FUNC restricted_packet_dense_assignment_kernel(DstEvaluatorTypeT& dst, const SrcEvaluatorTypeT& src, + const Functor& func, DstXprType& dstExpr) + : Base(dst, src, func, dstExpr) {} +}; /*************************************************************************** -* Part 5 : Entry point for dense rectangular assignment -***************************************************************************/ + * Part 5 : Entry point for dense rectangular assignment + ***************************************************************************/ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void resize_if_allowed(DstXprType &dst, const SrcXprType& src, const Functor &/*func*/) -{ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resize_if_allowed(DstXprType& dst, const SrcXprType& src, + const Functor& /*func*/) { EIGEN_ONLY_USED_FOR_DEBUG(dst); EIGEN_ONLY_USED_FOR_DEBUG(src); eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); } -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void resize_if_allowed(DstXprType &dst, const SrcXprType& src, const internal::assign_op &/*func*/) -{ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resize_if_allowed(DstXprType& dst, const SrcXprType& src, + const internal::assign_op& /*func*/) { Index dstRows = src.rows(); Index dstCols = src.cols(); - if(((dst.rows()!=dstRows) || (dst.cols()!=dstCols))) - dst.resize(dstRows, dstCols); + if (((dst.rows() != dstRows) || (dst.cols() != dstCols))) dst.resize(dstRows, dstCols); eigen_assert(dst.rows() == dstRows && dst.cols() == dstCols); } -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_dense_assignment_loop(DstXprType& dst, const SrcXprType& src, const Functor &func) -{ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void call_dense_assignment_loop(DstXprType& dst, + const SrcXprType& src, + const Functor& func) { typedef evaluator DstEvaluatorType; typedef evaluator SrcEvaluatorType; @@ -779,7 +731,7 @@ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_dense_assignment_loop(DstXprType DstEvaluatorType dstEvaluator(dst); - typedef generic_dense_assignment_kernel Kernel; + typedef generic_dense_assignment_kernel Kernel; Kernel kernel(dstEvaluator, srcEvaluator, func, dst.const_cast_derived()); dense_assignment_loop::run(kernel); @@ -787,166 +739,159 @@ EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_dense_assignment_loop(DstXprType // Specialization for filling the destination with a constant value. #ifndef EIGEN_GPU_COMPILE_PHASE -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_dense_assignment_loop(DstXprType& dst, const Eigen::CwiseNullaryOp, DstXprType>& src, const internal::assign_op& func) -{ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_dense_assignment_loop( + DstXprType& dst, + const Eigen::CwiseNullaryOp, DstXprType>& src, + const internal::assign_op& func) { resize_if_allowed(dst, src, func); std::fill_n(dst.data(), dst.size(), src.functor()()); } #endif -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_dense_assignment_loop(DstXprType& dst, const SrcXprType& src) -{ - call_dense_assignment_loop(dst, src, internal::assign_op()); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_dense_assignment_loop(DstXprType& dst, const SrcXprType& src) { + call_dense_assignment_loop(dst, src, internal::assign_op()); } /*************************************************************************** -* Part 6 : Generic assignment -***************************************************************************/ + * Part 6 : Generic assignment + ***************************************************************************/ // Based on the respective shapes of the destination and source, // the class AssignmentKind determine the kind of assignment mechanism. // AssignmentKind must define a Kind typedef. -template struct AssignmentKind; +template +struct AssignmentKind; // Assignment kind defined in this file: struct Dense2Dense {}; struct EigenBase2EigenBase {}; -template struct AssignmentKind { typedef EigenBase2EigenBase Kind; }; -template<> struct AssignmentKind { typedef Dense2Dense Kind; }; +template +struct AssignmentKind { + typedef EigenBase2EigenBase Kind; +}; +template <> +struct AssignmentKind { + typedef Dense2Dense Kind; +}; // This is the main assignment class -template< typename DstXprType, typename SrcXprType, typename Functor, - typename Kind = typename AssignmentKind< typename evaluator_traits::Shape , typename evaluator_traits::Shape >::Kind, +template ::Shape, + typename evaluator_traits::Shape>::Kind, typename EnableIf = void> struct Assignment; +// The only purpose of this call_assignment() function is to deal with noalias() / "assume-aliasing" and automatic +// transposition. Indeed, I (Gael) think that this concept of "assume-aliasing" was a mistake, and it makes thing quite +// complicated. So this intermediate function removes everything related to "assume-aliasing" such that Assignment does +// not has to bother about these annoying details. -// The only purpose of this call_assignment() function is to deal with noalias() / "assume-aliasing" and automatic transposition. -// Indeed, I (Gael) think that this concept of "assume-aliasing" was a mistake, and it makes thing quite complicated. -// So this intermediate function removes everything related to "assume-aliasing" such that Assignment -// does not has to bother about these annoying details. - -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void call_assignment(Dst& dst, const Src& src) -{ - call_assignment(dst, src, internal::assign_op()); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_assignment(Dst& dst, const Src& src) { + call_assignment(dst, src, internal::assign_op()); } -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void call_assignment(const Dst& dst, const Src& src) -{ - call_assignment(dst, src, internal::assign_op()); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_assignment(const Dst& dst, const Src& src) { + call_assignment(dst, src, internal::assign_op()); } // Deal with "assume-aliasing" -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void call_assignment(Dst& dst, const Src& src, const Func& func, typename enable_if< evaluator_assume_aliasing::value, void*>::type = 0) -{ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void call_assignment( + Dst& dst, const Src& src, const Func& func, std::enable_if_t::value, void*> = 0) { typename plain_matrix_type::type tmp(src); call_assignment_no_alias(dst, tmp, func); } -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void call_assignment(Dst& dst, const Src& src, const Func& func, typename enable_if::value, void*>::type = 0) -{ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_assignment( + Dst& dst, const Src& src, const Func& func, std::enable_if_t::value, void*> = 0) { call_assignment_no_alias(dst, src, func); } // by-pass "assume-aliasing" // When there is no aliasing, we require that 'dst' has been properly resized -template class StorageBase, typename Src, typename Func> -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void call_assignment(NoAlias& dst, const Src& src, const Func& func) -{ +template class StorageBase, typename Src, typename Func> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void call_assignment(NoAlias& dst, + const Src& src, const Func& func) { call_assignment_no_alias(dst.expression(), src, func); } - -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void call_assignment_no_alias(Dst& dst, const Src& src, const Func& func) -{ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void call_assignment_no_alias(Dst& dst, const Src& src, + const Func& func) { enum { - NeedToTranspose = ( (int(Dst::RowsAtCompileTime) == 1 && int(Src::ColsAtCompileTime) == 1) - || (int(Dst::ColsAtCompileTime) == 1 && int(Src::RowsAtCompileTime) == 1) - ) && int(Dst::SizeAtCompileTime) != 1 + NeedToTranspose = ((int(Dst::RowsAtCompileTime) == 1 && int(Src::ColsAtCompileTime) == 1) || + (int(Dst::ColsAtCompileTime) == 1 && int(Src::RowsAtCompileTime) == 1)) && + int(Dst::SizeAtCompileTime) != 1 }; - typedef typename internal::conditional, Dst>::type ActualDstTypeCleaned; - typedef typename internal::conditional, Dst&>::type ActualDstType; + typedef std::conditional_t, Dst> ActualDstTypeCleaned; + typedef std::conditional_t, Dst&> ActualDstType; ActualDstType actualDst(dst); // TODO check whether this is the right place to perform these checks: EIGEN_STATIC_ASSERT_LVALUE(Dst) - EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(ActualDstTypeCleaned,Src) - EIGEN_CHECK_BINARY_COMPATIBILIY(Func,typename ActualDstTypeCleaned::Scalar,typename Src::Scalar); + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(ActualDstTypeCleaned, Src) + EIGEN_CHECK_BINARY_COMPATIBILIY(Func, typename ActualDstTypeCleaned::Scalar, typename Src::Scalar); - Assignment::run(actualDst, src, func); + Assignment::run(actualDst, src, func); } -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void call_restricted_packet_assignment_no_alias(Dst& dst, const Src& src, const Func& func) -{ - typedef evaluator DstEvaluatorType; - typedef evaluator SrcEvaluatorType; - typedef restricted_packet_dense_assignment_kernel Kernel; +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_restricted_packet_assignment_no_alias(Dst& dst, const Src& src, + const Func& func) { + typedef evaluator DstEvaluatorType; + typedef evaluator SrcEvaluatorType; + typedef restricted_packet_dense_assignment_kernel Kernel; - EIGEN_STATIC_ASSERT_LVALUE(Dst) - EIGEN_CHECK_BINARY_COMPATIBILIY(Func,typename Dst::Scalar,typename Src::Scalar); + EIGEN_STATIC_ASSERT_LVALUE(Dst) + EIGEN_CHECK_BINARY_COMPATIBILIY(Func, typename Dst::Scalar, typename Src::Scalar); - SrcEvaluatorType srcEvaluator(src); - resize_if_allowed(dst, src, func); + SrcEvaluatorType srcEvaluator(src); + resize_if_allowed(dst, src, func); - DstEvaluatorType dstEvaluator(dst); - Kernel kernel(dstEvaluator, srcEvaluator, func, dst.const_cast_derived()); + DstEvaluatorType dstEvaluator(dst); + Kernel kernel(dstEvaluator, srcEvaluator, func, dst.const_cast_derived()); - dense_assignment_loop::run(kernel); + dense_assignment_loop::run(kernel); } -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void call_assignment_no_alias(Dst& dst, const Src& src) -{ - call_assignment_no_alias(dst, src, internal::assign_op()); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void call_assignment_no_alias(Dst& dst, const Src& src) { + call_assignment_no_alias(dst, src, internal::assign_op()); } -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void call_assignment_no_alias_no_transpose(Dst& dst, const Src& src, const Func& func) -{ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void call_assignment_no_alias_no_transpose(Dst& dst, + const Src& src, + const Func& func) { // TODO check whether this is the right place to perform these checks: EIGEN_STATIC_ASSERT_LVALUE(Dst) - EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Dst,Src) - EIGEN_CHECK_BINARY_COMPATIBILIY(Func,typename Dst::Scalar,typename Src::Scalar); + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Dst, Src) + EIGEN_CHECK_BINARY_COMPATIBILIY(Func, typename Dst::Scalar, typename Src::Scalar); - Assignment::run(dst, src, func); + Assignment::run(dst, src, func); } -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void call_assignment_no_alias_no_transpose(Dst& dst, const Src& src) -{ - call_assignment_no_alias_no_transpose(dst, src, internal::assign_op()); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR void call_assignment_no_alias_no_transpose(Dst& dst, + const Src& src) { + call_assignment_no_alias_no_transpose(dst, src, internal::assign_op()); } // forward declaration -template void check_for_aliasing(const Dst &dst, const Src &src); +template +EIGEN_DEVICE_FUNC void check_for_aliasing(const Dst& dst, const Src& src); // Generic Dense to Dense assignment // Note that the last template argument "Weak" is needed to make it possible to perform // both partial specialization+SFINAE without ambiguous specialization -template< typename DstXprType, typename SrcXprType, typename Functor, typename Weak> -struct Assignment -{ - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE void run(DstXprType &dst, const SrcXprType &src, const Functor &func) - { +template +struct Assignment { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(DstXprType& dst, const SrcXprType& src, const Functor& func) { #ifndef EIGEN_NO_DEBUG internal::check_for_aliasing(dst, src); #endif @@ -959,16 +904,14 @@ struct Assignment // TODO: not sure we have to keep that one, but it helps porting current code to new evaluator mechanism. // Note that the last template argument "Weak" is needed to make it possible to perform // both partial specialization+SFINAE without ambiguous specialization -template< typename DstXprType, typename SrcXprType, typename Functor, typename Weak> -struct Assignment -{ - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &/*func*/) - { +template +struct Assignment { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run( + DstXprType& dst, const SrcXprType& src, + const internal::assign_op& /*func*/) { Index dstRows = src.rows(); Index dstCols = src.cols(); - if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) - dst.resize(dstRows, dstCols); + if ((dst.rows() != dstRows) || (dst.cols() != dstCols)) dst.resize(dstRows, dstCols); eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); src.evalTo(dst); @@ -976,35 +919,33 @@ struct Assignment // NOTE The following two functions are templated to avoid their instantiation if not needed // This is needed because some expressions supports evalTo only and/or have 'void' as scalar type. - template - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE void run(DstXprType &dst, const SrcXprType &src, const internal::add_assign_op &/*func*/) - { + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run( + DstXprType& dst, const SrcXprType& src, + const internal::add_assign_op& /*func*/) { Index dstRows = src.rows(); Index dstCols = src.cols(); - if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) - dst.resize(dstRows, dstCols); + if ((dst.rows() != dstRows) || (dst.cols() != dstCols)) dst.resize(dstRows, dstCols); eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); src.addTo(dst); } - template - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE void run(DstXprType &dst, const SrcXprType &src, const internal::sub_assign_op &/*func*/) - { + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run( + DstXprType& dst, const SrcXprType& src, + const internal::sub_assign_op& /*func*/) { Index dstRows = src.rows(); Index dstCols = src.cols(); - if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) - dst.resize(dstRows, dstCols); + if ((dst.rows() != dstRows) || (dst.cols() != dstCols)) dst.resize(dstRows, dstCols); eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); src.subTo(dst); } }; -} // namespace internal +} // namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_ASSIGN_EVALUATOR_H +#endif // EIGEN_ASSIGN_EVALUATOR_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/BandMatrix.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/BandMatrix.h index 878c0240ac1..ca991cad26a 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/BandMatrix.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/BandMatrix.h @@ -10,344 +10,329 @@ #ifndef EIGEN_BANDMATRIX_H #define EIGEN_BANDMATRIX_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -class BandMatrixBase : public EigenBase -{ - public: +template +class BandMatrixBase : public EigenBase { + public: + enum { + Flags = internal::traits::Flags, + CoeffReadCost = internal::traits::CoeffReadCost, + RowsAtCompileTime = internal::traits::RowsAtCompileTime, + ColsAtCompileTime = internal::traits::ColsAtCompileTime, + MaxRowsAtCompileTime = internal::traits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = internal::traits::MaxColsAtCompileTime, + Supers = internal::traits::Supers, + Subs = internal::traits::Subs, + Options = internal::traits::Options + }; + typedef typename internal::traits::Scalar Scalar; + typedef Matrix DenseMatrixType; + typedef typename DenseMatrixType::StorageIndex StorageIndex; + typedef typename internal::traits::CoefficientsType CoefficientsType; + typedef EigenBase Base; - enum { - Flags = internal::traits::Flags, - CoeffReadCost = internal::traits::CoeffReadCost, - RowsAtCompileTime = internal::traits::RowsAtCompileTime, - ColsAtCompileTime = internal::traits::ColsAtCompileTime, - MaxRowsAtCompileTime = internal::traits::MaxRowsAtCompileTime, - MaxColsAtCompileTime = internal::traits::MaxColsAtCompileTime, - Supers = internal::traits::Supers, - Subs = internal::traits::Subs, - Options = internal::traits::Options - }; - typedef typename internal::traits::Scalar Scalar; - typedef Matrix DenseMatrixType; - typedef typename DenseMatrixType::StorageIndex StorageIndex; - typedef typename internal::traits::CoefficientsType CoefficientsType; - typedef EigenBase Base; + protected: + enum { + DataRowsAtCompileTime = ((Supers != Dynamic) && (Subs != Dynamic)) ? 1 + Supers + Subs : Dynamic, + SizeAtCompileTime = min_size_prefer_dynamic(RowsAtCompileTime, ColsAtCompileTime) + }; - protected: + public: + using Base::cols; + using Base::derived; + using Base::rows; + + /** \returns the number of super diagonals */ + inline Index supers() const { return derived().supers(); } + + /** \returns the number of sub diagonals */ + inline Index subs() const { return derived().subs(); } + + /** \returns an expression of the underlying coefficient matrix */ + inline const CoefficientsType& coeffs() const { return derived().coeffs(); } + + /** \returns an expression of the underlying coefficient matrix */ + inline CoefficientsType& coeffs() { return derived().coeffs(); } + + /** \returns a vector expression of the \a i -th column, + * only the meaningful part is returned. + * \warning the internal storage must be column major. */ + inline Block col(Index i) { + EIGEN_STATIC_ASSERT((int(Options) & int(RowMajor)) == 0, THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES); + Index start = 0; + Index len = coeffs().rows(); + if (i <= supers()) { + start = supers() - i; + len = (std::min)(rows(), std::max(0, coeffs().rows() - (supers() - i))); + } else if (i >= rows() - subs()) + len = std::max(0, coeffs().rows() - (i + 1 - rows() + subs())); + return Block(coeffs(), start, i, len, 1); + } + + /** \returns a vector expression of the main diagonal */ + inline Block diagonal() { + return Block(coeffs(), supers(), 0, 1, (std::min)(rows(), cols())); + } + + /** \returns a vector expression of the main diagonal (const version) */ + inline const Block diagonal() const { + return Block(coeffs(), supers(), 0, 1, (std::min)(rows(), cols())); + } + + template + struct DiagonalIntReturnType { enum { - DataRowsAtCompileTime = ((Supers!=Dynamic) && (Subs!=Dynamic)) - ? 1 + Supers + Subs - : Dynamic, - SizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_DYNAMIC(RowsAtCompileTime,ColsAtCompileTime) - }; - - public: - - using Base::derived; - using Base::rows; - using Base::cols; - - /** \returns the number of super diagonals */ - inline Index supers() const { return derived().supers(); } - - /** \returns the number of sub diagonals */ - inline Index subs() const { return derived().subs(); } - - /** \returns an expression of the underlying coefficient matrix */ - inline const CoefficientsType& coeffs() const { return derived().coeffs(); } - - /** \returns an expression of the underlying coefficient matrix */ - inline CoefficientsType& coeffs() { return derived().coeffs(); } - - /** \returns a vector expression of the \a i -th column, - * only the meaningful part is returned. - * \warning the internal storage must be column major. */ - inline Block col(Index i) - { - EIGEN_STATIC_ASSERT((int(Options) & int(RowMajor)) == 0, THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES); - Index start = 0; - Index len = coeffs().rows(); - if (i<=supers()) - { - start = supers()-i; - len = (std::min)(rows(),std::max(0,coeffs().rows() - (supers()-i))); - } - else if (i>=rows()-subs()) - len = std::max(0,coeffs().rows() - (i + 1 - rows() + subs())); - return Block(coeffs(), start, i, len, 1); - } - - /** \returns a vector expression of the main diagonal */ - inline Block diagonal() - { return Block(coeffs(),supers(),0,1,(std::min)(rows(),cols())); } - - /** \returns a vector expression of the main diagonal (const version) */ - inline const Block diagonal() const - { return Block(coeffs(),supers(),0,1,(std::min)(rows(),cols())); } - - template struct DiagonalIntReturnType { - enum { - ReturnOpposite = (int(Options) & int(SelfAdjoint)) && (((Index) > 0 && Supers == 0) || ((Index) < 0 && Subs == 0)), - Conjugate = ReturnOpposite && NumTraits::IsComplex, - ActualIndex = ReturnOpposite ? -Index : Index, - DiagonalSize = (RowsAtCompileTime==Dynamic || ColsAtCompileTime==Dynamic) - ? Dynamic - : (ActualIndex<0 - ? EIGEN_SIZE_MIN_PREFER_DYNAMIC(ColsAtCompileTime, RowsAtCompileTime + ActualIndex) - : EIGEN_SIZE_MIN_PREFER_DYNAMIC(RowsAtCompileTime, ColsAtCompileTime - ActualIndex)) - }; - typedef Block BuildType; - typedef typename internal::conditional,BuildType >, - BuildType>::type Type; + ReturnOpposite = + (int(Options) & int(SelfAdjoint)) && (((Index) > 0 && Supers == 0) || ((Index) < 0 && Subs == 0)), + Conjugate = ReturnOpposite && NumTraits::IsComplex, + ActualIndex = ReturnOpposite ? -Index : Index, + DiagonalSize = + (RowsAtCompileTime == Dynamic || ColsAtCompileTime == Dynamic) + ? Dynamic + : (ActualIndex < 0 ? min_size_prefer_dynamic(ColsAtCompileTime, RowsAtCompileTime + ActualIndex) + : min_size_prefer_dynamic(RowsAtCompileTime, ColsAtCompileTime - ActualIndex)) }; + typedef Block BuildType; + typedef std::conditional_t, BuildType>, BuildType> + Type; + }; - /** \returns a vector expression of the \a N -th sub or super diagonal */ - template inline typename DiagonalIntReturnType::Type diagonal() - { - return typename DiagonalIntReturnType::BuildType(coeffs(), supers()-N, (std::max)(0,N), 1, diagonalLength(N)); - } - - /** \returns a vector expression of the \a N -th sub or super diagonal */ - template inline const typename DiagonalIntReturnType::Type diagonal() const - { - return typename DiagonalIntReturnType::BuildType(coeffs(), supers()-N, (std::max)(0,N), 1, diagonalLength(N)); - } - - /** \returns a vector expression of the \a i -th sub or super diagonal */ - inline Block diagonal(Index i) - { - eigen_assert((i<0 && -i<=subs()) || (i>=0 && i<=supers())); - return Block(coeffs(), supers()-i, std::max(0,i), 1, diagonalLength(i)); - } - - /** \returns a vector expression of the \a i -th sub or super diagonal */ - inline const Block diagonal(Index i) const - { - eigen_assert((i<0 && -i<=subs()) || (i>=0 && i<=supers())); - return Block(coeffs(), supers()-i, std::max(0,i), 1, diagonalLength(i)); - } - - template inline void evalTo(Dest& dst) const - { - dst.resize(rows(),cols()); - dst.setZero(); - dst.diagonal() = diagonal(); - for (Index i=1; i<=supers();++i) - dst.diagonal(i) = diagonal(i); - for (Index i=1; i<=subs();++i) - dst.diagonal(-i) = diagonal(-i); - } - - DenseMatrixType toDenseMatrix() const - { - DenseMatrixType res(rows(),cols()); - evalTo(res); - return res; - } - - protected: - - inline Index diagonalLength(Index i) const - { return i<0 ? (std::min)(cols(),rows()+i) : (std::min)(rows(),cols()-i); } + /** \returns a vector expression of the \a N -th sub or super diagonal */ + template + inline typename DiagonalIntReturnType::Type diagonal() { + return typename DiagonalIntReturnType::BuildType(coeffs(), supers() - N, (std::max)(0, N), 1, diagonalLength(N)); + } + + /** \returns a vector expression of the \a N -th sub or super diagonal */ + template + inline const typename DiagonalIntReturnType::Type diagonal() const { + return typename DiagonalIntReturnType::BuildType(coeffs(), supers() - N, (std::max)(0, N), 1, diagonalLength(N)); + } + + /** \returns a vector expression of the \a i -th sub or super diagonal */ + inline Block diagonal(Index i) { + eigen_assert((i < 0 && -i <= subs()) || (i >= 0 && i <= supers())); + return Block(coeffs(), supers() - i, std::max(0, i), 1, diagonalLength(i)); + } + + /** \returns a vector expression of the \a i -th sub or super diagonal */ + inline const Block diagonal(Index i) const { + eigen_assert((i < 0 && -i <= subs()) || (i >= 0 && i <= supers())); + return Block(coeffs(), supers() - i, std::max(0, i), 1, + diagonalLength(i)); + } + + template + inline void evalTo(Dest& dst) const { + dst.resize(rows(), cols()); + dst.setZero(); + dst.diagonal() = diagonal(); + for (Index i = 1; i <= supers(); ++i) dst.diagonal(i) = diagonal(i); + for (Index i = 1; i <= subs(); ++i) dst.diagonal(-i) = diagonal(-i); + } + + DenseMatrixType toDenseMatrix() const { + DenseMatrixType res(rows(), cols()); + evalTo(res); + return res; + } + + protected: + inline Index diagonalLength(Index i) const { + return i < 0 ? (std::min)(cols(), rows() + i) : (std::min)(rows(), cols() - i); + } }; /** - * \class BandMatrix - * \ingroup Core_Module - * - * \brief Represents a rectangular matrix with a banded storage - * - * \tparam _Scalar Numeric type, i.e. float, double, int - * \tparam _Rows Number of rows, or \b Dynamic - * \tparam _Cols Number of columns, or \b Dynamic - * \tparam _Supers Number of super diagonal - * \tparam _Subs Number of sub diagonal - * \tparam _Options A combination of either \b #RowMajor or \b #ColMajor, and of \b #SelfAdjoint - * The former controls \ref TopicStorageOrders "storage order", and defaults to - * column-major. The latter controls whether the matrix represents a selfadjoint - * matrix in which case either Supers of Subs have to be null. - * - * \sa class TridiagonalMatrix - */ - -template -struct traits > -{ - typedef _Scalar Scalar; + * \class BandMatrix + * \ingroup Core_Module + * + * \brief Represents a rectangular matrix with a banded storage + * + * \tparam Scalar_ Numeric type, i.e. float, double, int + * \tparam Rows_ Number of rows, or \b Dynamic + * \tparam Cols_ Number of columns, or \b Dynamic + * \tparam Supers_ Number of super diagonal + * \tparam Subs_ Number of sub diagonal + * \tparam Options_ A combination of either \b #RowMajor or \b #ColMajor, and of \b #SelfAdjoint + * The former controls \ref TopicStorageOrders "storage order", and defaults to + * column-major. The latter controls whether the matrix represents a selfadjoint + * matrix in which case either Supers of Subs have to be null. + * + * \sa class TridiagonalMatrix + */ + +template +struct traits > { + typedef Scalar_ Scalar; typedef Dense StorageKind; typedef Eigen::Index StorageIndex; enum { CoeffReadCost = NumTraits::ReadCost, - RowsAtCompileTime = _Rows, - ColsAtCompileTime = _Cols, - MaxRowsAtCompileTime = _Rows, - MaxColsAtCompileTime = _Cols, + RowsAtCompileTime = Rows_, + ColsAtCompileTime = Cols_, + MaxRowsAtCompileTime = Rows_, + MaxColsAtCompileTime = Cols_, Flags = LvalueBit, - Supers = _Supers, - Subs = _Subs, - Options = _Options, - DataRowsAtCompileTime = ((Supers!=Dynamic) && (Subs!=Dynamic)) ? 1 + Supers + Subs : Dynamic + Supers = Supers_, + Subs = Subs_, + Options = Options_, + DataRowsAtCompileTime = ((Supers != Dynamic) && (Subs != Dynamic)) ? 1 + Supers + Subs : Dynamic }; - typedef Matrix CoefficientsType; + typedef Matrix + CoefficientsType; }; -template -class BandMatrix : public BandMatrixBase > -{ - public: - - typedef typename internal::traits::Scalar Scalar; - typedef typename internal::traits::StorageIndex StorageIndex; - typedef typename internal::traits::CoefficientsType CoefficientsType; - - explicit inline BandMatrix(Index rows=Rows, Index cols=Cols, Index supers=Supers, Index subs=Subs) - : m_coeffs(1+supers+subs,cols), - m_rows(rows), m_supers(supers), m_subs(subs) - { - } +template +class BandMatrix : public BandMatrixBase > { + public: + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::traits::StorageIndex StorageIndex; + typedef typename internal::traits::CoefficientsType CoefficientsType; - /** \returns the number of columns */ - inline EIGEN_CONSTEXPR Index rows() const { return m_rows.value(); } + explicit inline BandMatrix(Index rows = Rows, Index cols = Cols, Index supers = Supers, Index subs = Subs) + : m_coeffs(1 + supers + subs, cols), m_rows(rows), m_supers(supers), m_subs(subs) {} - /** \returns the number of rows */ - inline EIGEN_CONSTEXPR Index cols() const { return m_coeffs.cols(); } + /** \returns the number of columns */ + inline EIGEN_CONSTEXPR Index rows() const { return m_rows.value(); } - /** \returns the number of super diagonals */ - inline EIGEN_CONSTEXPR Index supers() const { return m_supers.value(); } + /** \returns the number of rows */ + inline EIGEN_CONSTEXPR Index cols() const { return m_coeffs.cols(); } - /** \returns the number of sub diagonals */ - inline EIGEN_CONSTEXPR Index subs() const { return m_subs.value(); } + /** \returns the number of super diagonals */ + inline EIGEN_CONSTEXPR Index supers() const { return m_supers.value(); } - inline const CoefficientsType& coeffs() const { return m_coeffs; } - inline CoefficientsType& coeffs() { return m_coeffs; } + /** \returns the number of sub diagonals */ + inline EIGEN_CONSTEXPR Index subs() const { return m_subs.value(); } - protected: + inline const CoefficientsType& coeffs() const { return m_coeffs; } + inline CoefficientsType& coeffs() { return m_coeffs; } - CoefficientsType m_coeffs; - internal::variable_if_dynamic m_rows; - internal::variable_if_dynamic m_supers; - internal::variable_if_dynamic m_subs; + protected: + CoefficientsType m_coeffs; + internal::variable_if_dynamic m_rows; + internal::variable_if_dynamic m_supers; + internal::variable_if_dynamic m_subs; }; -template +template class BandMatrixWrapper; -template -struct traits > -{ - typedef typename _CoefficientsType::Scalar Scalar; - typedef typename _CoefficientsType::StorageKind StorageKind; - typedef typename _CoefficientsType::StorageIndex StorageIndex; +template +struct traits > { + typedef typename CoefficientsType_::Scalar Scalar; + typedef typename CoefficientsType_::StorageKind StorageKind; + typedef typename CoefficientsType_::StorageIndex StorageIndex; enum { - CoeffReadCost = internal::traits<_CoefficientsType>::CoeffReadCost, - RowsAtCompileTime = _Rows, - ColsAtCompileTime = _Cols, - MaxRowsAtCompileTime = _Rows, - MaxColsAtCompileTime = _Cols, + CoeffReadCost = internal::traits::CoeffReadCost, + RowsAtCompileTime = Rows_, + ColsAtCompileTime = Cols_, + MaxRowsAtCompileTime = Rows_, + MaxColsAtCompileTime = Cols_, Flags = LvalueBit, - Supers = _Supers, - Subs = _Subs, - Options = _Options, - DataRowsAtCompileTime = ((Supers!=Dynamic) && (Subs!=Dynamic)) ? 1 + Supers + Subs : Dynamic + Supers = Supers_, + Subs = Subs_, + Options = Options_, + DataRowsAtCompileTime = ((Supers != Dynamic) && (Subs != Dynamic)) ? 1 + Supers + Subs : Dynamic }; - typedef _CoefficientsType CoefficientsType; + typedef CoefficientsType_ CoefficientsType; }; -template -class BandMatrixWrapper : public BandMatrixBase > -{ - public: +template +class BandMatrixWrapper + : public BandMatrixBase > { + public: + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::traits::CoefficientsType CoefficientsType; + typedef typename internal::traits::StorageIndex StorageIndex; - typedef typename internal::traits::Scalar Scalar; - typedef typename internal::traits::CoefficientsType CoefficientsType; - typedef typename internal::traits::StorageIndex StorageIndex; + explicit inline BandMatrixWrapper(const CoefficientsType& coeffs, Index rows = Rows_, Index cols = Cols_, + Index supers = Supers_, Index subs = Subs_) + : m_coeffs(coeffs), m_rows(rows), m_supers(supers), m_subs(subs) { + EIGEN_UNUSED_VARIABLE(cols); + // eigen_assert(coeffs.cols()==cols() && (supers()+subs()+1)==coeffs.rows()); + } - explicit inline BandMatrixWrapper(const CoefficientsType& coeffs, Index rows=_Rows, Index cols=_Cols, Index supers=_Supers, Index subs=_Subs) - : m_coeffs(coeffs), - m_rows(rows), m_supers(supers), m_subs(subs) - { - EIGEN_UNUSED_VARIABLE(cols); - //internal::assert(coeffs.cols()==cols() && (supers()+subs()+1)==coeffs.rows()); - } + /** \returns the number of columns */ + inline EIGEN_CONSTEXPR Index rows() const { return m_rows.value(); } - /** \returns the number of columns */ - inline EIGEN_CONSTEXPR Index rows() const { return m_rows.value(); } + /** \returns the number of rows */ + inline EIGEN_CONSTEXPR Index cols() const { return m_coeffs.cols(); } - /** \returns the number of rows */ - inline EIGEN_CONSTEXPR Index cols() const { return m_coeffs.cols(); } + /** \returns the number of super diagonals */ + inline EIGEN_CONSTEXPR Index supers() const { return m_supers.value(); } - /** \returns the number of super diagonals */ - inline EIGEN_CONSTEXPR Index supers() const { return m_supers.value(); } + /** \returns the number of sub diagonals */ + inline EIGEN_CONSTEXPR Index subs() const { return m_subs.value(); } - /** \returns the number of sub diagonals */ - inline EIGEN_CONSTEXPR Index subs() const { return m_subs.value(); } + inline const CoefficientsType& coeffs() const { return m_coeffs; } - inline const CoefficientsType& coeffs() const { return m_coeffs; } - - protected: - - const CoefficientsType& m_coeffs; - internal::variable_if_dynamic m_rows; - internal::variable_if_dynamic m_supers; - internal::variable_if_dynamic m_subs; + protected: + const CoefficientsType& m_coeffs; + internal::variable_if_dynamic m_rows; + internal::variable_if_dynamic m_supers; + internal::variable_if_dynamic m_subs; }; /** - * \class TridiagonalMatrix - * \ingroup Core_Module - * - * \brief Represents a tridiagonal matrix with a compact banded storage - * - * \tparam Scalar Numeric type, i.e. float, double, int - * \tparam Size Number of rows and cols, or \b Dynamic - * \tparam Options Can be 0 or \b SelfAdjoint - * - * \sa class BandMatrix - */ -template -class TridiagonalMatrix : public BandMatrix -{ - typedef BandMatrix Base; - typedef typename Base::StorageIndex StorageIndex; - public: - explicit TridiagonalMatrix(Index size = Size) : Base(size,size,Options&SelfAdjoint?0:1,1) {} - - inline typename Base::template DiagonalIntReturnType<1>::Type super() - { return Base::template diagonal<1>(); } - inline const typename Base::template DiagonalIntReturnType<1>::Type super() const - { return Base::template diagonal<1>(); } - inline typename Base::template DiagonalIntReturnType<-1>::Type sub() - { return Base::template diagonal<-1>(); } - inline const typename Base::template DiagonalIntReturnType<-1>::Type sub() const - { return Base::template diagonal<-1>(); } - protected: + * \class TridiagonalMatrix + * \ingroup Core_Module + * + * \brief Represents a tridiagonal matrix with a compact banded storage + * + * \tparam Scalar Numeric type, i.e. float, double, int + * \tparam Size Number of rows and cols, or \b Dynamic + * \tparam Options Can be 0 or \b SelfAdjoint + * + * \sa class BandMatrix + */ +template +class TridiagonalMatrix : public BandMatrix { + typedef BandMatrix Base; + typedef typename Base::StorageIndex StorageIndex; + + public: + explicit TridiagonalMatrix(Index size = Size) : Base(size, size, Options & SelfAdjoint ? 0 : 1, 1) {} + + inline typename Base::template DiagonalIntReturnType<1>::Type super() { return Base::template diagonal<1>(); } + inline const typename Base::template DiagonalIntReturnType<1>::Type super() const { + return Base::template diagonal<1>(); + } + inline typename Base::template DiagonalIntReturnType<-1>::Type sub() { return Base::template diagonal<-1>(); } + inline const typename Base::template DiagonalIntReturnType<-1>::Type sub() const { + return Base::template diagonal<-1>(); + } + + protected: }; - struct BandShape {}; -template -struct evaluator_traits > - : public evaluator_traits_base > -{ +template +struct evaluator_traits > + : public evaluator_traits_base > { typedef BandShape Shape; }; -template -struct evaluator_traits > - : public evaluator_traits_base > -{ +template +struct evaluator_traits > + : public evaluator_traits_base > { typedef BandShape Shape; }; -template<> struct AssignmentKind { typedef EigenBase2EigenBase Kind; }; +template <> +struct AssignmentKind { + typedef EigenBase2EigenBase Kind; +}; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_BANDMATRIX_H +#endif // EIGEN_BANDMATRIX_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Block.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Block.h index 3206d6633e6..9b16ed289e7 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Block.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Block.h @@ -11,438 +11,429 @@ #ifndef EIGEN_BLOCK_H #define EIGEN_BLOCK_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > : traits -{ - typedef typename traits::Scalar Scalar; - typedef typename traits::StorageKind StorageKind; - typedef typename traits::XprKind XprKind; - typedef typename ref_selector::type XprTypeNested; - typedef typename remove_reference::type _XprTypeNested; - enum{ - MatrixRows = traits::RowsAtCompileTime, - MatrixCols = traits::ColsAtCompileTime, +template +struct traits> : traits { + typedef typename traits::Scalar Scalar; + typedef typename traits::StorageKind StorageKind; + typedef typename traits::XprKind XprKind; + typedef typename ref_selector::type XprTypeNested; + typedef std::remove_reference_t XprTypeNested_; + enum { + MatrixRows = traits::RowsAtCompileTime, + MatrixCols = traits::ColsAtCompileTime, RowsAtCompileTime = MatrixRows == 0 ? 0 : BlockRows, ColsAtCompileTime = MatrixCols == 0 ? 0 : BlockCols, - MaxRowsAtCompileTime = BlockRows==0 ? 0 - : RowsAtCompileTime != Dynamic ? int(RowsAtCompileTime) - : int(traits::MaxRowsAtCompileTime), - MaxColsAtCompileTime = BlockCols==0 ? 0 - : ColsAtCompileTime != Dynamic ? int(ColsAtCompileTime) - : int(traits::MaxColsAtCompileTime), - - XprTypeIsRowMajor = (int(traits::Flags)&RowMajorBit) != 0, - IsRowMajor = (MaxRowsAtCompileTime==1&&MaxColsAtCompileTime!=1) ? 1 - : (MaxColsAtCompileTime==1&&MaxRowsAtCompileTime!=1) ? 0 - : XprTypeIsRowMajor, + MaxRowsAtCompileTime = BlockRows == 0 ? 0 + : RowsAtCompileTime != Dynamic ? int(RowsAtCompileTime) + : int(traits::MaxRowsAtCompileTime), + MaxColsAtCompileTime = BlockCols == 0 ? 0 + : ColsAtCompileTime != Dynamic ? int(ColsAtCompileTime) + : int(traits::MaxColsAtCompileTime), + + XprTypeIsRowMajor = (int(traits::Flags) & RowMajorBit) != 0, + IsRowMajor = (MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1) ? 1 + : (MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1) ? 0 + : XprTypeIsRowMajor, HasSameStorageOrderAsXprType = (IsRowMajor == XprTypeIsRowMajor), InnerSize = IsRowMajor ? int(ColsAtCompileTime) : int(RowsAtCompileTime), - InnerStrideAtCompileTime = HasSameStorageOrderAsXprType - ? int(inner_stride_at_compile_time::ret) - : int(outer_stride_at_compile_time::ret), - OuterStrideAtCompileTime = HasSameStorageOrderAsXprType - ? int(outer_stride_at_compile_time::ret) - : int(inner_stride_at_compile_time::ret), + InnerStrideAtCompileTime = HasSameStorageOrderAsXprType ? int(inner_stride_at_compile_time::ret) + : int(outer_stride_at_compile_time::ret), + OuterStrideAtCompileTime = HasSameStorageOrderAsXprType ? int(outer_stride_at_compile_time::ret) + : int(inner_stride_at_compile_time::ret), // FIXME, this traits is rather specialized for dense object and it needs to be cleaned further - FlagsLvalueBit = is_lvalue::value ? LvalueBit : 0, + FlagsLvalueBit = is_lvalue::value ? LvalueBit : 0, FlagsRowMajorBit = IsRowMajor ? RowMajorBit : 0, - Flags = (traits::Flags & (DirectAccessBit | (InnerPanel?CompressedAccessBit:0))) | FlagsLvalueBit | FlagsRowMajorBit, + Flags = (traits::Flags & (DirectAccessBit | (InnerPanel_ ? CompressedAccessBit : 0))) | FlagsLvalueBit | + FlagsRowMajorBit, // FIXME DirectAccessBit should not be handled by expressions // // Alignment is needed by MapBase's assertions - // We can sefely set it to false here. Internal alignment errors will be detected by an eigen_internal_assert in the respective evaluator - Alignment = 0 + // We can sefely set it to false here. Internal alignment errors will be detected by an eigen_internal_assert in the + // respective evaluator + Alignment = 0, + InnerPanel = InnerPanel_ ? 1 : 0 }; }; -template::ret> class BlockImpl_dense; +template ::ret> +class BlockImpl_dense; -} // end namespace internal +} // end namespace internal -template class BlockImpl; +template +class BlockImpl; /** \class Block - * \ingroup Core_Module - * - * \brief Expression of a fixed-size or dynamic-size block - * - * \tparam XprType the type of the expression in which we are taking a block - * \tparam BlockRows the number of rows of the block we are taking at compile time (optional) - * \tparam BlockCols the number of columns of the block we are taking at compile time (optional) - * \tparam InnerPanel is true, if the block maps to a set of rows of a row major matrix or - * to set of columns of a column major matrix (optional). The parameter allows to determine - * at compile time whether aligned access is possible on the block expression. - * - * This class represents an expression of either a fixed-size or dynamic-size block. It is the return - * type of DenseBase::block(Index,Index,Index,Index) and DenseBase::block(Index,Index) and - * most of the time this is the only way it is used. - * - * However, if you want to directly maniputate block expressions, - * for instance if you want to write a function returning such an expression, you - * will need to use this class. - * - * Here is an example illustrating the dynamic case: - * \include class_Block.cpp - * Output: \verbinclude class_Block.out - * - * \note Even though this expression has dynamic size, in the case where \a XprType - * has fixed size, this expression inherits a fixed maximal size which means that evaluating - * it does not cause a dynamic memory allocation. - * - * Here is an example illustrating the fixed-size case: - * \include class_FixedBlock.cpp - * Output: \verbinclude class_FixedBlock.out - * - * \sa DenseBase::block(Index,Index,Index,Index), DenseBase::block(Index,Index), class VectorBlock - */ -template class Block - : public BlockImpl::StorageKind> -{ - typedef BlockImpl::StorageKind> Impl; - public: - //typedef typename Impl::Base Base; - typedef Impl Base; - EIGEN_GENERIC_PUBLIC_INTERFACE(Block) - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Block) - - typedef typename internal::remove_all::type NestedExpression; - - /** Column or Row constructor - */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Block(XprType& xpr, Index i) : Impl(xpr,i) - { - eigen_assert( (i>=0) && ( - ((BlockRows==1) && (BlockCols==XprType::ColsAtCompileTime) && i= 0 && BlockRows >= 0 && startRow + BlockRows <= xpr.rows() - && startCol >= 0 && BlockCols >= 0 && startCol + BlockCols <= xpr.cols()); - } - - /** Dynamic-size constructor - */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Block(XprType& xpr, - Index startRow, Index startCol, - Index blockRows, Index blockCols) - : Impl(xpr, startRow, startCol, blockRows, blockCols) - { - eigen_assert((RowsAtCompileTime==Dynamic || RowsAtCompileTime==blockRows) - && (ColsAtCompileTime==Dynamic || ColsAtCompileTime==blockCols)); - eigen_assert(startRow >= 0 && blockRows >= 0 && startRow <= xpr.rows() - blockRows - && startCol >= 0 && blockCols >= 0 && startCol <= xpr.cols() - blockCols); - } + * \ingroup Core_Module + * + * \brief Expression of a fixed-size or dynamic-size block + * + * \tparam XprType the type of the expression in which we are taking a block + * \tparam BlockRows the number of rows of the block we are taking at compile time (optional) + * \tparam BlockCols the number of columns of the block we are taking at compile time (optional) + * \tparam InnerPanel is true, if the block maps to a set of rows of a row major matrix or + * to set of columns of a column major matrix (optional). The parameter allows to determine + * at compile time whether aligned access is possible on the block expression. + * + * This class represents an expression of either a fixed-size or dynamic-size block. It is the return + * type of DenseBase::block(Index,Index,Index,Index) and DenseBase::block(Index,Index) and + * most of the time this is the only way it is used. + * + * However, if you want to directly manipulate block expressions, + * for instance if you want to write a function returning such an expression, you + * will need to use this class. + * + * Here is an example illustrating the dynamic case: + * \include class_Block.cpp + * Output: \verbinclude class_Block.out + * + * \note Even though this expression has dynamic size, in the case where \a XprType + * has fixed size, this expression inherits a fixed maximal size which means that evaluating + * it does not cause a dynamic memory allocation. + * + * Here is an example illustrating the fixed-size case: + * \include class_FixedBlock.cpp + * Output: \verbinclude class_FixedBlock.out + * + * \sa DenseBase::block(Index,Index,Index,Index), DenseBase::block(Index,Index), class VectorBlock + */ +template +class Block + : public BlockImpl::StorageKind> { + typedef BlockImpl::StorageKind> Impl; + using BlockHelper = internal::block_xpr_helper; + + public: + // typedef typename Impl::Base Base; + typedef Impl Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(Block) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Block) + + typedef internal::remove_all_t NestedExpression; + + /** Column or Row constructor + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Block(XprType& xpr, Index i) : Impl(xpr, i) { + eigen_assert((i >= 0) && (((BlockRows == 1) && (BlockCols == XprType::ColsAtCompileTime) && i < xpr.rows()) || + ((BlockRows == XprType::RowsAtCompileTime) && (BlockCols == 1) && i < xpr.cols()))); + } + + /** Fixed-size constructor + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Block(XprType& xpr, Index startRow, Index startCol) + : Impl(xpr, startRow, startCol) { + EIGEN_STATIC_ASSERT(RowsAtCompileTime != Dynamic && ColsAtCompileTime != Dynamic, + THIS_METHOD_IS_ONLY_FOR_FIXED_SIZE) + eigen_assert(startRow >= 0 && BlockRows >= 0 && startRow + BlockRows <= xpr.rows() && startCol >= 0 && + BlockCols >= 0 && startCol + BlockCols <= xpr.cols()); + } + + /** Dynamic-size constructor + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Block(XprType& xpr, Index startRow, Index startCol, Index blockRows, + Index blockCols) + : Impl(xpr, startRow, startCol, blockRows, blockCols) { + eigen_assert((RowsAtCompileTime == Dynamic || RowsAtCompileTime == blockRows) && + (ColsAtCompileTime == Dynamic || ColsAtCompileTime == blockCols)); + eigen_assert(startRow >= 0 && blockRows >= 0 && startRow <= xpr.rows() - blockRows && startCol >= 0 && + blockCols >= 0 && startCol <= xpr.cols() - blockCols); + } + + // convert nested blocks (e.g. Block>) to a simple block expression (Block) + + using ConstUnwindReturnType = Block; + using UnwindReturnType = Block; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ConstUnwindReturnType unwind() const { + return ConstUnwindReturnType(BlockHelper::base(*this), BlockHelper::row(*this, 0), BlockHelper::col(*this, 0), + this->rows(), this->cols()); + } + + template ::value>> + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE UnwindReturnType unwind() { + return UnwindReturnType(BlockHelper::base(*this), BlockHelper::row(*this, 0), BlockHelper::col(*this, 0), + this->rows(), this->cols()); + } }; -// The generic default implementation for dense block simplu forward to the internal::BlockImpl_dense +// The generic default implementation for dense block simply forward to the internal::BlockImpl_dense // that must be specialized for direct and non-direct access... -template +template class BlockImpl - : public internal::BlockImpl_dense -{ - typedef internal::BlockImpl_dense Impl; - typedef typename XprType::StorageIndex StorageIndex; - public: - typedef Impl Base; - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(BlockImpl) - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockImpl(XprType& xpr, Index i) : Impl(xpr,i) {} - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockImpl(XprType& xpr, Index startRow, Index startCol) : Impl(xpr, startRow, startCol) {} - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE BlockImpl(XprType& xpr, Index startRow, Index startCol, Index blockRows, Index blockCols) + : public internal::BlockImpl_dense { + typedef internal::BlockImpl_dense Impl; + typedef typename XprType::StorageIndex StorageIndex; + + public: + typedef Impl Base; + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(BlockImpl) + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockImpl(XprType& xpr, Index i) : Impl(xpr, i) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockImpl(XprType& xpr, Index startRow, Index startCol) + : Impl(xpr, startRow, startCol) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockImpl(XprType& xpr, Index startRow, Index startCol, Index blockRows, + Index blockCols) : Impl(xpr, startRow, startCol, blockRows, blockCols) {} }; namespace internal { /** \internal Internal implementation of dense Blocks in the general case. */ -template class BlockImpl_dense - : public internal::dense_xpr_base >::type -{ - typedef Block BlockType; - typedef typename internal::ref_selector::non_const_type XprTypeNested; - public: - - typedef typename internal::dense_xpr_base::type Base; - EIGEN_DENSE_PUBLIC_INTERFACE(BlockType) - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(BlockImpl_dense) - - // class InnerIterator; // FIXME apparently never used - - /** Column or Row constructor - */ - EIGEN_DEVICE_FUNC - inline BlockImpl_dense(XprType& xpr, Index i) +template +class BlockImpl_dense : public internal::dense_xpr_base>::type { + typedef Block BlockType; + typedef typename internal::ref_selector::non_const_type XprTypeNested; + + public: + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(BlockType) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(BlockImpl_dense) + + // class InnerIterator; // FIXME apparently never used + + /** Column or Row constructor + */ + EIGEN_DEVICE_FUNC inline BlockImpl_dense(XprType& xpr, Index i) : m_xpr(xpr), // It is a row if and only if BlockRows==1 and BlockCols==XprType::ColsAtCompileTime, // and it is a column if and only if BlockRows==XprType::RowsAtCompileTime and BlockCols==1, // all other cases are invalid. // The case a 1x1 matrix seems ambiguous, but the result is the same anyway. - m_startRow( (BlockRows==1) && (BlockCols==XprType::ColsAtCompileTime) ? i : 0), - m_startCol( (BlockRows==XprType::RowsAtCompileTime) && (BlockCols==1) ? i : 0), - m_blockRows(BlockRows==1 ? 1 : xpr.rows()), - m_blockCols(BlockCols==1 ? 1 : xpr.cols()) - {} - - /** Fixed-size constructor - */ - EIGEN_DEVICE_FUNC - inline BlockImpl_dense(XprType& xpr, Index startRow, Index startCol) - : m_xpr(xpr), m_startRow(startRow), m_startCol(startCol), - m_blockRows(BlockRows), m_blockCols(BlockCols) - {} - - /** Dynamic-size constructor - */ - EIGEN_DEVICE_FUNC - inline BlockImpl_dense(XprType& xpr, - Index startRow, Index startCol, - Index blockRows, Index blockCols) - : m_xpr(xpr), m_startRow(startRow), m_startCol(startCol), - m_blockRows(blockRows), m_blockCols(blockCols) - {} - - EIGEN_DEVICE_FUNC inline Index rows() const { return m_blockRows.value(); } - EIGEN_DEVICE_FUNC inline Index cols() const { return m_blockCols.value(); } - - EIGEN_DEVICE_FUNC - inline Scalar& coeffRef(Index rowId, Index colId) - { - EIGEN_STATIC_ASSERT_LVALUE(XprType) - return m_xpr.coeffRef(rowId + m_startRow.value(), colId + m_startCol.value()); - } - - EIGEN_DEVICE_FUNC - inline const Scalar& coeffRef(Index rowId, Index colId) const - { - return m_xpr.derived().coeffRef(rowId + m_startRow.value(), colId + m_startCol.value()); - } - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index rowId, Index colId) const - { - return m_xpr.coeff(rowId + m_startRow.value(), colId + m_startCol.value()); - } - - EIGEN_DEVICE_FUNC - inline Scalar& coeffRef(Index index) - { - EIGEN_STATIC_ASSERT_LVALUE(XprType) - return m_xpr.coeffRef(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), - m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0)); - } - - EIGEN_DEVICE_FUNC - inline const Scalar& coeffRef(Index index) const - { - return m_xpr.coeffRef(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), - m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0)); - } - - EIGEN_DEVICE_FUNC - inline const CoeffReturnType coeff(Index index) const - { - return m_xpr.coeff(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), - m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0)); - } - - template - inline PacketScalar packet(Index rowId, Index colId) const - { - return m_xpr.template packet(rowId + m_startRow.value(), colId + m_startCol.value()); - } - - template - inline void writePacket(Index rowId, Index colId, const PacketScalar& val) - { - m_xpr.template writePacket(rowId + m_startRow.value(), colId + m_startCol.value(), val); - } - - template - inline PacketScalar packet(Index index) const - { - return m_xpr.template packet - (m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), - m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0)); - } - - template - inline void writePacket(Index index, const PacketScalar& val) - { - m_xpr.template writePacket - (m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), - m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0), val); - } - - #ifdef EIGEN_PARSED_BY_DOXYGEN - /** \sa MapBase::data() */ - EIGEN_DEVICE_FUNC inline const Scalar* data() const; - EIGEN_DEVICE_FUNC inline Index innerStride() const; - EIGEN_DEVICE_FUNC inline Index outerStride() const; - #endif - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const typename internal::remove_all::type& nestedExpression() const - { - return m_xpr; - } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - XprType& nestedExpression() { return m_xpr; } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - StorageIndex startRow() const EIGEN_NOEXCEPT - { - return m_startRow.value(); - } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - StorageIndex startCol() const EIGEN_NOEXCEPT - { - return m_startCol.value(); - } - - protected: - - XprTypeNested m_xpr; - const internal::variable_if_dynamic m_startRow; - const internal::variable_if_dynamic m_startCol; - const internal::variable_if_dynamic m_blockRows; - const internal::variable_if_dynamic m_blockCols; + m_startRow((BlockRows == 1) && (BlockCols == XprType::ColsAtCompileTime) ? i : 0), + m_startCol((BlockRows == XprType::RowsAtCompileTime) && (BlockCols == 1) ? i : 0), + m_blockRows(BlockRows == 1 ? 1 : xpr.rows()), + m_blockCols(BlockCols == 1 ? 1 : xpr.cols()) {} + + /** Fixed-size constructor + */ + EIGEN_DEVICE_FUNC inline BlockImpl_dense(XprType& xpr, Index startRow, Index startCol) + : m_xpr(xpr), m_startRow(startRow), m_startCol(startCol), m_blockRows(BlockRows), m_blockCols(BlockCols) {} + + /** Dynamic-size constructor + */ + EIGEN_DEVICE_FUNC inline BlockImpl_dense(XprType& xpr, Index startRow, Index startCol, Index blockRows, + Index blockCols) + : m_xpr(xpr), m_startRow(startRow), m_startCol(startCol), m_blockRows(blockRows), m_blockCols(blockCols) {} + + EIGEN_DEVICE_FUNC inline Index rows() const { return m_blockRows.value(); } + EIGEN_DEVICE_FUNC inline Index cols() const { return m_blockCols.value(); } + + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index rowId, Index colId) { + EIGEN_STATIC_ASSERT_LVALUE(XprType) + return m_xpr.coeffRef(rowId + m_startRow.value(), colId + m_startCol.value()); + } + + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index rowId, Index colId) const { + return m_xpr.derived().coeffRef(rowId + m_startRow.value(), colId + m_startCol.value()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index rowId, Index colId) const { + return m_xpr.coeff(rowId + m_startRow.value(), colId + m_startCol.value()); + } + + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index index) { + EIGEN_STATIC_ASSERT_LVALUE(XprType) + return m_xpr.coeffRef(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), + m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0)); + } + + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index index) const { + return m_xpr.coeffRef(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), + m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0)); + } + + EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index index) const { + return m_xpr.coeff(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), + m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0)); + } + + template + EIGEN_DEVICE_FUNC inline PacketScalar packet(Index rowId, Index colId) const { + return m_xpr.template packet(rowId + m_startRow.value(), colId + m_startCol.value()); + } + + template + EIGEN_DEVICE_FUNC inline void writePacket(Index rowId, Index colId, const PacketScalar& val) { + m_xpr.template writePacket(rowId + m_startRow.value(), colId + m_startCol.value(), val); + } + + template + EIGEN_DEVICE_FUNC inline PacketScalar packet(Index index) const { + return m_xpr.template packet(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), + m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0)); + } + + template + EIGEN_DEVICE_FUNC inline void writePacket(Index index, const PacketScalar& val) { + m_xpr.template writePacket(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), + m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0), val); + } + +#ifdef EIGEN_PARSED_BY_DOXYGEN + /** \sa MapBase::data() */ + EIGEN_DEVICE_FUNC inline const Scalar* data() const; + EIGEN_DEVICE_FUNC inline Index innerStride() const; + EIGEN_DEVICE_FUNC inline Index outerStride() const; +#endif + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const internal::remove_all_t& nestedExpression() const { + return m_xpr; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE XprType& nestedExpression() { return m_xpr; } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR StorageIndex startRow() const EIGEN_NOEXCEPT { + return m_startRow.value(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR StorageIndex startCol() const EIGEN_NOEXCEPT { + return m_startCol.value(); + } + + protected: + XprTypeNested m_xpr; + const internal::variable_if_dynamic + m_startRow; + const internal::variable_if_dynamic + m_startCol; + const internal::variable_if_dynamic m_blockRows; + const internal::variable_if_dynamic m_blockCols; }; /** \internal Internal implementation of dense Blocks in the direct access case.*/ -template -class BlockImpl_dense - : public MapBase > -{ - typedef Block BlockType; - typedef typename internal::ref_selector::non_const_type XprTypeNested; - enum { - XprTypeIsRowMajor = (int(traits::Flags)&RowMajorBit) != 0 - }; - public: - - typedef MapBase Base; - EIGEN_DENSE_PUBLIC_INTERFACE(BlockType) - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(BlockImpl_dense) - - /** Column or Row constructor - */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - BlockImpl_dense(XprType& xpr, Index i) - : Base(xpr.data() + i * ( ((BlockRows==1) && (BlockCols==XprType::ColsAtCompileTime) && (!XprTypeIsRowMajor)) - || ((BlockRows==XprType::RowsAtCompileTime) && (BlockCols==1) && ( XprTypeIsRowMajor)) ? xpr.innerStride() : xpr.outerStride()), - BlockRows==1 ? 1 : xpr.rows(), - BlockCols==1 ? 1 : xpr.cols()), +template +class BlockImpl_dense + : public MapBase> { + typedef Block BlockType; + typedef typename internal::ref_selector::non_const_type XprTypeNested; + enum { XprTypeIsRowMajor = (int(traits::Flags) & RowMajorBit) != 0 }; + + /** \internal Returns base+offset (unless base is null, in which case returns null). + * Adding an offset to nullptr is undefined behavior, so we must avoid it. + */ + template + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE static Scalar* add_to_nullable_pointer(Scalar* base, + Index offset) { + return base != nullptr ? base + offset : nullptr; + } + + public: + typedef MapBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(BlockType) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(BlockImpl_dense) + + /** Column or Row constructor + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockImpl_dense(XprType& xpr, Index i) + : Base((BlockRows == 0 || BlockCols == 0) + ? nullptr + : add_to_nullable_pointer( + xpr.data(), + i * (((BlockRows == 1) && (BlockCols == XprType::ColsAtCompileTime) && (!XprTypeIsRowMajor)) || + ((BlockRows == XprType::RowsAtCompileTime) && (BlockCols == 1) && + (XprTypeIsRowMajor)) + ? xpr.innerStride() + : xpr.outerStride())), + BlockRows == 1 ? 1 : xpr.rows(), BlockCols == 1 ? 1 : xpr.cols()), m_xpr(xpr), - m_startRow( (BlockRows==1) && (BlockCols==XprType::ColsAtCompileTime) ? i : 0), - m_startCol( (BlockRows==XprType::RowsAtCompileTime) && (BlockCols==1) ? i : 0) - { - init(); - } - - /** Fixed-size constructor - */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - BlockImpl_dense(XprType& xpr, Index startRow, Index startCol) - : Base(xpr.data()+xpr.innerStride()*(XprTypeIsRowMajor?startCol:startRow) + xpr.outerStride()*(XprTypeIsRowMajor?startRow:startCol)), - m_xpr(xpr), m_startRow(startRow), m_startCol(startCol) - { - init(); - } - - /** Dynamic-size constructor - */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - BlockImpl_dense(XprType& xpr, - Index startRow, Index startCol, - Index blockRows, Index blockCols) - : Base(xpr.data()+xpr.innerStride()*(XprTypeIsRowMajor?startCol:startRow) + xpr.outerStride()*(XprTypeIsRowMajor?startRow:startCol), blockRows, blockCols), - m_xpr(xpr), m_startRow(startRow), m_startCol(startCol) - { - init(); - } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const typename internal::remove_all::type& nestedExpression() const EIGEN_NOEXCEPT - { - return m_xpr; - } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - XprType& nestedExpression() { return m_xpr; } - - /** \sa MapBase::innerStride() */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index innerStride() const EIGEN_NOEXCEPT - { - return internal::traits::HasSameStorageOrderAsXprType - ? m_xpr.innerStride() - : m_xpr.outerStride(); - } - - /** \sa MapBase::outerStride() */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index outerStride() const EIGEN_NOEXCEPT - { - return internal::traits::HasSameStorageOrderAsXprType - ? m_xpr.outerStride() - : m_xpr.innerStride(); - } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - StorageIndex startRow() const EIGEN_NOEXCEPT { return m_startRow.value(); } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - StorageIndex startCol() const EIGEN_NOEXCEPT { return m_startCol.value(); } - - #ifndef __SUNPRO_CC + m_startRow((BlockRows == 1) && (BlockCols == XprType::ColsAtCompileTime) ? i : 0), + m_startCol((BlockRows == XprType::RowsAtCompileTime) && (BlockCols == 1) ? i : 0) { + init(); + } + + /** Fixed-size constructor + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockImpl_dense(XprType& xpr, Index startRow, Index startCol) + : Base((BlockRows == 0 || BlockCols == 0) + ? nullptr + : add_to_nullable_pointer(xpr.data(), + xpr.innerStride() * (XprTypeIsRowMajor ? startCol : startRow) + + xpr.outerStride() * (XprTypeIsRowMajor ? startRow : startCol))), + m_xpr(xpr), + m_startRow(startRow), + m_startCol(startCol) { + init(); + } + + /** Dynamic-size constructor + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockImpl_dense(XprType& xpr, Index startRow, Index startCol, Index blockRows, + Index blockCols) + : Base((blockRows == 0 || blockCols == 0) + ? nullptr + : add_to_nullable_pointer(xpr.data(), + xpr.innerStride() * (XprTypeIsRowMajor ? startCol : startRow) + + xpr.outerStride() * (XprTypeIsRowMajor ? startRow : startCol)), + blockRows, blockCols), + m_xpr(xpr), + m_startRow(startRow), + m_startCol(startCol) { + init(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const internal::remove_all_t& nestedExpression() const + EIGEN_NOEXCEPT { + return m_xpr; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE XprType& nestedExpression() { return m_xpr; } + + /** \sa MapBase::innerStride() */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index innerStride() const EIGEN_NOEXCEPT { + return internal::traits::HasSameStorageOrderAsXprType ? m_xpr.innerStride() : m_xpr.outerStride(); + } + + /** \sa MapBase::outerStride() */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index outerStride() const EIGEN_NOEXCEPT { + return internal::traits::HasSameStorageOrderAsXprType ? m_xpr.outerStride() : m_xpr.innerStride(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR StorageIndex startRow() const EIGEN_NOEXCEPT { + return m_startRow.value(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR StorageIndex startCol() const EIGEN_NOEXCEPT { + return m_startCol.value(); + } + +#ifndef __SUNPRO_CC // FIXME sunstudio is not friendly with the above friend... // META-FIXME there is no 'friend' keyword around here. Is this obsolete? - protected: - #endif - - #ifndef EIGEN_PARSED_BY_DOXYGEN - /** \internal used by allowAligned() */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - BlockImpl_dense(XprType& xpr, const Scalar* data, Index blockRows, Index blockCols) - : Base(data, blockRows, blockCols), m_xpr(xpr) - { - init(); - } - #endif - - protected: - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void init() - { - m_outerStride = internal::traits::HasSameStorageOrderAsXprType - ? m_xpr.outerStride() - : m_xpr.innerStride(); - } - - XprTypeNested m_xpr; - const internal::variable_if_dynamic m_startRow; - const internal::variable_if_dynamic m_startCol; - Index m_outerStride; + protected: +#endif + +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** \internal used by allowAligned() */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockImpl_dense(XprType& xpr, const Scalar* data, Index blockRows, + Index blockCols) + : Base(data, blockRows, blockCols), m_xpr(xpr) { + init(); + } +#endif + + protected: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void init() { + m_outerStride = + internal::traits::HasSameStorageOrderAsXprType ? m_xpr.outerStride() : m_xpr.innerStride(); + } + + XprTypeNested m_xpr; + const internal::variable_if_dynamic + m_startRow; + const internal::variable_if_dynamic + m_startCol; + Index m_outerStride; }; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_BLOCK_H +#endif // EIGEN_BLOCK_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/BooleanRedux.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/BooleanRedux.h deleted file mode 100644 index 852de8b90a5..00000000000 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/BooleanRedux.h +++ /dev/null @@ -1,162 +0,0 @@ -// This file is part of Eigen, a lightweight C++ template library -// for linear algebra. -// -// Copyright (C) 2008 Gael Guennebaud -// -// This Source Code Form is subject to the terms of the Mozilla -// Public License v. 2.0. If a copy of the MPL was not distributed -// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. - -#ifndef EIGEN_ALLANDANY_H -#define EIGEN_ALLANDANY_H - -namespace Eigen { - -namespace internal { - -template -struct all_unroller -{ - enum { - col = (UnrollCount-1) / Rows, - row = (UnrollCount-1) % Rows - }; - - EIGEN_DEVICE_FUNC static inline bool run(const Derived &mat) - { - return all_unroller::run(mat) && mat.coeff(row, col); - } -}; - -template -struct all_unroller -{ - EIGEN_DEVICE_FUNC static inline bool run(const Derived &/*mat*/) { return true; } -}; - -template -struct all_unroller -{ - EIGEN_DEVICE_FUNC static inline bool run(const Derived &) { return false; } -}; - -template -struct any_unroller -{ - enum { - col = (UnrollCount-1) / Rows, - row = (UnrollCount-1) % Rows - }; - - EIGEN_DEVICE_FUNC static inline bool run(const Derived &mat) - { - return any_unroller::run(mat) || mat.coeff(row, col); - } -}; - -template -struct any_unroller -{ - EIGEN_DEVICE_FUNC static inline bool run(const Derived & /*mat*/) { return false; } -}; - -template -struct any_unroller -{ - EIGEN_DEVICE_FUNC static inline bool run(const Derived &) { return false; } -}; - -} // end namespace internal - -/** \returns true if all coefficients are true - * - * Example: \include MatrixBase_all.cpp - * Output: \verbinclude MatrixBase_all.out - * - * \sa any(), Cwise::operator<() - */ -template -EIGEN_DEVICE_FUNC inline bool DenseBase::all() const -{ - typedef internal::evaluator Evaluator; - enum { - unroll = SizeAtCompileTime != Dynamic - && SizeAtCompileTime * (int(Evaluator::CoeffReadCost) + int(NumTraits::AddCost)) <= EIGEN_UNROLLING_LIMIT - }; - Evaluator evaluator(derived()); - if(unroll) - return internal::all_unroller::RowsAtCompileTime>::run(evaluator); - else - { - for(Index j = 0; j < cols(); ++j) - for(Index i = 0; i < rows(); ++i) - if (!evaluator.coeff(i, j)) return false; - return true; - } -} - -/** \returns true if at least one coefficient is true - * - * \sa all() - */ -template -EIGEN_DEVICE_FUNC inline bool DenseBase::any() const -{ - typedef internal::evaluator Evaluator; - enum { - unroll = SizeAtCompileTime != Dynamic - && SizeAtCompileTime * (int(Evaluator::CoeffReadCost) + int(NumTraits::AddCost)) <= EIGEN_UNROLLING_LIMIT - }; - Evaluator evaluator(derived()); - if(unroll) - return internal::any_unroller::RowsAtCompileTime>::run(evaluator); - else - { - for(Index j = 0; j < cols(); ++j) - for(Index i = 0; i < rows(); ++i) - if (evaluator.coeff(i, j)) return true; - return false; - } -} - -/** \returns the number of coefficients which evaluate to true - * - * \sa all(), any() - */ -template -EIGEN_DEVICE_FUNC inline Eigen::Index DenseBase::count() const -{ - return derived().template cast().template cast().sum(); -} - -/** \returns true is \c *this contains at least one Not A Number (NaN). - * - * \sa allFinite() - */ -template -inline bool DenseBase::hasNaN() const -{ -#if EIGEN_COMP_MSVC || (defined __FAST_MATH__) - return derived().array().isNaN().any(); -#else - return !((derived().array()==derived().array()).all()); -#endif -} - -/** \returns true if \c *this contains only finite numbers, i.e., no NaN and no +/-INF values. - * - * \sa hasNaN() - */ -template -inline bool DenseBase::allFinite() const -{ -#if EIGEN_COMP_MSVC || (defined __FAST_MATH__) - return derived().array().isFinite().all(); -#else - return !((derived()-derived()).hasNaN()); -#endif -} - -} // end namespace Eigen - -#endif // EIGEN_ALLANDANY_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CommaInitializer.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CommaInitializer.h index c0e29c75c22..c6291234b1b 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CommaInitializer.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CommaInitializer.h @@ -11,49 +11,46 @@ #ifndef EIGEN_COMMAINITIALIZER_H #define EIGEN_COMMAINITIALIZER_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { /** \class CommaInitializer - * \ingroup Core_Module - * - * \brief Helper class used by the comma initializer operator - * - * This class is internally used to implement the comma initializer feature. It is - * the return type of MatrixBase::operator<<, and most of the time this is the only - * way it is used. - * - * \sa \blank \ref MatrixBaseCommaInitRef "MatrixBase::operator<<", CommaInitializer::finished() - */ -template -struct CommaInitializer -{ + * \ingroup Core_Module + * + * \brief Helper class used by the comma initializer operator + * + * This class is internally used to implement the comma initializer feature. It is + * the return type of MatrixBase::operator<<, and most of the time this is the only + * way it is used. + * + * \sa \blank \ref MatrixBaseCommaInitRef "MatrixBase::operator<<", CommaInitializer::finished() + */ +template +struct CommaInitializer { typedef typename XprType::Scalar Scalar; - EIGEN_DEVICE_FUNC - inline CommaInitializer(XprType& xpr, const Scalar& s) - : m_xpr(xpr), m_row(0), m_col(1), m_currentBlockRows(1) - { - eigen_assert(m_xpr.rows() > 0 && m_xpr.cols() > 0 - && "Cannot comma-initialize a 0x0 matrix (operator<<)"); - m_xpr.coeffRef(0,0) = s; + EIGEN_DEVICE_FUNC inline CommaInitializer(XprType& xpr, const Scalar& s) + : m_xpr(xpr), m_row(0), m_col(1), m_currentBlockRows(1) { + eigen_assert(m_xpr.rows() > 0 && m_xpr.cols() > 0 && "Cannot comma-initialize a 0x0 matrix (operator<<)"); + m_xpr.coeffRef(0, 0) = s; } - template - EIGEN_DEVICE_FUNC - inline CommaInitializer(XprType& xpr, const DenseBase& other) - : m_xpr(xpr), m_row(0), m_col(other.cols()), m_currentBlockRows(other.rows()) - { - eigen_assert(m_xpr.rows() >= other.rows() && m_xpr.cols() >= other.cols() - && "Cannot comma-initialize a 0x0 matrix (operator<<)"); - m_xpr.block(0, 0, other.rows(), other.cols()) = other; + template + EIGEN_DEVICE_FUNC inline CommaInitializer(XprType& xpr, const DenseBase& other) + : m_xpr(xpr), m_row(0), m_col(other.cols()), m_currentBlockRows(other.rows()) { + eigen_assert(m_xpr.rows() >= other.rows() && m_xpr.cols() >= other.cols() && + "Cannot comma-initialize a 0x0 matrix (operator<<)"); + m_xpr.template block(0, 0, other.rows(), + other.cols()) = other; } - /* Copy/Move constructor which transfers ownership. This is crucial in + /* Copy/Move constructor which transfers ownership. This is crucial in * absence of return value optimization to avoid assertions during destruction. */ // FIXME in C++11 mode this could be replaced by a proper RValue constructor - EIGEN_DEVICE_FUNC - inline CommaInitializer(const CommaInitializer& o) - : m_xpr(o.m_xpr), m_row(o.m_row), m_col(o.m_col), m_currentBlockRows(o.m_currentBlockRows) { + EIGEN_DEVICE_FUNC inline CommaInitializer(const CommaInitializer& o) + : m_xpr(o.m_xpr), m_row(o.m_row), m_col(o.m_col), m_currentBlockRows(o.m_currentBlockRows) { // Mark original object as finished. In absence of R-value references we need to const_cast: const_cast(o).m_row = m_xpr.rows(); const_cast(o).m_col = m_xpr.cols(); @@ -61,104 +58,92 @@ struct CommaInitializer } /* inserts a scalar value in the target matrix */ - EIGEN_DEVICE_FUNC - CommaInitializer& operator,(const Scalar& s) - { - if (m_col==m_xpr.cols()) - { - m_row+=m_currentBlockRows; + EIGEN_DEVICE_FUNC CommaInitializer &operator,(const Scalar& s) { + if (m_col == m_xpr.cols()) { + m_row += m_currentBlockRows; m_col = 0; m_currentBlockRows = 1; - eigen_assert(m_row - EIGEN_DEVICE_FUNC - CommaInitializer& operator,(const DenseBase& other) - { - if (m_col==m_xpr.cols() && (other.cols()!=0 || other.rows()!=m_currentBlockRows)) - { - m_row+=m_currentBlockRows; + template + EIGEN_DEVICE_FUNC CommaInitializer &operator,(const DenseBase& other) { + if (m_col == m_xpr.cols() && (other.cols() != 0 || other.rows() != m_currentBlockRows)) { + m_row += m_currentBlockRows; m_col = 0; m_currentBlockRows = other.rows(); - eigen_assert(m_row+m_currentBlockRows<=m_xpr.rows() - && "Too many rows passed to comma initializer (operator<<)"); + eigen_assert(m_row + m_currentBlockRows <= m_xpr.rows() && + "Too many rows passed to comma initializer (operator<<)"); } - eigen_assert((m_col + other.cols() <= m_xpr.cols()) - && "Too many coefficients passed to comma initializer (operator<<)"); - eigen_assert(m_currentBlockRows==other.rows()); - m_xpr.template block - (m_row, m_col, other.rows(), other.cols()) = other; + eigen_assert((m_col + other.cols() <= m_xpr.cols()) && + "Too many coefficients passed to comma initializer (operator<<)"); + eigen_assert(m_currentBlockRows == other.rows()); + m_xpr.template block(m_row, m_col, other.rows(), + other.cols()) = other; m_col += other.cols(); return *this; } - EIGEN_DEVICE_FUNC - inline ~CommaInitializer() + EIGEN_DEVICE_FUNC inline ~CommaInitializer() #if defined VERIFY_RAISES_ASSERT && (!defined EIGEN_NO_ASSERTION_CHECKING) && defined EIGEN_EXCEPTIONS - EIGEN_EXCEPTION_SPEC(Eigen::eigen_assert_exception) + EIGEN_EXCEPTION_SPEC(Eigen::eigen_assert_exception) #endif { finished(); } /** \returns the built matrix once all its coefficients have been set. - * Calling finished is 100% optional. Its purpose is to write expressions - * like this: - * \code - * quaternion.fromRotationMatrix((Matrix3f() << axis0, axis1, axis2).finished()); - * \endcode - */ - EIGEN_DEVICE_FUNC - inline XprType& finished() { - eigen_assert(((m_row+m_currentBlockRows) == m_xpr.rows() || m_xpr.cols() == 0) - && m_col == m_xpr.cols() - && "Too few coefficients passed to comma initializer (operator<<)"); - return m_xpr; + * Calling finished is 100% optional. Its purpose is to write expressions + * like this: + * \code + * quaternion.fromRotationMatrix((Matrix3f() << axis0, axis1, axis2).finished()); + * \endcode + */ + EIGEN_DEVICE_FUNC inline XprType& finished() { + eigen_assert(((m_row + m_currentBlockRows) == m_xpr.rows() || m_xpr.cols() == 0) && m_col == m_xpr.cols() && + "Too few coefficients passed to comma initializer (operator<<)"); + return m_xpr; } - XprType& m_xpr; // target expression - Index m_row; // current row id - Index m_col; // current col id - Index m_currentBlockRows; // current block height + XprType& m_xpr; // target expression + Index m_row; // current row id + Index m_col; // current col id + Index m_currentBlockRows; // current block height }; /** \anchor MatrixBaseCommaInitRef - * Convenient operator to set the coefficients of a matrix. - * - * The coefficients must be provided in a row major order and exactly match - * the size of the matrix. Otherwise an assertion is raised. - * - * Example: \include MatrixBase_set.cpp - * Output: \verbinclude MatrixBase_set.out - * - * \note According the c++ standard, the argument expressions of this comma initializer are evaluated in arbitrary order. - * - * \sa CommaInitializer::finished(), class CommaInitializer - */ -template -EIGEN_DEVICE_FUNC inline CommaInitializer DenseBase::operator<< (const Scalar& s) -{ + * Convenient operator to set the coefficients of a matrix. + * + * The coefficients must be provided in a row major order and exactly match + * the size of the matrix. Otherwise an assertion is raised. + * + * Example: \include MatrixBase_set.cpp + * Output: \verbinclude MatrixBase_set.out + * + * \note According the c++ standard, the argument expressions of this comma initializer are evaluated in arbitrary + * order. + * + * \sa CommaInitializer::finished(), class CommaInitializer + */ +template +EIGEN_DEVICE_FUNC inline CommaInitializer DenseBase::operator<<(const Scalar& s) { return CommaInitializer(*static_cast(this), s); } /** \sa operator<<(const Scalar&) */ -template -template -EIGEN_DEVICE_FUNC inline CommaInitializer -DenseBase::operator<<(const DenseBase& other) -{ - return CommaInitializer(*static_cast(this), other); +template +template +EIGEN_DEVICE_FUNC inline CommaInitializer DenseBase::operator<<( + const DenseBase& other) { + return CommaInitializer(*static_cast(this), other); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_COMMAINITIALIZER_H +#endif // EIGEN_COMMAINITIALIZER_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ConditionEstimator.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ConditionEstimator.h index 51a2e5f1b6f..dd1770b1abc 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ConditionEstimator.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ConditionEstimator.h @@ -10,6 +10,9 @@ #ifndef EIGEN_CONDITIONESTIMATOR_H #define EIGEN_CONDITIONESTIMATOR_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { @@ -19,7 +22,7 @@ struct rcond_compute_sign { static inline Vector run(const Vector& v) { const RealVector v_abs = v.cwiseAbs(); return (v_abs.array() == static_cast(0)) - .select(Vector::Ones(v.size()), v.cwiseQuotient(v_abs)); + .select(Vector::Ones(v.size()), v.cwiseQuotient(v_abs)); } }; @@ -28,33 +31,32 @@ template struct rcond_compute_sign { static inline Vector run(const Vector& v) { return (v.array() < static_cast(0)) - .select(-Vector::Ones(v.size()), Vector::Ones(v.size())); + .select(-Vector::Ones(v.size()), Vector::Ones(v.size())); } }; /** - * \returns an estimate of ||inv(matrix)||_1 given a decomposition of - * \a matrix that implements .solve() and .adjoint().solve() methods. - * - * This function implements Algorithms 4.1 and 5.1 from - * http://www.maths.manchester.ac.uk/~higham/narep/narep135.pdf - * which also forms the basis for the condition number estimators in - * LAPACK. Since at most 10 calls to the solve method of dec are - * performed, the total cost is O(dims^2), as opposed to O(dims^3) - * needed to compute the inverse matrix explicitly. - * - * The most common usage is in estimating the condition number - * ||matrix||_1 * ||inv(matrix)||_1. The first term ||matrix||_1 can be - * computed directly in O(n^2) operations. - * - * Supports the following decompositions: FullPivLU, PartialPivLU, LDLT, and - * LLT. - * - * \sa FullPivLU, PartialPivLU, LDLT, LLT. - */ + * \returns an estimate of ||inv(matrix)||_1 given a decomposition of + * \a matrix that implements .solve() and .adjoint().solve() methods. + * + * This function implements Algorithms 4.1 and 5.1 from + * http://www.maths.manchester.ac.uk/~higham/narep/narep135.pdf + * which also forms the basis for the condition number estimators in + * LAPACK. Since at most 10 calls to the solve method of dec are + * performed, the total cost is O(dims^2), as opposed to O(dims^3) + * needed to compute the inverse matrix explicitly. + * + * The most common usage is in estimating the condition number + * ||matrix||_1 * ||inv(matrix)||_1. The first term ||matrix||_1 can be + * computed directly in O(n^2) operations. + * + * Supports the following decompositions: FullPivLU, PartialPivLU, LDLT, and + * LLT. + * + * \sa FullPivLU, PartialPivLU, LDLT, LLT. + */ template -typename Decomposition::RealScalar rcond_invmatrix_L1_norm_estimate(const Decomposition& dec) -{ +typename Decomposition::RealScalar rcond_invmatrix_L1_norm_estimate(const Decomposition& dec) { typedef typename Decomposition::MatrixType MatrixType; typedef typename Decomposition::Scalar Scalar; typedef typename Decomposition::RealScalar RealScalar; @@ -64,17 +66,16 @@ typename Decomposition::RealScalar rcond_invmatrix_L1_norm_estimate(const Decomp eigen_assert(dec.rows() == dec.cols()); const Index n = dec.rows(); - if (n == 0) - return 0; + if (n == 0) return 0; - // Disable Index to float conversion warning + // Disable Index to float conversion warning #ifdef __INTEL_COMPILER - #pragma warning push - #pragma warning ( disable : 2259 ) +#pragma warning push +#pragma warning(disable : 2259) #endif Vector v = dec.solve(Vector::Ones(n) / Scalar(n)); #ifdef __INTEL_COMPILER - #pragma warning pop +#pragma warning pop #endif // lower_bound is a lower bound on @@ -82,8 +83,7 @@ typename Decomposition::RealScalar rcond_invmatrix_L1_norm_estimate(const Decomp // and is the objective maximized by the ("super-") gradient ascent // algorithm below. RealScalar lower_bound = v.template lpNorm<1>(); - if (n == 1) - return lower_bound; + if (n == 1) return lower_bound; // Gradient ascent algorithm follows: We know that the optimum is achieved at // one of the simplices v = e_i, so in each iteration we follow a @@ -93,8 +93,7 @@ typename Decomposition::RealScalar rcond_invmatrix_L1_norm_estimate(const Decomp Vector old_sign_vector; Index v_max_abs_index = -1; Index old_v_max_abs_index = v_max_abs_index; - for (int k = 0; k < 4; ++k) - { + for (int k = 0; k < 4; ++k) { sign_vector = internal::rcond_compute_sign::run(v); if (k > 0 && !is_complex && sign_vector == old_sign_vector) { // Break if the solution stagnated. @@ -142,30 +141,29 @@ typename Decomposition::RealScalar rcond_invmatrix_L1_norm_estimate(const Decomp } /** \brief Reciprocal condition number estimator. - * - * Computing a decomposition of a dense matrix takes O(n^3) operations, while - * this method estimates the condition number quickly and reliably in O(n^2) - * operations. - * - * \returns an estimate of the reciprocal condition number - * (1 / (||matrix||_1 * ||inv(matrix)||_1)) of matrix, given ||matrix||_1 and - * its decomposition. Supports the following decompositions: FullPivLU, - * PartialPivLU, LDLT, and LLT. - * - * \sa FullPivLU, PartialPivLU, LDLT, LLT. - */ + * + * Computing a decomposition of a dense matrix takes O(n^3) operations, while + * this method estimates the condition number quickly and reliably in O(n^2) + * operations. + * + * \returns an estimate of the reciprocal condition number + * (1 / (||matrix||_1 * ||inv(matrix)||_1)) of matrix, given ||matrix||_1 and + * its decomposition. Supports the following decompositions: FullPivLU, + * PartialPivLU, LDLT, and LLT. + * + * \sa FullPivLU, PartialPivLU, LDLT, LLT. + */ template -typename Decomposition::RealScalar -rcond_estimate_helper(typename Decomposition::RealScalar matrix_norm, const Decomposition& dec) -{ +typename Decomposition::RealScalar rcond_estimate_helper(typename Decomposition::RealScalar matrix_norm, + const Decomposition& dec) { typedef typename Decomposition::RealScalar RealScalar; eigen_assert(dec.rows() == dec.cols()); - if (dec.rows() == 0) return NumTraits::infinity(); - if (matrix_norm == RealScalar(0)) return RealScalar(0); - if (dec.rows() == 1) return RealScalar(1); + if (dec.rows() == 0) return NumTraits::infinity(); + if (numext::is_exactly_zero(matrix_norm)) return RealScalar(0); + if (dec.rows() == 1) return RealScalar(1); const RealScalar inverse_matrix_norm = rcond_invmatrix_L1_norm_estimate(dec); - return (inverse_matrix_norm == RealScalar(0) ? RealScalar(0) - : (RealScalar(1) / inverse_matrix_norm) / matrix_norm); + return (numext::is_exactly_zero(inverse_matrix_norm) ? RealScalar(0) + : (RealScalar(1) / inverse_matrix_norm) / matrix_norm); } } // namespace internal diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CoreEvaluators.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CoreEvaluators.h index 0ff8c8deb82..5e1cbf6ecf4 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CoreEvaluators.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CoreEvaluators.h @@ -9,29 +9,44 @@ // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. - #ifndef EIGEN_COREEVALUATORS_H #define EIGEN_COREEVALUATORS_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { // This class returns the evaluator kind from the expression storage kind. // Default assumes index based accessors -template +template struct storage_kind_to_evaluator_kind { typedef IndexBased Kind; }; // This class returns the evaluator shape from the expression storage kind. // It can be Dense, Sparse, Triangular, Diagonal, SelfAdjoint, Band, etc. -template struct storage_kind_to_shape; +template +struct storage_kind_to_shape; -template<> struct storage_kind_to_shape { typedef DenseShape Shape; }; -template<> struct storage_kind_to_shape { typedef SolverShape Shape; }; -template<> struct storage_kind_to_shape { typedef PermutationShape Shape; }; -template<> struct storage_kind_to_shape { typedef TranspositionsShape Shape; }; +template <> +struct storage_kind_to_shape { + typedef DenseShape Shape; +}; +template <> +struct storage_kind_to_shape { + typedef SolverShape Shape; +}; +template <> +struct storage_kind_to_shape { + typedef PermutationShape Shape; +}; +template <> +struct storage_kind_to_shape { + typedef TranspositionsShape Shape; +}; // Evaluators have to be specialized with respect to various criteria such as: // - storage/structure/shape @@ -39,88 +54,80 @@ template<> struct storage_kind_to_shape { typedef Transp // - etc. // Therefore, we need specialization of evaluator providing additional template arguments for each kind of evaluators. // We currently distinguish the following kind of evaluators: -// - unary_evaluator for expressions taking only one arguments (CwiseUnaryOp, CwiseUnaryView, Transpose, MatrixWrapper, ArrayWrapper, Reverse, Replicate) +// - unary_evaluator for expressions taking only one arguments (CwiseUnaryOp, CwiseUnaryView, Transpose, +// MatrixWrapper, ArrayWrapper, Reverse, Replicate) // - binary_evaluator for expression taking two arguments (CwiseBinaryOp) // - ternary_evaluator for expression taking three arguments (CwiseTernaryOp) -// - product_evaluator for linear algebra products (Product); special case of binary_evaluator because it requires additional tags for dispatching. +// - product_evaluator for linear algebra products (Product); special case of binary_evaluator because it requires +// additional tags for dispatching. // - mapbase_evaluator for Map, Block, Ref // - block_evaluator for Block (special dispatching to a mapbase_evaluator or unary_evaluator) -template< typename T, - typename Arg1Kind = typename evaluator_traits::Kind, - typename Arg2Kind = typename evaluator_traits::Kind, - typename Arg3Kind = typename evaluator_traits::Kind, +template ::Kind, + typename Arg2Kind = typename evaluator_traits::Kind, + typename Arg3Kind = typename evaluator_traits::Kind, typename Arg1Scalar = typename traits::Scalar, typename Arg2Scalar = typename traits::Scalar, - typename Arg3Scalar = typename traits::Scalar> struct ternary_evaluator; + typename Arg3Scalar = typename traits::Scalar> +struct ternary_evaluator; -template< typename T, - typename LhsKind = typename evaluator_traits::Kind, - typename RhsKind = typename evaluator_traits::Kind, +template ::Kind, + typename RhsKind = typename evaluator_traits::Kind, typename LhsScalar = typename traits::Scalar, - typename RhsScalar = typename traits::Scalar> struct binary_evaluator; + typename RhsScalar = typename traits::Scalar> +struct binary_evaluator; -template< typename T, - typename Kind = typename evaluator_traits::Kind, - typename Scalar = typename T::Scalar> struct unary_evaluator; +template ::Kind, + typename Scalar = typename T::Scalar> +struct unary_evaluator; // evaluator_traits contains traits for evaluator -template -struct evaluator_traits_base -{ +template +struct evaluator_traits_base { // by default, get evaluator kind and shape from storage typedef typename storage_kind_to_evaluator_kind::StorageKind>::Kind Kind; typedef typename storage_kind_to_shape::StorageKind>::Shape Shape; }; // Default evaluator traits -template -struct evaluator_traits : public evaluator_traits_base -{ -}; +template +struct evaluator_traits : public evaluator_traits_base {}; -template::Shape > +template ::Shape> struct evaluator_assume_aliasing { static const bool value = false; }; // By default, we assume a unary expression: -template -struct evaluator : public unary_evaluator -{ +template +struct evaluator : public unary_evaluator { typedef unary_evaluator Base; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit evaluator(const T& xpr) : Base(xpr) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const T& xpr) : Base(xpr) {} }; - // TODO: Think about const-correctness -template -struct evaluator - : evaluator -{ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit evaluator(const T& xpr) : evaluator(xpr) {} +template +struct evaluator : evaluator { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const T& xpr) : evaluator(xpr) {} }; // ---------- base class for all evaluators ---------- -template -struct evaluator_base -{ - // TODO that's not very nice to have to propagate all these traits. They are currently only needed to handle outer,inner indices. +template +struct evaluator_base { + // TODO that's not very nice to have to propagate all these traits. They are currently only needed to handle + // outer,inner indices. typedef traits ExpressionTraits; - enum { - Alignment = 0 - }; + enum { Alignment = 0 }; // noncopyable: // Don't make this class inherit noncopyable as this kills EBO (Empty Base Optimization) // and make complex evaluator much larger than then should do. EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE evaluator_base() {} EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ~evaluator_base() {} -private: + + private: EIGEN_DEVICE_FUNC evaluator_base(const evaluator_base&); EIGEN_DEVICE_FUNC const evaluator_base& operator=(const evaluator_base&); }; @@ -133,36 +140,34 @@ struct evaluator_base // so no need for more sophisticated dispatching. // this helper permits to completely eliminate m_outerStride if it is known at compiletime. -template class plainobjectbase_evaluator_data { -public: - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - plainobjectbase_evaluator_data(const Scalar* ptr, Index outerStride) : data(ptr) - { +template +class plainobjectbase_evaluator_data { + public: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE plainobjectbase_evaluator_data(const Scalar* ptr, Index outerStride) + : data(ptr) { #ifndef EIGEN_INTERNAL_DEBUGGING EIGEN_UNUSED_VARIABLE(outerStride); #endif - eigen_internal_assert(outerStride==OuterStride); + eigen_internal_assert(outerStride == OuterStride); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index outerStride() const EIGEN_NOEXCEPT { return OuterStride; } - const Scalar *data; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index outerStride() const EIGEN_NOEXCEPT { return OuterStride; } + const Scalar* data; }; -template class plainobjectbase_evaluator_data { -public: - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - plainobjectbase_evaluator_data(const Scalar* ptr, Index outerStride) : data(ptr), m_outerStride(outerStride) {} - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Index outerStride() const { return m_outerStride; } - const Scalar *data; -protected: +template +class plainobjectbase_evaluator_data { + public: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE plainobjectbase_evaluator_data(const Scalar* ptr, Index outerStride) + : data(ptr), m_outerStride(outerStride) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index outerStride() const { return m_outerStride; } + const Scalar* data; + + protected: Index m_outerStride; }; -template -struct evaluator > - : evaluator_base -{ +template +struct evaluator > : evaluator_base { typedef PlainObjectBase PlainObjectType; typedef typename PlainObjectType::Scalar Scalar; typedef typename PlainObjectType::CoeffReturnType CoeffReturnType; @@ -179,132 +184,94 @@ struct evaluator > }; enum { // We do not need to know the outer stride for vectors - OuterStrideAtCompileTime = IsVectorAtCompileTime ? 0 - : int(IsRowMajor) ? ColsAtCompileTime - : RowsAtCompileTime + OuterStrideAtCompileTime = IsVectorAtCompileTime ? 0 + : int(IsRowMajor) ? ColsAtCompileTime + : RowsAtCompileTime }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - evaluator() - : m_d(0,OuterStrideAtCompileTime) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE evaluator() : m_d(0, OuterStrideAtCompileTime) { EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit evaluator(const PlainObjectType& m) - : m_d(m.data(),IsVectorAtCompileTime ? 0 : m.outerStride()) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const PlainObjectType& m) + : m_d(m.data(), IsVectorAtCompileTime ? 0 : m.outerStride()) { EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { if (IsRowMajor) return m_d.data[row * m_d.outerStride() + col]; else return m_d.data[row + col * m_d.outerStride()]; } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { - return m_d.data[index]; - } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_d.data[index]; } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index row, Index col) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col) { if (IsRowMajor) return const_cast(m_d.data)[row * m_d.outerStride() + col]; else return const_cast(m_d.data)[row + col * m_d.outerStride()]; } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index index) - { - return const_cast(m_d.data)[index]; - } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { return const_cast(m_d.data)[index]; } - template - EIGEN_STRONG_INLINE - PacketType packet(Index row, Index col) const - { + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { if (IsRowMajor) return ploadt(m_d.data + row * m_d.outerStride() + col); else return ploadt(m_d.data + row + col * m_d.outerStride()); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index index) const - { + template + EIGEN_STRONG_INLINE PacketType packet(Index index) const { return ploadt(m_d.data + index); } - template - EIGEN_STRONG_INLINE - void writePacket(Index row, Index col, const PacketType& x) - { + template + EIGEN_STRONG_INLINE void writePacket(Index row, Index col, const PacketType& x) { if (IsRowMajor) - return pstoret - (const_cast(m_d.data) + row * m_d.outerStride() + col, x); + return pstoret(const_cast(m_d.data) + row * m_d.outerStride() + col, x); else - return pstoret - (const_cast(m_d.data) + row + col * m_d.outerStride(), x); + return pstoret(const_cast(m_d.data) + row + col * m_d.outerStride(), x); } - template - EIGEN_STRONG_INLINE - void writePacket(Index index, const PacketType& x) - { + template + EIGEN_STRONG_INLINE void writePacket(Index index, const PacketType& x) { return pstoret(const_cast(m_d.data) + index, x); } -protected: - - plainobjectbase_evaluator_data m_d; + protected: + plainobjectbase_evaluator_data m_d; }; -template +template struct evaluator > - : evaluator > > -{ + : evaluator > > { typedef Matrix XprType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - evaluator() {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE evaluator() {} - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit evaluator(const XprType& m) - : evaluator >(m) - { } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const XprType& m) + : evaluator >(m) {} }; -template +template struct evaluator > - : evaluator > > -{ + : evaluator > > { typedef Array XprType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - evaluator() {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE evaluator() {} - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit evaluator(const XprType& m) - : evaluator >(m) - { } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const XprType& m) + : evaluator >(m) {} }; // -------------------- Transpose -------------------- -template -struct unary_evaluator, IndexBased> - : evaluator_base > -{ +template +struct unary_evaluator, IndexBased> : evaluator_base > { typedef Transpose XprType; enum { @@ -313,65 +280,44 @@ struct unary_evaluator, IndexBased> Alignment = evaluator::Alignment }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit unary_evaluator(const XprType& t) : m_argImpl(t.nestedExpression()) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit unary_evaluator(const XprType& t) : m_argImpl(t.nestedExpression()) {} typedef typename XprType::Scalar Scalar; typedef typename XprType::CoeffReturnType CoeffReturnType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { return m_argImpl.coeff(col, row); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { - return m_argImpl.coeff(index); - } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_argImpl.coeff(index); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index row, Index col) - { - return m_argImpl.coeffRef(col, row); - } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col) { return m_argImpl.coeffRef(col, row); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - typename XprType::Scalar& coeffRef(Index index) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename XprType::Scalar& coeffRef(Index index) { return m_argImpl.coeffRef(index); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index row, Index col) const - { - return m_argImpl.template packet(col, row); + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { + return m_argImpl.template packet(col, row); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index index) const - { - return m_argImpl.template packet(index); + template + EIGEN_STRONG_INLINE PacketType packet(Index index) const { + return m_argImpl.template packet(index); } - template - EIGEN_STRONG_INLINE - void writePacket(Index row, Index col, const PacketType& x) - { - m_argImpl.template writePacket(col, row, x); + template + EIGEN_STRONG_INLINE void writePacket(Index row, Index col, const PacketType& x) { + m_argImpl.template writePacket(col, row, x); } - template - EIGEN_STRONG_INLINE - void writePacket(Index index, const PacketType& x) - { - m_argImpl.template writePacket(index, x); + template + EIGEN_STRONG_INLINE void writePacket(Index index, const PacketType& x) { + m_argImpl.template writePacket(index, x); } -protected: + protected: evaluator m_argImpl; }; @@ -379,63 +325,83 @@ struct unary_evaluator, IndexBased> // Like Matrix and Array, this is not really a unary expression, so we directly specialize evaluator. // Likewise, there is not need to more sophisticated dispatching here. -template::value, - bool has_unary = has_unary_operator::value, - bool has_binary = has_binary_operator::value> -struct nullary_wrapper -{ +template ::value, + bool has_unary = has_unary_operator::value, + bool has_binary = has_binary_operator::value> +struct nullary_wrapper { template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i, IndexType j) const { return op(i,j); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i, IndexType j) const { + return op(i, j); + } template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i) const { return op(i); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i) const { + return op(i); + } - template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i, IndexType j) const { return op.template packetOp(i,j); } - template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i) const { return op.template packetOp(i); } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i, IndexType j) const { + return op.template packetOp(i, j); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i) const { + return op.template packetOp(i); + } }; -template -struct nullary_wrapper -{ +template +struct nullary_wrapper { template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType=0, IndexType=0) const { return op(); } - template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType=0, IndexType=0) const { return op.template packetOp(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType = 0, IndexType = 0) const { + return op(); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType = 0, IndexType = 0) const { + return op.template packetOp(); + } }; -template -struct nullary_wrapper -{ +template +struct nullary_wrapper { template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i, IndexType j=0) const { return op(i,j); } - template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i, IndexType j=0) const { return op.template packetOp(i,j); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i, IndexType j = 0) const { + return op(i, j); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i, IndexType j = 0) const { + return op.template packetOp(i, j); + } }; // We need the following specialization for vector-only functors assigned to a runtime vector, // for instance, using linspace and assigning a RowVectorXd to a MatrixXd or even a row of a MatrixXd. // In this case, i==0 and j is used for the actual iteration. -template -struct nullary_wrapper -{ +template +struct nullary_wrapper { template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i, IndexType j) const { - eigen_assert(i==0 || j==0); - return op(i+j); + eigen_assert(i == 0 || j == 0); + return op(i + j); } - template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i, IndexType j) const { - eigen_assert(i==0 || j==0); - return op.template packetOp(i+j); + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i, IndexType j) const { + eigen_assert(i == 0 || j == 0); + return op.template packetOp(i + j); } template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i) const { return op(i); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i) const { + return op(i); + } template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i) const { return op.template packetOp(i); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i) const { + return op.template packetOp(i); + } }; -template -struct nullary_wrapper {}; +template +struct nullary_wrapper {}; -#if 0 && EIGEN_COMP_MSVC>0 +#if 0 && EIGEN_COMP_MSVC > 0 // Disable this ugly workaround. This is now handled in traits::match, // but this piece of code might still become handly if some other weird compilation // erros pop up again. @@ -491,127 +457,100 @@ struct nullary_wrapper has_binary_operator >::value>().template packetOp(op,i); } }; -#endif // MSVC workaround +#endif // MSVC workaround -template -struct evaluator > - : evaluator_base > -{ - typedef CwiseNullaryOp XprType; - typedef typename internal::remove_all::type PlainObjectTypeCleaned; +template +struct evaluator > + : evaluator_base > { + typedef CwiseNullaryOp XprType; + typedef internal::remove_all_t PlainObjectTypeCleaned; enum { CoeffReadCost = internal::functor_traits::Cost, - Flags = (evaluator::Flags - & ( HereditaryBits - | (functor_has_linear_access::ret ? LinearAccessBit : 0) - | (functor_traits::PacketAccess ? PacketAccessBit : 0))) - | (functor_traits::IsRepeatable ? 0 : EvalBeforeNestingBit), + Flags = (evaluator::Flags & + (HereditaryBits | (functor_has_linear_access::ret ? LinearAccessBit : 0) | + (functor_traits::PacketAccess ? PacketAccessBit : 0))) | + (functor_traits::IsRepeatable ? 0 : EvalBeforeNestingBit), Alignment = AlignedMax }; - EIGEN_DEVICE_FUNC explicit evaluator(const XprType& n) - : m_functor(n.functor()), m_wrapper() - { + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& n) : m_functor(n.functor()), m_wrapper() { EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } typedef typename XprType::CoeffReturnType CoeffReturnType; template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(IndexType row, IndexType col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(IndexType row, IndexType col) const { return m_wrapper(m_functor, row, col); } template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(IndexType index) const - { - return m_wrapper(m_functor,index); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(IndexType index) const { + return m_wrapper(m_functor, index); } - template - EIGEN_STRONG_INLINE - PacketType packet(IndexType row, IndexType col) const - { + template + EIGEN_STRONG_INLINE PacketType packet(IndexType row, IndexType col) const { return m_wrapper.template packetOp(m_functor, row, col); } - template - EIGEN_STRONG_INLINE - PacketType packet(IndexType index) const - { + template + EIGEN_STRONG_INLINE PacketType packet(IndexType index) const { return m_wrapper.template packetOp(m_functor, index); } -protected: + protected: const NullaryOp m_functor; - const internal::nullary_wrapper m_wrapper; + const internal::nullary_wrapper m_wrapper; }; // -------------------- CwiseUnaryOp -------------------- -template -struct unary_evaluator, IndexBased > - : evaluator_base > -{ +template +struct unary_evaluator, IndexBased> : evaluator_base > { typedef CwiseUnaryOp XprType; enum { CoeffReadCost = int(evaluator::CoeffReadCost) + int(functor_traits::Cost), - Flags = evaluator::Flags - & (HereditaryBits | LinearAccessBit | (functor_traits::PacketAccess ? PacketAccessBit : 0)), + Flags = evaluator::Flags & + (HereditaryBits | LinearAccessBit | (functor_traits::PacketAccess ? PacketAccessBit : 0)), Alignment = evaluator::Alignment }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit unary_evaluator(const XprType& op) : m_d(op) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit unary_evaluator(const XprType& op) : m_d(op) { EIGEN_INTERNAL_CHECK_COST_VALUE(functor_traits::Cost); EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } typedef typename XprType::CoeffReturnType CoeffReturnType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { return m_d.func()(m_d.argImpl.coeff(row, col)); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_d.func()(m_d.argImpl.coeff(index)); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index row, Index col) const - { + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { return m_d.func().packetOp(m_d.argImpl.template packet(row, col)); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index index) const - { + template + EIGEN_STRONG_INLINE PacketType packet(Index index) const { return m_d.func().packetOp(m_d.argImpl.template packet(index)); } -protected: - + protected: // this helper permits to completely eliminate the functor if it is empty - struct Data - { - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Data(const XprType& xpr) : op(xpr.functor()), argImpl(xpr.nestedExpression()) {} - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const UnaryOp& func() const { return op; } + struct Data { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Data(const XprType& xpr) + : op(xpr.functor()), argImpl(xpr.nestedExpression()) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const UnaryOp& func() const { return op; } UnaryOp op; evaluator argImpl; }; @@ -619,93 +558,279 @@ struct unary_evaluator, IndexBased > Data m_d; }; +// ----------------------- Casting --------------------- + +template +struct unary_evaluator, ArgType>, IndexBased> { + using CastOp = core_cast_op; + using XprType = CwiseUnaryOp; + + // Use the largest packet type by default + using SrcPacketType = typename packet_traits::type; + static constexpr int SrcPacketSize = unpacket_traits::size; + static constexpr int SrcPacketBytes = SrcPacketSize * sizeof(SrcType); + + enum { + CoeffReadCost = int(evaluator::CoeffReadCost) + int(functor_traits::Cost), + PacketAccess = functor_traits::PacketAccess, + ActualPacketAccessBit = PacketAccess ? PacketAccessBit : 0, + Flags = evaluator::Flags & (HereditaryBits | LinearAccessBit | ActualPacketAccessBit), + IsRowMajor = (evaluator::Flags & RowMajorBit), + Alignment = evaluator::Alignment + }; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit unary_evaluator(const XprType& xpr) + : m_argImpl(xpr.nestedExpression()), m_rows(xpr.rows()), m_cols(xpr.cols()) { + EIGEN_INTERNAL_CHECK_COST_VALUE(functor_traits::Cost); + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + template + using AltSrcScalarOp = std::enable_if_t<(unpacket_traits::size < SrcPacketSize && + !find_packet_by_size::size>::value), + bool>; + template + using SrcPacketArgs1 = + std::enable_if_t<(find_packet_by_size::size>::value), bool>; + template + using SrcPacketArgs2 = std::enable_if_t<(unpacket_traits::size) == (2 * SrcPacketSize), bool>; + template + using SrcPacketArgs4 = std::enable_if_t<(unpacket_traits::size) == (4 * SrcPacketSize), bool>; + template + using SrcPacketArgs8 = std::enable_if_t<(unpacket_traits::size) == (8 * SrcPacketSize), bool>; + + template = true> + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool check_array_bounds(Index, Index col, Index packetSize) const { + return col + packetSize <= cols(); + } + template = true> + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool check_array_bounds(Index row, Index, Index packetSize) const { + return row + packetSize <= rows(); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool check_array_bounds(Index index, Index packetSize) const { + return index + packetSize <= size(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE SrcType srcCoeff(Index row, Index col, Index offset) const { + Index actualRow = IsRowMajor ? row : row + offset; + Index actualCol = IsRowMajor ? col + offset : col; + return m_argImpl.coeff(actualRow, actualCol); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE SrcType srcCoeff(Index index, Index offset) const { + Index actualIndex = index + offset; + return m_argImpl.coeff(actualIndex); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DstType coeff(Index row, Index col) const { + return cast(srcCoeff(row, col, 0)); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DstType coeff(Index index) const { + return cast(srcCoeff(index, 0)); + } + + template + EIGEN_STRONG_INLINE PacketType srcPacket(Index row, Index col, Index offset) const { + constexpr int PacketSize = unpacket_traits::size; + Index actualRow = IsRowMajor ? row : row + (offset * PacketSize); + Index actualCol = IsRowMajor ? col + (offset * PacketSize) : col; + eigen_assert(check_array_bounds(actualRow, actualCol, PacketSize) && "Array index out of bounds"); + return m_argImpl.template packet(actualRow, actualCol); + } + template + EIGEN_STRONG_INLINE PacketType srcPacket(Index index, Index offset) const { + constexpr int PacketSize = unpacket_traits::size; + Index actualIndex = index + (offset * PacketSize); + eigen_assert(check_array_bounds(actualIndex, PacketSize) && "Array index out of bounds"); + return m_argImpl.template packet(actualIndex); + } + + // There is no source packet type with equal or fewer elements than DstPacketType. + // This is problematic as the evaluation loop may attempt to access data outside the bounds of the array. + // For example, consider the cast utilizing pcast with an array of size 4: {0.0f,1.0f,2.0f,3.0f}. + // The first iteration of the evaulation loop will load 16 bytes: {0.0f,1.0f,2.0f,3.0f} and cast to {0.0,1.0}, which + // is acceptable. The second iteration will load 16 bytes: {2.0f,3.0f,?,?}, which is outside the bounds of the array. + + // Instead, perform runtime check to determine if the load would access data outside the bounds of the array. + // If not, perform full load. Otherwise, revert to a scalar loop to perform a partial load. + // In either case, perform a vectorized cast of the source packet. + template = true> + EIGEN_STRONG_INLINE DstPacketType packet(Index row, Index col) const { + constexpr int DstPacketSize = unpacket_traits::size; + constexpr int SrcBytesIncrement = DstPacketSize * sizeof(SrcType); + constexpr int SrcLoadMode = plain_enum_min(SrcBytesIncrement, LoadMode); + SrcPacketType src; + if (EIGEN_PREDICT_TRUE(check_array_bounds(row, col, SrcPacketSize))) { + src = srcPacket(row, col, 0); + } else { + Array srcArray; + for (size_t k = 0; k < DstPacketSize; k++) srcArray[k] = srcCoeff(row, col, k); + for (size_t k = DstPacketSize; k < SrcPacketSize; k++) srcArray[k] = SrcType(0); + src = pload(srcArray.data()); + } + return pcast(src); + } + // Use the source packet type with the same size as DstPacketType, if it exists + template = true> + EIGEN_STRONG_INLINE DstPacketType packet(Index row, Index col) const { + constexpr int DstPacketSize = unpacket_traits::size; + using SizedSrcPacketType = typename find_packet_by_size::type; + constexpr int SrcBytesIncrement = DstPacketSize * sizeof(SrcType); + constexpr int SrcLoadMode = plain_enum_min(SrcBytesIncrement, LoadMode); + return pcast(srcPacket(row, col, 0)); + } + // unpacket_traits::size == 2 * SrcPacketSize + template = true> + EIGEN_STRONG_INLINE DstPacketType packet(Index row, Index col) const { + constexpr int SrcLoadMode = plain_enum_min(SrcPacketBytes, LoadMode); + return pcast(srcPacket(row, col, 0), + srcPacket(row, col, 1)); + } + // unpacket_traits::size == 4 * SrcPacketSize + template = true> + EIGEN_STRONG_INLINE DstPacketType packet(Index row, Index col) const { + constexpr int SrcLoadMode = plain_enum_min(SrcPacketBytes, LoadMode); + return pcast(srcPacket(row, col, 0), srcPacket(row, col, 1), + srcPacket(row, col, 2), + srcPacket(row, col, 3)); + } + // unpacket_traits::size == 8 * SrcPacketSize + template = true> + EIGEN_STRONG_INLINE DstPacketType packet(Index row, Index col) const { + constexpr int SrcLoadMode = plain_enum_min(SrcPacketBytes, LoadMode); + return pcast( + srcPacket(row, col, 0), srcPacket(row, col, 1), srcPacket(row, col, 2), + srcPacket(row, col, 3), srcPacket(row, col, 4), srcPacket(row, col, 5), + srcPacket(row, col, 6), srcPacket(row, col, 7)); + } + + // Analagous routines for linear access. + template = true> + EIGEN_STRONG_INLINE DstPacketType packet(Index index) const { + constexpr int DstPacketSize = unpacket_traits::size; + constexpr int SrcBytesIncrement = DstPacketSize * sizeof(SrcType); + constexpr int SrcLoadMode = plain_enum_min(SrcBytesIncrement, LoadMode); + SrcPacketType src; + if (EIGEN_PREDICT_TRUE(check_array_bounds(index, SrcPacketSize))) { + src = srcPacket(index, 0); + } else { + Array srcArray; + for (size_t k = 0; k < DstPacketSize; k++) srcArray[k] = srcCoeff(index, k); + for (size_t k = DstPacketSize; k < SrcPacketSize; k++) srcArray[k] = SrcType(0); + src = pload(srcArray.data()); + } + return pcast(src); + } + template = true> + EIGEN_STRONG_INLINE DstPacketType packet(Index index) const { + constexpr int DstPacketSize = unpacket_traits::size; + using SizedSrcPacketType = typename find_packet_by_size::type; + constexpr int SrcBytesIncrement = DstPacketSize * sizeof(SrcType); + constexpr int SrcLoadMode = plain_enum_min(SrcBytesIncrement, LoadMode); + return pcast(srcPacket(index, 0)); + } + template = true> + EIGEN_STRONG_INLINE DstPacketType packet(Index index) const { + constexpr int SrcLoadMode = plain_enum_min(SrcPacketBytes, LoadMode); + return pcast(srcPacket(index, 0), srcPacket(index, 1)); + } + template = true> + EIGEN_STRONG_INLINE DstPacketType packet(Index index) const { + constexpr int SrcLoadMode = plain_enum_min(SrcPacketBytes, LoadMode); + return pcast(srcPacket(index, 0), srcPacket(index, 1), + srcPacket(index, 2), srcPacket(index, 3)); + } + template = true> + EIGEN_STRONG_INLINE DstPacketType packet(Index index) const { + constexpr int SrcLoadMode = plain_enum_min(SrcPacketBytes, LoadMode); + return pcast(srcPacket(index, 0), srcPacket(index, 1), + srcPacket(index, 2), srcPacket(index, 3), + srcPacket(index, 4), srcPacket(index, 5), + srcPacket(index, 6), srcPacket(index, 7)); + } + + constexpr EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rows() const { return m_rows; } + constexpr EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index cols() const { return m_cols; } + constexpr EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index size() const { return m_rows * m_cols; } + + protected: + const evaluator m_argImpl; + const variable_if_dynamic m_rows; + const variable_if_dynamic m_cols; +}; + // -------------------- CwiseTernaryOp -------------------- // this is a ternary expression -template +template struct evaluator > - : public ternary_evaluator > -{ + : public ternary_evaluator > { typedef CwiseTernaryOp XprType; typedef ternary_evaluator > Base; EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) : Base(xpr) {} }; -template +template struct ternary_evaluator, IndexBased, IndexBased> - : evaluator_base > -{ + : evaluator_base > { typedef CwiseTernaryOp XprType; enum { - CoeffReadCost = int(evaluator::CoeffReadCost) + int(evaluator::CoeffReadCost) + int(evaluator::CoeffReadCost) + int(functor_traits::Cost), + CoeffReadCost = int(evaluator::CoeffReadCost) + int(evaluator::CoeffReadCost) + + int(evaluator::CoeffReadCost) + int(functor_traits::Cost), Arg1Flags = evaluator::Flags, Arg2Flags = evaluator::Flags, Arg3Flags = evaluator::Flags, - SameType = is_same::value && is_same::value, - StorageOrdersAgree = (int(Arg1Flags)&RowMajorBit)==(int(Arg2Flags)&RowMajorBit) && (int(Arg1Flags)&RowMajorBit)==(int(Arg3Flags)&RowMajorBit), - Flags0 = (int(Arg1Flags) | int(Arg2Flags) | int(Arg3Flags)) & ( - HereditaryBits - | (int(Arg1Flags) & int(Arg2Flags) & int(Arg3Flags) & - ( (StorageOrdersAgree ? LinearAccessBit : 0) - | (functor_traits::PacketAccess && StorageOrdersAgree && SameType ? PacketAccessBit : 0) - ) - ) - ), + SameType = is_same::value && + is_same::value, + StorageOrdersAgree = (int(Arg1Flags) & RowMajorBit) == (int(Arg2Flags) & RowMajorBit) && + (int(Arg1Flags) & RowMajorBit) == (int(Arg3Flags) & RowMajorBit), + Flags0 = (int(Arg1Flags) | int(Arg2Flags) | int(Arg3Flags)) & + (HereditaryBits | + (int(Arg1Flags) & int(Arg2Flags) & int(Arg3Flags) & + ((StorageOrdersAgree ? LinearAccessBit : 0) | + (functor_traits::PacketAccess && StorageOrdersAgree && SameType ? PacketAccessBit : 0)))), Flags = (Flags0 & ~RowMajorBit) | (Arg1Flags & RowMajorBit), - Alignment = EIGEN_PLAIN_ENUM_MIN( - EIGEN_PLAIN_ENUM_MIN(evaluator::Alignment, evaluator::Alignment), - evaluator::Alignment) + Alignment = plain_enum_min(plain_enum_min(evaluator::Alignment, evaluator::Alignment), + evaluator::Alignment) }; - EIGEN_DEVICE_FUNC explicit ternary_evaluator(const XprType& xpr) : m_d(xpr) - { + EIGEN_DEVICE_FUNC explicit ternary_evaluator(const XprType& xpr) : m_d(xpr) { EIGEN_INTERNAL_CHECK_COST_VALUE(functor_traits::Cost); EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } typedef typename XprType::CoeffReturnType CoeffReturnType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { return m_d.func()(m_d.arg1Impl.coeff(row, col), m_d.arg2Impl.coeff(row, col), m_d.arg3Impl.coeff(row, col)); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_d.func()(m_d.arg1Impl.coeff(index), m_d.arg2Impl.coeff(index), m_d.arg3Impl.coeff(index)); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index row, Index col) const - { - return m_d.func().packetOp(m_d.arg1Impl.template packet(row, col), - m_d.arg2Impl.template packet(row, col), - m_d.arg3Impl.template packet(row, col)); + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { + return m_d.func().packetOp(m_d.arg1Impl.template packet(row, col), + m_d.arg2Impl.template packet(row, col), + m_d.arg3Impl.template packet(row, col)); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index index) const - { - return m_d.func().packetOp(m_d.arg1Impl.template packet(index), - m_d.arg2Impl.template packet(index), - m_d.arg3Impl.template packet(index)); + template + EIGEN_STRONG_INLINE PacketType packet(Index index) const { + return m_d.func().packetOp(m_d.arg1Impl.template packet(index), + m_d.arg2Impl.template packet(index), + m_d.arg3Impl.template packet(index)); } -protected: + protected: // this helper permits to completely eliminate the functor if it is empty - struct Data - { - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Data(const XprType& xpr) : op(xpr.functor()), arg1Impl(xpr.arg1()), arg2Impl(xpr.arg2()), arg3Impl(xpr.arg3()) {} - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const TernaryOp& func() const { return op; } + struct Data { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Data(const XprType& xpr) + : op(xpr.functor()), arg1Impl(xpr.arg1()), arg2Impl(xpr.arg2()), arg3Impl(xpr.arg3()) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const TernaryOp& func() const { return op; } TernaryOp op; evaluator arg1Impl; evaluator arg2Impl; @@ -715,91 +840,93 @@ struct ternary_evaluator, IndexBased Data m_d; }; +// specialization for expresions like (a < b).select(c, d) to enable full vectorization +template +struct evaluator, Arg1, Arg2, + CwiseBinaryOp, CmpLhsType, CmpRhsType>>> + : public ternary_evaluator< + CwiseTernaryOp, Arg1, Arg2, + CwiseBinaryOp, CmpLhsType, CmpRhsType>>> { + using DummyTernaryOp = scalar_boolean_select_op; + using DummyArg3 = CwiseBinaryOp, CmpLhsType, CmpRhsType>; + using DummyXprType = CwiseTernaryOp; + + using TernaryOp = scalar_boolean_select_op; + using Arg3 = CwiseBinaryOp, CmpLhsType, CmpRhsType>; + using XprType = CwiseTernaryOp; + + using Base = ternary_evaluator; + + EIGEN_DEVICE_FUNC explicit evaluator(const DummyXprType& xpr) + : Base(XprType(xpr.arg1(), xpr.arg2(), Arg3(xpr.arg3().lhs(), xpr.arg3().rhs()))) {} +}; + // -------------------- CwiseBinaryOp -------------------- // this is a binary expression -template -struct evaluator > - : public binary_evaluator > -{ +template +struct evaluator > : public binary_evaluator > { typedef CwiseBinaryOp XprType; typedef binary_evaluator > Base; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit evaluator(const XprType& xpr) : Base(xpr) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const XprType& xpr) : Base(xpr) {} }; -template +template struct binary_evaluator, IndexBased, IndexBased> - : evaluator_base > -{ + : evaluator_base > { typedef CwiseBinaryOp XprType; enum { - CoeffReadCost = int(evaluator::CoeffReadCost) + int(evaluator::CoeffReadCost) + int(functor_traits::Cost), + CoeffReadCost = + int(evaluator::CoeffReadCost) + int(evaluator::CoeffReadCost) + int(functor_traits::Cost), LhsFlags = evaluator::Flags, RhsFlags = evaluator::Flags, - SameType = is_same::value, - StorageOrdersAgree = (int(LhsFlags)&RowMajorBit)==(int(RhsFlags)&RowMajorBit), - Flags0 = (int(LhsFlags) | int(RhsFlags)) & ( - HereditaryBits - | (int(LhsFlags) & int(RhsFlags) & - ( (StorageOrdersAgree ? LinearAccessBit : 0) - | (functor_traits::PacketAccess && StorageOrdersAgree && SameType ? PacketAccessBit : 0) - ) - ) - ), + SameType = is_same::value, + StorageOrdersAgree = (int(LhsFlags) & RowMajorBit) == (int(RhsFlags) & RowMajorBit), + Flags0 = (int(LhsFlags) | int(RhsFlags)) & + (HereditaryBits | + (int(LhsFlags) & int(RhsFlags) & + ((StorageOrdersAgree ? LinearAccessBit : 0) | + (functor_traits::PacketAccess && StorageOrdersAgree && SameType ? PacketAccessBit : 0)))), Flags = (Flags0 & ~RowMajorBit) | (LhsFlags & RowMajorBit), - Alignment = EIGEN_PLAIN_ENUM_MIN(evaluator::Alignment,evaluator::Alignment) + Alignment = plain_enum_min(evaluator::Alignment, evaluator::Alignment) }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit binary_evaluator(const XprType& xpr) : m_d(xpr) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit binary_evaluator(const XprType& xpr) : m_d(xpr) { EIGEN_INTERNAL_CHECK_COST_VALUE(functor_traits::Cost); EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } typedef typename XprType::CoeffReturnType CoeffReturnType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { return m_d.func()(m_d.lhsImpl.coeff(row, col), m_d.rhsImpl.coeff(row, col)); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_d.func()(m_d.lhsImpl.coeff(index), m_d.rhsImpl.coeff(index)); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index row, Index col) const - { - return m_d.func().packetOp(m_d.lhsImpl.template packet(row, col), - m_d.rhsImpl.template packet(row, col)); + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { + return m_d.func().packetOp(m_d.lhsImpl.template packet(row, col), + m_d.rhsImpl.template packet(row, col)); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index index) const - { - return m_d.func().packetOp(m_d.lhsImpl.template packet(index), - m_d.rhsImpl.template packet(index)); + template + EIGEN_STRONG_INLINE PacketType packet(Index index) const { + return m_d.func().packetOp(m_d.lhsImpl.template packet(index), + m_d.rhsImpl.template packet(index)); } -protected: - + protected: // this helper permits to completely eliminate the functor if it is empty - struct Data - { - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Data(const XprType& xpr) : op(xpr.functor()), lhsImpl(xpr.lhs()), rhsImpl(xpr.rhs()) {} - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const BinaryOp& func() const { return op; } + struct Data { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Data(const XprType& xpr) + : op(xpr.functor()), lhsImpl(xpr.lhs()), rhsImpl(xpr.rhs()) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const BinaryOp& func() const { return op; } BinaryOp op; evaluator lhsImpl; evaluator rhsImpl; @@ -810,22 +937,20 @@ struct binary_evaluator, IndexBased, IndexBase // -------------------- CwiseUnaryView -------------------- -template -struct unary_evaluator, IndexBased> - : evaluator_base > -{ - typedef CwiseUnaryView XprType; +template +struct unary_evaluator, IndexBased> + : evaluator_base > { + typedef CwiseUnaryView XprType; enum { CoeffReadCost = int(evaluator::CoeffReadCost) + int(functor_traits::Cost), Flags = (evaluator::Flags & (HereditaryBits | LinearAccessBit | DirectAccessBit)), - Alignment = 0 // FIXME it is not very clear why alignment is necessarily lost... + Alignment = 0 // FIXME it is not very clear why alignment is necessarily lost... }; - EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& op) : m_d(op) - { + EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& op) : m_d(op) { EIGEN_INTERNAL_CHECK_COST_VALUE(functor_traits::Cost); EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } @@ -833,39 +958,28 @@ struct unary_evaluator, IndexBased> typedef typename XprType::Scalar Scalar; typedef typename XprType::CoeffReturnType CoeffReturnType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { return m_d.func()(m_d.argImpl.coeff(row, col)); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_d.func()(m_d.argImpl.coeff(index)); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index row, Index col) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col) { return m_d.func()(m_d.argImpl.coeffRef(row, col)); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index index) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { return m_d.func()(m_d.argImpl.coeffRef(index)); } -protected: - + protected: // this helper permits to completely eliminate the functor if it is empty - struct Data - { - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Data(const XprType& xpr) : op(xpr.functor()), argImpl(xpr.nestedExpression()) {} - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const UnaryOp& func() const { return op; } + struct Data { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Data(const XprType& xpr) + : op(xpr.functor()), argImpl(xpr.nestedExpression()) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const UnaryOp& func() const { return op; } UnaryOp op; evaluator argImpl; }; @@ -877,13 +991,12 @@ struct unary_evaluator, IndexBased> // FIXME perhaps the PlainObjectType could be provided by Derived::PlainObject ? // but that might complicate template specialization -template +template struct mapbase_evaluator; -template -struct mapbase_evaluator : evaluator_base -{ - typedef Derived XprType; +template +struct mapbase_evaluator : evaluator_base { + typedef Derived XprType; typedef typename XprType::PointerType PointerType; typedef typename XprType::Scalar Scalar; typedef typename XprType::CoeffReturnType CoeffReturnType; @@ -894,78 +1007,58 @@ struct mapbase_evaluator : evaluator_base CoeffReadCost = NumTraits::ReadCost }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit mapbase_evaluator(const XprType& map) - : m_data(const_cast(map.data())), - m_innerStride(map.innerStride()), - m_outerStride(map.outerStride()) - { - EIGEN_STATIC_ASSERT(EIGEN_IMPLIES(evaluator::Flags&PacketAccessBit, internal::inner_stride_at_compile_time::ret==1), + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit mapbase_evaluator(const XprType& map) + : m_data(const_cast(map.data())), + m_innerStride(map.innerStride()), + m_outerStride(map.outerStride()) { + EIGEN_STATIC_ASSERT(check_implication((evaluator::Flags & PacketAccessBit) != 0, + internal::inner_stride_at_compile_time::ret == 1), PACKET_ACCESS_REQUIRES_TO_HAVE_INNER_STRIDE_FIXED_TO_1); EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { return m_data[col * colStride() + row * rowStride()]; } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_data[index * m_innerStride.value()]; } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index row, Index col) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col) { return m_data[col * colStride() + row * rowStride()]; } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index index) - { - return m_data[index * m_innerStride.value()]; - } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { return m_data[index * m_innerStride.value()]; } - template - EIGEN_STRONG_INLINE - PacketType packet(Index row, Index col) const - { + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { PointerType ptr = m_data + row * rowStride() + col * colStride(); return internal::ploadt(ptr); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index index) const - { + template + EIGEN_STRONG_INLINE PacketType packet(Index index) const { return internal::ploadt(m_data + index * m_innerStride.value()); } - template - EIGEN_STRONG_INLINE - void writePacket(Index row, Index col, const PacketType& x) - { + template + EIGEN_STRONG_INLINE void writePacket(Index row, Index col, const PacketType& x) { PointerType ptr = m_data + row * rowStride() + col * colStride(); return internal::pstoret(ptr, x); } - template - EIGEN_STRONG_INLINE - void writePacket(Index index, const PacketType& x) - { + template + EIGEN_STRONG_INLINE void writePacket(Index index, const PacketType& x) { internal::pstoret(m_data + index * m_innerStride.value(), x); } -protected: - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index rowStride() const EIGEN_NOEXCEPT { + + protected: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index rowStride() const EIGEN_NOEXCEPT { return XprType::IsRowMajor ? m_outerStride.value() : m_innerStride.value(); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index colStride() const EIGEN_NOEXCEPT { - return XprType::IsRowMajor ? m_innerStride.value() : m_outerStride.value(); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index colStride() const EIGEN_NOEXCEPT { + return XprType::IsRowMajor ? m_innerStride.value() : m_outerStride.value(); } PointerType m_data; @@ -973,10 +1066,9 @@ struct mapbase_evaluator : evaluator_base const internal::variable_if_dynamic m_outerStride; }; -template +template struct evaluator > - : public mapbase_evaluator, PlainObjectType> -{ + : public mapbase_evaluator, PlainObjectType> { typedef Map XprType; typedef typename XprType::Scalar Scalar; // TODO: should check for smaller packet types once we can handle multi-sized packet types @@ -984,34 +1076,32 @@ struct evaluator > enum { InnerStrideAtCompileTime = StrideType::InnerStrideAtCompileTime == 0 - ? int(PlainObjectType::InnerStrideAtCompileTime) - : int(StrideType::InnerStrideAtCompileTime), + ? int(PlainObjectType::InnerStrideAtCompileTime) + : int(StrideType::InnerStrideAtCompileTime), OuterStrideAtCompileTime = StrideType::OuterStrideAtCompileTime == 0 - ? int(PlainObjectType::OuterStrideAtCompileTime) - : int(StrideType::OuterStrideAtCompileTime), + ? int(PlainObjectType::OuterStrideAtCompileTime) + : int(StrideType::OuterStrideAtCompileTime), HasNoInnerStride = InnerStrideAtCompileTime == 1, HasNoOuterStride = StrideType::OuterStrideAtCompileTime == 0, HasNoStride = HasNoInnerStride && HasNoOuterStride, - IsDynamicSize = PlainObjectType::SizeAtCompileTime==Dynamic, + IsDynamicSize = PlainObjectType::SizeAtCompileTime == Dynamic, PacketAccessMask = bool(HasNoInnerStride) ? ~int(0) : ~int(PacketAccessBit), - LinearAccessMask = bool(HasNoStride) || bool(PlainObjectType::IsVectorAtCompileTime) ? ~int(0) : ~int(LinearAccessBit), - Flags = int( evaluator::Flags) & (LinearAccessMask&PacketAccessMask), + LinearAccessMask = + bool(HasNoStride) || bool(PlainObjectType::IsVectorAtCompileTime) ? ~int(0) : ~int(LinearAccessBit), + Flags = int(evaluator::Flags) & (LinearAccessMask & PacketAccessMask), - Alignment = int(MapOptions)&int(AlignedMask) + Alignment = int(MapOptions) & int(AlignedMask) }; - EIGEN_DEVICE_FUNC explicit evaluator(const XprType& map) - : mapbase_evaluator(map) - { } + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& map) : mapbase_evaluator(map) {} }; // -------------------- Ref -------------------- -template +template struct evaluator > - : public mapbase_evaluator, PlainObjectType> -{ + : public mapbase_evaluator, PlainObjectType> { typedef Ref XprType; enum { @@ -1019,21 +1109,19 @@ struct evaluator > Alignment = evaluator >::Alignment }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit evaluator(const XprType& ref) - : mapbase_evaluator(ref) - { } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const XprType& ref) + : mapbase_evaluator(ref) {} }; // -------------------- Block -------------------- -template::ret> struct block_evaluator; +template ::ret> +struct block_evaluator; -template +template struct evaluator > - : block_evaluator -{ + : block_evaluator { typedef Block XprType; typedef typename XprType::Scalar Scalar; // TODO: should check for smaller packet types once we can handle multi-sized packet types @@ -1047,323 +1135,272 @@ struct evaluator > MaxRowsAtCompileTime = traits::MaxRowsAtCompileTime, MaxColsAtCompileTime = traits::MaxColsAtCompileTime, - ArgTypeIsRowMajor = (int(evaluator::Flags)&RowMajorBit) != 0, - IsRowMajor = (MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1) ? 1 - : (MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1) ? 0 - : ArgTypeIsRowMajor, + ArgTypeIsRowMajor = (int(evaluator::Flags) & RowMajorBit) != 0, + IsRowMajor = (MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1) ? 1 + : (MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1) ? 0 + : ArgTypeIsRowMajor, HasSameStorageOrderAsArgType = (IsRowMajor == ArgTypeIsRowMajor), InnerSize = IsRowMajor ? int(ColsAtCompileTime) : int(RowsAtCompileTime), - InnerStrideAtCompileTime = HasSameStorageOrderAsArgType - ? int(inner_stride_at_compile_time::ret) - : int(outer_stride_at_compile_time::ret), - OuterStrideAtCompileTime = HasSameStorageOrderAsArgType - ? int(outer_stride_at_compile_time::ret) - : int(inner_stride_at_compile_time::ret), + InnerStrideAtCompileTime = HasSameStorageOrderAsArgType ? int(inner_stride_at_compile_time::ret) + : int(outer_stride_at_compile_time::ret), + OuterStrideAtCompileTime = HasSameStorageOrderAsArgType ? int(outer_stride_at_compile_time::ret) + : int(inner_stride_at_compile_time::ret), MaskPacketAccessBit = (InnerStrideAtCompileTime == 1 || HasSameStorageOrderAsArgType) ? PacketAccessBit : 0, - FlagsLinearAccessBit = (RowsAtCompileTime == 1 || ColsAtCompileTime == 1 || (InnerPanel && (evaluator::Flags&LinearAccessBit))) ? LinearAccessBit : 0, - FlagsRowMajorBit = XprType::Flags&RowMajorBit, - Flags0 = evaluator::Flags & ( (HereditaryBits & ~RowMajorBit) | - DirectAccessBit | - MaskPacketAccessBit), + FlagsLinearAccessBit = (RowsAtCompileTime == 1 || ColsAtCompileTime == 1 || + (InnerPanel && (evaluator::Flags & LinearAccessBit))) + ? LinearAccessBit + : 0, + FlagsRowMajorBit = XprType::Flags & RowMajorBit, + Flags0 = evaluator::Flags & ((HereditaryBits & ~RowMajorBit) | DirectAccessBit | MaskPacketAccessBit), Flags = Flags0 | FlagsLinearAccessBit | FlagsRowMajorBit, PacketAlignment = unpacket_traits::alignment, - Alignment0 = (InnerPanel && (OuterStrideAtCompileTime!=Dynamic) - && (OuterStrideAtCompileTime!=0) - && (((OuterStrideAtCompileTime * int(sizeof(Scalar))) % int(PacketAlignment)) == 0)) ? int(PacketAlignment) : 0, - Alignment = EIGEN_PLAIN_ENUM_MIN(evaluator::Alignment, Alignment0) + Alignment0 = (InnerPanel && (OuterStrideAtCompileTime != Dynamic) && (OuterStrideAtCompileTime != 0) && + (((OuterStrideAtCompileTime * int(sizeof(Scalar))) % int(PacketAlignment)) == 0)) + ? int(PacketAlignment) + : 0, + Alignment = plain_enum_min(evaluator::Alignment, Alignment0) }; typedef block_evaluator block_evaluator_type; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit evaluator(const XprType& block) : block_evaluator_type(block) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const XprType& block) : block_evaluator_type(block) { EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } }; // no direct-access => dispatch to a unary evaluator -template +template struct block_evaluator - : unary_evaluator > -{ + : unary_evaluator > { typedef Block XprType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit block_evaluator(const XprType& block) - : unary_evaluator(block) - {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit block_evaluator(const XprType& block) + : unary_evaluator(block) {} }; -template +template struct unary_evaluator, IndexBased> - : evaluator_base > -{ + : evaluator_base > { typedef Block XprType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit unary_evaluator(const XprType& block) - : m_argImpl(block.nestedExpression()), - m_startRow(block.startRow()), - m_startCol(block.startCol()), - m_linear_offset(ForwardLinearAccess?(ArgType::IsRowMajor ? block.startRow()*block.nestedExpression().cols() + block.startCol() : block.startCol()*block.nestedExpression().rows() + block.startRow()):0) - { } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit unary_evaluator(const XprType& block) + : m_argImpl(block.nestedExpression()), + m_startRow(block.startRow()), + m_startCol(block.startCol()), + m_linear_offset(ForwardLinearAccess + ? (ArgType::IsRowMajor + ? block.startRow() * block.nestedExpression().cols() + block.startCol() + : block.startCol() * block.nestedExpression().rows() + block.startRow()) + : 0) {} typedef typename XprType::Scalar Scalar; typedef typename XprType::CoeffReturnType CoeffReturnType; enum { RowsAtCompileTime = XprType::RowsAtCompileTime, - ForwardLinearAccess = (InnerPanel || int(XprType::IsRowMajor)==int(ArgType::IsRowMajor)) && bool(evaluator::Flags&LinearAccessBit) + ForwardLinearAccess = (InnerPanel || int(XprType::IsRowMajor) == int(ArgType::IsRowMajor)) && + bool(evaluator::Flags & LinearAccessBit) }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { return m_argImpl.coeff(m_startRow.value() + row, m_startCol.value() + col); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return linear_coeff_impl(index, bool_constant()); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index row, Index col) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col) { return m_argImpl.coeffRef(m_startRow.value() + row, m_startCol.value() + col); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index index) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { return linear_coeffRef_impl(index, bool_constant()); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index row, Index col) const - { - return m_argImpl.template packet(m_startRow.value() + row, m_startCol.value() + col); + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { + return m_argImpl.template packet(m_startRow.value() + row, m_startCol.value() + col); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index index) const - { + template + EIGEN_STRONG_INLINE PacketType packet(Index index) const { if (ForwardLinearAccess) - return m_argImpl.template packet(m_linear_offset.value() + index); + return m_argImpl.template packet(m_linear_offset.value() + index); else - return packet(RowsAtCompileTime == 1 ? 0 : index, - RowsAtCompileTime == 1 ? index : 0); + return packet(RowsAtCompileTime == 1 ? 0 : index, RowsAtCompileTime == 1 ? index : 0); } - template - EIGEN_STRONG_INLINE - void writePacket(Index row, Index col, const PacketType& x) - { - return m_argImpl.template writePacket(m_startRow.value() + row, m_startCol.value() + col, x); + template + EIGEN_STRONG_INLINE void writePacket(Index row, Index col, const PacketType& x) { + return m_argImpl.template writePacket(m_startRow.value() + row, m_startCol.value() + col, x); } - template - EIGEN_STRONG_INLINE - void writePacket(Index index, const PacketType& x) - { + template + EIGEN_STRONG_INLINE void writePacket(Index index, const PacketType& x) { if (ForwardLinearAccess) - return m_argImpl.template writePacket(m_linear_offset.value() + index, x); + return m_argImpl.template writePacket(m_linear_offset.value() + index, x); else - return writePacket(RowsAtCompileTime == 1 ? 0 : index, - RowsAtCompileTime == 1 ? index : 0, - x); + return writePacket(RowsAtCompileTime == 1 ? 0 : index, RowsAtCompileTime == 1 ? index : 0, + x); } -protected: - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType linear_coeff_impl(Index index, internal::true_type /* ForwardLinearAccess */) const - { + protected: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType + linear_coeff_impl(Index index, internal::true_type /* ForwardLinearAccess */) const { return m_argImpl.coeff(m_linear_offset.value() + index); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType linear_coeff_impl(Index index, internal::false_type /* not ForwardLinearAccess */) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType + linear_coeff_impl(Index index, internal::false_type /* not ForwardLinearAccess */) const { return coeff(RowsAtCompileTime == 1 ? 0 : index, RowsAtCompileTime == 1 ? index : 0); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& linear_coeffRef_impl(Index index, internal::true_type /* ForwardLinearAccess */) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& linear_coeffRef_impl(Index index, + internal::true_type /* ForwardLinearAccess */) { return m_argImpl.coeffRef(m_linear_offset.value() + index); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& linear_coeffRef_impl(Index index, internal::false_type /* not ForwardLinearAccess */) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& linear_coeffRef_impl( + Index index, internal::false_type /* not ForwardLinearAccess */) { return coeffRef(RowsAtCompileTime == 1 ? 0 : index, RowsAtCompileTime == 1 ? index : 0); } evaluator m_argImpl; - const variable_if_dynamic m_startRow; - const variable_if_dynamic m_startCol; + const variable_if_dynamic m_startRow; + const variable_if_dynamic m_startCol; const variable_if_dynamic m_linear_offset; }; // TODO: This evaluator does not actually use the child evaluator; // all action is via the data() as returned by the Block expression. -template +template struct block_evaluator - : mapbase_evaluator, - typename Block::PlainObject> -{ + : mapbase_evaluator, + typename Block::PlainObject> { typedef Block XprType; typedef typename XprType::Scalar Scalar; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit block_evaluator(const XprType& block) - : mapbase_evaluator(block) - { - // TODO: for the 3.3 release, this should be turned to an internal assertion, but let's keep it as is for the beta lifetime - eigen_assert(((internal::UIntPtr(block.data()) % EIGEN_PLAIN_ENUM_MAX(1,evaluator::Alignment)) == 0) && "data is not aligned"); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit block_evaluator(const XprType& block) + : mapbase_evaluator(block) { + eigen_internal_assert((internal::is_constant_evaluated() || + (std::uintptr_t(block.data()) % plain_enum_max(1, evaluator::Alignment)) == 0) && + "data is not aligned"); } }; - // -------------------- Select -------------------- // NOTE shall we introduce a ternary_evaluator? // TODO enable vectorization for Select -template +template struct evaluator > - : evaluator_base > -{ + : evaluator_base > { typedef Select XprType; enum { - CoeffReadCost = evaluator::CoeffReadCost - + EIGEN_PLAIN_ENUM_MAX(evaluator::CoeffReadCost, - evaluator::CoeffReadCost), + CoeffReadCost = evaluator::CoeffReadCost + + plain_enum_max(evaluator::CoeffReadCost, evaluator::CoeffReadCost), Flags = (unsigned int)evaluator::Flags & evaluator::Flags & HereditaryBits, - Alignment = EIGEN_PLAIN_ENUM_MIN(evaluator::Alignment, evaluator::Alignment) + Alignment = plain_enum_min(evaluator::Alignment, evaluator::Alignment) }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit evaluator(const XprType& select) - : m_conditionImpl(select.conditionMatrix()), - m_thenImpl(select.thenMatrix()), - m_elseImpl(select.elseMatrix()) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const XprType& select) + : m_conditionImpl(select.conditionMatrix()), m_thenImpl(select.thenMatrix()), m_elseImpl(select.elseMatrix()) { EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } typedef typename XprType::CoeffReturnType CoeffReturnType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { if (m_conditionImpl.coeff(row, col)) return m_thenImpl.coeff(row, col); else return m_elseImpl.coeff(row, col); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { if (m_conditionImpl.coeff(index)) return m_thenImpl.coeff(index); else return m_elseImpl.coeff(index); } -protected: + protected: evaluator m_conditionImpl; evaluator m_thenImpl; evaluator m_elseImpl; }; - // -------------------- Replicate -------------------- -template +template struct unary_evaluator > - : evaluator_base > -{ + : evaluator_base > { typedef Replicate XprType; typedef typename XprType::CoeffReturnType CoeffReturnType; - enum { - Factor = (RowFactor==Dynamic || ColFactor==Dynamic) ? Dynamic : RowFactor*ColFactor - }; - typedef typename internal::nested_eval::type ArgTypeNested; - typedef typename internal::remove_all::type ArgTypeNestedCleaned; + enum { Factor = (RowFactor == Dynamic || ColFactor == Dynamic) ? Dynamic : RowFactor * ColFactor }; + typedef typename internal::nested_eval::type ArgTypeNested; + typedef internal::remove_all_t ArgTypeNestedCleaned; enum { CoeffReadCost = evaluator::CoeffReadCost, LinearAccessMask = XprType::IsVectorAtCompileTime ? LinearAccessBit : 0, - Flags = (evaluator::Flags & (HereditaryBits|LinearAccessMask) & ~RowMajorBit) | (traits::Flags & RowMajorBit), + Flags = (evaluator::Flags & (HereditaryBits | LinearAccessMask) & ~RowMajorBit) | + (traits::Flags & RowMajorBit), Alignment = evaluator::Alignment }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit unary_evaluator(const XprType& replicate) - : m_arg(replicate.nestedExpression()), - m_argImpl(m_arg), - m_rows(replicate.nestedExpression().rows()), - m_cols(replicate.nestedExpression().cols()) - {} - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit unary_evaluator(const XprType& replicate) + : m_arg(replicate.nestedExpression()), + m_argImpl(m_arg), + m_rows(replicate.nestedExpression().rows()), + m_cols(replicate.nestedExpression().cols()) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { // try to avoid using modulo; this is a pure optimization strategy - const Index actual_row = internal::traits::RowsAtCompileTime==1 ? 0 - : RowFactor==1 ? row - : row % m_rows.value(); - const Index actual_col = internal::traits::ColsAtCompileTime==1 ? 0 - : ColFactor==1 ? col - : col % m_cols.value(); + const Index actual_row = internal::traits::RowsAtCompileTime == 1 ? 0 + : RowFactor == 1 ? row + : row % m_rows.value(); + const Index actual_col = internal::traits::ColsAtCompileTime == 1 ? 0 + : ColFactor == 1 ? col + : col % m_cols.value(); return m_argImpl.coeff(actual_row, actual_col); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { // try to avoid using modulo; this is a pure optimization strategy - const Index actual_index = internal::traits::RowsAtCompileTime==1 - ? (ColFactor==1 ? index : index%m_cols.value()) - : (RowFactor==1 ? index : index%m_rows.value()); + const Index actual_index = internal::traits::RowsAtCompileTime == 1 + ? (ColFactor == 1 ? index : index % m_cols.value()) + : (RowFactor == 1 ? index : index % m_rows.value()); return m_argImpl.coeff(actual_index); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index row, Index col) const - { - const Index actual_row = internal::traits::RowsAtCompileTime==1 ? 0 - : RowFactor==1 ? row - : row % m_rows.value(); - const Index actual_col = internal::traits::ColsAtCompileTime==1 ? 0 - : ColFactor==1 ? col - : col % m_cols.value(); + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { + const Index actual_row = internal::traits::RowsAtCompileTime == 1 ? 0 + : RowFactor == 1 ? row + : row % m_rows.value(); + const Index actual_col = internal::traits::ColsAtCompileTime == 1 ? 0 + : ColFactor == 1 ? col + : col % m_cols.value(); - return m_argImpl.template packet(actual_row, actual_col); + return m_argImpl.template packet(actual_row, actual_col); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index index) const - { - const Index actual_index = internal::traits::RowsAtCompileTime==1 - ? (ColFactor==1 ? index : index%m_cols.value()) - : (RowFactor==1 ? index : index%m_rows.value()); + template + EIGEN_STRONG_INLINE PacketType packet(Index index) const { + const Index actual_index = internal::traits::RowsAtCompileTime == 1 + ? (ColFactor == 1 ? index : index % m_cols.value()) + : (RowFactor == 1 ? index : index % m_rows.value()); - return m_argImpl.template packet(actual_index); + return m_argImpl.template packet(actual_index); } -protected: + protected: const ArgTypeNested m_arg; evaluator m_argImpl; const variable_if_dynamic m_rows; @@ -1375,113 +1412,78 @@ struct unary_evaluator > // evaluator_wrapper_base is a common base class for the // MatrixWrapper and ArrayWrapper evaluators. -template -struct evaluator_wrapper_base - : evaluator_base -{ - typedef typename remove_all::type ArgType; +template +struct evaluator_wrapper_base : evaluator_base { + typedef remove_all_t ArgType; enum { CoeffReadCost = evaluator::CoeffReadCost, Flags = evaluator::Flags, Alignment = evaluator::Alignment }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit evaluator_wrapper_base(const ArgType& arg) : m_argImpl(arg) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator_wrapper_base(const ArgType& arg) : m_argImpl(arg) {} typedef typename ArgType::Scalar Scalar; typedef typename ArgType::CoeffReturnType CoeffReturnType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { return m_argImpl.coeff(row, col); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { - return m_argImpl.coeff(index); - } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_argImpl.coeff(index); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index row, Index col) - { - return m_argImpl.coeffRef(row, col); - } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col) { return m_argImpl.coeffRef(row, col); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index index) - { - return m_argImpl.coeffRef(index); - } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { return m_argImpl.coeffRef(index); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index row, Index col) const - { - return m_argImpl.template packet(row, col); + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { + return m_argImpl.template packet(row, col); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index index) const - { - return m_argImpl.template packet(index); + template + EIGEN_STRONG_INLINE PacketType packet(Index index) const { + return m_argImpl.template packet(index); } - template - EIGEN_STRONG_INLINE - void writePacket(Index row, Index col, const PacketType& x) - { + template + EIGEN_STRONG_INLINE void writePacket(Index row, Index col, const PacketType& x) { m_argImpl.template writePacket(row, col, x); } - template - EIGEN_STRONG_INLINE - void writePacket(Index index, const PacketType& x) - { + template + EIGEN_STRONG_INLINE void writePacket(Index index, const PacketType& x) { m_argImpl.template writePacket(index, x); } -protected: + protected: evaluator m_argImpl; }; -template -struct unary_evaluator > - : evaluator_wrapper_base > -{ +template +struct unary_evaluator > : evaluator_wrapper_base > { typedef MatrixWrapper XprType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit unary_evaluator(const XprType& wrapper) - : evaluator_wrapper_base >(wrapper.nestedExpression()) - { } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit unary_evaluator(const XprType& wrapper) + : evaluator_wrapper_base >(wrapper.nestedExpression()) {} }; -template -struct unary_evaluator > - : evaluator_wrapper_base > -{ +template +struct unary_evaluator > : evaluator_wrapper_base > { typedef ArrayWrapper XprType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit unary_evaluator(const XprType& wrapper) - : evaluator_wrapper_base >(wrapper.nestedExpression()) - { } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit unary_evaluator(const XprType& wrapper) + : evaluator_wrapper_base >(wrapper.nestedExpression()) {} }; - // -------------------- Reverse -------------------- // defined in Reverse.h: -template struct reverse_packet_cond; +template +struct reverse_packet_cond; -template -struct unary_evaluator > - : evaluator_base > -{ +template +struct unary_evaluator > : evaluator_base > { typedef Reverse XprType; typedef typename XprType::Scalar Scalar; typedef typename XprType::CoeffReturnType CoeffReturnType; @@ -1489,109 +1491,88 @@ struct unary_evaluator > enum { IsRowMajor = XprType::IsRowMajor, IsColMajor = !IsRowMajor, - ReverseRow = (Direction == Vertical) || (Direction == BothDirections), + ReverseRow = (Direction == Vertical) || (Direction == BothDirections), ReverseCol = (Direction == Horizontal) || (Direction == BothDirections), - ReversePacket = (Direction == BothDirections) - || ((Direction == Vertical) && IsColMajor) - || ((Direction == Horizontal) && IsRowMajor), + ReversePacket = (Direction == BothDirections) || ((Direction == Vertical) && IsColMajor) || + ((Direction == Horizontal) && IsRowMajor), CoeffReadCost = evaluator::CoeffReadCost, // let's enable LinearAccess only with vectorization because of the product overhead // FIXME enable DirectAccess with negative strides? Flags0 = evaluator::Flags, - LinearAccess = ( (Direction==BothDirections) && (int(Flags0)&PacketAccessBit) ) - || ((ReverseRow && XprType::ColsAtCompileTime==1) || (ReverseCol && XprType::RowsAtCompileTime==1)) - ? LinearAccessBit : 0, + LinearAccess = + ((Direction == BothDirections) && (int(Flags0) & PacketAccessBit)) || + ((ReverseRow && XprType::ColsAtCompileTime == 1) || (ReverseCol && XprType::RowsAtCompileTime == 1)) + ? LinearAccessBit + : 0, Flags = int(Flags0) & (HereditaryBits | PacketAccessBit | LinearAccess), - Alignment = 0 // FIXME in some rare cases, Alignment could be preserved, like a Vector4f. + Alignment = 0 // FIXME in some rare cases, Alignment could be preserved, like a Vector4f. }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit unary_evaluator(const XprType& reverse) - : m_argImpl(reverse.nestedExpression()), - m_rows(ReverseRow ? reverse.nestedExpression().rows() : 1), - m_cols(ReverseCol ? reverse.nestedExpression().cols() : 1) - { } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit unary_evaluator(const XprType& reverse) + : m_argImpl(reverse.nestedExpression()), + m_rows(ReverseRow ? reverse.nestedExpression().rows() : 1), + m_cols(ReverseCol ? reverse.nestedExpression().cols() : 1) {} - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { - return m_argImpl.coeff(ReverseRow ? m_rows.value() - row - 1 : row, - ReverseCol ? m_cols.value() - col - 1 : col); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { + return m_argImpl.coeff(ReverseRow ? m_rows.value() - row - 1 : row, ReverseCol ? m_cols.value() - col - 1 : col); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_argImpl.coeff(m_rows.value() * m_cols.value() - index - 1); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index row, Index col) - { - return m_argImpl.coeffRef(ReverseRow ? m_rows.value() - row - 1 : row, - ReverseCol ? m_cols.value() - col - 1 : col); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col) { + return m_argImpl.coeffRef(ReverseRow ? m_rows.value() - row - 1 : row, ReverseCol ? m_cols.value() - col - 1 : col); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index index) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { return m_argImpl.coeffRef(m_rows.value() * m_cols.value() - index - 1); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index row, Index col) const - { + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { enum { PacketSize = unpacket_traits::size, - OffsetRow = ReverseRow && IsColMajor ? PacketSize : 1, - OffsetCol = ReverseCol && IsRowMajor ? PacketSize : 1 + OffsetRow = ReverseRow && IsColMajor ? PacketSize : 1, + OffsetCol = ReverseCol && IsRowMajor ? PacketSize : 1 }; - typedef internal::reverse_packet_cond reverse_packet; - return reverse_packet::run(m_argImpl.template packet( - ReverseRow ? m_rows.value() - row - OffsetRow : row, - ReverseCol ? m_cols.value() - col - OffsetCol : col)); + typedef internal::reverse_packet_cond reverse_packet; + return reverse_packet::run(m_argImpl.template packet( + ReverseRow ? m_rows.value() - row - OffsetRow : row, ReverseCol ? m_cols.value() - col - OffsetCol : col)); } - template - EIGEN_STRONG_INLINE - PacketType packet(Index index) const - { + template + EIGEN_STRONG_INLINE PacketType packet(Index index) const { enum { PacketSize = unpacket_traits::size }; - return preverse(m_argImpl.template packet(m_rows.value() * m_cols.value() - index - PacketSize)); + return preverse( + m_argImpl.template packet(m_rows.value() * m_cols.value() - index - PacketSize)); } - template - EIGEN_STRONG_INLINE - void writePacket(Index row, Index col, const PacketType& x) - { + template + EIGEN_STRONG_INLINE void writePacket(Index row, Index col, const PacketType& x) { // FIXME we could factorize some code with packet(i,j) enum { PacketSize = unpacket_traits::size, - OffsetRow = ReverseRow && IsColMajor ? PacketSize : 1, - OffsetCol = ReverseCol && IsRowMajor ? PacketSize : 1 + OffsetRow = ReverseRow && IsColMajor ? PacketSize : 1, + OffsetCol = ReverseCol && IsRowMajor ? PacketSize : 1 }; - typedef internal::reverse_packet_cond reverse_packet; - m_argImpl.template writePacket( - ReverseRow ? m_rows.value() - row - OffsetRow : row, - ReverseCol ? m_cols.value() - col - OffsetCol : col, - reverse_packet::run(x)); + typedef internal::reverse_packet_cond reverse_packet; + m_argImpl.template writePacket(ReverseRow ? m_rows.value() - row - OffsetRow : row, + ReverseCol ? m_cols.value() - col - OffsetCol : col, + reverse_packet::run(x)); } - template - EIGEN_STRONG_INLINE - void writePacket(Index index, const PacketType& x) - { + template + EIGEN_STRONG_INLINE void writePacket(Index index, const PacketType& x) { enum { PacketSize = unpacket_traits::size }; - m_argImpl.template writePacket - (m_rows.value() * m_cols.value() - index - PacketSize, preverse(x)); + m_argImpl.template writePacket(m_rows.value() * m_cols.value() - index - PacketSize, preverse(x)); } -protected: + protected: evaluator m_argImpl; // If we do not reverse rows, then we do not need to know the number of rows; same for columns @@ -1600,68 +1581,56 @@ struct unary_evaluator > const variable_if_dynamic m_cols; }; - // -------------------- Diagonal -------------------- -template -struct evaluator > - : evaluator_base > -{ +template +struct evaluator > : evaluator_base > { typedef Diagonal XprType; enum { CoeffReadCost = evaluator::CoeffReadCost, - Flags = (unsigned int)(evaluator::Flags & (HereditaryBits | DirectAccessBit) & ~RowMajorBit) | LinearAccessBit, + Flags = + (unsigned int)(evaluator::Flags & (HereditaryBits | DirectAccessBit) & ~RowMajorBit) | LinearAccessBit, Alignment = 0 }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit evaluator(const XprType& diagonal) - : m_argImpl(diagonal.nestedExpression()), - m_index(diagonal.index()) - { } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const XprType& diagonal) + : m_argImpl(diagonal.nestedExpression()), m_index(diagonal.index()) {} typedef typename XprType::Scalar Scalar; typedef typename XprType::CoeffReturnType CoeffReturnType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index) const { return m_argImpl.coeff(row + rowOffset(), row + colOffset()); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_argImpl.coeff(index + rowOffset(), index + colOffset()); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index row, Index) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index) { return m_argImpl.coeffRef(row + rowOffset(), row + colOffset()); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index index) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { return m_argImpl.coeffRef(index + rowOffset(), index + colOffset()); } -protected: + protected: evaluator m_argImpl; const internal::variable_if_dynamicindex m_index; -private: - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index rowOffset() const { return m_index.value() > 0 ? 0 : -m_index.value(); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index colOffset() const { return m_index.value() > 0 ? m_index.value() : 0; } + private: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index rowOffset() const { + return m_index.value() > 0 ? 0 : -m_index.value(); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index colOffset() const { + return m_index.value() > 0 ? m_index.value() : 0; + } }; - //---------------------------------------------------------------------- // deprecated code //---------------------------------------------------------------------- @@ -1670,72 +1639,49 @@ struct evaluator > // expression class for evaluating nested expression to a temporary -template class EvalToTemp; +template +class EvalToTemp; -template -struct traits > - : public traits -{ }; +template +struct traits > : public traits {}; -template -class EvalToTemp - : public dense_xpr_base >::type -{ +template +class EvalToTemp : public dense_xpr_base >::type { public: - typedef typename dense_xpr_base::type Base; EIGEN_GENERIC_PUBLIC_INTERFACE(EvalToTemp) - explicit EvalToTemp(const ArgType& arg) - : m_arg(arg) - { } + explicit EvalToTemp(const ArgType& arg) : m_arg(arg) {} - const ArgType& arg() const - { - return m_arg; - } + const ArgType& arg() const { return m_arg; } - EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT - { - return m_arg.rows(); - } + EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_arg.rows(); } - EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT - { - return m_arg.cols(); - } + EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_arg.cols(); } private: const ArgType& m_arg; }; -template -struct evaluator > - : public evaluator -{ - typedef EvalToTemp XprType; - typedef typename ArgType::PlainObject PlainObject; +template +struct evaluator > : public evaluator { + typedef EvalToTemp XprType; + typedef typename ArgType::PlainObject PlainObject; typedef evaluator Base; - EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) - : m_result(xpr.arg()) - { - ::new (static_cast(this)) Base(m_result); + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) : m_result(xpr.arg()) { + internal::construct_at(this, m_result); } // This constructor is used when nesting an EvalTo evaluator in another evaluator - EIGEN_DEVICE_FUNC evaluator(const ArgType& arg) - : m_result(arg) - { - ::new (static_cast(this)) Base(m_result); - } + EIGEN_DEVICE_FUNC evaluator(const ArgType& arg) : m_result(arg) { internal::construct_at(this, m_result); } -protected: + protected: PlainObject m_result; }; -} // namespace internal +} // namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_COREEVALUATORS_H +#endif // EIGEN_COREEVALUATORS_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CoreIterators.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CoreIterators.h index b967196813b..f62cf238e75 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CoreIterators.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CoreIterators.h @@ -10,100 +10,111 @@ #ifndef EIGEN_COREITERATORS_H #define EIGEN_COREITERATORS_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { /* This file contains the respective InnerIterator definition of the expressions defined in Eigen/Core */ namespace internal { -template +template class inner_iterator_selector; } /** \class InnerIterator - * \brief An InnerIterator allows to loop over the element of any matrix expression. - * - * \warning To be used with care because an evaluator is constructed every time an InnerIterator iterator is constructed. - * - * TODO: add a usage example - */ -template -class InnerIterator -{ -protected: + * \brief An InnerIterator allows to loop over the element of any matrix expression. + * + * \warning To be used with care because an evaluator is constructed every time an InnerIterator iterator is + * constructed. + * + * TODO: add a usage example + */ +template +class InnerIterator { + protected: typedef internal::inner_iterator_selector::Kind> IteratorType; typedef internal::evaluator EvaluatorType; typedef typename internal::traits::Scalar Scalar; -public: + + public: /** Construct an iterator over the \a outerId -th row or column of \a xpr */ - InnerIterator(const XprType &xpr, const Index &outerId) - : m_eval(xpr), m_iter(m_eval, outerId, xpr.innerSize()) - {} - + InnerIterator(const XprType &xpr, const Index &outerId) : m_eval(xpr), m_iter(m_eval, outerId, xpr.innerSize()) {} + /// \returns the value of the current coefficient. - EIGEN_STRONG_INLINE Scalar value() const { return m_iter.value(); } + EIGEN_STRONG_INLINE Scalar value() const { return m_iter.value(); } /** Increment the iterator \c *this to the next non-zero coefficient. - * Explicit zeros are not skipped over. To skip explicit zeros, see class SparseView - */ - EIGEN_STRONG_INLINE InnerIterator& operator++() { m_iter.operator++(); return *this; } - EIGEN_STRONG_INLINE InnerIterator& operator+=(Index i) { m_iter.operator+=(i); return *this; } - EIGEN_STRONG_INLINE InnerIterator operator+(Index i) - { InnerIterator result(*this); result+=i; return result; } - + * Explicit zeros are not skipped over. To skip explicit zeros, see class SparseView + */ + EIGEN_STRONG_INLINE InnerIterator &operator++() { + m_iter.operator++(); + return *this; + } + EIGEN_STRONG_INLINE InnerIterator &operator+=(Index i) { + m_iter.operator+=(i); + return *this; + } + EIGEN_STRONG_INLINE InnerIterator operator+(Index i) { + InnerIterator result(*this); + result += i; + return result; + } /// \returns the column or row index of the current coefficient. - EIGEN_STRONG_INLINE Index index() const { return m_iter.index(); } + EIGEN_STRONG_INLINE Index index() const { return m_iter.index(); } /// \returns the row index of the current coefficient. - EIGEN_STRONG_INLINE Index row() const { return m_iter.row(); } + EIGEN_STRONG_INLINE Index row() const { return m_iter.row(); } /// \returns the column index of the current coefficient. - EIGEN_STRONG_INLINE Index col() const { return m_iter.col(); } + EIGEN_STRONG_INLINE Index col() const { return m_iter.col(); } /// \returns \c true if the iterator \c *this still references a valid coefficient. - EIGEN_STRONG_INLINE operator bool() const { return m_iter; } - -protected: + EIGEN_STRONG_INLINE operator bool() const { return m_iter; } + + protected: EvaluatorType m_eval; IteratorType m_iter; -private: + + private: // If you get here, then you're not using the right InnerIterator type, e.g.: // SparseMatrix A; // SparseMatrix::InnerIterator it(A,0); - template InnerIterator(const EigenBase&,Index outer); + template + InnerIterator(const EigenBase &, Index outer); }; namespace internal { // Generic inner iterator implementation for dense objects -template -class inner_iterator_selector -{ -protected: +template +class inner_iterator_selector { + protected: typedef evaluator EvaluatorType; typedef typename traits::Scalar Scalar; - enum { IsRowMajor = (XprType::Flags&RowMajorBit)==RowMajorBit }; - -public: + enum { IsRowMajor = (XprType::Flags & RowMajorBit) == RowMajorBit }; + + public: EIGEN_STRONG_INLINE inner_iterator_selector(const EvaluatorType &eval, const Index &outerId, const Index &innerSize) - : m_eval(eval), m_inner(0), m_outer(outerId), m_end(innerSize) - {} + : m_eval(eval), m_inner(0), m_outer(outerId), m_end(innerSize) {} - EIGEN_STRONG_INLINE Scalar value() const - { - return (IsRowMajor) ? m_eval.coeff(m_outer, m_inner) - : m_eval.coeff(m_inner, m_outer); + EIGEN_STRONG_INLINE Scalar value() const { + return (IsRowMajor) ? m_eval.coeff(m_outer, m_inner) : m_eval.coeff(m_inner, m_outer); } - EIGEN_STRONG_INLINE inner_iterator_selector& operator++() { m_inner++; return *this; } + EIGEN_STRONG_INLINE inner_iterator_selector &operator++() { + m_inner++; + return *this; + } EIGEN_STRONG_INLINE Index index() const { return m_inner; } inline Index row() const { return IsRowMajor ? m_outer : index(); } inline Index col() const { return IsRowMajor ? index() : m_outer; } - EIGEN_STRONG_INLINE operator bool() const { return m_inner < m_end && m_inner>=0; } + EIGEN_STRONG_INLINE operator bool() const { return m_inner < m_end && m_inner >= 0; } -protected: - const EvaluatorType& m_eval; + protected: + const EvaluatorType &m_eval; Index m_inner; const Index m_outer; const Index m_end; @@ -111,22 +122,20 @@ class inner_iterator_selector // For iterator-based evaluator, inner-iterator is already implemented as // evaluator<>::InnerIterator -template -class inner_iterator_selector - : public evaluator::InnerIterator -{ -protected: +template +class inner_iterator_selector : public evaluator::InnerIterator { + protected: typedef typename evaluator::InnerIterator Base; typedef evaluator EvaluatorType; - -public: - EIGEN_STRONG_INLINE inner_iterator_selector(const EvaluatorType &eval, const Index &outerId, const Index &/*innerSize*/) - : Base(eval, outerId) - {} + + public: + EIGEN_STRONG_INLINE inner_iterator_selector(const EvaluatorType &eval, const Index &outerId, + const Index & /*innerSize*/) + : Base(eval, outerId) {} }; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_COREITERATORS_H +#endif // EIGEN_COREITERATORS_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseBinaryOp.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseBinaryOp.h index 2202b1cc6b7..aa79b60813d 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseBinaryOp.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseBinaryOp.h @@ -11,15 +11,17 @@ #ifndef EIGEN_CWISE_BINARY_OP_H #define EIGEN_CWISE_BINARY_OP_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > -{ +template +struct traits> { // we must not inherit from traits since it has // the potential to cause problems with MSVC - typedef typename remove_all::type Ancestor; + typedef remove_all_t Ancestor; typedef typename traits::XprKind XprKind; enum { RowsAtCompileTime = traits::RowsAtCompileTime, @@ -30,154 +32,135 @@ struct traits > // even though we require Lhs and Rhs to have the same scalar type (see CwiseBinaryOp constructor), // we still want to handle the case when the result type is different. - typedef typename result_of< - BinaryOp( - const typename Lhs::Scalar&, - const typename Rhs::Scalar& - ) - >::type Scalar; - typedef typename cwise_promote_storage_type::StorageKind, - typename traits::StorageKind, + typedef typename result_of::type Scalar; + typedef typename cwise_promote_storage_type::StorageKind, typename traits::StorageKind, BinaryOp>::ret StorageKind; - typedef typename promote_index_type::StorageIndex, - typename traits::StorageIndex>::type StorageIndex; + typedef typename promote_index_type::StorageIndex, typename traits::StorageIndex>::type + StorageIndex; typedef typename Lhs::Nested LhsNested; typedef typename Rhs::Nested RhsNested; - typedef typename remove_reference::type _LhsNested; - typedef typename remove_reference::type _RhsNested; + typedef std::remove_reference_t LhsNested_; + typedef std::remove_reference_t RhsNested_; enum { - Flags = cwise_promote_storage_order::StorageKind,typename traits::StorageKind,_LhsNested::Flags & RowMajorBit,_RhsNested::Flags & RowMajorBit>::value + Flags = cwise_promote_storage_order::StorageKind, typename traits::StorageKind, + LhsNested_::Flags & RowMajorBit, RhsNested_::Flags & RowMajorBit>::value }; }; -} // end namespace internal +} // end namespace internal -template +template class CwiseBinaryOpImpl; /** \class CwiseBinaryOp - * \ingroup Core_Module - * - * \brief Generic expression where a coefficient-wise binary operator is applied to two expressions - * - * \tparam BinaryOp template functor implementing the operator - * \tparam LhsType the type of the left-hand side - * \tparam RhsType the type of the right-hand side - * - * This class represents an expression where a coefficient-wise binary operator is applied to two expressions. - * It is the return type of binary operators, by which we mean only those binary operators where - * both the left-hand side and the right-hand side are Eigen expressions. - * For example, the return type of matrix1+matrix2 is a CwiseBinaryOp. - * - * Most of the time, this is the only way that it is used, so you typically don't have to name - * CwiseBinaryOp types explicitly. - * - * \sa MatrixBase::binaryExpr(const MatrixBase &,const CustomBinaryOp &) const, class CwiseUnaryOp, class CwiseNullaryOp - */ -template -class CwiseBinaryOp : - public CwiseBinaryOpImpl< - BinaryOp, LhsType, RhsType, - typename internal::cwise_promote_storage_type::StorageKind, - typename internal::traits::StorageKind, - BinaryOp>::ret>, - internal::no_assignment_operator -{ - public: - - typedef typename internal::remove_all::type Functor; - typedef typename internal::remove_all::type Lhs; - typedef typename internal::remove_all::type Rhs; - - typedef typename CwiseBinaryOpImpl< - BinaryOp, LhsType, RhsType, - typename internal::cwise_promote_storage_type::StorageKind, - typename internal::traits::StorageKind, - BinaryOp>::ret>::Base Base; - EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseBinaryOp) - - typedef typename internal::ref_selector::type LhsNested; - typedef typename internal::ref_selector::type RhsNested; - typedef typename internal::remove_reference::type _LhsNested; - typedef typename internal::remove_reference::type _RhsNested; - -#if EIGEN_COMP_MSVC && EIGEN_HAS_CXX11 - //Required for Visual Studio or the Copy constructor will probably not get inlined! - EIGEN_STRONG_INLINE - CwiseBinaryOp(const CwiseBinaryOp&) = default; + * \ingroup Core_Module + * + * \brief Generic expression where a coefficient-wise binary operator is applied to two expressions + * + * \tparam BinaryOp template functor implementing the operator + * \tparam LhsType the type of the left-hand side + * \tparam RhsType the type of the right-hand side + * + * This class represents an expression where a coefficient-wise binary operator is applied to two expressions. + * It is the return type of binary operators, by which we mean only those binary operators where + * both the left-hand side and the right-hand side are Eigen expressions. + * For example, the return type of matrix1+matrix2 is a CwiseBinaryOp. + * + * Most of the time, this is the only way that it is used, so you typically don't have to name + * CwiseBinaryOp types explicitly. + * + * \sa MatrixBase::binaryExpr(const MatrixBase &,const CustomBinaryOp &) const, class CwiseUnaryOp, class + * CwiseNullaryOp + */ +template +class CwiseBinaryOp : public CwiseBinaryOpImpl::StorageKind, + typename internal::traits::StorageKind, BinaryOp>::ret>, + internal::no_assignment_operator { + public: + typedef internal::remove_all_t Functor; + typedef internal::remove_all_t Lhs; + typedef internal::remove_all_t Rhs; + + typedef typename CwiseBinaryOpImpl< + BinaryOp, LhsType, RhsType, + typename internal::cwise_promote_storage_type::StorageKind, + typename internal::traits::StorageKind, BinaryOp>::ret>::Base + Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseBinaryOp) + + EIGEN_CHECK_BINARY_COMPATIBILIY(BinaryOp, typename Lhs::Scalar, typename Rhs::Scalar) + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Lhs, Rhs) + + typedef typename internal::ref_selector::type LhsNested; + typedef typename internal::ref_selector::type RhsNested; + typedef std::remove_reference_t LhsNested_; + typedef std::remove_reference_t RhsNested_; + +#if EIGEN_COMP_MSVC + // Required for Visual Studio or the Copy constructor will probably not get inlined! + EIGEN_STRONG_INLINE CwiseBinaryOp(const CwiseBinaryOp&) = default; #endif - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CwiseBinaryOp(const Lhs& aLhs, const Rhs& aRhs, const BinaryOp& func = BinaryOp()) - : m_lhs(aLhs), m_rhs(aRhs), m_functor(func) - { - EIGEN_CHECK_BINARY_COMPATIBILIY(BinaryOp,typename Lhs::Scalar,typename Rhs::Scalar); - // require the sizes to match - EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Lhs, Rhs) - eigen_assert(aLhs.rows() == aRhs.rows() && aLhs.cols() == aRhs.cols()); - } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index rows() const EIGEN_NOEXCEPT { - // return the fixed size type if available to enable compile time optimizations - return internal::traits::type>::RowsAtCompileTime==Dynamic ? m_rhs.rows() : m_lhs.rows(); - } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index cols() const EIGEN_NOEXCEPT { - // return the fixed size type if available to enable compile time optimizations - return internal::traits::type>::ColsAtCompileTime==Dynamic ? m_rhs.cols() : m_lhs.cols(); - } - - /** \returns the left hand side nested expression */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const _LhsNested& lhs() const { return m_lhs; } - /** \returns the right hand side nested expression */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const _RhsNested& rhs() const { return m_rhs; } - /** \returns the functor representing the binary operation */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const BinaryOp& functor() const { return m_functor; } - - protected: - LhsNested m_lhs; - RhsNested m_rhs; - const BinaryOp m_functor; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CwiseBinaryOp(const Lhs& aLhs, const Rhs& aRhs, + const BinaryOp& func = BinaryOp()) + : m_lhs(aLhs), m_rhs(aRhs), m_functor(func) { + eigen_assert(aLhs.rows() == aRhs.rows() && aLhs.cols() == aRhs.cols()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { + // return the fixed size type if available to enable compile time optimizations + return internal::traits>::RowsAtCompileTime == Dynamic ? m_rhs.rows() + : m_lhs.rows(); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { + // return the fixed size type if available to enable compile time optimizations + return internal::traits>::ColsAtCompileTime == Dynamic ? m_rhs.cols() + : m_lhs.cols(); + } + + /** \returns the left hand side nested expression */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const LhsNested_& lhs() const { return m_lhs; } + /** \returns the right hand side nested expression */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const RhsNested_& rhs() const { return m_rhs; } + /** \returns the functor representing the binary operation */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const BinaryOp& functor() const { return m_functor; } + + protected: + LhsNested m_lhs; + RhsNested m_rhs; + const BinaryOp m_functor; }; // Generic API dispatcher -template -class CwiseBinaryOpImpl - : public internal::generic_xpr_base >::type -{ -public: - typedef typename internal::generic_xpr_base >::type Base; +template +class CwiseBinaryOpImpl : public internal::generic_xpr_base>::type { + public: + typedef typename internal::generic_xpr_base>::type Base; }; /** replaces \c *this by \c *this - \a other. - * - * \returns a reference to \c *this - */ -template -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived & -MatrixBase::operator-=(const MatrixBase &other) -{ - call_assignment(derived(), other.derived(), internal::sub_assign_op()); + * + * \returns a reference to \c *this + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::operator-=(const MatrixBase& other) { + call_assignment(derived(), other.derived(), internal::sub_assign_op()); return derived(); } /** replaces \c *this by \c *this + \a other. - * - * \returns a reference to \c *this - */ -template -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived & -MatrixBase::operator+=(const MatrixBase& other) -{ - call_assignment(derived(), other.derived(), internal::add_assign_op()); + * + * \returns a reference to \c *this + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::operator+=(const MatrixBase& other) { + call_assignment(derived(), other.derived(), internal::add_assign_op()); return derived(); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_CWISE_BINARY_OP_H +#endif // EIGEN_CWISE_BINARY_OP_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseNullaryOp.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseNullaryOp.h index 289ec510a8a..39c33cf0347 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseNullaryOp.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseNullaryOp.h @@ -10,18 +10,18 @@ #ifndef EIGEN_CWISE_NULLARY_OP_H #define EIGEN_CWISE_NULLARY_OP_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > : traits -{ - enum { - Flags = traits::Flags & RowMajorBit - }; +template +struct traits > : traits { + enum { Flags = traits::Flags & RowMajorBit }; }; -} // namespace internal +} // namespace internal /** \class CwiseNullaryOp * \ingroup Core_Module @@ -40,11 +40,14 @@ struct traits > : traits - \c operator()() if the procedural generation does not depend on the coefficient entries (e.g., random numbers) - \c operator()(Index i)if the procedural generation makes sense for vectors only and that it depends on the coefficient index \c i (e.g., linspace) - \c operator()(Index i,Index j)if the procedural generation depends on the matrix coordinates \c i, \c j (e.g., to generate a checkerboard with 0 and 1) + \c operator()() if the procedural generation does not depend on the coefficient entries + (e.g., random numbers) \c operator()(Index i)if the procedural generation makes + sense for vectors only and that it depends on the coefficient index \c i (e.g., linspace) \c + operator()(Index i,Index j)if the procedural generation depends on the matrix coordinates \c i, \c j (e.g., + to generate a checkerboard with 0 and 1) - * It is also possible to expose the last two operators if the generation makes sense for matrices but can be optimized for vectors. + * It is also possible to expose the last two operators if the generation makes sense for matrices but can be optimized + for vectors. * * See DenseBase::NullaryExpr(Index,const CustomNullaryOp&) for an example binding * C++11 random number generators. @@ -56,779 +59,748 @@ struct traits > : traits -class CwiseNullaryOp : public internal::dense_xpr_base< CwiseNullaryOp >::type, internal::no_assignment_operator -{ - public: - - typedef typename internal::dense_xpr_base::type Base; - EIGEN_DENSE_PUBLIC_INTERFACE(CwiseNullaryOp) - - EIGEN_DEVICE_FUNC - CwiseNullaryOp(Index rows, Index cols, const NullaryOp& func = NullaryOp()) - : m_rows(rows), m_cols(cols), m_functor(func) - { - eigen_assert(rows >= 0 - && (RowsAtCompileTime == Dynamic || RowsAtCompileTime == rows) - && cols >= 0 - && (ColsAtCompileTime == Dynamic || ColsAtCompileTime == cols)); - } +template +class CwiseNullaryOp : public internal::dense_xpr_base >::type, + internal::no_assignment_operator { + public: + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(CwiseNullaryOp) + + EIGEN_DEVICE_FUNC CwiseNullaryOp(Index rows, Index cols, const NullaryOp& func = NullaryOp()) + : m_rows(rows), m_cols(cols), m_functor(func) { + eigen_assert(rows >= 0 && (RowsAtCompileTime == Dynamic || RowsAtCompileTime == rows) && cols >= 0 && + (ColsAtCompileTime == Dynamic || ColsAtCompileTime == cols)); + } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index rows() const { return m_rows.value(); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index cols() const { return m_cols.value(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index rows() const { return m_rows.value(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index cols() const { return m_cols.value(); } - /** \returns the functor representing the nullary operation */ - EIGEN_DEVICE_FUNC - const NullaryOp& functor() const { return m_functor; } + /** \returns the functor representing the nullary operation */ + EIGEN_DEVICE_FUNC const NullaryOp& functor() const { return m_functor; } - protected: - const internal::variable_if_dynamic m_rows; - const internal::variable_if_dynamic m_cols; - const NullaryOp m_functor; + protected: + const internal::variable_if_dynamic m_rows; + const internal::variable_if_dynamic m_cols; + const NullaryOp m_functor; }; - /** \returns an expression of a matrix defined by a custom functor \a func - * - * The parameters \a rows and \a cols are the number of rows and of columns of - * the returned matrix. Must be compatible with this MatrixBase type. - * - * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, - * it is redundant to pass \a rows and \a cols as arguments, so Zero() should be used - * instead. - * - * The template parameter \a CustomNullaryOp is the type of the functor. - * - * \sa class CwiseNullaryOp - */ -template -template + * + * The parameters \a rows and \a cols are the number of rows and of columns of + * the returned matrix. Must be compatible with this MatrixBase type. + * + * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, + * it is redundant to pass \a rows and \a cols as arguments, so Zero() should be used + * instead. + * + * The template parameter \a CustomNullaryOp is the type of the functor. + * + * \sa class CwiseNullaryOp + */ +template +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE #ifndef EIGEN_PARSED_BY_DOXYGEN -const CwiseNullaryOp::PlainObject> + const CwiseNullaryOp::PlainObject> #else -const CwiseNullaryOp + const CwiseNullaryOp #endif -DenseBase::NullaryExpr(Index rows, Index cols, const CustomNullaryOp& func) -{ + DenseBase::NullaryExpr(Index rows, Index cols, const CustomNullaryOp& func) { return CwiseNullaryOp(rows, cols, func); } /** \returns an expression of a matrix defined by a custom functor \a func - * - * The parameter \a size is the size of the returned vector. - * Must be compatible with this MatrixBase type. - * - * \only_for_vectors - * - * This variant is meant to be used for dynamic-size vector types. For fixed-size types, - * it is redundant to pass \a size as argument, so Zero() should be used - * instead. - * - * The template parameter \a CustomNullaryOp is the type of the functor. - * - * Here is an example with C++11 random generators: \include random_cpp11.cpp - * Output: \verbinclude random_cpp11.out - * - * \sa class CwiseNullaryOp - */ -template -template + * + * The parameter \a size is the size of the returned vector. + * Must be compatible with this MatrixBase type. + * + * \only_for_vectors + * + * This variant is meant to be used for dynamic-size vector types. For fixed-size types, + * it is redundant to pass \a size as argument, so Zero() should be used + * instead. + * + * The template parameter \a CustomNullaryOp is the type of the functor. + * + * Here is an example with C++11 random generators: \include random_cpp11.cpp + * Output: \verbinclude random_cpp11.out + * + * \sa class CwiseNullaryOp + */ +template +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE #ifndef EIGEN_PARSED_BY_DOXYGEN -const CwiseNullaryOp::PlainObject> + const CwiseNullaryOp::PlainObject> #else -const CwiseNullaryOp + const CwiseNullaryOp #endif -DenseBase::NullaryExpr(Index size, const CustomNullaryOp& func) -{ + DenseBase::NullaryExpr(Index size, const CustomNullaryOp& func) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) - if(RowsAtCompileTime == 1) return CwiseNullaryOp(1, size, func); - else return CwiseNullaryOp(size, 1, func); + if (RowsAtCompileTime == 1) + return CwiseNullaryOp(1, size, func); + else + return CwiseNullaryOp(size, 1, func); } /** \returns an expression of a matrix defined by a custom functor \a func - * - * This variant is only for fixed-size DenseBase types. For dynamic-size types, you - * need to use the variants taking size arguments. - * - * The template parameter \a CustomNullaryOp is the type of the functor. - * - * \sa class CwiseNullaryOp - */ -template -template + * + * This variant is only for fixed-size DenseBase types. For dynamic-size types, you + * need to use the variants taking size arguments. + * + * The template parameter \a CustomNullaryOp is the type of the functor. + * + * \sa class CwiseNullaryOp + */ +template +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE #ifndef EIGEN_PARSED_BY_DOXYGEN -const CwiseNullaryOp::PlainObject> + const CwiseNullaryOp::PlainObject> #else -const CwiseNullaryOp + const CwiseNullaryOp #endif -DenseBase::NullaryExpr(const CustomNullaryOp& func) -{ + DenseBase::NullaryExpr(const CustomNullaryOp& func) { return CwiseNullaryOp(RowsAtCompileTime, ColsAtCompileTime, func); } /** \returns an expression of a constant matrix of value \a value - * - * The parameters \a rows and \a cols are the number of rows and of columns of - * the returned matrix. Must be compatible with this DenseBase type. - * - * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, - * it is redundant to pass \a rows and \a cols as arguments, so Zero() should be used - * instead. - * - * The template parameter \a CustomNullaryOp is the type of the functor. - * - * \sa class CwiseNullaryOp - */ -template + * + * The parameters \a rows and \a cols are the number of rows and of columns of + * the returned matrix. Must be compatible with this DenseBase type. + * + * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, + * it is redundant to pass \a rows and \a cols as arguments, so Zero() should be used + * instead. + * + * The template parameter \a CustomNullaryOp is the type of the functor. + * + * \sa class CwiseNullaryOp + */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType -DenseBase::Constant(Index rows, Index cols, const Scalar& value) -{ +DenseBase::Constant(Index rows, Index cols, const Scalar& value) { return DenseBase::NullaryExpr(rows, cols, internal::scalar_constant_op(value)); } /** \returns an expression of a constant matrix of value \a value - * - * The parameter \a size is the size of the returned vector. - * Must be compatible with this DenseBase type. - * - * \only_for_vectors - * - * This variant is meant to be used for dynamic-size vector types. For fixed-size types, - * it is redundant to pass \a size as argument, so Zero() should be used - * instead. - * - * The template parameter \a CustomNullaryOp is the type of the functor. - * - * \sa class CwiseNullaryOp - */ -template + * + * The parameter \a size is the size of the returned vector. + * Must be compatible with this DenseBase type. + * + * \only_for_vectors + * + * This variant is meant to be used for dynamic-size vector types. For fixed-size types, + * it is redundant to pass \a size as argument, so Zero() should be used + * instead. + * + * The template parameter \a CustomNullaryOp is the type of the functor. + * + * \sa class CwiseNullaryOp + */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType -DenseBase::Constant(Index size, const Scalar& value) -{ +DenseBase::Constant(Index size, const Scalar& value) { return DenseBase::NullaryExpr(size, internal::scalar_constant_op(value)); } /** \returns an expression of a constant matrix of value \a value - * - * This variant is only for fixed-size DenseBase types. For dynamic-size types, you - * need to use the variants taking size arguments. - * - * The template parameter \a CustomNullaryOp is the type of the functor. - * - * \sa class CwiseNullaryOp - */ -template + * + * This variant is only for fixed-size DenseBase types. For dynamic-size types, you + * need to use the variants taking size arguments. + * + * The template parameter \a CustomNullaryOp is the type of the functor. + * + * \sa class CwiseNullaryOp + */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType -DenseBase::Constant(const Scalar& value) -{ +DenseBase::Constant(const Scalar& value) { EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) - return DenseBase::NullaryExpr(RowsAtCompileTime, ColsAtCompileTime, internal::scalar_constant_op(value)); + return DenseBase::NullaryExpr(RowsAtCompileTime, ColsAtCompileTime, + internal::scalar_constant_op(value)); } /** \deprecated because of accuracy loss. In Eigen 3.3, it is an alias for LinSpaced(Index,const Scalar&,const Scalar&) - * - * \only_for_vectors - * - * Example: \include DenseBase_LinSpaced_seq_deprecated.cpp - * Output: \verbinclude DenseBase_LinSpaced_seq_deprecated.out - * - * \sa LinSpaced(Index,const Scalar&, const Scalar&), setLinSpaced(Index,const Scalar&,const Scalar&) - */ -template -EIGEN_DEPRECATED EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::RandomAccessLinSpacedReturnType -DenseBase::LinSpaced(Sequential_t, Index size, const Scalar& low, const Scalar& high) -{ + * + * \only_for_vectors + * + * Example: \include DenseBase_LinSpaced_seq_deprecated.cpp + * Output: \verbinclude DenseBase_LinSpaced_seq_deprecated.out + * + * \sa LinSpaced(Index,const Scalar&, const Scalar&), setLinSpaced(Index,const Scalar&,const Scalar&) + */ +template +EIGEN_DEPRECATED EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase< + Derived>::RandomAccessLinSpacedReturnType +DenseBase::LinSpaced(Sequential_t, Index size, const Scalar& low, const Scalar& high) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) - return DenseBase::NullaryExpr(size, internal::linspaced_op(low,high,size)); + return DenseBase::NullaryExpr(size, internal::linspaced_op(low, high, size)); } /** \deprecated because of accuracy loss. In Eigen 3.3, it is an alias for LinSpaced(const Scalar&,const Scalar&) - * - * \sa LinSpaced(const Scalar&, const Scalar&) - */ -template -EIGEN_DEPRECATED EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::RandomAccessLinSpacedReturnType -DenseBase::LinSpaced(Sequential_t, const Scalar& low, const Scalar& high) -{ + * + * \sa LinSpaced(const Scalar&, const Scalar&) + */ +template +EIGEN_DEPRECATED EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase< + Derived>::RandomAccessLinSpacedReturnType +DenseBase::LinSpaced(Sequential_t, const Scalar& low, const Scalar& high) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) - return DenseBase::NullaryExpr(Derived::SizeAtCompileTime, internal::linspaced_op(low,high,Derived::SizeAtCompileTime)); + return DenseBase::NullaryExpr(Derived::SizeAtCompileTime, + internal::linspaced_op(low, high, Derived::SizeAtCompileTime)); } /** - * \brief Sets a linearly spaced vector. - * - * The function generates 'size' equally spaced values in the closed interval [low,high]. - * When size is set to 1, a vector of length 1 containing 'high' is returned. - * - * \only_for_vectors - * - * Example: \include DenseBase_LinSpaced.cpp - * Output: \verbinclude DenseBase_LinSpaced.out - * - * For integer scalar types, an even spacing is possible if and only if the length of the range, - * i.e., \c high-low is a scalar multiple of \c size-1, or if \c size is a scalar multiple of the - * number of values \c high-low+1 (meaning each value can be repeated the same number of time). - * If one of these two considions is not satisfied, then \c high is lowered to the largest value - * satisfying one of this constraint. - * Here are some examples: - * - * Example: \include DenseBase_LinSpacedInt.cpp - * Output: \verbinclude DenseBase_LinSpacedInt.out - * - * \sa setLinSpaced(Index,const Scalar&,const Scalar&), CwiseNullaryOp - */ -template + * \brief Sets a linearly spaced vector. + * + * The function generates 'size' equally spaced values in the closed interval [low,high]. + * When size is set to 1, a vector of length 1 containing 'high' is returned. + * + * \only_for_vectors + * + * Example: \include DenseBase_LinSpaced.cpp + * Output: \verbinclude DenseBase_LinSpaced.out + * + * For integer scalar types, an even spacing is possible if and only if the length of the range, + * i.e., \c high-low is a scalar multiple of \c size-1, or if \c size is a scalar multiple of the + * number of values \c high-low+1 (meaning each value can be repeated the same number of time). + * If one of these two considions is not satisfied, then \c high is lowered to the largest value + * satisfying one of this constraint. + * Here are some examples: + * + * Example: \include DenseBase_LinSpacedInt.cpp + * Output: \verbinclude DenseBase_LinSpacedInt.out + * + * \sa setLinSpaced(Index,const Scalar&,const Scalar&), CwiseNullaryOp + */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::RandomAccessLinSpacedReturnType -DenseBase::LinSpaced(Index size, const Scalar& low, const Scalar& high) -{ +DenseBase::LinSpaced(Index size, const Scalar& low, const Scalar& high) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) - return DenseBase::NullaryExpr(size, internal::linspaced_op(low,high,size)); + return DenseBase::NullaryExpr(size, internal::linspaced_op(low, high, size)); } /** - * \copydoc DenseBase::LinSpaced(Index, const Scalar&, const Scalar&) - * Special version for fixed size types which does not require the size parameter. - */ -template + * \copydoc DenseBase::LinSpaced(Index, const Scalar&, const Scalar&) + * Special version for fixed size types which does not require the size parameter. + */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::RandomAccessLinSpacedReturnType -DenseBase::LinSpaced(const Scalar& low, const Scalar& high) -{ +DenseBase::LinSpaced(const Scalar& low, const Scalar& high) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) - return DenseBase::NullaryExpr(Derived::SizeAtCompileTime, internal::linspaced_op(low,high,Derived::SizeAtCompileTime)); + return DenseBase::NullaryExpr(Derived::SizeAtCompileTime, + internal::linspaced_op(low, high, Derived::SizeAtCompileTime)); +} + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::RandomAccessEqualSpacedReturnType +DenseBase::EqualSpaced(Index size, const Scalar& low, const Scalar& step) { + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return DenseBase::NullaryExpr(size, internal::equalspaced_op(low, step)); +} + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::RandomAccessEqualSpacedReturnType +DenseBase::EqualSpaced(const Scalar& low, const Scalar& step) { + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return DenseBase::NullaryExpr(Derived::SizeAtCompileTime, internal::equalspaced_op(low, step)); } /** \returns true if all coefficients in this matrix are approximately equal to \a val, to within precision \a prec */ -template -EIGEN_DEVICE_FUNC bool DenseBase::isApproxToConstant -(const Scalar& val, const RealScalar& prec) const -{ - typename internal::nested_eval::type self(derived()); - for(Index j = 0; j < cols(); ++j) - for(Index i = 0; i < rows(); ++i) - if(!internal::isApprox(self.coeff(i, j), val, prec)) - return false; +template +EIGEN_DEVICE_FUNC bool DenseBase::isApproxToConstant(const Scalar& val, const RealScalar& prec) const { + typename internal::nested_eval::type self(derived()); + for (Index j = 0; j < cols(); ++j) + for (Index i = 0; i < rows(); ++i) + if (!internal::isApprox(self.coeff(i, j), val, prec)) return false; return true; } /** This is just an alias for isApproxToConstant(). - * - * \returns true if all coefficients in this matrix are approximately equal to \a value, to within precision \a prec */ -template -EIGEN_DEVICE_FUNC bool DenseBase::isConstant -(const Scalar& val, const RealScalar& prec) const -{ + * + * \returns true if all coefficients in this matrix are approximately equal to \a value, to within precision \a prec */ +template +EIGEN_DEVICE_FUNC bool DenseBase::isConstant(const Scalar& val, const RealScalar& prec) const { return isApproxToConstant(val, prec); } /** Alias for setConstant(): sets all coefficients in this expression to \a val. - * - * \sa setConstant(), Constant(), class CwiseNullaryOp - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void DenseBase::fill(const Scalar& val) -{ + * + * \sa setConstant(), Constant(), class CwiseNullaryOp + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void DenseBase::fill(const Scalar& val) { setConstant(val); } /** Sets all coefficients in this expression to value \a val. - * - * \sa fill(), setConstant(Index,const Scalar&), setConstant(Index,Index,const Scalar&), setZero(), setOnes(), Constant(), class CwiseNullaryOp, setZero(), setOnes() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setConstant(const Scalar& val) -{ + * + * \sa fill(), setConstant(Index,const Scalar&), setConstant(Index,Index,const Scalar&), setZero(), setOnes(), + * Constant(), class CwiseNullaryOp, setZero(), setOnes() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setConstant(const Scalar& val) { return derived() = Constant(rows(), cols(), val); } /** Resizes to the given \a size, and sets all coefficients in this expression to the given value \a val. - * - * \only_for_vectors - * - * Example: \include Matrix_setConstant_int.cpp - * Output: \verbinclude Matrix_setConstant_int.out - * - * \sa MatrixBase::setConstant(const Scalar&), setConstant(Index,Index,const Scalar&), class CwiseNullaryOp, MatrixBase::Constant(const Scalar&) - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setConstant(Index size, const Scalar& val) -{ + * + * \only_for_vectors + * + * Example: \include Matrix_setConstant_int.cpp + * Output: \verbinclude Matrix_setConstant_int.out + * + * \sa MatrixBase::setConstant(const Scalar&), setConstant(Index,Index,const Scalar&), class CwiseNullaryOp, + * MatrixBase::Constant(const Scalar&) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& PlainObjectBase::setConstant(Index size, const Scalar& val) { resize(size); return setConstant(val); } /** Resizes to the given size, and sets all coefficients in this expression to the given value \a val. - * - * \param rows the new number of rows - * \param cols the new number of columns - * \param val the value to which all coefficients are set - * - * Example: \include Matrix_setConstant_int_int.cpp - * Output: \verbinclude Matrix_setConstant_int_int.out - * - * \sa MatrixBase::setConstant(const Scalar&), setConstant(Index,const Scalar&), class CwiseNullaryOp, MatrixBase::Constant(const Scalar&) - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setConstant(Index rows, Index cols, const Scalar& val) -{ + * + * \param rows the new number of rows + * \param cols the new number of columns + * \param val the value to which all coefficients are set + * + * Example: \include Matrix_setConstant_int_int.cpp + * Output: \verbinclude Matrix_setConstant_int_int.out + * + * \sa MatrixBase::setConstant(const Scalar&), setConstant(Index,const Scalar&), class CwiseNullaryOp, + * MatrixBase::Constant(const Scalar&) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& PlainObjectBase::setConstant(Index rows, Index cols, + const Scalar& val) { resize(rows, cols); return setConstant(val); } /** Resizes to the given size, changing only the number of columns, and sets all - * coefficients in this expression to the given value \a val. For the parameter - * of type NoChange_t, just pass the special value \c NoChange. - * - * \sa MatrixBase::setConstant(const Scalar&), setConstant(Index,const Scalar&), class CwiseNullaryOp, MatrixBase::Constant(const Scalar&) - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setConstant(NoChange_t, Index cols, const Scalar& val) -{ + * coefficients in this expression to the given value \a val. For the parameter + * of type NoChange_t, just pass the special value \c NoChange. + * + * \sa MatrixBase::setConstant(const Scalar&), setConstant(Index,const Scalar&), class CwiseNullaryOp, + * MatrixBase::Constant(const Scalar&) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& PlainObjectBase::setConstant(NoChange_t, Index cols, + const Scalar& val) { return setConstant(rows(), cols, val); } /** Resizes to the given size, changing only the number of rows, and sets all - * coefficients in this expression to the given value \a val. For the parameter - * of type NoChange_t, just pass the special value \c NoChange. - * - * \sa MatrixBase::setConstant(const Scalar&), setConstant(Index,const Scalar&), class CwiseNullaryOp, MatrixBase::Constant(const Scalar&) - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setConstant(Index rows, NoChange_t, const Scalar& val) -{ + * coefficients in this expression to the given value \a val. For the parameter + * of type NoChange_t, just pass the special value \c NoChange. + * + * \sa MatrixBase::setConstant(const Scalar&), setConstant(Index,const Scalar&), class CwiseNullaryOp, + * MatrixBase::Constant(const Scalar&) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& PlainObjectBase::setConstant(Index rows, NoChange_t, + const Scalar& val) { return setConstant(rows, cols(), val); } - /** - * \brief Sets a linearly spaced vector. - * - * The function generates 'size' equally spaced values in the closed interval [low,high]. - * When size is set to 1, a vector of length 1 containing 'high' is returned. - * - * \only_for_vectors - * - * Example: \include DenseBase_setLinSpaced.cpp - * Output: \verbinclude DenseBase_setLinSpaced.out - * - * For integer scalar types, do not miss the explanations on the definition - * of \link LinSpaced(Index,const Scalar&,const Scalar&) even spacing \endlink. - * - * \sa LinSpaced(Index,const Scalar&,const Scalar&), CwiseNullaryOp - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setLinSpaced(Index newSize, const Scalar& low, const Scalar& high) -{ + * \brief Sets a linearly spaced vector. + * + * The function generates 'size' equally spaced values in the closed interval [low,high]. + * When size is set to 1, a vector of length 1 containing 'high' is returned. + * + * \only_for_vectors + * + * Example: \include DenseBase_setLinSpaced.cpp + * Output: \verbinclude DenseBase_setLinSpaced.out + * + * For integer scalar types, do not miss the explanations on the definition + * of \link LinSpaced(Index,const Scalar&,const Scalar&) even spacing \endlink. + * + * \sa LinSpaced(Index,const Scalar&,const Scalar&), CwiseNullaryOp + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setLinSpaced(Index newSize, const Scalar& low, + const Scalar& high) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) - return derived() = Derived::NullaryExpr(newSize, internal::linspaced_op(low,high,newSize)); + return derived() = Derived::NullaryExpr(newSize, internal::linspaced_op(low, high, newSize)); } /** - * \brief Sets a linearly spaced vector. - * - * The function fills \c *this with equally spaced values in the closed interval [low,high]. - * When size is set to 1, a vector of length 1 containing 'high' is returned. - * - * \only_for_vectors - * - * For integer scalar types, do not miss the explanations on the definition - * of \link LinSpaced(Index,const Scalar&,const Scalar&) even spacing \endlink. - * - * \sa LinSpaced(Index,const Scalar&,const Scalar&), setLinSpaced(Index, const Scalar&, const Scalar&), CwiseNullaryOp - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setLinSpaced(const Scalar& low, const Scalar& high) -{ + * \brief Sets a linearly spaced vector. + * + * The function fills \c *this with equally spaced values in the closed interval [low,high]. + * When size is set to 1, a vector of length 1 containing 'high' is returned. + * + * \only_for_vectors + * + * For integer scalar types, do not miss the explanations on the definition + * of \link LinSpaced(Index,const Scalar&,const Scalar&) even spacing \endlink. + * + * \sa LinSpaced(Index,const Scalar&,const Scalar&), setLinSpaced(Index, const Scalar&, const Scalar&), CwiseNullaryOp + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setLinSpaced(const Scalar& low, const Scalar& high) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) return setLinSpaced(size(), low, high); } +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setEqualSpaced(Index newSize, const Scalar& low, + const Scalar& step) { + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return derived() = Derived::NullaryExpr(newSize, internal::equalspaced_op(low, step)); +} +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setEqualSpaced(const Scalar& low, + const Scalar& step) { + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return setEqualSpaced(size(), low, step); +} + // zero: /** \returns an expression of a zero matrix. - * - * The parameters \a rows and \a cols are the number of rows and of columns of - * the returned matrix. Must be compatible with this MatrixBase type. - * - * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, - * it is redundant to pass \a rows and \a cols as arguments, so Zero() should be used - * instead. - * - * Example: \include MatrixBase_zero_int_int.cpp - * Output: \verbinclude MatrixBase_zero_int_int.out - * - * \sa Zero(), Zero(Index) - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType -DenseBase::Zero(Index rows, Index cols) -{ + * + * The parameters \a rows and \a cols are the number of rows and of columns of + * the returned matrix. Must be compatible with this MatrixBase type. + * + * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, + * it is redundant to pass \a rows and \a cols as arguments, so Zero() should be used + * instead. + * + * Example: \include MatrixBase_zero_int_int.cpp + * Output: \verbinclude MatrixBase_zero_int_int.out + * + * \sa Zero(), Zero(Index) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType DenseBase::Zero( + Index rows, Index cols) { return Constant(rows, cols, Scalar(0)); } /** \returns an expression of a zero vector. - * - * The parameter \a size is the size of the returned vector. - * Must be compatible with this MatrixBase type. - * - * \only_for_vectors - * - * This variant is meant to be used for dynamic-size vector types. For fixed-size types, - * it is redundant to pass \a size as argument, so Zero() should be used - * instead. - * - * Example: \include MatrixBase_zero_int.cpp - * Output: \verbinclude MatrixBase_zero_int.out - * - * \sa Zero(), Zero(Index,Index) - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType -DenseBase::Zero(Index size) -{ + * + * The parameter \a size is the size of the returned vector. + * Must be compatible with this MatrixBase type. + * + * \only_for_vectors + * + * This variant is meant to be used for dynamic-size vector types. For fixed-size types, + * it is redundant to pass \a size as argument, so Zero() should be used + * instead. + * + * Example: \include MatrixBase_zero_int.cpp + * Output: \verbinclude MatrixBase_zero_int.out + * + * \sa Zero(), Zero(Index,Index) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType DenseBase::Zero( + Index size) { return Constant(size, Scalar(0)); } /** \returns an expression of a fixed-size zero matrix or vector. - * - * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you - * need to use the variants taking size arguments. - * - * Example: \include MatrixBase_zero.cpp - * Output: \verbinclude MatrixBase_zero.out - * - * \sa Zero(Index), Zero(Index,Index) - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType -DenseBase::Zero() -{ + * + * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you + * need to use the variants taking size arguments. + * + * Example: \include MatrixBase_zero.cpp + * Output: \verbinclude MatrixBase_zero.out + * + * \sa Zero(Index), Zero(Index,Index) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType DenseBase::Zero() { return Constant(Scalar(0)); } /** \returns true if *this is approximately equal to the zero matrix, - * within the precision given by \a prec. - * - * Example: \include MatrixBase_isZero.cpp - * Output: \verbinclude MatrixBase_isZero.out - * - * \sa class CwiseNullaryOp, Zero() - */ -template -EIGEN_DEVICE_FUNC bool DenseBase::isZero(const RealScalar& prec) const -{ - typename internal::nested_eval::type self(derived()); - for(Index j = 0; j < cols(); ++j) - for(Index i = 0; i < rows(); ++i) - if(!internal::isMuchSmallerThan(self.coeff(i, j), static_cast(1), prec)) - return false; + * within the precision given by \a prec. + * + * Example: \include MatrixBase_isZero.cpp + * Output: \verbinclude MatrixBase_isZero.out + * + * \sa class CwiseNullaryOp, Zero() + */ +template +EIGEN_DEVICE_FUNC bool DenseBase::isZero(const RealScalar& prec) const { + typename internal::nested_eval::type self(derived()); + for (Index j = 0; j < cols(); ++j) + for (Index i = 0; i < rows(); ++i) + if (!internal::isMuchSmallerThan(self.coeff(i, j), static_cast(1), prec)) return false; return true; } /** Sets all coefficients in this expression to zero. - * - * Example: \include MatrixBase_setZero.cpp - * Output: \verbinclude MatrixBase_setZero.out - * - * \sa class CwiseNullaryOp, Zero() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setZero() -{ + * + * Example: \include MatrixBase_setZero.cpp + * Output: \verbinclude MatrixBase_setZero.out + * + * \sa class CwiseNullaryOp, Zero() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setZero() { return setConstant(Scalar(0)); } /** Resizes to the given \a size, and sets all coefficients in this expression to zero. - * - * \only_for_vectors - * - * Example: \include Matrix_setZero_int.cpp - * Output: \verbinclude Matrix_setZero_int.out - * - * \sa DenseBase::setZero(), setZero(Index,Index), class CwiseNullaryOp, DenseBase::Zero() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setZero(Index newSize) -{ + * + * \only_for_vectors + * + * Example: \include Matrix_setZero_int.cpp + * Output: \verbinclude Matrix_setZero_int.out + * + * \sa DenseBase::setZero(), setZero(Index,Index), class CwiseNullaryOp, DenseBase::Zero() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& PlainObjectBase::setZero(Index newSize) { resize(newSize); return setConstant(Scalar(0)); } /** Resizes to the given size, and sets all coefficients in this expression to zero. - * - * \param rows the new number of rows - * \param cols the new number of columns - * - * Example: \include Matrix_setZero_int_int.cpp - * Output: \verbinclude Matrix_setZero_int_int.out - * - * \sa DenseBase::setZero(), setZero(Index), class CwiseNullaryOp, DenseBase::Zero() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setZero(Index rows, Index cols) -{ + * + * \param rows the new number of rows + * \param cols the new number of columns + * + * Example: \include Matrix_setZero_int_int.cpp + * Output: \verbinclude Matrix_setZero_int_int.out + * + * \sa DenseBase::setZero(), setZero(Index), class CwiseNullaryOp, DenseBase::Zero() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& PlainObjectBase::setZero(Index rows, Index cols) { resize(rows, cols); return setConstant(Scalar(0)); } /** Resizes to the given size, changing only the number of columns, and sets all - * coefficients in this expression to zero. For the parameter of type NoChange_t, - * just pass the special value \c NoChange. - * - * \sa DenseBase::setZero(), setZero(Index), setZero(Index, Index), setZero(Index, NoChange_t), class CwiseNullaryOp, DenseBase::Zero() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setZero(NoChange_t, Index cols) -{ + * coefficients in this expression to zero. For the parameter of type NoChange_t, + * just pass the special value \c NoChange. + * + * \sa DenseBase::setZero(), setZero(Index), setZero(Index, Index), setZero(Index, NoChange_t), class CwiseNullaryOp, + * DenseBase::Zero() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& PlainObjectBase::setZero(NoChange_t, Index cols) { return setZero(rows(), cols); } /** Resizes to the given size, changing only the number of rows, and sets all - * coefficients in this expression to zero. For the parameter of type NoChange_t, - * just pass the special value \c NoChange. - * - * \sa DenseBase::setZero(), setZero(Index), setZero(Index, Index), setZero(NoChange_t, Index), class CwiseNullaryOp, DenseBase::Zero() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setZero(Index rows, NoChange_t) -{ + * coefficients in this expression to zero. For the parameter of type NoChange_t, + * just pass the special value \c NoChange. + * + * \sa DenseBase::setZero(), setZero(Index), setZero(Index, Index), setZero(NoChange_t, Index), class CwiseNullaryOp, + * DenseBase::Zero() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& PlainObjectBase::setZero(Index rows, NoChange_t) { return setZero(rows, cols()); } // ones: /** \returns an expression of a matrix where all coefficients equal one. - * - * The parameters \a rows and \a cols are the number of rows and of columns of - * the returned matrix. Must be compatible with this MatrixBase type. - * - * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, - * it is redundant to pass \a rows and \a cols as arguments, so Ones() should be used - * instead. - * - * Example: \include MatrixBase_ones_int_int.cpp - * Output: \verbinclude MatrixBase_ones_int_int.out - * - * \sa Ones(), Ones(Index), isOnes(), class Ones - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType -DenseBase::Ones(Index rows, Index cols) -{ + * + * The parameters \a rows and \a cols are the number of rows and of columns of + * the returned matrix. Must be compatible with this MatrixBase type. + * + * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, + * it is redundant to pass \a rows and \a cols as arguments, so Ones() should be used + * instead. + * + * Example: \include MatrixBase_ones_int_int.cpp + * Output: \verbinclude MatrixBase_ones_int_int.out + * + * \sa Ones(), Ones(Index), isOnes(), class Ones + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType DenseBase::Ones( + Index rows, Index cols) { return Constant(rows, cols, Scalar(1)); } /** \returns an expression of a vector where all coefficients equal one. - * - * The parameter \a newSize is the size of the returned vector. - * Must be compatible with this MatrixBase type. - * - * \only_for_vectors - * - * This variant is meant to be used for dynamic-size vector types. For fixed-size types, - * it is redundant to pass \a size as argument, so Ones() should be used - * instead. - * - * Example: \include MatrixBase_ones_int.cpp - * Output: \verbinclude MatrixBase_ones_int.out - * - * \sa Ones(), Ones(Index,Index), isOnes(), class Ones - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType -DenseBase::Ones(Index newSize) -{ + * + * The parameter \a newSize is the size of the returned vector. + * Must be compatible with this MatrixBase type. + * + * \only_for_vectors + * + * This variant is meant to be used for dynamic-size vector types. For fixed-size types, + * it is redundant to pass \a size as argument, so Ones() should be used + * instead. + * + * Example: \include MatrixBase_ones_int.cpp + * Output: \verbinclude MatrixBase_ones_int.out + * + * \sa Ones(), Ones(Index,Index), isOnes(), class Ones + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType DenseBase::Ones( + Index newSize) { return Constant(newSize, Scalar(1)); } /** \returns an expression of a fixed-size matrix or vector where all coefficients equal one. - * - * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you - * need to use the variants taking size arguments. - * - * Example: \include MatrixBase_ones.cpp - * Output: \verbinclude MatrixBase_ones.out - * - * \sa Ones(Index), Ones(Index,Index), isOnes(), class Ones - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType -DenseBase::Ones() -{ + * + * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you + * need to use the variants taking size arguments. + * + * Example: \include MatrixBase_ones.cpp + * Output: \verbinclude MatrixBase_ones.out + * + * \sa Ones(Index), Ones(Index,Index), isOnes(), class Ones + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType DenseBase::Ones() { return Constant(Scalar(1)); } /** \returns true if *this is approximately equal to the matrix where all coefficients - * are equal to 1, within the precision given by \a prec. - * - * Example: \include MatrixBase_isOnes.cpp - * Output: \verbinclude MatrixBase_isOnes.out - * - * \sa class CwiseNullaryOp, Ones() - */ -template -EIGEN_DEVICE_FUNC bool DenseBase::isOnes -(const RealScalar& prec) const -{ + * are equal to 1, within the precision given by \a prec. + * + * Example: \include MatrixBase_isOnes.cpp + * Output: \verbinclude MatrixBase_isOnes.out + * + * \sa class CwiseNullaryOp, Ones() + */ +template +EIGEN_DEVICE_FUNC bool DenseBase::isOnes(const RealScalar& prec) const { return isApproxToConstant(Scalar(1), prec); } /** Sets all coefficients in this expression to one. - * - * Example: \include MatrixBase_setOnes.cpp - * Output: \verbinclude MatrixBase_setOnes.out - * - * \sa class CwiseNullaryOp, Ones() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setOnes() -{ + * + * Example: \include MatrixBase_setOnes.cpp + * Output: \verbinclude MatrixBase_setOnes.out + * + * \sa class CwiseNullaryOp, Ones() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setOnes() { return setConstant(Scalar(1)); } /** Resizes to the given \a newSize, and sets all coefficients in this expression to one. - * - * \only_for_vectors - * - * Example: \include Matrix_setOnes_int.cpp - * Output: \verbinclude Matrix_setOnes_int.out - * - * \sa MatrixBase::setOnes(), setOnes(Index,Index), class CwiseNullaryOp, MatrixBase::Ones() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setOnes(Index newSize) -{ + * + * \only_for_vectors + * + * Example: \include Matrix_setOnes_int.cpp + * Output: \verbinclude Matrix_setOnes_int.out + * + * \sa MatrixBase::setOnes(), setOnes(Index,Index), class CwiseNullaryOp, MatrixBase::Ones() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& PlainObjectBase::setOnes(Index newSize) { resize(newSize); return setConstant(Scalar(1)); } /** Resizes to the given size, and sets all coefficients in this expression to one. - * - * \param rows the new number of rows - * \param cols the new number of columns - * - * Example: \include Matrix_setOnes_int_int.cpp - * Output: \verbinclude Matrix_setOnes_int_int.out - * - * \sa MatrixBase::setOnes(), setOnes(Index), class CwiseNullaryOp, MatrixBase::Ones() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setOnes(Index rows, Index cols) -{ + * + * \param rows the new number of rows + * \param cols the new number of columns + * + * Example: \include Matrix_setOnes_int_int.cpp + * Output: \verbinclude Matrix_setOnes_int_int.out + * + * \sa MatrixBase::setOnes(), setOnes(Index), class CwiseNullaryOp, MatrixBase::Ones() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& PlainObjectBase::setOnes(Index rows, Index cols) { resize(rows, cols); return setConstant(Scalar(1)); } /** Resizes to the given size, changing only the number of rows, and sets all - * coefficients in this expression to one. For the parameter of type NoChange_t, - * just pass the special value \c NoChange. - * - * \sa MatrixBase::setOnes(), setOnes(Index), setOnes(Index, Index), setOnes(NoChange_t, Index), class CwiseNullaryOp, MatrixBase::Ones() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setOnes(Index rows, NoChange_t) -{ + * coefficients in this expression to one. For the parameter of type NoChange_t, + * just pass the special value \c NoChange. + * + * \sa MatrixBase::setOnes(), setOnes(Index), setOnes(Index, Index), setOnes(NoChange_t, Index), class CwiseNullaryOp, + * MatrixBase::Ones() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& PlainObjectBase::setOnes(Index rows, NoChange_t) { return setOnes(rows, cols()); } /** Resizes to the given size, changing only the number of columns, and sets all - * coefficients in this expression to one. For the parameter of type NoChange_t, - * just pass the special value \c NoChange. - * - * \sa MatrixBase::setOnes(), setOnes(Index), setOnes(Index, Index), setOnes(Index, NoChange_t) class CwiseNullaryOp, MatrixBase::Ones() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setOnes(NoChange_t, Index cols) -{ + * coefficients in this expression to one. For the parameter of type NoChange_t, + * just pass the special value \c NoChange. + * + * \sa MatrixBase::setOnes(), setOnes(Index), setOnes(Index, Index), setOnes(Index, NoChange_t) class CwiseNullaryOp, + * MatrixBase::Ones() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& PlainObjectBase::setOnes(NoChange_t, Index cols) { return setOnes(rows(), cols); } // Identity: /** \returns an expression of the identity matrix (not necessarily square). - * - * The parameters \a rows and \a cols are the number of rows and of columns of - * the returned matrix. Must be compatible with this MatrixBase type. - * - * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, - * it is redundant to pass \a rows and \a cols as arguments, so Identity() should be used - * instead. - * - * Example: \include MatrixBase_identity_int_int.cpp - * Output: \verbinclude MatrixBase_identity_int_int.out - * - * \sa Identity(), setIdentity(), isIdentity() - */ -template + * + * The parameters \a rows and \a cols are the number of rows and of columns of + * the returned matrix. Must be compatible with this MatrixBase type. + * + * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, + * it is redundant to pass \a rows and \a cols as arguments, so Identity() should be used + * instead. + * + * Example: \include MatrixBase_identity_int_int.cpp + * Output: \verbinclude MatrixBase_identity_int_int.out + * + * \sa Identity(), setIdentity(), isIdentity() + */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::IdentityReturnType -MatrixBase::Identity(Index rows, Index cols) -{ +MatrixBase::Identity(Index rows, Index cols) { return DenseBase::NullaryExpr(rows, cols, internal::scalar_identity_op()); } /** \returns an expression of the identity matrix (not necessarily square). - * - * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you - * need to use the variant taking size arguments. - * - * Example: \include MatrixBase_identity.cpp - * Output: \verbinclude MatrixBase_identity.out - * - * \sa Identity(Index,Index), setIdentity(), isIdentity() - */ -template + * + * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you + * need to use the variant taking size arguments. + * + * Example: \include MatrixBase_identity.cpp + * Output: \verbinclude MatrixBase_identity.out + * + * \sa Identity(Index,Index), setIdentity(), isIdentity() + */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::IdentityReturnType -MatrixBase::Identity() -{ +MatrixBase::Identity() { EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) return MatrixBase::NullaryExpr(RowsAtCompileTime, ColsAtCompileTime, internal::scalar_identity_op()); } /** \returns true if *this is approximately equal to the identity matrix - * (not necessarily square), - * within the precision given by \a prec. - * - * Example: \include MatrixBase_isIdentity.cpp - * Output: \verbinclude MatrixBase_isIdentity.out - * - * \sa class CwiseNullaryOp, Identity(), Identity(Index,Index), setIdentity() - */ -template -bool MatrixBase::isIdentity -(const RealScalar& prec) const -{ - typename internal::nested_eval::type self(derived()); - for(Index j = 0; j < cols(); ++j) - { - for(Index i = 0; i < rows(); ++i) - { - if(i == j) - { - if(!internal::isApprox(self.coeff(i, j), static_cast(1), prec)) - return false; - } - else - { - if(!internal::isMuchSmallerThan(self.coeff(i, j), static_cast(1), prec)) - return false; + * (not necessarily square), + * within the precision given by \a prec. + * + * Example: \include MatrixBase_isIdentity.cpp + * Output: \verbinclude MatrixBase_isIdentity.out + * + * \sa class CwiseNullaryOp, Identity(), Identity(Index,Index), setIdentity() + */ +template +bool MatrixBase::isIdentity(const RealScalar& prec) const { + typename internal::nested_eval::type self(derived()); + for (Index j = 0; j < cols(); ++j) { + for (Index i = 0; i < rows(); ++i) { + if (i == j) { + if (!internal::isApprox(self.coeff(i, j), static_cast(1), prec)) return false; + } else { + if (!internal::isMuchSmallerThan(self.coeff(i, j), static_cast(1), prec)) return false; } } } @@ -837,165 +809,163 @@ bool MatrixBase::isIdentity namespace internal { -template=16)> -struct setIdentity_impl -{ - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE Derived& run(Derived& m) - { +template = 16)> +struct setIdentity_impl { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Derived& run(Derived& m) { return m = Derived::Identity(m.rows(), m.cols()); } }; -template -struct setIdentity_impl -{ - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE Derived& run(Derived& m) - { +template +struct setIdentity_impl { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Derived& run(Derived& m) { m.setZero(); const Index size = numext::mini(m.rows(), m.cols()); - for(Index i = 0; i < size; ++i) m.coeffRef(i,i) = typename Derived::Scalar(1); + for (Index i = 0; i < size; ++i) m.coeffRef(i, i) = typename Derived::Scalar(1); return m; } }; -} // end namespace internal +} // end namespace internal /** Writes the identity expression (not necessarily square) into *this. - * - * Example: \include MatrixBase_setIdentity.cpp - * Output: \verbinclude MatrixBase_setIdentity.out - * - * \sa class CwiseNullaryOp, Identity(), Identity(Index,Index), isIdentity() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::setIdentity() -{ + * + * Example: \include MatrixBase_setIdentity.cpp + * Output: \verbinclude MatrixBase_setIdentity.out + * + * \sa class CwiseNullaryOp, Identity(), Identity(Index,Index), isIdentity() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::setIdentity() { return internal::setIdentity_impl::run(derived()); } /** \brief Resizes to the given size, and writes the identity expression (not necessarily square) into *this. - * - * \param rows the new number of rows - * \param cols the new number of columns - * - * Example: \include Matrix_setIdentity_int_int.cpp - * Output: \verbinclude Matrix_setIdentity_int_int.out - * - * \sa MatrixBase::setIdentity(), class CwiseNullaryOp, MatrixBase::Identity() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::setIdentity(Index rows, Index cols) -{ + * + * \param rows the new number of rows + * \param cols the new number of columns + * + * Example: \include Matrix_setIdentity_int_int.cpp + * Output: \verbinclude Matrix_setIdentity_int_int.out + * + * \sa MatrixBase::setIdentity(), class CwiseNullaryOp, MatrixBase::Identity() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::setIdentity(Index rows, Index cols) { derived().resize(rows, cols); return setIdentity(); } /** \returns an expression of the i-th unit (basis) vector. - * - * \only_for_vectors - * - * \sa MatrixBase::Unit(Index), MatrixBase::UnitX(), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::Unit(Index newSize, Index i) -{ + * + * \only_for_vectors + * + * \sa MatrixBase::Unit(Index), MatrixBase::UnitX(), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::Unit( + Index newSize, Index i) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) - return BasisReturnType(SquareMatrixType::Identity(newSize,newSize), i); + return BasisReturnType(SquareMatrixType::Identity(newSize, newSize), i); } /** \returns an expression of the i-th unit (basis) vector. - * - * \only_for_vectors - * - * This variant is for fixed-size vector only. - * - * \sa MatrixBase::Unit(Index,Index), MatrixBase::UnitX(), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::Unit(Index i) -{ + * + * \only_for_vectors + * + * This variant is for fixed-size vector only. + * + * \sa MatrixBase::Unit(Index,Index), MatrixBase::UnitX(), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::Unit( + Index i) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) - return BasisReturnType(SquareMatrixType::Identity(),i); + return BasisReturnType(SquareMatrixType::Identity(), i); } /** \returns an expression of the X axis unit vector (1{,0}^*) - * - * \only_for_vectors - * - * \sa MatrixBase::Unit(Index,Index), MatrixBase::Unit(Index), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::UnitX() -{ return Derived::Unit(0); } + * + * \only_for_vectors + * + * \sa MatrixBase::Unit(Index,Index), MatrixBase::Unit(Index), MatrixBase::UnitY(), MatrixBase::UnitZ(), + * MatrixBase::UnitW() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::UnitX() { + return Derived::Unit(0); +} /** \returns an expression of the Y axis unit vector (0,1{,0}^*) - * - * \only_for_vectors - * - * \sa MatrixBase::Unit(Index,Index), MatrixBase::Unit(Index), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::UnitY() -{ return Derived::Unit(1); } + * + * \only_for_vectors + * + * \sa MatrixBase::Unit(Index,Index), MatrixBase::Unit(Index), MatrixBase::UnitY(), MatrixBase::UnitZ(), + * MatrixBase::UnitW() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::UnitY() { + return Derived::Unit(1); +} /** \returns an expression of the Z axis unit vector (0,0,1{,0}^*) - * - * \only_for_vectors - * - * \sa MatrixBase::Unit(Index,Index), MatrixBase::Unit(Index), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::UnitZ() -{ return Derived::Unit(2); } + * + * \only_for_vectors + * + * \sa MatrixBase::Unit(Index,Index), MatrixBase::Unit(Index), MatrixBase::UnitY(), MatrixBase::UnitZ(), + * MatrixBase::UnitW() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::UnitZ() { + return Derived::Unit(2); +} /** \returns an expression of the W axis unit vector (0,0,0,1) - * - * \only_for_vectors - * - * \sa MatrixBase::Unit(Index,Index), MatrixBase::Unit(Index), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::UnitW() -{ return Derived::Unit(3); } + * + * \only_for_vectors + * + * \sa MatrixBase::Unit(Index,Index), MatrixBase::Unit(Index), MatrixBase::UnitY(), MatrixBase::UnitZ(), + * MatrixBase::UnitW() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::UnitW() { + return Derived::Unit(3); +} /** \brief Set the coefficients of \c *this to the i-th unit (basis) vector - * - * \param i index of the unique coefficient to be set to 1 - * - * \only_for_vectors - * - * \sa MatrixBase::setIdentity(), class CwiseNullaryOp, MatrixBase::Unit(Index,Index) - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::setUnit(Index i) -{ + * + * \param i index of the unique coefficient to be set to 1 + * + * \only_for_vectors + * + * \sa MatrixBase::setIdentity(), class CwiseNullaryOp, MatrixBase::Unit(Index,Index) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::setUnit(Index i) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived); - eigen_assert(i -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::setUnit(Index newSize, Index i) -{ + * + * \param newSize the new size of the vector + * \param i index of the unique coefficient to be set to 1 + * + * \only_for_vectors + * + * \sa MatrixBase::setIdentity(), class CwiseNullaryOp, MatrixBase::Unit(Index,Index) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::setUnit(Index newSize, Index i) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived); - eigen_assert(i -struct traits > { +struct traits> { // we must not inherit from traits since it has // the potential to cause problems with MSVC - typedef typename remove_all::type Ancestor; + typedef remove_all_t Ancestor; typedef typename traits::XprKind XprKind; enum { RowsAtCompileTime = traits::RowsAtCompileTime, @@ -31,9 +34,8 @@ struct traits > { // even though we require Arg1, Arg2, and Arg3 to have the same scalar type // (see CwiseTernaryOp constructor), // we still want to handle the case when the result type is different. - typedef typename result_of::type Scalar; + typedef typename result_of::type Scalar; typedef typename internal::traits::StorageKind StorageKind; typedef typename internal::traits::StorageIndex StorageIndex; @@ -41,138 +43,114 @@ struct traits > { typedef typename Arg1::Nested Arg1Nested; typedef typename Arg2::Nested Arg2Nested; typedef typename Arg3::Nested Arg3Nested; - typedef typename remove_reference::type _Arg1Nested; - typedef typename remove_reference::type _Arg2Nested; - typedef typename remove_reference::type _Arg3Nested; - enum { Flags = _Arg1Nested::Flags & RowMajorBit }; + typedef std::remove_reference_t Arg1Nested_; + typedef std::remove_reference_t Arg2Nested_; + typedef std::remove_reference_t Arg3Nested_; + enum { Flags = Arg1Nested_::Flags & RowMajorBit }; }; } // end namespace internal -template +template class CwiseTernaryOpImpl; /** \class CwiseTernaryOp - * \ingroup Core_Module - * - * \brief Generic expression where a coefficient-wise ternary operator is + * \ingroup Core_Module + * + * \brief Generic expression where a coefficient-wise ternary operator is * applied to two expressions - * - * \tparam TernaryOp template functor implementing the operator - * \tparam Arg1Type the type of the first argument - * \tparam Arg2Type the type of the second argument - * \tparam Arg3Type the type of the third argument - * - * This class represents an expression where a coefficient-wise ternary + * + * \tparam TernaryOp template functor implementing the operator + * \tparam Arg1Type the type of the first argument + * \tparam Arg2Type the type of the second argument + * \tparam Arg3Type the type of the third argument + * + * This class represents an expression where a coefficient-wise ternary * operator is applied to three expressions. - * It is the return type of ternary operators, by which we mean only those + * It is the return type of ternary operators, by which we mean only those * ternary operators where - * all three arguments are Eigen expressions. - * For example, the return type of betainc(matrix1, matrix2, matrix3) is a + * all three arguments are Eigen expressions. + * For example, the return type of betainc(matrix1, matrix2, matrix3) is a * CwiseTernaryOp. - * - * Most of the time, this is the only way that it is used, so you typically + * + * Most of the time, this is the only way that it is used, so you typically * don't have to name - * CwiseTernaryOp types explicitly. - * - * \sa MatrixBase::ternaryExpr(const MatrixBase &, const + * CwiseTernaryOp types explicitly. + * + * \sa MatrixBase::ternaryExpr(const MatrixBase &, const * MatrixBase &, const CustomTernaryOp &) const, class CwiseBinaryOp, * class CwiseUnaryOp, class CwiseNullaryOp - */ -template -class CwiseTernaryOp : public CwiseTernaryOpImpl< - TernaryOp, Arg1Type, Arg2Type, Arg3Type, - typename internal::traits::StorageKind>, - internal::no_assignment_operator -{ + */ +template +class CwiseTernaryOp : public CwiseTernaryOpImpl::StorageKind>, + internal::no_assignment_operator { public: - typedef typename internal::remove_all::type Arg1; - typedef typename internal::remove_all::type Arg2; - typedef typename internal::remove_all::type Arg3; - - typedef typename CwiseTernaryOpImpl< - TernaryOp, Arg1Type, Arg2Type, Arg3Type, - typename internal::traits::StorageKind>::Base Base; + typedef internal::remove_all_t Arg1; + typedef internal::remove_all_t Arg2; + typedef internal::remove_all_t Arg3; + + // require the sizes to match + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Arg1, Arg2) + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Arg1, Arg3) + + // The index types should match + EIGEN_STATIC_ASSERT((internal::is_same::StorageKind, + typename internal::traits::StorageKind>::value), + STORAGE_KIND_MUST_MATCH) + EIGEN_STATIC_ASSERT((internal::is_same::StorageKind, + typename internal::traits::StorageKind>::value), + STORAGE_KIND_MUST_MATCH) + + typedef typename CwiseTernaryOpImpl::StorageKind>::Base Base; EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseTernaryOp) typedef typename internal::ref_selector::type Arg1Nested; typedef typename internal::ref_selector::type Arg2Nested; typedef typename internal::ref_selector::type Arg3Nested; - typedef typename internal::remove_reference::type _Arg1Nested; - typedef typename internal::remove_reference::type _Arg2Nested; - typedef typename internal::remove_reference::type _Arg3Nested; - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE CwiseTernaryOp(const Arg1& a1, const Arg2& a2, - const Arg3& a3, - const TernaryOp& func = TernaryOp()) + typedef std::remove_reference_t Arg1Nested_; + typedef std::remove_reference_t Arg2Nested_; + typedef std::remove_reference_t Arg3Nested_; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CwiseTernaryOp(const Arg1& a1, const Arg2& a2, const Arg3& a3, + const TernaryOp& func = TernaryOp()) : m_arg1(a1), m_arg2(a2), m_arg3(a3), m_functor(func) { - // require the sizes to match - EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Arg1, Arg2) - EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Arg1, Arg3) - - // The index types should match - EIGEN_STATIC_ASSERT((internal::is_same< - typename internal::traits::StorageKind, - typename internal::traits::StorageKind>::value), - STORAGE_KIND_MUST_MATCH) - EIGEN_STATIC_ASSERT((internal::is_same< - typename internal::traits::StorageKind, - typename internal::traits::StorageKind>::value), - STORAGE_KIND_MUST_MATCH) - - eigen_assert(a1.rows() == a2.rows() && a1.cols() == a2.cols() && - a1.rows() == a3.rows() && a1.cols() == a3.cols()); + eigen_assert(a1.rows() == a2.rows() && a1.cols() == a2.cols() && a1.rows() == a3.rows() && a1.cols() == a3.cols()); } - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Index rows() const { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rows() const { // return the fixed size type if available to enable compile time // optimizations - if (internal::traits::type>:: - RowsAtCompileTime == Dynamic && - internal::traits::type>:: - RowsAtCompileTime == Dynamic) + if (internal::traits>::RowsAtCompileTime == Dynamic && + internal::traits>::RowsAtCompileTime == Dynamic) return m_arg3.rows(); - else if (internal::traits::type>:: - RowsAtCompileTime == Dynamic && - internal::traits::type>:: - RowsAtCompileTime == Dynamic) + else if (internal::traits>::RowsAtCompileTime == Dynamic && + internal::traits>::RowsAtCompileTime == Dynamic) return m_arg2.rows(); else return m_arg1.rows(); } - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Index cols() const { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index cols() const { // return the fixed size type if available to enable compile time // optimizations - if (internal::traits::type>:: - ColsAtCompileTime == Dynamic && - internal::traits::type>:: - ColsAtCompileTime == Dynamic) + if (internal::traits>::ColsAtCompileTime == Dynamic && + internal::traits>::ColsAtCompileTime == Dynamic) return m_arg3.cols(); - else if (internal::traits::type>:: - ColsAtCompileTime == Dynamic && - internal::traits::type>:: - ColsAtCompileTime == Dynamic) + else if (internal::traits>::ColsAtCompileTime == Dynamic && + internal::traits>::ColsAtCompileTime == Dynamic) return m_arg2.cols(); else return m_arg1.cols(); } /** \returns the first argument nested expression */ - EIGEN_DEVICE_FUNC - const _Arg1Nested& arg1() const { return m_arg1; } + EIGEN_DEVICE_FUNC const Arg1Nested_& arg1() const { return m_arg1; } /** \returns the first argument nested expression */ - EIGEN_DEVICE_FUNC - const _Arg2Nested& arg2() const { return m_arg2; } + EIGEN_DEVICE_FUNC const Arg2Nested_& arg2() const { return m_arg2; } /** \returns the third argument nested expression */ - EIGEN_DEVICE_FUNC - const _Arg3Nested& arg3() const { return m_arg3; } + EIGEN_DEVICE_FUNC const Arg3Nested_& arg3() const { return m_arg3; } /** \returns the functor representing the ternary operation */ - EIGEN_DEVICE_FUNC - const TernaryOp& functor() const { return m_functor; } + EIGEN_DEVICE_FUNC const TernaryOp& functor() const { return m_functor; } protected: Arg1Nested m_arg1; @@ -182,14 +160,10 @@ class CwiseTernaryOp : public CwiseTernaryOpImpl< }; // Generic API dispatcher -template -class CwiseTernaryOpImpl - : public internal::generic_xpr_base< - CwiseTernaryOp >::type { +template +class CwiseTernaryOpImpl : public internal::generic_xpr_base>::type { public: - typedef typename internal::generic_xpr_base< - CwiseTernaryOp >::type Base; + typedef typename internal::generic_xpr_base>::type Base; }; } // end namespace Eigen diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseUnaryOp.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseUnaryOp.h index e68c4f74808..42ed459a0f0 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseUnaryOp.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseUnaryOp.h @@ -11,93 +11,81 @@ #ifndef EIGEN_CWISE_UNARY_OP_H #define EIGEN_CWISE_UNARY_OP_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > - : traits -{ - typedef typename result_of< - UnaryOp(const typename XprType::Scalar&) - >::type Scalar; +template +struct traits > : traits { + typedef typename result_of::type Scalar; typedef typename XprType::Nested XprTypeNested; - typedef typename remove_reference::type _XprTypeNested; - enum { - Flags = _XprTypeNested::Flags & RowMajorBit - }; + typedef std::remove_reference_t XprTypeNested_; + enum { Flags = XprTypeNested_::Flags & RowMajorBit }; }; -} +} // namespace internal -template +template class CwiseUnaryOpImpl; /** \class CwiseUnaryOp - * \ingroup Core_Module - * - * \brief Generic expression where a coefficient-wise unary operator is applied to an expression - * - * \tparam UnaryOp template functor implementing the operator - * \tparam XprType the type of the expression to which we are applying the unary operator - * - * This class represents an expression where a unary operator is applied to an expression. - * It is the return type of all operations taking exactly 1 input expression, regardless of the - * presence of other inputs such as scalars. For example, the operator* in the expression 3*matrix - * is considered unary, because only the right-hand side is an expression, and its - * return type is a specialization of CwiseUnaryOp. - * - * Most of the time, this is the only way that it is used, so you typically don't have to name - * CwiseUnaryOp types explicitly. - * - * \sa MatrixBase::unaryExpr(const CustomUnaryOp &) const, class CwiseBinaryOp, class CwiseNullaryOp - */ -template -class CwiseUnaryOp : public CwiseUnaryOpImpl::StorageKind>, internal::no_assignment_operator -{ - public: - - typedef typename CwiseUnaryOpImpl::StorageKind>::Base Base; - EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseUnaryOp) - typedef typename internal::ref_selector::type XprTypeNested; - typedef typename internal::remove_all::type NestedExpression; + * \ingroup Core_Module + * + * \brief Generic expression where a coefficient-wise unary operator is applied to an expression + * + * \tparam UnaryOp template functor implementing the operator + * \tparam XprType the type of the expression to which we are applying the unary operator + * + * This class represents an expression where a unary operator is applied to an expression. + * It is the return type of all operations taking exactly 1 input expression, regardless of the + * presence of other inputs such as scalars. For example, the operator* in the expression 3*matrix + * is considered unary, because only the right-hand side is an expression, and its + * return type is a specialization of CwiseUnaryOp. + * + * Most of the time, this is the only way that it is used, so you typically don't have to name + * CwiseUnaryOp types explicitly. + * + * \sa MatrixBase::unaryExpr(const CustomUnaryOp &) const, class CwiseBinaryOp, class CwiseNullaryOp + */ +template +class CwiseUnaryOp : public CwiseUnaryOpImpl::StorageKind>, + internal::no_assignment_operator { + public: + typedef typename CwiseUnaryOpImpl::StorageKind>::Base Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseUnaryOp) + typedef typename internal::ref_selector::type XprTypeNested; + typedef internal::remove_all_t NestedExpression; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit CwiseUnaryOp(const XprType& xpr, const UnaryOp& func = UnaryOp()) + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit CwiseUnaryOp(const XprType& xpr, const UnaryOp& func = UnaryOp()) : m_xpr(xpr), m_functor(func) {} - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index rows() const EIGEN_NOEXCEPT { return m_xpr.rows(); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index cols() const EIGEN_NOEXCEPT { return m_xpr.cols(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_xpr.rows(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_xpr.cols(); } - /** \returns the functor representing the unary operation */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const UnaryOp& functor() const { return m_functor; } + /** \returns the functor representing the unary operation */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const UnaryOp& functor() const { return m_functor; } - /** \returns the nested expression */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const typename internal::remove_all::type& - nestedExpression() const { return m_xpr; } + /** \returns the nested expression */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const internal::remove_all_t& nestedExpression() const { + return m_xpr; + } - /** \returns the nested expression */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - typename internal::remove_all::type& - nestedExpression() { return m_xpr; } + /** \returns the nested expression */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::remove_all_t& nestedExpression() { return m_xpr; } - protected: - XprTypeNested m_xpr; - const UnaryOp m_functor; + protected: + XprTypeNested m_xpr; + const UnaryOp m_functor; }; // Generic API dispatcher -template -class CwiseUnaryOpImpl - : public internal::generic_xpr_base >::type -{ -public: +template +class CwiseUnaryOpImpl : public internal::generic_xpr_base >::type { + public: typedef typename internal::generic_xpr_base >::type Base; }; -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_CWISE_UNARY_OP_H +#endif // EIGEN_CWISE_UNARY_OP_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseUnaryView.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseUnaryView.h index a06d7621ec1..49b14101115 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseUnaryView.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/CwiseUnaryView.h @@ -10,123 +10,158 @@ #ifndef EIGEN_CWISE_UNARY_VIEW_H #define EIGEN_CWISE_UNARY_VIEW_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > - : traits -{ - typedef typename result_of< - ViewOp(const typename traits::Scalar&) - >::type Scalar; +template +struct traits > : traits { + typedef typename result_of::Scalar&)>::type1 ScalarRef; + static_assert(std::is_reference::value, "Views must return a reference type."); + typedef remove_all_t Scalar; typedef typename MatrixType::Nested MatrixTypeNested; - typedef typename remove_all::type _MatrixTypeNested; + typedef remove_all_t MatrixTypeNested_; enum { FlagsLvalueBit = is_lvalue::value ? LvalueBit : 0, - Flags = traits<_MatrixTypeNested>::Flags & (RowMajorBit | FlagsLvalueBit | DirectAccessBit), // FIXME DirectAccessBit should not be handled by expressions - MatrixTypeInnerStride = inner_stride_at_compile_time::ret, + Flags = + traits::Flags & + (RowMajorBit | FlagsLvalueBit | DirectAccessBit), // FIXME DirectAccessBit should not be handled by expressions + MatrixTypeInnerStride = inner_stride_at_compile_time::ret, // need to cast the sizeof's from size_t to int explicitly, otherwise: // "error: no integral type can represent all of the enumerator values - InnerStrideAtCompileTime = MatrixTypeInnerStride == Dynamic - ? int(Dynamic) - : int(MatrixTypeInnerStride) * int(sizeof(typename traits::Scalar) / sizeof(Scalar)), - OuterStrideAtCompileTime = outer_stride_at_compile_time::ret == Dynamic - ? int(Dynamic) - : outer_stride_at_compile_time::ret * int(sizeof(typename traits::Scalar) / sizeof(Scalar)) + InnerStrideAtCompileTime = + StrideType::InnerStrideAtCompileTime == 0 + ? (MatrixTypeInnerStride == Dynamic + ? int(Dynamic) + : int(MatrixTypeInnerStride) * int(sizeof(typename traits::Scalar) / sizeof(Scalar))) + : int(StrideType::InnerStrideAtCompileTime), + + OuterStrideAtCompileTime = StrideType::OuterStrideAtCompileTime == 0 + ? (outer_stride_at_compile_time::ret == Dynamic + ? int(Dynamic) + : outer_stride_at_compile_time::ret * + int(sizeof(typename traits::Scalar) / sizeof(Scalar))) + : int(StrideType::OuterStrideAtCompileTime) }; }; -} - -template -class CwiseUnaryViewImpl; -/** \class CwiseUnaryView - * \ingroup Core_Module - * - * \brief Generic lvalue expression of a coefficient-wise unary operator of a matrix or a vector - * - * \tparam ViewOp template functor implementing the view - * \tparam MatrixType the type of the matrix we are applying the unary operator - * - * This class represents a lvalue expression of a generic unary view operator of a matrix or a vector. - * It is the return type of real() and imag(), and most of the time this is the only way it is used. - * - * \sa MatrixBase::unaryViewExpr(const CustomUnaryOp &) const, class CwiseUnaryOp - */ -template -class CwiseUnaryView : public CwiseUnaryViewImpl::StorageKind> -{ - public: - - typedef typename CwiseUnaryViewImpl::StorageKind>::Base Base; - EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseUnaryView) - typedef typename internal::ref_selector::non_const_type MatrixTypeNested; - typedef typename internal::remove_all::type NestedExpression; - - explicit EIGEN_DEVICE_FUNC inline CwiseUnaryView(MatrixType& mat, const ViewOp& func = ViewOp()) - : m_matrix(mat), m_functor(func) {} +// Generic API dispatcher +template ::value> +class CwiseUnaryViewImpl : public generic_xpr_base >::type { + public: + typedef typename generic_xpr_base >::type Base; +}; - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CwiseUnaryView) +template +class CwiseUnaryViewImpl + : public dense_xpr_base >::type { + public: + typedef CwiseUnaryView Derived; + typedef typename dense_xpr_base >::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Derived) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CwiseUnaryViewImpl) + + EIGEN_DEVICE_FUNC inline const Scalar* data() const { return &(this->coeffRef(0)); } + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const { + return StrideType::InnerStrideAtCompileTime != 0 ? int(StrideType::InnerStrideAtCompileTime) + : derived().nestedExpression().innerStride() * + sizeof(typename traits::Scalar) / sizeof(Scalar); + } + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const { + return StrideType::OuterStrideAtCompileTime != 0 ? int(StrideType::OuterStrideAtCompileTime) + : derived().nestedExpression().outerStride() * + sizeof(typename traits::Scalar) / sizeof(Scalar); + } + + protected: + EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(CwiseUnaryViewImpl) + + // Allow const access to coeffRef for the case of direct access being enabled. + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index index) const { + return internal::evaluator(derived()).coeffRef(index); + } + + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index row, Index col) const { + return internal::evaluator(derived()).coeffRef(row, col); + } +}; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index rows() const EIGEN_NOEXCEPT { return m_matrix.rows(); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index cols() const EIGEN_NOEXCEPT { return m_matrix.cols(); } +template +class CwiseUnaryViewImpl + : public CwiseUnaryViewImpl { + public: + typedef CwiseUnaryViewImpl Base; + typedef CwiseUnaryView Derived; + EIGEN_DENSE_PUBLIC_INTERFACE(Derived) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CwiseUnaryViewImpl) - /** \returns the functor representing unary operation */ - EIGEN_DEVICE_FUNC const ViewOp& functor() const { return m_functor; } + using Base::data; + EIGEN_DEVICE_FUNC inline Scalar* data() { return &(this->coeffRef(0)); } - /** \returns the nested expression */ - EIGEN_DEVICE_FUNC const typename internal::remove_all::type& - nestedExpression() const { return m_matrix; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col) { + return internal::evaluator(derived()).coeffRef(row, col); + } - /** \returns the nested expression */ - EIGEN_DEVICE_FUNC typename internal::remove_reference::type& - nestedExpression() { return m_matrix; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { + return internal::evaluator(derived()).coeffRef(index); + } - protected: - MatrixTypeNested m_matrix; - ViewOp m_functor; + protected: + EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(CwiseUnaryViewImpl) }; -// Generic API dispatcher -template -class CwiseUnaryViewImpl - : public internal::generic_xpr_base >::type -{ -public: - typedef typename internal::generic_xpr_base >::type Base; -}; +} // namespace internal + +/** \class CwiseUnaryView + * \ingroup Core_Module + * + * \brief Generic lvalue expression of a coefficient-wise unary operator of a matrix or a vector + * + * \tparam ViewOp template functor implementing the view + * \tparam MatrixType the type of the matrix we are applying the unary operator + * + * This class represents a lvalue expression of a generic unary view operator of a matrix or a vector. + * It is the return type of real() and imag(), and most of the time this is the only way it is used. + * + * \sa MatrixBase::unaryViewExpr(const CustomUnaryOp &) const, class CwiseUnaryOp + */ +template +class CwiseUnaryView : public internal::CwiseUnaryViewImpl::StorageKind> { + public: + typedef typename internal::CwiseUnaryViewImpl::StorageKind>::Base Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseUnaryView) + typedef typename internal::ref_selector::non_const_type MatrixTypeNested; + typedef internal::remove_all_t NestedExpression; + + explicit EIGEN_DEVICE_FUNC inline CwiseUnaryView(MatrixType& mat, const ViewOp& func = ViewOp()) + : m_matrix(mat), m_functor(func) {} -template -class CwiseUnaryViewImpl - : public internal::dense_xpr_base< CwiseUnaryView >::type -{ - public: + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CwiseUnaryView) - typedef CwiseUnaryView Derived; - typedef typename internal::dense_xpr_base< CwiseUnaryView >::type Base; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_matrix.rows(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_matrix.cols(); } - EIGEN_DENSE_PUBLIC_INTERFACE(Derived) - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CwiseUnaryViewImpl) + /** \returns the functor representing unary operation */ + EIGEN_DEVICE_FUNC const ViewOp& functor() const { return m_functor; } - EIGEN_DEVICE_FUNC inline Scalar* data() { return &(this->coeffRef(0)); } - EIGEN_DEVICE_FUNC inline const Scalar* data() const { return &(this->coeff(0)); } + /** \returns the nested expression */ + EIGEN_DEVICE_FUNC const internal::remove_all_t& nestedExpression() const { return m_matrix; } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const - { - return derived().nestedExpression().innerStride() * sizeof(typename internal::traits::Scalar) / sizeof(Scalar); - } + /** \returns the nested expression */ + EIGEN_DEVICE_FUNC std::remove_reference_t& nestedExpression() { return m_matrix; } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const - { - return derived().nestedExpression().outerStride() * sizeof(typename internal::traits::Scalar) / sizeof(Scalar); - } - protected: - EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(CwiseUnaryViewImpl) + protected: + MatrixTypeNested m_matrix; + ViewOp m_functor; }; -} // end namespace Eigen +} // namespace Eigen -#endif // EIGEN_CWISE_UNARY_VIEW_H +#endif // EIGEN_CWISE_UNARY_VIEW_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DenseBase.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DenseBase.h index 9b16db68d48..297c42679d9 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DenseBase.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DenseBase.h @@ -11,691 +11,635 @@ #ifndef EIGEN_DENSEBASE_H #define EIGEN_DENSEBASE_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" -namespace internal { +namespace Eigen { // The index type defined by EIGEN_DEFAULT_DENSE_INDEX_TYPE must be a signed type. -// This dummy function simply aims at checking that at compile time. -static inline void check_DenseIndex_is_signed() { - EIGEN_STATIC_ASSERT(NumTraits::IsSigned,THE_INDEX_TYPE_MUST_BE_A_SIGNED_TYPE) -} - -} // end namespace internal +EIGEN_STATIC_ASSERT(NumTraits::IsSigned, THE_INDEX_TYPE_MUST_BE_A_SIGNED_TYPE) /** \class DenseBase - * \ingroup Core_Module - * - * \brief Base class for all dense matrices, vectors, and arrays - * - * This class is the base that is inherited by all dense objects (matrix, vector, arrays, - * and related expression types). The common Eigen API for dense objects is contained in this class. - * - * \tparam Derived is the derived type, e.g., a matrix type or an expression. - * - * This class can be extended with the help of the plugin mechanism described on the page - * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_DENSEBASE_PLUGIN. - * - * \sa \blank \ref TopicClassHierarchy - */ -template class DenseBase + * \ingroup Core_Module + * + * \brief Base class for all dense matrices, vectors, and arrays + * + * This class is the base that is inherited by all dense objects (matrix, vector, arrays, + * and related expression types). The common Eigen API for dense objects is contained in this class. + * + * \tparam Derived is the derived type, e.g., a matrix type or an expression. + * + * This class can be extended with the help of the plugin mechanism described on the page + * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_DENSEBASE_PLUGIN. + * + * \sa \blank \ref TopicClassHierarchy + */ +template +class DenseBase #ifndef EIGEN_PARSED_BY_DOXYGEN - : public DenseCoeffsBase::value> + : public DenseCoeffsBase::value> #else - : public DenseCoeffsBase -#endif // not EIGEN_PARSED_BY_DOXYGEN + : public DenseCoeffsBase +#endif // not EIGEN_PARSED_BY_DOXYGEN { - public: + public: + /** Inner iterator type to iterate over the coefficients of a row or column. + * \sa class InnerIterator + */ + typedef Eigen::InnerIterator InnerIterator; + + typedef typename internal::traits::StorageKind StorageKind; + + /** + * \brief The type used to store indices + * \details This typedef is relevant for types that store multiple indices such as + * PermutationMatrix or Transpositions, otherwise it defaults to Eigen::Index + * \sa \blank \ref TopicPreprocessorDirectives, Eigen::Index, SparseMatrixBase. + */ + typedef typename internal::traits::StorageIndex StorageIndex; + + /** The numeric type of the expression' coefficients, e.g. float, double, int or std::complex, etc. */ + typedef typename internal::traits::Scalar Scalar; + + /** The numeric type of the expression' coefficients, e.g. float, double, int or std::complex, etc. + * + * It is an alias for the Scalar type */ + typedef Scalar value_type; + + typedef typename NumTraits::Real RealScalar; + typedef DenseCoeffsBase::value> Base; + + using Base::coeff; + using Base::coeffByOuterInner; + using Base::colIndexByOuterInner; + using Base::cols; + using Base::const_cast_derived; + using Base::derived; + using Base::rowIndexByOuterInner; + using Base::rows; + using Base::size; + using Base::operator(); + using Base::operator[]; + using Base::colStride; + using Base::innerStride; + using Base::outerStride; + using Base::rowStride; + using Base::stride; + using Base::w; + using Base::x; + using Base::y; + using Base::z; + typedef typename Base::CoeffReturnType CoeffReturnType; + + enum { + + RowsAtCompileTime = internal::traits::RowsAtCompileTime, + /**< The number of rows at compile-time. This is just a copy of the value provided + * by the \a Derived type. If a value is not known at compile-time, + * it is set to the \a Dynamic constant. + * \sa MatrixBase::rows(), MatrixBase::cols(), ColsAtCompileTime, SizeAtCompileTime */ + + ColsAtCompileTime = internal::traits::ColsAtCompileTime, + /**< The number of columns at compile-time. This is just a copy of the value provided + * by the \a Derived type. If a value is not known at compile-time, + * it is set to the \a Dynamic constant. + * \sa MatrixBase::rows(), MatrixBase::cols(), RowsAtCompileTime, SizeAtCompileTime */ + + SizeAtCompileTime = (internal::size_of_xpr_at_compile_time::ret), + /**< This is equal to the number of coefficients, i.e. the number of + * rows times the number of columns, or to \a Dynamic if this is not + * known at compile-time. \sa RowsAtCompileTime, ColsAtCompileTime */ + + MaxRowsAtCompileTime = internal::traits::MaxRowsAtCompileTime, + /**< This value is equal to the maximum possible number of rows that this expression + * might have. If this expression might have an arbitrarily high number of rows, + * this value is set to \a Dynamic. + * + * This value is useful to know when evaluating an expression, in order to determine + * whether it is possible to avoid doing a dynamic memory allocation. + * + * \sa RowsAtCompileTime, MaxColsAtCompileTime, MaxSizeAtCompileTime + */ - /** Inner iterator type to iterate over the coefficients of a row or column. - * \sa class InnerIterator - */ - typedef Eigen::InnerIterator InnerIterator; + MaxColsAtCompileTime = internal::traits::MaxColsAtCompileTime, + /**< This value is equal to the maximum possible number of columns that this expression + * might have. If this expression might have an arbitrarily high number of columns, + * this value is set to \a Dynamic. + * + * This value is useful to know when evaluating an expression, in order to determine + * whether it is possible to avoid doing a dynamic memory allocation. + * + * \sa ColsAtCompileTime, MaxRowsAtCompileTime, MaxSizeAtCompileTime + */ - typedef typename internal::traits::StorageKind StorageKind; + MaxSizeAtCompileTime = internal::size_at_compile_time(internal::traits::MaxRowsAtCompileTime, + internal::traits::MaxColsAtCompileTime), + /**< This value is equal to the maximum possible number of coefficients that this expression + * might have. If this expression might have an arbitrarily high number of coefficients, + * this value is set to \a Dynamic. + * + * This value is useful to know when evaluating an expression, in order to determine + * whether it is possible to avoid doing a dynamic memory allocation. + * + * \sa SizeAtCompileTime, MaxRowsAtCompileTime, MaxColsAtCompileTime + */ - /** - * \brief The type used to store indices - * \details This typedef is relevant for types that store multiple indices such as - * PermutationMatrix or Transpositions, otherwise it defaults to Eigen::Index - * \sa \blank \ref TopicPreprocessorDirectives, Eigen::Index, SparseMatrixBase. + IsVectorAtCompileTime = + internal::traits::RowsAtCompileTime == 1 || internal::traits::ColsAtCompileTime == 1, + /**< This is set to true if either the number of rows or the number of + * columns is known at compile-time to be equal to 1. Indeed, in that case, + * we are dealing with a column-vector (if there is only one column) or with + * a row-vector (if there is only one row). */ + + NumDimensions = int(MaxSizeAtCompileTime) == 1 ? 0 + : bool(IsVectorAtCompileTime) ? 1 + : 2, + /**< This value is equal to Tensor::NumDimensions, i.e. 0 for scalars, 1 for vectors, + * and 2 for matrices. */ - typedef typename internal::traits::StorageIndex StorageIndex; - - /** The numeric type of the expression' coefficients, e.g. float, double, int or std::complex, etc. */ - typedef typename internal::traits::Scalar Scalar; - - /** The numeric type of the expression' coefficients, e.g. float, double, int or std::complex, etc. - * - * It is an alias for the Scalar type */ - typedef Scalar value_type; - - typedef typename NumTraits::Real RealScalar; - typedef DenseCoeffsBase::value> Base; - - using Base::derived; - using Base::const_cast_derived; - using Base::rows; - using Base::cols; - using Base::size; - using Base::rowIndexByOuterInner; - using Base::colIndexByOuterInner; - using Base::coeff; - using Base::coeffByOuterInner; - using Base::operator(); - using Base::operator[]; - using Base::x; - using Base::y; - using Base::z; - using Base::w; - using Base::stride; - using Base::innerStride; - using Base::outerStride; - using Base::rowStride; - using Base::colStride; - typedef typename Base::CoeffReturnType CoeffReturnType; - - enum { - - RowsAtCompileTime = internal::traits::RowsAtCompileTime, - /**< The number of rows at compile-time. This is just a copy of the value provided - * by the \a Derived type. If a value is not known at compile-time, - * it is set to the \a Dynamic constant. - * \sa MatrixBase::rows(), MatrixBase::cols(), ColsAtCompileTime, SizeAtCompileTime */ - - ColsAtCompileTime = internal::traits::ColsAtCompileTime, - /**< The number of columns at compile-time. This is just a copy of the value provided - * by the \a Derived type. If a value is not known at compile-time, - * it is set to the \a Dynamic constant. - * \sa MatrixBase::rows(), MatrixBase::cols(), RowsAtCompileTime, SizeAtCompileTime */ - - - SizeAtCompileTime = (internal::size_at_compile_time::RowsAtCompileTime, - internal::traits::ColsAtCompileTime>::ret), - /**< This is equal to the number of coefficients, i.e. the number of - * rows times the number of columns, or to \a Dynamic if this is not - * known at compile-time. \sa RowsAtCompileTime, ColsAtCompileTime */ - - MaxRowsAtCompileTime = internal::traits::MaxRowsAtCompileTime, - /**< This value is equal to the maximum possible number of rows that this expression - * might have. If this expression might have an arbitrarily high number of rows, - * this value is set to \a Dynamic. - * - * This value is useful to know when evaluating an expression, in order to determine - * whether it is possible to avoid doing a dynamic memory allocation. - * - * \sa RowsAtCompileTime, MaxColsAtCompileTime, MaxSizeAtCompileTime - */ - - MaxColsAtCompileTime = internal::traits::MaxColsAtCompileTime, - /**< This value is equal to the maximum possible number of columns that this expression - * might have. If this expression might have an arbitrarily high number of columns, - * this value is set to \a Dynamic. - * - * This value is useful to know when evaluating an expression, in order to determine - * whether it is possible to avoid doing a dynamic memory allocation. - * - * \sa ColsAtCompileTime, MaxRowsAtCompileTime, MaxSizeAtCompileTime - */ - - MaxSizeAtCompileTime = (internal::size_at_compile_time::MaxRowsAtCompileTime, - internal::traits::MaxColsAtCompileTime>::ret), - /**< This value is equal to the maximum possible number of coefficients that this expression - * might have. If this expression might have an arbitrarily high number of coefficients, - * this value is set to \a Dynamic. - * - * This value is useful to know when evaluating an expression, in order to determine - * whether it is possible to avoid doing a dynamic memory allocation. - * - * \sa SizeAtCompileTime, MaxRowsAtCompileTime, MaxColsAtCompileTime - */ - - IsVectorAtCompileTime = internal::traits::RowsAtCompileTime == 1 - || internal::traits::ColsAtCompileTime == 1, - /**< This is set to true if either the number of rows or the number of - * columns is known at compile-time to be equal to 1. Indeed, in that case, - * we are dealing with a column-vector (if there is only one column) or with - * a row-vector (if there is only one row). */ - - NumDimensions = int(MaxSizeAtCompileTime) == 1 ? 0 : bool(IsVectorAtCompileTime) ? 1 : 2, - /**< This value is equal to Tensor::NumDimensions, i.e. 0 for scalars, 1 for vectors, - * and 2 for matrices. - */ - - Flags = internal::traits::Flags, - /**< This stores expression \ref flags flags which may or may not be inherited by new expressions - * constructed from this one. See the \ref flags "list of flags". - */ - - IsRowMajor = int(Flags) & RowMajorBit, /**< True if this expression has row-major storage order. */ - - InnerSizeAtCompileTime = int(IsVectorAtCompileTime) ? int(SizeAtCompileTime) - : int(IsRowMajor) ? int(ColsAtCompileTime) : int(RowsAtCompileTime), - - InnerStrideAtCompileTime = internal::inner_stride_at_compile_time::ret, - OuterStrideAtCompileTime = internal::outer_stride_at_compile_time::ret - }; - - typedef typename internal::find_best_packet::type PacketScalar; - - enum { IsPlainObjectBase = 0 }; - - /** The plain matrix type corresponding to this expression. - * \sa PlainObject */ - typedef Matrix::Scalar, - internal::traits::RowsAtCompileTime, - internal::traits::ColsAtCompileTime, - AutoAlign | (internal::traits::Flags&RowMajorBit ? RowMajor : ColMajor), - internal::traits::MaxRowsAtCompileTime, - internal::traits::MaxColsAtCompileTime - > PlainMatrix; - - /** The plain array type corresponding to this expression. - * \sa PlainObject */ - typedef Array::Scalar, - internal::traits::RowsAtCompileTime, + + Flags = internal::traits::Flags, + /**< This stores expression \ref flags flags which may or may not be inherited by new expressions + * constructed from this one. See the \ref flags "list of flags". + */ + + IsRowMajor = int(Flags) & RowMajorBit, /**< True if this expression has row-major storage order. */ + + InnerSizeAtCompileTime = int(IsVectorAtCompileTime) ? int(SizeAtCompileTime) + : int(IsRowMajor) ? int(ColsAtCompileTime) + : int(RowsAtCompileTime), + + InnerStrideAtCompileTime = internal::inner_stride_at_compile_time::ret, + OuterStrideAtCompileTime = internal::outer_stride_at_compile_time::ret + }; + + typedef typename internal::find_best_packet::type PacketScalar; + + enum { IsPlainObjectBase = 0 }; + + /** The plain matrix type corresponding to this expression. + * \sa PlainObject */ + typedef Matrix::Scalar, internal::traits::RowsAtCompileTime, + internal::traits::ColsAtCompileTime, + AutoAlign | (internal::traits::Flags & RowMajorBit ? RowMajor : ColMajor), + internal::traits::MaxRowsAtCompileTime, internal::traits::MaxColsAtCompileTime> + PlainMatrix; + + /** The plain array type corresponding to this expression. + * \sa PlainObject */ + typedef Array::Scalar, internal::traits::RowsAtCompileTime, internal::traits::ColsAtCompileTime, - AutoAlign | (internal::traits::Flags&RowMajorBit ? RowMajor : ColMajor), - internal::traits::MaxRowsAtCompileTime, - internal::traits::MaxColsAtCompileTime - > PlainArray; - - /** \brief The plain matrix or array type corresponding to this expression. - * - * This is not necessarily exactly the return type of eval(). In the case of plain matrices, - * the return type of eval() is a const reference to a matrix, not a matrix! It is however guaranteed - * that the return type of eval() is either PlainObject or const PlainObject&. - */ - typedef typename internal::conditional::XprKind,MatrixXpr >::value, - PlainMatrix, PlainArray>::type PlainObject; - - /** \returns the number of nonzero coefficients which is in practice the number - * of stored coefficients. */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index nonZeros() const { return size(); } - - /** \returns the outer size. - * - * \note For a vector, this returns just 1. For a matrix (non-vector), this is the major dimension - * with respect to the \ref TopicStorageOrders "storage order", i.e., the number of columns for a - * column-major matrix, and the number of rows for a row-major matrix. */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - Index outerSize() const - { - return IsVectorAtCompileTime ? 1 - : int(IsRowMajor) ? this->rows() : this->cols(); - } - - /** \returns the inner size. - * - * \note For a vector, this is just the size. For a matrix (non-vector), this is the minor dimension - * with respect to the \ref TopicStorageOrders "storage order", i.e., the number of rows for a - * column-major matrix, and the number of columns for a row-major matrix. */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - Index innerSize() const - { - return IsVectorAtCompileTime ? this->size() - : int(IsRowMajor) ? this->cols() : this->rows(); - } - - /** Only plain matrices/arrays, not expressions, may be resized; therefore the only useful resize methods are - * Matrix::resize() and Array::resize(). The present method only asserts that the new size equals the old size, and does - * nothing else. - */ - EIGEN_DEVICE_FUNC - void resize(Index newSize) - { - EIGEN_ONLY_USED_FOR_DEBUG(newSize); - eigen_assert(newSize == this->size() - && "DenseBase::resize() does not actually allow to resize."); - } - /** Only plain matrices/arrays, not expressions, may be resized; therefore the only useful resize methods are - * Matrix::resize() and Array::resize(). The present method only asserts that the new size equals the old size, and does - * nothing else. - */ - EIGEN_DEVICE_FUNC - void resize(Index rows, Index cols) - { - EIGEN_ONLY_USED_FOR_DEBUG(rows); - EIGEN_ONLY_USED_FOR_DEBUG(cols); - eigen_assert(rows == this->rows() && cols == this->cols() - && "DenseBase::resize() does not actually allow to resize."); - } + AutoAlign | (internal::traits::Flags & RowMajorBit ? RowMajor : ColMajor), + internal::traits::MaxRowsAtCompileTime, internal::traits::MaxColsAtCompileTime> + PlainArray; + + /** \brief The plain matrix or array type corresponding to this expression. + * + * This is not necessarily exactly the return type of eval(). In the case of plain matrices, + * the return type of eval() is a const reference to a matrix, not a matrix! It is however guaranteed + * that the return type of eval() is either PlainObject or const PlainObject&. + */ + typedef std::conditional_t::XprKind, MatrixXpr>::value, + PlainMatrix, PlainArray> + PlainObject; + + /** \returns the outer size. + * + * \note For a vector, this returns just 1. For a matrix (non-vector), this is the major dimension + * with respect to the \ref TopicStorageOrders "storage order", i.e., the number of columns for a + * column-major matrix, and the number of rows for a row-major matrix. */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index outerSize() const { + return IsVectorAtCompileTime ? 1 : int(IsRowMajor) ? this->rows() : this->cols(); + } + + /** \returns the inner size. + * + * \note For a vector, this is just the size. For a matrix (non-vector), this is the minor dimension + * with respect to the \ref TopicStorageOrders "storage order", i.e., the number of rows for a + * column-major matrix, and the number of columns for a row-major matrix. */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index innerSize() const { + return IsVectorAtCompileTime ? this->size() : int(IsRowMajor) ? this->cols() : this->rows(); + } + + /** Only plain matrices/arrays, not expressions, may be resized; therefore the only useful resize methods are + * Matrix::resize() and Array::resize(). The present method only asserts that the new size equals the old size, and + * does nothing else. + */ + EIGEN_DEVICE_FUNC void resize(Index newSize) { + EIGEN_ONLY_USED_FOR_DEBUG(newSize); + eigen_assert(newSize == this->size() && "DenseBase::resize() does not actually allow to resize."); + } + /** Only plain matrices/arrays, not expressions, may be resized; therefore the only useful resize methods are + * Matrix::resize() and Array::resize(). The present method only asserts that the new size equals the old size, and + * does nothing else. + */ + EIGEN_DEVICE_FUNC void resize(Index rows, Index cols) { + EIGEN_ONLY_USED_FOR_DEBUG(rows); + EIGEN_ONLY_USED_FOR_DEBUG(cols); + eigen_assert(rows == this->rows() && cols == this->cols() && + "DenseBase::resize() does not actually allow to resize."); + } #ifndef EIGEN_PARSED_BY_DOXYGEN - /** \internal Represents a matrix with all coefficients equal to one another*/ - typedef CwiseNullaryOp,PlainObject> ConstantReturnType; - /** \internal \deprecated Represents a vector with linearly spaced coefficients that allows sequential access only. */ - EIGEN_DEPRECATED typedef CwiseNullaryOp,PlainObject> SequentialLinSpacedReturnType; - /** \internal Represents a vector with linearly spaced coefficients that allows random access. */ - typedef CwiseNullaryOp,PlainObject> RandomAccessLinSpacedReturnType; - /** \internal the return type of MatrixBase::eigenvalues() */ - typedef Matrix::Scalar>::Real, internal::traits::ColsAtCompileTime, 1> EigenvaluesReturnType; - -#endif // not EIGEN_PARSED_BY_DOXYGEN - - /** Copies \a other into *this. \returns a reference to *this. */ - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator=(const DenseBase& other); - - /** Special case of the template operator=, in order to prevent the compiler - * from generating a default operator= (issue hit with g++ 4.1) - */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator=(const DenseBase& other); - - template - EIGEN_DEVICE_FUNC - Derived& operator=(const EigenBase &other); - - template - EIGEN_DEVICE_FUNC - Derived& operator+=(const EigenBase &other); - - template - EIGEN_DEVICE_FUNC - Derived& operator-=(const EigenBase &other); - - template - EIGEN_DEVICE_FUNC - Derived& operator=(const ReturnByValue& func); - - /** \internal - * Copies \a other into *this without evaluating other. \returns a reference to *this. */ - template - /** \deprecated */ - EIGEN_DEPRECATED EIGEN_DEVICE_FUNC - Derived& lazyAssign(const DenseBase& other); - - EIGEN_DEVICE_FUNC - CommaInitializer operator<< (const Scalar& s); - - template - /** \deprecated it now returns \c *this */ - EIGEN_DEPRECATED - const Derived& flagged() const - { return derived(); } - - template - EIGEN_DEVICE_FUNC - CommaInitializer operator<< (const DenseBase& other); - - typedef Transpose TransposeReturnType; - EIGEN_DEVICE_FUNC - TransposeReturnType transpose(); - typedef typename internal::add_const >::type ConstTransposeReturnType; - EIGEN_DEVICE_FUNC - ConstTransposeReturnType transpose() const; - EIGEN_DEVICE_FUNC - void transposeInPlace(); - - EIGEN_DEVICE_FUNC static const ConstantReturnType - Constant(Index rows, Index cols, const Scalar& value); - EIGEN_DEVICE_FUNC static const ConstantReturnType - Constant(Index size, const Scalar& value); - EIGEN_DEVICE_FUNC static const ConstantReturnType - Constant(const Scalar& value); - - EIGEN_DEPRECATED EIGEN_DEVICE_FUNC static const RandomAccessLinSpacedReturnType - LinSpaced(Sequential_t, Index size, const Scalar& low, const Scalar& high); - EIGEN_DEPRECATED EIGEN_DEVICE_FUNC static const RandomAccessLinSpacedReturnType - LinSpaced(Sequential_t, const Scalar& low, const Scalar& high); - - EIGEN_DEVICE_FUNC static const RandomAccessLinSpacedReturnType - LinSpaced(Index size, const Scalar& low, const Scalar& high); - EIGEN_DEVICE_FUNC static const RandomAccessLinSpacedReturnType - LinSpaced(const Scalar& low, const Scalar& high); - - template EIGEN_DEVICE_FUNC - static const CwiseNullaryOp - NullaryExpr(Index rows, Index cols, const CustomNullaryOp& func); - template EIGEN_DEVICE_FUNC - static const CwiseNullaryOp - NullaryExpr(Index size, const CustomNullaryOp& func); - template EIGEN_DEVICE_FUNC - static const CwiseNullaryOp - NullaryExpr(const CustomNullaryOp& func); - - EIGEN_DEVICE_FUNC static const ConstantReturnType Zero(Index rows, Index cols); - EIGEN_DEVICE_FUNC static const ConstantReturnType Zero(Index size); - EIGEN_DEVICE_FUNC static const ConstantReturnType Zero(); - EIGEN_DEVICE_FUNC static const ConstantReturnType Ones(Index rows, Index cols); - EIGEN_DEVICE_FUNC static const ConstantReturnType Ones(Index size); - EIGEN_DEVICE_FUNC static const ConstantReturnType Ones(); - - EIGEN_DEVICE_FUNC void fill(const Scalar& value); - EIGEN_DEVICE_FUNC Derived& setConstant(const Scalar& value); - EIGEN_DEVICE_FUNC Derived& setLinSpaced(Index size, const Scalar& low, const Scalar& high); - EIGEN_DEVICE_FUNC Derived& setLinSpaced(const Scalar& low, const Scalar& high); - EIGEN_DEVICE_FUNC Derived& setZero(); - EIGEN_DEVICE_FUNC Derived& setOnes(); - EIGEN_DEVICE_FUNC Derived& setRandom(); - - template EIGEN_DEVICE_FUNC - bool isApprox(const DenseBase& other, - const RealScalar& prec = NumTraits::dummy_precision()) const; - EIGEN_DEVICE_FUNC - bool isMuchSmallerThan(const RealScalar& other, - const RealScalar& prec = NumTraits::dummy_precision()) const; - template EIGEN_DEVICE_FUNC - bool isMuchSmallerThan(const DenseBase& other, - const RealScalar& prec = NumTraits::dummy_precision()) const; - - EIGEN_DEVICE_FUNC bool isApproxToConstant(const Scalar& value, const RealScalar& prec = NumTraits::dummy_precision()) const; - EIGEN_DEVICE_FUNC bool isConstant(const Scalar& value, const RealScalar& prec = NumTraits::dummy_precision()) const; - EIGEN_DEVICE_FUNC bool isZero(const RealScalar& prec = NumTraits::dummy_precision()) const; - EIGEN_DEVICE_FUNC bool isOnes(const RealScalar& prec = NumTraits::dummy_precision()) const; - - inline bool hasNaN() const; - inline bool allFinite() const; - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator*=(const Scalar& other); - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator/=(const Scalar& other); - - typedef typename internal::add_const_on_value_type::type>::type EvalReturnType; - /** \returns the matrix or vector obtained by evaluating this expression. - * - * Notice that in the case of a plain matrix or vector (not an expression) this function just returns - * a const reference, in order to avoid a useless copy. - * - * \warning Be careful with eval() and the auto C++ keyword, as detailed in this \link TopicPitfalls_auto_keyword page \endlink. - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE EvalReturnType eval() const - { - // Even though MSVC does not honor strong inlining when the return type - // is a dynamic matrix, we desperately need strong inlining for fixed - // size types on MSVC. - return typename internal::eval::type(derived()); - } - - /** swaps *this with the expression \a other. - * - */ - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void swap(const DenseBase& other) - { - EIGEN_STATIC_ASSERT(!OtherDerived::IsPlainObjectBase,THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY); - eigen_assert(rows()==other.rows() && cols()==other.cols()); - call_assignment(derived(), other.const_cast_derived(), internal::swap_assign_op()); - } - - /** swaps *this with the matrix or array \a other. - * - */ - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void swap(PlainObjectBase& other) - { - eigen_assert(rows()==other.rows() && cols()==other.cols()); - call_assignment(derived(), other.derived(), internal::swap_assign_op()); - } - - EIGEN_DEVICE_FUNC inline const NestByValue nestByValue() const; - EIGEN_DEVICE_FUNC inline const ForceAlignedAccess forceAlignedAccess() const; - EIGEN_DEVICE_FUNC inline ForceAlignedAccess forceAlignedAccess(); - template EIGEN_DEVICE_FUNC - inline const typename internal::conditional,Derived&>::type forceAlignedAccessIf() const; - template EIGEN_DEVICE_FUNC - inline typename internal::conditional,Derived&>::type forceAlignedAccessIf(); - - EIGEN_DEVICE_FUNC Scalar sum() const; - EIGEN_DEVICE_FUNC Scalar mean() const; - EIGEN_DEVICE_FUNC Scalar trace() const; - - EIGEN_DEVICE_FUNC Scalar prod() const; - - template - EIGEN_DEVICE_FUNC typename internal::traits::Scalar minCoeff() const; - template - EIGEN_DEVICE_FUNC typename internal::traits::Scalar maxCoeff() const; - - - // By default, the fastest version with undefined NaN propagation semantics is - // used. - // TODO(rmlarsen): Replace with default template argument when we move to - // c++11 or beyond. - EIGEN_DEVICE_FUNC inline typename internal::traits::Scalar minCoeff() const { - return minCoeff(); - } - EIGEN_DEVICE_FUNC inline typename internal::traits::Scalar maxCoeff() const { - return maxCoeff(); - } - - template - EIGEN_DEVICE_FUNC - typename internal::traits::Scalar minCoeff(IndexType* row, IndexType* col) const; - template - EIGEN_DEVICE_FUNC - typename internal::traits::Scalar maxCoeff(IndexType* row, IndexType* col) const; - template - EIGEN_DEVICE_FUNC - typename internal::traits::Scalar minCoeff(IndexType* index) const; - template - EIGEN_DEVICE_FUNC - typename internal::traits::Scalar maxCoeff(IndexType* index) const; - - // TODO(rmlarsen): Replace these methods with a default template argument. - template - EIGEN_DEVICE_FUNC inline - typename internal::traits::Scalar minCoeff(IndexType* row, IndexType* col) const { - return minCoeff(row, col); - } - template - EIGEN_DEVICE_FUNC inline - typename internal::traits::Scalar maxCoeff(IndexType* row, IndexType* col) const { - return maxCoeff(row, col); - } - template - EIGEN_DEVICE_FUNC inline - typename internal::traits::Scalar minCoeff(IndexType* index) const { - return minCoeff(index); - } - template - EIGEN_DEVICE_FUNC inline - typename internal::traits::Scalar maxCoeff(IndexType* index) const { - return maxCoeff(index); - } - - template - EIGEN_DEVICE_FUNC - Scalar redux(const BinaryOp& func) const; - - template - EIGEN_DEVICE_FUNC - void visit(Visitor& func) const; - - /** \returns a WithFormat proxy object allowing to print a matrix the with given - * format \a fmt. - * - * See class IOFormat for some examples. - * - * \sa class IOFormat, class WithFormat - */ - inline const WithFormat format(const IOFormat& fmt) const - { - return WithFormat(derived(), fmt); - } - - /** \returns the unique coefficient of a 1x1 expression */ - EIGEN_DEVICE_FUNC - CoeffReturnType value() const - { - EIGEN_STATIC_ASSERT_SIZE_1x1(Derived) - eigen_assert(this->rows() == 1 && this->cols() == 1); - return derived().coeff(0,0); - } - - EIGEN_DEVICE_FUNC bool all() const; - EIGEN_DEVICE_FUNC bool any() const; - EIGEN_DEVICE_FUNC Index count() const; - - typedef VectorwiseOp RowwiseReturnType; - typedef const VectorwiseOp ConstRowwiseReturnType; - typedef VectorwiseOp ColwiseReturnType; - typedef const VectorwiseOp ConstColwiseReturnType; - - /** \returns a VectorwiseOp wrapper of *this for broadcasting and partial reductions - * - * Example: \include MatrixBase_rowwise.cpp - * Output: \verbinclude MatrixBase_rowwise.out - * - * \sa colwise(), class VectorwiseOp, \ref TutorialReductionsVisitorsBroadcasting - */ - //Code moved here due to a CUDA compiler bug - EIGEN_DEVICE_FUNC inline ConstRowwiseReturnType rowwise() const { - return ConstRowwiseReturnType(derived()); - } - EIGEN_DEVICE_FUNC RowwiseReturnType rowwise(); - - /** \returns a VectorwiseOp wrapper of *this broadcasting and partial reductions - * - * Example: \include MatrixBase_colwise.cpp - * Output: \verbinclude MatrixBase_colwise.out - * - * \sa rowwise(), class VectorwiseOp, \ref TutorialReductionsVisitorsBroadcasting - */ - EIGEN_DEVICE_FUNC inline ConstColwiseReturnType colwise() const { - return ConstColwiseReturnType(derived()); - } - EIGEN_DEVICE_FUNC ColwiseReturnType colwise(); - - typedef CwiseNullaryOp,PlainObject> RandomReturnType; - static const RandomReturnType Random(Index rows, Index cols); - static const RandomReturnType Random(Index size); - static const RandomReturnType Random(); - - template - inline EIGEN_DEVICE_FUNC const Select - select(const DenseBase& thenMatrix, - const DenseBase& elseMatrix) const; - - template - inline EIGEN_DEVICE_FUNC const Select - select(const DenseBase& thenMatrix, const typename ThenDerived::Scalar& elseScalar) const; - - template - inline EIGEN_DEVICE_FUNC const Select - select(const typename ElseDerived::Scalar& thenScalar, const DenseBase& elseMatrix) const; - - template RealScalar lpNorm() const; - - template - EIGEN_DEVICE_FUNC - const Replicate replicate() const; - /** - * \return an expression of the replication of \c *this - * - * Example: \include MatrixBase_replicate_int_int.cpp - * Output: \verbinclude MatrixBase_replicate_int_int.out - * - * \sa VectorwiseOp::replicate(), DenseBase::replicate(), class Replicate - */ - //Code moved here due to a CUDA compiler bug - EIGEN_DEVICE_FUNC - const Replicate replicate(Index rowFactor, Index colFactor) const - { - return Replicate(derived(), rowFactor, colFactor); - } - - typedef Reverse ReverseReturnType; - typedef const Reverse ConstReverseReturnType; - EIGEN_DEVICE_FUNC ReverseReturnType reverse(); - /** This is the const version of reverse(). */ - //Code moved here due to a CUDA compiler bug - EIGEN_DEVICE_FUNC ConstReverseReturnType reverse() const - { - return ConstReverseReturnType(derived()); - } - EIGEN_DEVICE_FUNC void reverseInPlace(); - - #ifdef EIGEN_PARSED_BY_DOXYGEN - /** STL-like RandomAccessIterator - * iterator type as returned by the begin() and end() methods. - */ - typedef random_access_iterator_type iterator; - /** This is the const version of iterator (aka read-only) */ - typedef random_access_iterator_type const_iterator; - #else - typedef typename internal::conditional< (Flags&DirectAccessBit)==DirectAccessBit, - internal::pointer_based_stl_iterator, - internal::generic_randaccess_stl_iterator - >::type iterator_type; - - typedef typename internal::conditional< (Flags&DirectAccessBit)==DirectAccessBit, - internal::pointer_based_stl_iterator, - internal::generic_randaccess_stl_iterator - >::type const_iterator_type; - - // Stl-style iterators are supported only for vectors. - - typedef typename internal::conditional< IsVectorAtCompileTime, - iterator_type, - void - >::type iterator; - - typedef typename internal::conditional< IsVectorAtCompileTime, - const_iterator_type, - void - >::type const_iterator; - #endif - - inline iterator begin(); - inline const_iterator begin() const; - inline const_iterator cbegin() const; - inline iterator end(); - inline const_iterator end() const; - inline const_iterator cend() const; + /** \internal Represents a matrix with all coefficients equal to one another*/ + typedef CwiseNullaryOp, PlainObject> ConstantReturnType; + /** \internal \deprecated Represents a vector with linearly spaced coefficients that allows sequential access only. */ + EIGEN_DEPRECATED typedef CwiseNullaryOp, PlainObject> SequentialLinSpacedReturnType; + /** \internal Represents a vector with linearly spaced coefficients that allows random access. */ + typedef CwiseNullaryOp, PlainObject> RandomAccessLinSpacedReturnType; + /** \internal Represents a vector with equally spaced coefficients that allows random access. */ + typedef CwiseNullaryOp, PlainObject> RandomAccessEqualSpacedReturnType; + /** \internal the return type of MatrixBase::eigenvalues() */ + typedef Matrix::Scalar>::Real, + internal::traits::ColsAtCompileTime, 1> + EigenvaluesReturnType; + +#endif // not EIGEN_PARSED_BY_DOXYGEN + + /** Copies \a other into *this. \returns a reference to *this. */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator=(const DenseBase& other); + + /** Special case of the template operator=, in order to prevent the compiler + * from generating a default operator= (issue hit with g++ 4.1) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator=(const DenseBase& other); + + template + EIGEN_DEVICE_FUNC Derived& operator=(const EigenBase& other); + + template + EIGEN_DEVICE_FUNC Derived& operator+=(const EigenBase& other); + + template + EIGEN_DEVICE_FUNC Derived& operator-=(const EigenBase& other); + + template + EIGEN_DEVICE_FUNC Derived& operator=(const ReturnByValue& func); + + /** \internal + * Copies \a other into *this without evaluating other. \returns a reference to *this. */ + template + /** \deprecated */ + EIGEN_DEPRECATED EIGEN_DEVICE_FUNC Derived& lazyAssign(const DenseBase& other); + + EIGEN_DEVICE_FUNC CommaInitializer operator<<(const Scalar& s); + + template + /** \deprecated it now returns \c *this */ + EIGEN_DEPRECATED const Derived& flagged() const { + return derived(); + } + + template + EIGEN_DEVICE_FUNC CommaInitializer operator<<(const DenseBase& other); + + typedef Transpose TransposeReturnType; + EIGEN_DEVICE_FUNC TransposeReturnType transpose(); + typedef Transpose ConstTransposeReturnType; + EIGEN_DEVICE_FUNC const ConstTransposeReturnType transpose() const; + EIGEN_DEVICE_FUNC void transposeInPlace(); + + EIGEN_DEVICE_FUNC static const ConstantReturnType Constant(Index rows, Index cols, const Scalar& value); + EIGEN_DEVICE_FUNC static const ConstantReturnType Constant(Index size, const Scalar& value); + EIGEN_DEVICE_FUNC static const ConstantReturnType Constant(const Scalar& value); + + EIGEN_DEPRECATED EIGEN_DEVICE_FUNC static const RandomAccessLinSpacedReturnType LinSpaced(Sequential_t, Index size, + const Scalar& low, + const Scalar& high); + EIGEN_DEPRECATED EIGEN_DEVICE_FUNC static const RandomAccessLinSpacedReturnType LinSpaced(Sequential_t, + const Scalar& low, + const Scalar& high); + + EIGEN_DEVICE_FUNC static const RandomAccessLinSpacedReturnType LinSpaced(Index size, const Scalar& low, + const Scalar& high); + EIGEN_DEVICE_FUNC static const RandomAccessLinSpacedReturnType LinSpaced(const Scalar& low, const Scalar& high); + + EIGEN_DEVICE_FUNC static const RandomAccessEqualSpacedReturnType EqualSpaced(Index size, const Scalar& low, + const Scalar& step); + EIGEN_DEVICE_FUNC static const RandomAccessEqualSpacedReturnType EqualSpaced(const Scalar& low, const Scalar& step); + + template + EIGEN_DEVICE_FUNC static const CwiseNullaryOp NullaryExpr(Index rows, Index cols, + const CustomNullaryOp& func); + template + EIGEN_DEVICE_FUNC static const CwiseNullaryOp NullaryExpr(Index size, + const CustomNullaryOp& func); + template + EIGEN_DEVICE_FUNC static const CwiseNullaryOp NullaryExpr(const CustomNullaryOp& func); + + EIGEN_DEVICE_FUNC static const ConstantReturnType Zero(Index rows, Index cols); + EIGEN_DEVICE_FUNC static const ConstantReturnType Zero(Index size); + EIGEN_DEVICE_FUNC static const ConstantReturnType Zero(); + EIGEN_DEVICE_FUNC static const ConstantReturnType Ones(Index rows, Index cols); + EIGEN_DEVICE_FUNC static const ConstantReturnType Ones(Index size); + EIGEN_DEVICE_FUNC static const ConstantReturnType Ones(); + + EIGEN_DEVICE_FUNC void fill(const Scalar& value); + EIGEN_DEVICE_FUNC Derived& setConstant(const Scalar& value); + EIGEN_DEVICE_FUNC Derived& setLinSpaced(Index size, const Scalar& low, const Scalar& high); + EIGEN_DEVICE_FUNC Derived& setLinSpaced(const Scalar& low, const Scalar& high); + EIGEN_DEVICE_FUNC Derived& setEqualSpaced(Index size, const Scalar& low, const Scalar& step); + EIGEN_DEVICE_FUNC Derived& setEqualSpaced(const Scalar& low, const Scalar& step); + EIGEN_DEVICE_FUNC Derived& setZero(); + EIGEN_DEVICE_FUNC Derived& setOnes(); + EIGEN_DEVICE_FUNC Derived& setRandom(); + + template + EIGEN_DEVICE_FUNC bool isApprox(const DenseBase& other, + const RealScalar& prec = NumTraits::dummy_precision()) const; + EIGEN_DEVICE_FUNC bool isMuchSmallerThan(const RealScalar& other, + const RealScalar& prec = NumTraits::dummy_precision()) const; + template + EIGEN_DEVICE_FUNC bool isMuchSmallerThan(const DenseBase& other, + const RealScalar& prec = NumTraits::dummy_precision()) const; + + EIGEN_DEVICE_FUNC bool isApproxToConstant(const Scalar& value, + const RealScalar& prec = NumTraits::dummy_precision()) const; + EIGEN_DEVICE_FUNC bool isConstant(const Scalar& value, + const RealScalar& prec = NumTraits::dummy_precision()) const; + EIGEN_DEVICE_FUNC bool isZero(const RealScalar& prec = NumTraits::dummy_precision()) const; + EIGEN_DEVICE_FUNC bool isOnes(const RealScalar& prec = NumTraits::dummy_precision()) const; + + EIGEN_DEVICE_FUNC inline bool hasNaN() const; + EIGEN_DEVICE_FUNC inline bool allFinite() const; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator*=(const Scalar& other); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator/=(const Scalar& other); + + typedef internal::add_const_on_value_type_t::type> EvalReturnType; + /** \returns the matrix or vector obtained by evaluating this expression. + * + * Notice that in the case of a plain matrix or vector (not an expression) this function just returns + * a const reference, in order to avoid a useless copy. + * + * \warning Be careful with eval() and the auto C++ keyword, as detailed in this \link TopicPitfalls_auto_keyword page + * \endlink. + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EvalReturnType eval() const { + // Even though MSVC does not honor strong inlining when the return type + // is a dynamic matrix, we desperately need strong inlining for fixed + // size types on MSVC. + return typename internal::eval::type(derived()); + } + + /** swaps *this with the expression \a other. + * + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void swap(const DenseBase& other) { + EIGEN_STATIC_ASSERT(!OtherDerived::IsPlainObjectBase, THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY); + eigen_assert(rows() == other.rows() && cols() == other.cols()); + call_assignment(derived(), other.const_cast_derived(), internal::swap_assign_op()); + } + + /** swaps *this with the matrix or array \a other. + * + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void swap(PlainObjectBase& other) { + eigen_assert(rows() == other.rows() && cols() == other.cols()); + call_assignment(derived(), other.derived(), internal::swap_assign_op()); + } + + EIGEN_DEVICE_FUNC inline const NestByValue nestByValue() const; + EIGEN_DEVICE_FUNC inline const ForceAlignedAccess forceAlignedAccess() const; + EIGEN_DEVICE_FUNC inline ForceAlignedAccess forceAlignedAccess(); + template + EIGEN_DEVICE_FUNC inline const std::conditional_t, Derived&> + forceAlignedAccessIf() const; + template + EIGEN_DEVICE_FUNC inline std::conditional_t, Derived&> forceAlignedAccessIf(); + + EIGEN_DEVICE_FUNC Scalar sum() const; + EIGEN_DEVICE_FUNC Scalar mean() const; + EIGEN_DEVICE_FUNC Scalar trace() const; + + EIGEN_DEVICE_FUNC Scalar prod() const; + + template + EIGEN_DEVICE_FUNC typename internal::traits::Scalar minCoeff() const; + template + EIGEN_DEVICE_FUNC typename internal::traits::Scalar maxCoeff() const; + + // By default, the fastest version with undefined NaN propagation semantics is + // used. + // TODO(rmlarsen): Replace with default template argument when we move to + // c++11 or beyond. + EIGEN_DEVICE_FUNC inline typename internal::traits::Scalar minCoeff() const { + return minCoeff(); + } + EIGEN_DEVICE_FUNC inline typename internal::traits::Scalar maxCoeff() const { + return maxCoeff(); + } + + template + EIGEN_DEVICE_FUNC typename internal::traits::Scalar minCoeff(IndexType* row, IndexType* col) const; + template + EIGEN_DEVICE_FUNC typename internal::traits::Scalar maxCoeff(IndexType* row, IndexType* col) const; + template + EIGEN_DEVICE_FUNC typename internal::traits::Scalar minCoeff(IndexType* index) const; + template + EIGEN_DEVICE_FUNC typename internal::traits::Scalar maxCoeff(IndexType* index) const; + + // TODO(rmlarsen): Replace these methods with a default template argument. + template + EIGEN_DEVICE_FUNC inline typename internal::traits::Scalar minCoeff(IndexType* row, IndexType* col) const { + return minCoeff(row, col); + } + template + EIGEN_DEVICE_FUNC inline typename internal::traits::Scalar maxCoeff(IndexType* row, IndexType* col) const { + return maxCoeff(row, col); + } + template + EIGEN_DEVICE_FUNC inline typename internal::traits::Scalar minCoeff(IndexType* index) const { + return minCoeff(index); + } + template + EIGEN_DEVICE_FUNC inline typename internal::traits::Scalar maxCoeff(IndexType* index) const { + return maxCoeff(index); + } + + template + EIGEN_DEVICE_FUNC Scalar redux(const BinaryOp& func) const; + + template + EIGEN_DEVICE_FUNC void visit(Visitor& func) const; + + /** \returns a WithFormat proxy object allowing to print a matrix the with given + * format \a fmt. + * + * See class IOFormat for some examples. + * + * \sa class IOFormat, class WithFormat + */ + inline const WithFormat format(const IOFormat& fmt) const { return WithFormat(derived(), fmt); } + + /** \returns the unique coefficient of a 1x1 expression */ + EIGEN_DEVICE_FUNC CoeffReturnType value() const { + EIGEN_STATIC_ASSERT_SIZE_1x1(Derived) eigen_assert(this->rows() == 1 && this->cols() == 1); + return derived().coeff(0, 0); + } + + EIGEN_DEVICE_FUNC bool all() const; + EIGEN_DEVICE_FUNC bool any() const; + EIGEN_DEVICE_FUNC Index count() const; + + typedef VectorwiseOp RowwiseReturnType; + typedef const VectorwiseOp ConstRowwiseReturnType; + typedef VectorwiseOp ColwiseReturnType; + typedef const VectorwiseOp ConstColwiseReturnType; + + /** \returns a VectorwiseOp wrapper of *this for broadcasting and partial reductions + * + * Example: \include MatrixBase_rowwise.cpp + * Output: \verbinclude MatrixBase_rowwise.out + * + * \sa colwise(), class VectorwiseOp, \ref TutorialReductionsVisitorsBroadcasting + */ + // Code moved here due to a CUDA compiler bug + EIGEN_DEVICE_FUNC inline ConstRowwiseReturnType rowwise() const { return ConstRowwiseReturnType(derived()); } + EIGEN_DEVICE_FUNC RowwiseReturnType rowwise(); + + /** \returns a VectorwiseOp wrapper of *this broadcasting and partial reductions + * + * Example: \include MatrixBase_colwise.cpp + * Output: \verbinclude MatrixBase_colwise.out + * + * \sa rowwise(), class VectorwiseOp, \ref TutorialReductionsVisitorsBroadcasting + */ + EIGEN_DEVICE_FUNC inline ConstColwiseReturnType colwise() const { return ConstColwiseReturnType(derived()); } + EIGEN_DEVICE_FUNC ColwiseReturnType colwise(); + + typedef CwiseNullaryOp, PlainObject> RandomReturnType; + static const RandomReturnType Random(Index rows, Index cols); + static const RandomReturnType Random(Index size); + static const RandomReturnType Random(); + + template + inline EIGEN_DEVICE_FUNC + CwiseTernaryOp::Scalar, + typename DenseBase::Scalar, Scalar>, + ThenDerived, ElseDerived, Derived> + select(const DenseBase& thenMatrix, const DenseBase& elseMatrix) const; + + template + inline EIGEN_DEVICE_FUNC + CwiseTernaryOp::Scalar, + typename DenseBase::Scalar, Scalar>, + ThenDerived, typename DenseBase::ConstantReturnType, Derived> + select(const DenseBase& thenMatrix, const typename DenseBase::Scalar& elseScalar) const; + + template + inline EIGEN_DEVICE_FUNC + CwiseTernaryOp::Scalar, + typename DenseBase::Scalar, Scalar>, + typename DenseBase::ConstantReturnType, ElseDerived, Derived> + select(const typename DenseBase::Scalar& thenScalar, const DenseBase& elseMatrix) const; + + template + RealScalar lpNorm() const; + + template + EIGEN_DEVICE_FUNC const Replicate replicate() const; + /** + * \return an expression of the replication of \c *this + * + * Example: \include MatrixBase_replicate_int_int.cpp + * Output: \verbinclude MatrixBase_replicate_int_int.out + * + * \sa VectorwiseOp::replicate(), DenseBase::replicate(), class Replicate + */ + // Code moved here due to a CUDA compiler bug + EIGEN_DEVICE_FUNC const Replicate replicate(Index rowFactor, Index colFactor) const { + return Replicate(derived(), rowFactor, colFactor); + } + + typedef Reverse ReverseReturnType; + typedef const Reverse ConstReverseReturnType; + EIGEN_DEVICE_FUNC ReverseReturnType reverse(); + /** This is the const version of reverse(). */ + // Code moved here due to a CUDA compiler bug + EIGEN_DEVICE_FUNC ConstReverseReturnType reverse() const { return ConstReverseReturnType(derived()); } + EIGEN_DEVICE_FUNC void reverseInPlace(); + +#ifdef EIGEN_PARSED_BY_DOXYGEN + /** STL-like RandomAccessIterator + * iterator type as returned by the begin() and end() methods. + */ + typedef random_access_iterator_type iterator; + /** This is the const version of iterator (aka read-only) */ + typedef random_access_iterator_type const_iterator; +#else + typedef std::conditional_t<(Flags & DirectAccessBit) == DirectAccessBit, + internal::pointer_based_stl_iterator, + internal::generic_randaccess_stl_iterator > + iterator_type; + + typedef std::conditional_t<(Flags & DirectAccessBit) == DirectAccessBit, + internal::pointer_based_stl_iterator, + internal::generic_randaccess_stl_iterator > + const_iterator_type; + + // Stl-style iterators are supported only for vectors. + + typedef std::conditional_t iterator; + + typedef std::conditional_t const_iterator; +#endif + + inline iterator begin(); + inline const_iterator begin() const; + inline const_iterator cbegin() const; + inline iterator end(); + inline const_iterator end() const; + inline const_iterator cend() const; #define EIGEN_CURRENT_STORAGE_BASE_CLASS Eigen::DenseBase #define EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL #define EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(COND) -#define EIGEN_DOC_UNARY_ADDONS(X,Y) -# include "../plugins/CommonCwiseUnaryOps.h" -# include "../plugins/BlockMethods.h" -# include "../plugins/IndexedViewMethods.h" -# include "../plugins/ReshapedMethods.h" -# ifdef EIGEN_DENSEBASE_PLUGIN -# include EIGEN_DENSEBASE_PLUGIN -# endif +#define EIGEN_DOC_UNARY_ADDONS(X, Y) +#include "../plugins/CommonCwiseUnaryOps.inc" +#include "../plugins/BlockMethods.inc" +#include "../plugins/IndexedViewMethods.inc" +#include "../plugins/ReshapedMethods.inc" +#ifdef EIGEN_DENSEBASE_PLUGIN +#include EIGEN_DENSEBASE_PLUGIN +#endif #undef EIGEN_CURRENT_STORAGE_BASE_CLASS #undef EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL #undef EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF #undef EIGEN_DOC_UNARY_ADDONS - // disable the use of evalTo for dense objects with a nice compilation error - template - EIGEN_DEVICE_FUNC - inline void evalTo(Dest& ) const - { - EIGEN_STATIC_ASSERT((internal::is_same::value),THE_EVAL_EVALTO_FUNCTION_SHOULD_NEVER_BE_CALLED_FOR_DENSE_OBJECTS); - } - - protected: - EIGEN_DEFAULT_COPY_CONSTRUCTOR(DenseBase) - /** Default constructor. Do nothing. */ - EIGEN_DEVICE_FUNC DenseBase() - { + // disable the use of evalTo for dense objects with a nice compilation error + template + EIGEN_DEVICE_FUNC inline void evalTo(Dest&) const { + EIGEN_STATIC_ASSERT((internal::is_same::value), + THE_EVAL_EVALTO_FUNCTION_SHOULD_NEVER_BE_CALLED_FOR_DENSE_OBJECTS); + } + + protected: + EIGEN_DEFAULT_COPY_CONSTRUCTOR(DenseBase) + /** Default constructor. Do nothing. */ +#ifdef EIGEN_INTERNAL_DEBUGGING + EIGEN_DEVICE_FUNC constexpr DenseBase(){ /* Just checks for self-consistency of the flags. * Only do it when debugging Eigen, as this borders on paranoia and could slow compilation down */ -#ifdef EIGEN_INTERNAL_DEBUGGING - EIGEN_STATIC_ASSERT((EIGEN_IMPLIES(MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1, int(IsRowMajor)) - && EIGEN_IMPLIES(MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1, int(!IsRowMajor))), - INVALID_STORAGE_ORDER_FOR_THIS_VECTOR_EXPRESSION) + EIGEN_STATIC_ASSERT( + (internal::check_implication(MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1, int(IsRowMajor)) && + internal::check_implication(MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1, int(!IsRowMajor))), + INVALID_STORAGE_ORDER_FOR_THIS_VECTOR_EXPRESSION)} +#else + EIGEN_DEVICE_FUNC constexpr DenseBase() = default; #endif - } - private: - EIGEN_DEVICE_FUNC explicit DenseBase(int); - EIGEN_DEVICE_FUNC DenseBase(int,int); - template EIGEN_DEVICE_FUNC explicit DenseBase(const DenseBase&); + private : EIGEN_DEVICE_FUNC explicit DenseBase(int); + EIGEN_DEVICE_FUNC DenseBase(int, int); + template + EIGEN_DEVICE_FUNC explicit DenseBase(const DenseBase&); }; -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_DENSEBASE_H +#endif // EIGEN_DENSEBASE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DenseCoeffsBase.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DenseCoeffsBase.h index 37fcdb59119..30e0aa38a79 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DenseCoeffsBase.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DenseCoeffsBase.h @@ -10,676 +10,560 @@ #ifndef EIGEN_DENSECOEFFSBASE_H #define EIGEN_DENSECOEFFSBASE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template struct add_const_on_value_type_if_arithmetic -{ - typedef typename conditional::value, T, typename add_const_on_value_type::type>::type type; +template +struct add_const_on_value_type_if_arithmetic { + typedef std::conditional_t::value, T, add_const_on_value_type_t> type; }; -} +} // namespace internal /** \brief Base class providing read-only coefficient access to matrices and arrays. - * \ingroup Core_Module - * \tparam Derived Type of the derived class - * - * \note #ReadOnlyAccessors Constant indicating read-only access - * - * This class defines the \c operator() \c const function and friends, which can be used to read specific - * entries of a matrix or array. - * - * \sa DenseCoeffsBase, DenseCoeffsBase, - * \ref TopicClassHierarchy - */ -template -class DenseCoeffsBase : public EigenBase -{ - public: - typedef typename internal::traits::StorageKind StorageKind; - typedef typename internal::traits::Scalar Scalar; - typedef typename internal::packet_traits::type PacketScalar; - - // Explanation for this CoeffReturnType typedef. - // - This is the return type of the coeff() method. - // - The LvalueBit means exactly that we can offer a coeffRef() method, which means exactly that we can get references - // to coeffs, which means exactly that we can have coeff() return a const reference (as opposed to returning a value). - // - The is_artihmetic check is required since "const int", "const double", etc. will cause warnings on some systems - // while the declaration of "const T", where T is a non arithmetic type does not. Always returning "const Scalar&" is - // not possible, since the underlying expressions might not offer a valid address the reference could be referring to. - typedef typename internal::conditional::Flags&LvalueBit), - const Scalar&, - typename internal::conditional::value, Scalar, const Scalar>::type - >::type CoeffReturnType; - - typedef typename internal::add_const_on_value_type_if_arithmetic< - typename internal::packet_traits::type - >::type PacketReturnType; - - typedef EigenBase Base; - using Base::rows; - using Base::cols; - using Base::size; - using Base::derived; - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Index rowIndexByOuterInner(Index outer, Index inner) const - { - return int(Derived::RowsAtCompileTime) == 1 ? 0 - : int(Derived::ColsAtCompileTime) == 1 ? inner - : int(Derived::Flags)&RowMajorBit ? outer - : inner; - } - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Index colIndexByOuterInner(Index outer, Index inner) const - { - return int(Derived::ColsAtCompileTime) == 1 ? 0 - : int(Derived::RowsAtCompileTime) == 1 ? inner - : int(Derived::Flags)&RowMajorBit ? inner - : outer; - } - - /** Short version: don't use this function, use - * \link operator()(Index,Index) const \endlink instead. - * - * Long version: this function is similar to - * \link operator()(Index,Index) const \endlink, but without the assertion. - * Use this for limiting the performance cost of debugging code when doing - * repeated coefficient access. Only use this when it is guaranteed that the - * parameters \a row and \a col are in range. - * - * If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this - * function equivalent to \link operator()(Index,Index) const \endlink. - * - * \sa operator()(Index,Index) const, coeffRef(Index,Index), coeff(Index) const - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const - { - eigen_internal_assert(row >= 0 && row < rows() - && col >= 0 && col < cols()); - return internal::evaluator(derived()).coeff(row,col); - } - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE CoeffReturnType coeffByOuterInner(Index outer, Index inner) const - { - return coeff(rowIndexByOuterInner(outer, inner), - colIndexByOuterInner(outer, inner)); - } - - /** \returns the coefficient at given the given row and column. - * - * \sa operator()(Index,Index), operator[](Index) - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE CoeffReturnType operator()(Index row, Index col) const - { - eigen_assert(row >= 0 && row < rows() - && col >= 0 && col < cols()); - return coeff(row, col); - } - - /** Short version: don't use this function, use - * \link operator[](Index) const \endlink instead. - * - * Long version: this function is similar to - * \link operator[](Index) const \endlink, but without the assertion. - * Use this for limiting the performance cost of debugging code when doing - * repeated coefficient access. Only use this when it is guaranteed that the - * parameter \a index is in range. - * - * If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this - * function equivalent to \link operator[](Index) const \endlink. - * - * \sa operator[](Index) const, coeffRef(Index), coeff(Index,Index) const - */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE CoeffReturnType - coeff(Index index) const - { - EIGEN_STATIC_ASSERT(internal::evaluator::Flags & LinearAccessBit, - THIS_COEFFICIENT_ACCESSOR_TAKING_ONE_ACCESS_IS_ONLY_FOR_EXPRESSIONS_ALLOWING_LINEAR_ACCESS) - eigen_internal_assert(index >= 0 && index < size()); - return internal::evaluator(derived()).coeff(index); - } - - - /** \returns the coefficient at given index. - * - * This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit. - * - * \sa operator[](Index), operator()(Index,Index) const, x() const, y() const, - * z() const, w() const - */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE CoeffReturnType - operator[](Index index) const - { - EIGEN_STATIC_ASSERT(Derived::IsVectorAtCompileTime, - THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD) - eigen_assert(index >= 0 && index < size()); - return coeff(index); - } - - /** \returns the coefficient at given index. - * - * This is synonymous to operator[](Index) const. - * - * This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit. - * - * \sa operator[](Index), operator()(Index,Index) const, x() const, y() const, - * z() const, w() const - */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE CoeffReturnType - operator()(Index index) const - { - eigen_assert(index >= 0 && index < size()); - return coeff(index); - } - - /** equivalent to operator[](0). */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE CoeffReturnType - x() const { return (*this)[0]; } - - /** equivalent to operator[](1). */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE CoeffReturnType - y() const - { - EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime==-1 || Derived::SizeAtCompileTime>=2, OUT_OF_RANGE_ACCESS); - return (*this)[1]; - } - - /** equivalent to operator[](2). */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE CoeffReturnType - z() const - { - EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime==-1 || Derived::SizeAtCompileTime>=3, OUT_OF_RANGE_ACCESS); - return (*this)[2]; - } - - /** equivalent to operator[](3). */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE CoeffReturnType - w() const - { - EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime==-1 || Derived::SizeAtCompileTime>=4, OUT_OF_RANGE_ACCESS); - return (*this)[3]; - } - - /** \internal - * \returns the packet of coefficients starting at the given row and column. It is your responsibility - * to ensure that a packet really starts there. This method is only available on expressions having the - * PacketAccessBit. - * - * The \a LoadMode parameter may have the value \a #Aligned or \a #Unaligned. Its effect is to select - * the appropriate vectorization instruction. Aligned access is faster, but is only possible for packets - * starting at an address which is a multiple of the packet size. - */ - - template - EIGEN_STRONG_INLINE PacketReturnType packet(Index row, Index col) const - { - typedef typename internal::packet_traits::type DefaultPacketType; - eigen_internal_assert(row >= 0 && row < rows() && col >= 0 && col < cols()); - return internal::evaluator(derived()).template packet(row,col); - } - - - /** \internal */ - template - EIGEN_STRONG_INLINE PacketReturnType packetByOuterInner(Index outer, Index inner) const - { - return packet(rowIndexByOuterInner(outer, inner), - colIndexByOuterInner(outer, inner)); - } - - /** \internal - * \returns the packet of coefficients starting at the given index. It is your responsibility - * to ensure that a packet really starts there. This method is only available on expressions having the - * PacketAccessBit and the LinearAccessBit. - * - * The \a LoadMode parameter may have the value \a #Aligned or \a #Unaligned. Its effect is to select - * the appropriate vectorization instruction. Aligned access is faster, but is only possible for packets - * starting at an address which is a multiple of the packet size. - */ - - template - EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const - { - EIGEN_STATIC_ASSERT(internal::evaluator::Flags & LinearAccessBit, - THIS_COEFFICIENT_ACCESSOR_TAKING_ONE_ACCESS_IS_ONLY_FOR_EXPRESSIONS_ALLOWING_LINEAR_ACCESS) - typedef typename internal::packet_traits::type DefaultPacketType; - eigen_internal_assert(index >= 0 && index < size()); - return internal::evaluator(derived()).template packet(index); - } - - protected: - // explanation: DenseBase is doing "using ..." on the methods from DenseCoeffsBase. - // But some methods are only available in the DirectAccess case. - // So we add dummy methods here with these names, so that "using... " doesn't fail. - // It's not private so that the child class DenseBase can access them, and it's not public - // either since it's an implementation detail, so has to be protected. - void coeffRef(); - void coeffRefByOuterInner(); - void writePacket(); - void writePacketByOuterInner(); - void copyCoeff(); - void copyCoeffByOuterInner(); - void copyPacket(); - void copyPacketByOuterInner(); - void stride(); - void innerStride(); - void outerStride(); - void rowStride(); - void colStride(); + * \ingroup Core_Module + * \tparam Derived Type of the derived class + * + * \note #ReadOnlyAccessors Constant indicating read-only access + * + * This class defines the \c operator() \c const function and friends, which can be used to read specific + * entries of a matrix or array. + * + * \sa DenseCoeffsBase, DenseCoeffsBase, + * \ref TopicClassHierarchy + */ +template +class DenseCoeffsBase : public EigenBase { + public: + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::packet_traits::type PacketScalar; + + // Explanation for this CoeffReturnType typedef. + // - This is the return type of the coeff() method. + // - The LvalueBit means exactly that we can offer a coeffRef() method, which means exactly that we can get references + // to coeffs, which means exactly that we can have coeff() return a const reference (as opposed to returning a value). + // - The is_arithmetic check is required since "const int", "const double", etc. will cause warnings on some systems + // while the declaration of "const T", where T is a non arithmetic type does not. Always returning "const Scalar&" is + // not possible, since the underlying expressions might not offer a valid address the reference could be referring to. + typedef std::conditional_t::Flags& LvalueBit), const Scalar&, + std::conditional_t::value, Scalar, const Scalar>> + CoeffReturnType; + + typedef typename internal::add_const_on_value_type_if_arithmetic::type>::type + PacketReturnType; + + typedef EigenBase Base; + using Base::cols; + using Base::derived; + using Base::rows; + using Base::size; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rowIndexByOuterInner(Index outer, Index inner) const { + return int(Derived::RowsAtCompileTime) == 1 ? 0 + : int(Derived::ColsAtCompileTime) == 1 ? inner + : int(Derived::Flags) & RowMajorBit ? outer + : inner; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index colIndexByOuterInner(Index outer, Index inner) const { + return int(Derived::ColsAtCompileTime) == 1 ? 0 + : int(Derived::RowsAtCompileTime) == 1 ? inner + : int(Derived::Flags) & RowMajorBit ? inner + : outer; + } + + /** Short version: don't use this function, use + * \link operator()(Index,Index) const \endlink instead. + * + * Long version: this function is similar to + * \link operator()(Index,Index) const \endlink, but without the assertion. + * Use this for limiting the performance cost of debugging code when doing + * repeated coefficient access. Only use this when it is guaranteed that the + * parameters \a row and \a col are in range. + * + * If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this + * function equivalent to \link operator()(Index,Index) const \endlink. + * + * \sa operator()(Index,Index) const, coeffRef(Index,Index), coeff(Index) const + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR CoeffReturnType coeff(Index row, Index col) const { + eigen_internal_assert(row >= 0 && row < rows() && col >= 0 && col < cols()); + return internal::evaluator(derived()).coeff(row, col); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR CoeffReturnType coeffByOuterInner(Index outer, + Index inner) const { + return coeff(rowIndexByOuterInner(outer, inner), colIndexByOuterInner(outer, inner)); + } + + /** \returns the coefficient at given the given row and column. + * + * \sa operator()(Index,Index), operator[](Index) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR CoeffReturnType operator()(Index row, Index col) const { + eigen_assert(row >= 0 && row < rows() && col >= 0 && col < cols()); + return coeff(row, col); + } + + /** Short version: don't use this function, use + * \link operator[](Index) const \endlink instead. + * + * Long version: this function is similar to + * \link operator[](Index) const \endlink, but without the assertion. + * Use this for limiting the performance cost of debugging code when doing + * repeated coefficient access. Only use this when it is guaranteed that the + * parameter \a index is in range. + * + * If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this + * function equivalent to \link operator[](Index) const \endlink. + * + * \sa operator[](Index) const, coeffRef(Index), coeff(Index,Index) const + */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR CoeffReturnType coeff(Index index) const { + EIGEN_STATIC_ASSERT(internal::evaluator::Flags & LinearAccessBit, + THIS_COEFFICIENT_ACCESSOR_TAKING_ONE_ACCESS_IS_ONLY_FOR_EXPRESSIONS_ALLOWING_LINEAR_ACCESS) + eigen_internal_assert(index >= 0 && index < size()); + return internal::evaluator(derived()).coeff(index); + } + + /** \returns the coefficient at given index. + * + * This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit. + * + * \sa operator[](Index), operator()(Index,Index) const, x() const, y() const, + * z() const, w() const + */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR CoeffReturnType operator[](Index index) const { + EIGEN_STATIC_ASSERT(Derived::IsVectorAtCompileTime, + THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD) + eigen_assert(index >= 0 && index < size()); + return coeff(index); + } + + /** \returns the coefficient at given index. + * + * This is synonymous to operator[](Index) const. + * + * This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit. + * + * \sa operator[](Index), operator()(Index,Index) const, x() const, y() const, + * z() const, w() const + */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR CoeffReturnType operator()(Index index) const { + eigen_assert(index >= 0 && index < size()); + return coeff(index); + } + + /** equivalent to operator[](0). */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR CoeffReturnType x() const { return (*this)[0]; } + + /** equivalent to operator[](1). */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR CoeffReturnType y() const { + EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime == -1 || Derived::SizeAtCompileTime >= 2, OUT_OF_RANGE_ACCESS); + return (*this)[1]; + } + + /** equivalent to operator[](2). */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR CoeffReturnType z() const { + EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime == -1 || Derived::SizeAtCompileTime >= 3, OUT_OF_RANGE_ACCESS); + return (*this)[2]; + } + + /** equivalent to operator[](3). */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR CoeffReturnType w() const { + EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime == -1 || Derived::SizeAtCompileTime >= 4, OUT_OF_RANGE_ACCESS); + return (*this)[3]; + } + + /** \internal + * \returns the packet of coefficients starting at the given row and column. It is your responsibility + * to ensure that a packet really starts there. This method is only available on expressions having the + * PacketAccessBit. + * + * The \a LoadMode parameter may have the value \a #Aligned or \a #Unaligned. Its effect is to select + * the appropriate vectorization instruction. Aligned access is faster, but is only possible for packets + * starting at an address which is a multiple of the packet size. + */ + + template + EIGEN_STRONG_INLINE PacketReturnType packet(Index row, Index col) const { + typedef typename internal::packet_traits::type DefaultPacketType; + eigen_internal_assert(row >= 0 && row < rows() && col >= 0 && col < cols()); + return internal::evaluator(derived()).template packet(row, col); + } + + /** \internal */ + template + EIGEN_STRONG_INLINE PacketReturnType packetByOuterInner(Index outer, Index inner) const { + return packet(rowIndexByOuterInner(outer, inner), colIndexByOuterInner(outer, inner)); + } + + /** \internal + * \returns the packet of coefficients starting at the given index. It is your responsibility + * to ensure that a packet really starts there. This method is only available on expressions having the + * PacketAccessBit and the LinearAccessBit. + * + * The \a LoadMode parameter may have the value \a #Aligned or \a #Unaligned. Its effect is to select + * the appropriate vectorization instruction. Aligned access is faster, but is only possible for packets + * starting at an address which is a multiple of the packet size. + */ + + template + EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const { + EIGEN_STATIC_ASSERT(internal::evaluator::Flags & LinearAccessBit, + THIS_COEFFICIENT_ACCESSOR_TAKING_ONE_ACCESS_IS_ONLY_FOR_EXPRESSIONS_ALLOWING_LINEAR_ACCESS) + typedef typename internal::packet_traits::type DefaultPacketType; + eigen_internal_assert(index >= 0 && index < size()); + return internal::evaluator(derived()).template packet(index); + } + + protected: + // explanation: DenseBase is doing "using ..." on the methods from DenseCoeffsBase. + // But some methods are only available in the DirectAccess case. + // So we add dummy methods here with these names, so that "using... " doesn't fail. + // It's not private so that the child class DenseBase can access them, and it's not public + // either since it's an implementation detail, so has to be protected. + void coeffRef(); + void coeffRefByOuterInner(); + void writePacket(); + void writePacketByOuterInner(); + void copyCoeff(); + void copyCoeffByOuterInner(); + void copyPacket(); + void copyPacketByOuterInner(); + void stride(); + void innerStride(); + void outerStride(); + void rowStride(); + void colStride(); }; /** \brief Base class providing read/write coefficient access to matrices and arrays. - * \ingroup Core_Module - * \tparam Derived Type of the derived class - * - * \note #WriteAccessors Constant indicating read/write access - * - * This class defines the non-const \c operator() function and friends, which can be used to write specific - * entries of a matrix or array. This class inherits DenseCoeffsBase which - * defines the const variant for reading specific entries. - * - * \sa DenseCoeffsBase, \ref TopicClassHierarchy - */ -template -class DenseCoeffsBase : public DenseCoeffsBase -{ - public: - - typedef DenseCoeffsBase Base; - - typedef typename internal::traits::StorageKind StorageKind; - typedef typename internal::traits::Scalar Scalar; - typedef typename internal::packet_traits::type PacketScalar; - typedef typename NumTraits::Real RealScalar; - - using Base::coeff; - using Base::rows; - using Base::cols; - using Base::size; - using Base::derived; - using Base::rowIndexByOuterInner; - using Base::colIndexByOuterInner; - using Base::operator[]; - using Base::operator(); - using Base::x; - using Base::y; - using Base::z; - using Base::w; - - /** Short version: don't use this function, use - * \link operator()(Index,Index) \endlink instead. - * - * Long version: this function is similar to - * \link operator()(Index,Index) \endlink, but without the assertion. - * Use this for limiting the performance cost of debugging code when doing - * repeated coefficient access. Only use this when it is guaranteed that the - * parameters \a row and \a col are in range. - * - * If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this - * function equivalent to \link operator()(Index,Index) \endlink. - * - * \sa operator()(Index,Index), coeff(Index, Index) const, coeffRef(Index) - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col) - { - eigen_internal_assert(row >= 0 && row < rows() - && col >= 0 && col < cols()); - return internal::evaluator(derived()).coeffRef(row,col); - } - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Scalar& - coeffRefByOuterInner(Index outer, Index inner) - { - return coeffRef(rowIndexByOuterInner(outer, inner), - colIndexByOuterInner(outer, inner)); - } - - /** \returns a reference to the coefficient at given the given row and column. - * - * \sa operator[](Index) - */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Scalar& - operator()(Index row, Index col) - { - eigen_assert(row >= 0 && row < rows() - && col >= 0 && col < cols()); - return coeffRef(row, col); - } - - - /** Short version: don't use this function, use - * \link operator[](Index) \endlink instead. - * - * Long version: this function is similar to - * \link operator[](Index) \endlink, but without the assertion. - * Use this for limiting the performance cost of debugging code when doing - * repeated coefficient access. Only use this when it is guaranteed that the - * parameters \a row and \a col are in range. - * - * If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this - * function equivalent to \link operator[](Index) \endlink. - * - * \sa operator[](Index), coeff(Index) const, coeffRef(Index,Index) - */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Scalar& - coeffRef(Index index) - { - EIGEN_STATIC_ASSERT(internal::evaluator::Flags & LinearAccessBit, - THIS_COEFFICIENT_ACCESSOR_TAKING_ONE_ACCESS_IS_ONLY_FOR_EXPRESSIONS_ALLOWING_LINEAR_ACCESS) - eigen_internal_assert(index >= 0 && index < size()); - return internal::evaluator(derived()).coeffRef(index); - } - - /** \returns a reference to the coefficient at given index. - * - * This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit. - * - * \sa operator[](Index) const, operator()(Index,Index), x(), y(), z(), w() - */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Scalar& - operator[](Index index) - { - EIGEN_STATIC_ASSERT(Derived::IsVectorAtCompileTime, - THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD) - eigen_assert(index >= 0 && index < size()); - return coeffRef(index); - } - - /** \returns a reference to the coefficient at given index. - * - * This is synonymous to operator[](Index). - * - * This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit. - * - * \sa operator[](Index) const, operator()(Index,Index), x(), y(), z(), w() - */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Scalar& - operator()(Index index) - { - eigen_assert(index >= 0 && index < size()); - return coeffRef(index); - } - - /** equivalent to operator[](0). */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Scalar& - x() { return (*this)[0]; } - - /** equivalent to operator[](1). */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Scalar& - y() - { - EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime==-1 || Derived::SizeAtCompileTime>=2, OUT_OF_RANGE_ACCESS); - return (*this)[1]; - } - - /** equivalent to operator[](2). */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Scalar& - z() - { - EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime==-1 || Derived::SizeAtCompileTime>=3, OUT_OF_RANGE_ACCESS); - return (*this)[2]; - } - - /** equivalent to operator[](3). */ - - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Scalar& - w() - { - EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime==-1 || Derived::SizeAtCompileTime>=4, OUT_OF_RANGE_ACCESS); - return (*this)[3]; - } + * \ingroup Core_Module + * \tparam Derived Type of the derived class + * + * \note #WriteAccessors Constant indicating read/write access + * + * This class defines the non-const \c operator() function and friends, which can be used to write specific + * entries of a matrix or array. This class inherits DenseCoeffsBase which + * defines the const variant for reading specific entries. + * + * \sa DenseCoeffsBase, \ref TopicClassHierarchy + */ +template +class DenseCoeffsBase : public DenseCoeffsBase { + public: + typedef DenseCoeffsBase Base; + + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::packet_traits::type PacketScalar; + typedef typename NumTraits::Real RealScalar; + + using Base::coeff; + using Base::colIndexByOuterInner; + using Base::cols; + using Base::derived; + using Base::rowIndexByOuterInner; + using Base::rows; + using Base::size; + using Base::operator[]; + using Base::operator(); + using Base::w; + using Base::x; + using Base::y; + using Base::z; + + /** Short version: don't use this function, use + * \link operator()(Index,Index) \endlink instead. + * + * Long version: this function is similar to + * \link operator()(Index,Index) \endlink, but without the assertion. + * Use this for limiting the performance cost of debugging code when doing + * repeated coefficient access. Only use this when it is guaranteed that the + * parameters \a row and \a col are in range. + * + * If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this + * function equivalent to \link operator()(Index,Index) \endlink. + * + * \sa operator()(Index,Index), coeff(Index, Index) const, coeffRef(Index) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col) { + eigen_internal_assert(row >= 0 && row < rows() && col >= 0 && col < cols()); + return internal::evaluator(derived()).coeffRef(row, col); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRefByOuterInner(Index outer, Index inner) { + return coeffRef(rowIndexByOuterInner(outer, inner), colIndexByOuterInner(outer, inner)); + } + + /** \returns a reference to the coefficient at given the given row and column. + * + * \sa operator[](Index) + */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator()(Index row, Index col) { + eigen_assert(row >= 0 && row < rows() && col >= 0 && col < cols()); + return coeffRef(row, col); + } + + /** Short version: don't use this function, use + * \link operator[](Index) \endlink instead. + * + * Long version: this function is similar to + * \link operator[](Index) \endlink, but without the assertion. + * Use this for limiting the performance cost of debugging code when doing + * repeated coefficient access. Only use this when it is guaranteed that the + * parameters \a row and \a col are in range. + * + * If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this + * function equivalent to \link operator[](Index) \endlink. + * + * \sa operator[](Index), coeff(Index) const, coeffRef(Index,Index) + */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { + EIGEN_STATIC_ASSERT(internal::evaluator::Flags & LinearAccessBit, + THIS_COEFFICIENT_ACCESSOR_TAKING_ONE_ACCESS_IS_ONLY_FOR_EXPRESSIONS_ALLOWING_LINEAR_ACCESS) + eigen_internal_assert(index >= 0 && index < size()); + return internal::evaluator(derived()).coeffRef(index); + } + + /** \returns a reference to the coefficient at given index. + * + * This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit. + * + * \sa operator[](Index) const, operator()(Index,Index), x(), y(), z(), w() + */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator[](Index index) { + EIGEN_STATIC_ASSERT(Derived::IsVectorAtCompileTime, + THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD) + eigen_assert(index >= 0 && index < size()); + return coeffRef(index); + } + + /** \returns a reference to the coefficient at given index. + * + * This is synonymous to operator[](Index). + * + * This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit. + * + * \sa operator[](Index) const, operator()(Index,Index), x(), y(), z(), w() + */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Scalar& operator()(Index index) { + eigen_assert(index >= 0 && index < size()); + return coeffRef(index); + } + + /** equivalent to operator[](0). */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Scalar& x() { return (*this)[0]; } + + /** equivalent to operator[](1). */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Scalar& y() { + EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime == -1 || Derived::SizeAtCompileTime >= 2, OUT_OF_RANGE_ACCESS); + return (*this)[1]; + } + + /** equivalent to operator[](2). */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Scalar& z() { + EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime == -1 || Derived::SizeAtCompileTime >= 3, OUT_OF_RANGE_ACCESS); + return (*this)[2]; + } + + /** equivalent to operator[](3). */ + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Scalar& w() { + EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime == -1 || Derived::SizeAtCompileTime >= 4, OUT_OF_RANGE_ACCESS); + return (*this)[3]; + } }; /** \brief Base class providing direct read-only coefficient access to matrices and arrays. - * \ingroup Core_Module - * \tparam Derived Type of the derived class - * - * \note #DirectAccessors Constant indicating direct access - * - * This class defines functions to work with strides which can be used to access entries directly. This class - * inherits DenseCoeffsBase which defines functions to access entries read-only using - * \c operator() . - * - * \sa \blank \ref TopicClassHierarchy - */ -template -class DenseCoeffsBase : public DenseCoeffsBase -{ - public: - - typedef DenseCoeffsBase Base; - typedef typename internal::traits::Scalar Scalar; - typedef typename NumTraits::Real RealScalar; - - using Base::rows; - using Base::cols; - using Base::size; - using Base::derived; - - /** \returns the pointer increment between two consecutive elements within a slice in the inner direction. - * - * \sa outerStride(), rowStride(), colStride() - */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index innerStride() const - { - return derived().innerStride(); - } - - /** \returns the pointer increment between two consecutive inner slices (for example, between two consecutive columns - * in a column-major matrix). - * - * \sa innerStride(), rowStride(), colStride() - */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outerStride() const - { - return derived().outerStride(); - } - - // FIXME shall we remove it ? - EIGEN_CONSTEXPR inline Index stride() const - { - return Derived::IsVectorAtCompileTime ? innerStride() : outerStride(); - } - - /** \returns the pointer increment between two consecutive rows. - * - * \sa innerStride(), outerStride(), colStride() - */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rowStride() const - { - return Derived::IsRowMajor ? outerStride() : innerStride(); - } - - /** \returns the pointer increment between two consecutive columns. - * - * \sa innerStride(), outerStride(), rowStride() - */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index colStride() const - { - return Derived::IsRowMajor ? innerStride() : outerStride(); - } + * \ingroup Core_Module + * \tparam Derived Type of the derived class + * + * \note #DirectAccessors Constant indicating direct access + * + * This class defines functions to work with strides which can be used to access entries directly. This class + * inherits DenseCoeffsBase which defines functions to access entries read-only using + * \c operator() . + * + * \sa \blank \ref TopicClassHierarchy + */ +template +class DenseCoeffsBase : public DenseCoeffsBase { + public: + typedef DenseCoeffsBase Base; + typedef typename internal::traits::Scalar Scalar; + typedef typename NumTraits::Real RealScalar; + + using Base::cols; + using Base::derived; + using Base::rows; + using Base::size; + + /** \returns the pointer increment between two consecutive elements within a slice in the inner direction. + * + * \sa outerStride(), rowStride(), colStride() + */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const { return derived().innerStride(); } + + /** \returns the pointer increment between two consecutive inner slices (for example, between two consecutive columns + * in a column-major matrix). + * + * \sa innerStride(), rowStride(), colStride() + */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const { return derived().outerStride(); } + + // FIXME shall we remove it ? + EIGEN_CONSTEXPR inline Index stride() const { return Derived::IsVectorAtCompileTime ? innerStride() : outerStride(); } + + /** \returns the pointer increment between two consecutive rows. + * + * \sa innerStride(), outerStride(), colStride() + */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rowStride() const { + return Derived::IsRowMajor ? outerStride() : innerStride(); + } + + /** \returns the pointer increment between two consecutive columns. + * + * \sa innerStride(), outerStride(), rowStride() + */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index colStride() const { + return Derived::IsRowMajor ? innerStride() : outerStride(); + } }; /** \brief Base class providing direct read/write coefficient access to matrices and arrays. - * \ingroup Core_Module - * \tparam Derived Type of the derived class - * - * \note #DirectWriteAccessors Constant indicating direct access - * - * This class defines functions to work with strides which can be used to access entries directly. This class - * inherits DenseCoeffsBase which defines functions to access entries read/write using - * \c operator(). - * - * \sa \blank \ref TopicClassHierarchy - */ -template -class DenseCoeffsBase - : public DenseCoeffsBase -{ - public: - - typedef DenseCoeffsBase Base; - typedef typename internal::traits::Scalar Scalar; - typedef typename NumTraits::Real RealScalar; - - using Base::rows; - using Base::cols; - using Base::size; - using Base::derived; - - /** \returns the pointer increment between two consecutive elements within a slice in the inner direction. - * - * \sa outerStride(), rowStride(), colStride() - */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index innerStride() const EIGEN_NOEXCEPT - { - return derived().innerStride(); - } - - /** \returns the pointer increment between two consecutive inner slices (for example, between two consecutive columns - * in a column-major matrix). - * - * \sa innerStride(), rowStride(), colStride() - */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outerStride() const EIGEN_NOEXCEPT - { - return derived().outerStride(); - } - - // FIXME shall we remove it ? - EIGEN_CONSTEXPR inline Index stride() const EIGEN_NOEXCEPT - { - return Derived::IsVectorAtCompileTime ? innerStride() : outerStride(); - } - - /** \returns the pointer increment between two consecutive rows. - * - * \sa innerStride(), outerStride(), colStride() - */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rowStride() const EIGEN_NOEXCEPT - { - return Derived::IsRowMajor ? outerStride() : innerStride(); - } - - /** \returns the pointer increment between two consecutive columns. - * - * \sa innerStride(), outerStride(), rowStride() - */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index colStride() const EIGEN_NOEXCEPT - { - return Derived::IsRowMajor ? innerStride() : outerStride(); - } + * \ingroup Core_Module + * \tparam Derived Type of the derived class + * + * \note #DirectWriteAccessors Constant indicating direct access + * + * This class defines functions to work with strides which can be used to access entries directly. This class + * inherits DenseCoeffsBase which defines functions to access entries read/write using + * \c operator(). + * + * \sa \blank \ref TopicClassHierarchy + */ +template +class DenseCoeffsBase : public DenseCoeffsBase { + public: + typedef DenseCoeffsBase Base; + typedef typename internal::traits::Scalar Scalar; + typedef typename NumTraits::Real RealScalar; + + using Base::cols; + using Base::derived; + using Base::rows; + using Base::size; + + /** \returns the pointer increment between two consecutive elements within a slice in the inner direction. + * + * \sa outerStride(), rowStride(), colStride() + */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const EIGEN_NOEXCEPT { return derived().innerStride(); } + + /** \returns the pointer increment between two consecutive inner slices (for example, between two consecutive columns + * in a column-major matrix). + * + * \sa innerStride(), rowStride(), colStride() + */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const EIGEN_NOEXCEPT { return derived().outerStride(); } + + // FIXME shall we remove it ? + EIGEN_CONSTEXPR inline Index stride() const EIGEN_NOEXCEPT { + return Derived::IsVectorAtCompileTime ? innerStride() : outerStride(); + } + + /** \returns the pointer increment between two consecutive rows. + * + * \sa innerStride(), outerStride(), colStride() + */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rowStride() const EIGEN_NOEXCEPT { + return Derived::IsRowMajor ? outerStride() : innerStride(); + } + + /** \returns the pointer increment between two consecutive columns. + * + * \sa innerStride(), outerStride(), rowStride() + */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index colStride() const EIGEN_NOEXCEPT { + return Derived::IsRowMajor ? innerStride() : outerStride(); + } }; namespace internal { -template -struct first_aligned_impl -{ - static EIGEN_CONSTEXPR inline Index run(const Derived&) EIGEN_NOEXCEPT - { return 0; } +template +struct first_aligned_impl { + static EIGEN_CONSTEXPR inline Index run(const Derived&) EIGEN_NOEXCEPT { return 0; } }; -template -struct first_aligned_impl -{ - static inline Index run(const Derived& m) - { - return internal::first_aligned(m.data(), m.size()); - } +template +struct first_aligned_impl { + static inline Index run(const Derived& m) { return internal::first_aligned(m.data(), m.size()); } }; -/** \internal \returns the index of the first element of the array stored by \a m that is properly aligned with respect to \a Alignment for vectorization. - * - * \tparam Alignment requested alignment in Bytes. - * - * There is also the variant first_aligned(const Scalar*, Integer) defined in Memory.h. See it for more - * documentation. - */ -template -static inline Index first_aligned(const DenseBase& m) -{ +/** \internal \returns the index of the first element of the array stored by \a m that is properly aligned with respect + * to \a Alignment for vectorization. + * + * \tparam Alignment requested alignment in Bytes. + * + * There is also the variant first_aligned(const Scalar*, Integer) defined in Memory.h. See it for more + * documentation. + */ +template +static inline Index first_aligned(const DenseBase& m) { enum { ReturnZero = (int(evaluator::Alignment) >= Alignment) || !(Derived::Flags & DirectAccessBit) }; return first_aligned_impl::run(m.derived()); } -template -static inline Index first_default_aligned(const DenseBase& m) -{ +template +static inline Index first_default_aligned(const DenseBase& m) { typedef typename Derived::Scalar Scalar; typedef typename packet_traits::type DefaultPacketType; - return internal::first_aligned::alignment),Derived>(m); + return internal::first_aligned::alignment), Derived>(m); } -template::ret> -struct inner_stride_at_compile_time -{ +template ::ret> +struct inner_stride_at_compile_time { enum { ret = traits::InnerStrideAtCompileTime }; }; -template -struct inner_stride_at_compile_time -{ +template +struct inner_stride_at_compile_time { enum { ret = 0 }; }; -template::ret> -struct outer_stride_at_compile_time -{ +template ::ret> +struct outer_stride_at_compile_time { enum { ret = traits::OuterStrideAtCompileTime }; }; -template -struct outer_stride_at_compile_time -{ +template +struct outer_stride_at_compile_time { enum { ret = 0 }; }; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_DENSECOEFFSBASE_H +#endif // EIGEN_DENSECOEFFSBASE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DenseStorage.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DenseStorage.h index 08ef6c53061..f61693982ed 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DenseStorage.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DenseStorage.h @@ -13,168 +13,132 @@ #define EIGEN_MATRIXSTORAGE_H #ifdef EIGEN_DENSE_STORAGE_CTOR_PLUGIN - #define EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(X) X; EIGEN_DENSE_STORAGE_CTOR_PLUGIN; +#define EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(X) \ + X; \ + EIGEN_DENSE_STORAGE_CTOR_PLUGIN; #else - #define EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(X) +#define EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(X) #endif +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { struct constructor_without_unaligned_array_assert {}; -template -EIGEN_DEVICE_FUNC -void check_static_allocation_size() -{ - // if EIGEN_STACK_ALLOCATION_LIMIT is defined to 0, then no limit - #if EIGEN_STACK_ALLOCATION_LIMIT +template +EIGEN_DEVICE_FUNC constexpr void check_static_allocation_size() { +// if EIGEN_STACK_ALLOCATION_LIMIT is defined to 0, then no limit +#if EIGEN_STACK_ALLOCATION_LIMIT EIGEN_STATIC_ASSERT(Size * sizeof(T) <= EIGEN_STACK_ALLOCATION_LIMIT, OBJECT_ALLOCATED_ON_STACK_IS_TOO_BIG); - #endif +#endif } /** \internal - * Static array. If the MatrixOrArrayOptions require auto-alignment, the array will be automatically aligned: - * to 16 bytes boundary if the total size is a multiple of 16 bytes. - */ + * Static array. If the MatrixOrArrayOptions require auto-alignment, the array will be automatically aligned: + * to 16 bytes boundary if the total size is a multiple of 16 bytes. + */ template ::value > -struct plain_array -{ + int Alignment = (MatrixOrArrayOptions & DontAlign) ? 0 : compute_default_alignment::value> +struct plain_array { T array[Size]; - EIGEN_DEVICE_FUNC - plain_array() - { - check_static_allocation_size(); - } + EIGEN_DEVICE_FUNC constexpr plain_array() { check_static_allocation_size(); } - EIGEN_DEVICE_FUNC - plain_array(constructor_without_unaligned_array_assert) - { - check_static_allocation_size(); + EIGEN_DEVICE_FUNC constexpr plain_array(constructor_without_unaligned_array_assert) { + check_static_allocation_size(); } }; #if defined(EIGEN_DISABLE_UNALIGNED_ARRAY_ASSERT) - #define EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(sizemask) -#elif EIGEN_GNUC_AT_LEAST(4,7) - // GCC 4.7 is too aggressive in its optimizations and remove the alignment test based on the fact the array is declared to be aligned. - // See this bug report: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=53900 - // Hiding the origin of the array pointer behind a function argument seems to do the trick even if the function is inlined: - template - EIGEN_ALWAYS_INLINE PtrType eigen_unaligned_array_assert_workaround_gcc47(PtrType array) { return array; } - #define EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(sizemask) \ - eigen_assert((internal::UIntPtr(eigen_unaligned_array_assert_workaround_gcc47(array)) & (sizemask)) == 0 \ - && "this assertion is explained here: " \ - "http://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html" \ - " **** READ THIS WEB PAGE !!! ****"); +#define EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(sizemask) #else - #define EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(sizemask) \ - eigen_assert((internal::UIntPtr(array) & (sizemask)) == 0 \ - && "this assertion is explained here: " \ - "http://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html" \ - " **** READ THIS WEB PAGE !!! ****"); +#define EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(sizemask) \ + eigen_assert((internal::is_constant_evaluated() || (std::uintptr_t(array) & (sizemask)) == 0) && \ + "this assertion is explained here: " \ + "http://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html" \ + " **** READ THIS WEB PAGE !!! ****"); #endif template -struct plain_array -{ +struct plain_array { EIGEN_ALIGN_TO_BOUNDARY(8) T array[Size]; - EIGEN_DEVICE_FUNC - plain_array() - { + EIGEN_DEVICE_FUNC constexpr plain_array() { EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(7); - check_static_allocation_size(); + check_static_allocation_size(); } - EIGEN_DEVICE_FUNC - plain_array(constructor_without_unaligned_array_assert) - { - check_static_allocation_size(); + EIGEN_DEVICE_FUNC constexpr plain_array(constructor_without_unaligned_array_assert) { + check_static_allocation_size(); } }; template -struct plain_array -{ +struct plain_array { EIGEN_ALIGN_TO_BOUNDARY(16) T array[Size]; - EIGEN_DEVICE_FUNC - plain_array() - { + EIGEN_DEVICE_FUNC constexpr plain_array() { EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(15); - check_static_allocation_size(); + check_static_allocation_size(); } - EIGEN_DEVICE_FUNC - plain_array(constructor_without_unaligned_array_assert) - { - check_static_allocation_size(); + EIGEN_DEVICE_FUNC constexpr plain_array(constructor_without_unaligned_array_assert) { + check_static_allocation_size(); } }; template -struct plain_array -{ +struct plain_array { EIGEN_ALIGN_TO_BOUNDARY(32) T array[Size]; - EIGEN_DEVICE_FUNC - plain_array() - { + EIGEN_DEVICE_FUNC constexpr plain_array() { EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(31); - check_static_allocation_size(); + check_static_allocation_size(); } - EIGEN_DEVICE_FUNC - plain_array(constructor_without_unaligned_array_assert) - { - check_static_allocation_size(); + EIGEN_DEVICE_FUNC constexpr plain_array(constructor_without_unaligned_array_assert) { + check_static_allocation_size(); } }; template -struct plain_array -{ +struct plain_array { EIGEN_ALIGN_TO_BOUNDARY(64) T array[Size]; - EIGEN_DEVICE_FUNC - plain_array() - { + EIGEN_DEVICE_FUNC constexpr plain_array() { EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(63); - check_static_allocation_size(); + check_static_allocation_size(); } - EIGEN_DEVICE_FUNC - plain_array(constructor_without_unaligned_array_assert) - { - check_static_allocation_size(); + EIGEN_DEVICE_FUNC constexpr plain_array(constructor_without_unaligned_array_assert) { + check_static_allocation_size(); } }; template -struct plain_array -{ +struct plain_array { T array[1]; - EIGEN_DEVICE_FUNC plain_array() {} - EIGEN_DEVICE_FUNC plain_array(constructor_without_unaligned_array_assert) {} + EIGEN_DEVICE_FUNC constexpr plain_array() {} + EIGEN_DEVICE_FUNC constexpr plain_array(constructor_without_unaligned_array_assert) {} }; struct plain_array_helper { - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - static void copy(const plain_array& src, const Eigen::Index size, - plain_array& dst) { + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static void copy( + const plain_array& src, const Eigen::Index size, + plain_array& dst) { smart_copy(src.array, src.array + size, dst.array); } - - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - static void swap(plain_array& a, const Eigen::Index a_size, - plain_array& b, const Eigen::Index b_size) { + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static void swap(plain_array& a, + const Eigen::Index a_size, + plain_array& b, + const Eigen::Index b_size) { if (a_size < b_size) { std::swap_ranges(b.array, b.array + a_size, a.array); smart_move(b.array + a_size, b.array + b_size, a.array + a_size); @@ -187,466 +151,500 @@ struct plain_array_helper { } }; -} // end namespace internal +} // end namespace internal /** \internal - * - * \class DenseStorage - * \ingroup Core_Module - * - * \brief Stores the data of a matrix - * - * This class stores the data of fixed-size, dynamic-size or mixed matrices - * in a way as compact as possible. - * - * \sa Matrix - */ -template class DenseStorage; + * + * \class DenseStorage + * \ingroup Core_Module + * + * \brief Stores the data of a matrix + * + * This class stores the data of fixed-size, dynamic-size or mixed matrices + * in a way as compact as possible. + * + * \sa Matrix + */ +template +class DenseStorage; // purely fixed-size matrix -template class DenseStorage -{ - internal::plain_array m_data; - public: - EIGEN_DEVICE_FUNC DenseStorage() { - EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = Size) - } - EIGEN_DEVICE_FUNC - explicit DenseStorage(internal::constructor_without_unaligned_array_assert) +template +class DenseStorage { + internal::plain_array m_data; + + public: + constexpr EIGEN_DEVICE_FUNC DenseStorage(){EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN( + Index size = + Size)} EIGEN_DEVICE_FUNC explicit constexpr DenseStorage(internal::constructor_without_unaligned_array_assert) : m_data(internal::constructor_without_unaligned_array_assert()) {} -#if !EIGEN_HAS_CXX11 || defined(EIGEN_DENSE_STORAGE_CTOR_PLUGIN) - EIGEN_DEVICE_FUNC - DenseStorage(const DenseStorage& other) : m_data(other.m_data) { - EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = Size) - } -#else - EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage&) = default; -#endif -#if !EIGEN_HAS_CXX11 - EIGEN_DEVICE_FUNC - DenseStorage& operator=(const DenseStorage& other) - { - if (this != &other) m_data = other.m_data; - return *this; - } +#if defined(EIGEN_DENSE_STORAGE_CTOR_PLUGIN) + EIGEN_DEVICE_FUNC constexpr DenseStorage(const DenseStorage& other) + : m_data(other.m_data){EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = Size)} #else - EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage&) = default; -#endif -#if EIGEN_HAS_RVALUE_REFERENCES -#if !EIGEN_HAS_CXX11 - EIGEN_DEVICE_FUNC DenseStorage(DenseStorage&& other) EIGEN_NOEXCEPT - : m_data(std::move(other.m_data)) - { - } - EIGEN_DEVICE_FUNC DenseStorage& operator=(DenseStorage&& other) EIGEN_NOEXCEPT - { - if (this != &other) - m_data = std::move(other.m_data); - return *this; - } -#else - EIGEN_DEVICE_FUNC DenseStorage(DenseStorage&&) = default; - EIGEN_DEVICE_FUNC DenseStorage& operator=(DenseStorage&&) = default; -#endif + EIGEN_DEVICE_FUNC constexpr DenseStorage(const DenseStorage&) = default; #endif - EIGEN_DEVICE_FUNC DenseStorage(Index size, Index rows, Index cols) { - EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) - eigen_internal_assert(size==rows*cols && rows==_Rows && cols==_Cols); - EIGEN_UNUSED_VARIABLE(size); - EIGEN_UNUSED_VARIABLE(rows); - EIGEN_UNUSED_VARIABLE(cols); - } - EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { - numext::swap(m_data, other.m_data); - } - EIGEN_DEVICE_FUNC static EIGEN_CONSTEXPR Index rows(void) EIGEN_NOEXCEPT {return _Rows;} - EIGEN_DEVICE_FUNC static EIGEN_CONSTEXPR Index cols(void) EIGEN_NOEXCEPT {return _Cols;} - EIGEN_DEVICE_FUNC void conservativeResize(Index,Index,Index) {} - EIGEN_DEVICE_FUNC void resize(Index,Index,Index) {} - EIGEN_DEVICE_FUNC const T *data() const { return m_data.array; } - EIGEN_DEVICE_FUNC T *data() { return m_data.array; } + EIGEN_DEVICE_FUNC constexpr DenseStorage + & + operator=(const DenseStorage&) = default; + EIGEN_DEVICE_FUNC constexpr DenseStorage(DenseStorage&&) = default; + EIGEN_DEVICE_FUNC constexpr DenseStorage& operator=(DenseStorage&&) = default; + EIGEN_DEVICE_FUNC constexpr DenseStorage(Index size, Index rows, Index cols) { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) + eigen_internal_assert(size == rows * cols && rows == Rows_ && cols == Cols_); + EIGEN_UNUSED_VARIABLE(size); + EIGEN_UNUSED_VARIABLE(rows); + EIGEN_UNUSED_VARIABLE(cols); + } + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { numext::swap(m_data, other.m_data); } + EIGEN_DEVICE_FUNC static constexpr Index rows(void) EIGEN_NOEXCEPT { return Rows_; } + EIGEN_DEVICE_FUNC static constexpr Index cols(void) EIGEN_NOEXCEPT { return Cols_; } + EIGEN_DEVICE_FUNC constexpr void conservativeResize(Index, Index, Index) {} + EIGEN_DEVICE_FUNC constexpr void resize(Index, Index, Index) {} + EIGEN_DEVICE_FUNC constexpr const T* data() const { return m_data.array; } + EIGEN_DEVICE_FUNC constexpr T* data() { return m_data.array; } }; // null matrix -template class DenseStorage -{ - public: - EIGEN_DEVICE_FUNC DenseStorage() {} - EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) {} - EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage&) {} - EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage&) { return *this; } - EIGEN_DEVICE_FUNC DenseStorage(Index,Index,Index) {} - EIGEN_DEVICE_FUNC void swap(DenseStorage& ) {} - EIGEN_DEVICE_FUNC static EIGEN_CONSTEXPR Index rows(void) EIGEN_NOEXCEPT {return _Rows;} - EIGEN_DEVICE_FUNC static EIGEN_CONSTEXPR Index cols(void) EIGEN_NOEXCEPT {return _Cols;} - EIGEN_DEVICE_FUNC void conservativeResize(Index,Index,Index) {} - EIGEN_DEVICE_FUNC void resize(Index,Index,Index) {} - EIGEN_DEVICE_FUNC const T *data() const { return 0; } - EIGEN_DEVICE_FUNC T *data() { return 0; } +template +class DenseStorage { + public: + static_assert(Rows_ * Cols_ == 0, "The fixed number of rows times columns must equal the storage size."); + EIGEN_DEVICE_FUNC constexpr DenseStorage() {} + EIGEN_DEVICE_FUNC explicit constexpr DenseStorage(internal::constructor_without_unaligned_array_assert) {} + EIGEN_DEVICE_FUNC constexpr DenseStorage(const DenseStorage&) {} + EIGEN_DEVICE_FUNC constexpr DenseStorage& operator=(const DenseStorage&) { return *this; } + EIGEN_DEVICE_FUNC constexpr DenseStorage(Index, Index, Index) {} + EIGEN_DEVICE_FUNC constexpr void swap(DenseStorage&) {} + EIGEN_DEVICE_FUNC static constexpr Index rows(void) EIGEN_NOEXCEPT { return Rows_; } + EIGEN_DEVICE_FUNC static constexpr Index cols(void) EIGEN_NOEXCEPT { return Cols_; } + EIGEN_DEVICE_FUNC constexpr void conservativeResize(Index, Index, Index) {} + EIGEN_DEVICE_FUNC constexpr void resize(Index, Index, Index) {} + EIGEN_DEVICE_FUNC constexpr const T* data() const { return 0; } + EIGEN_DEVICE_FUNC constexpr T* data() { return 0; } }; // more specializations for null matrices; these are necessary to resolve ambiguities -template class DenseStorage -: public DenseStorage { }; +template +class DenseStorage { + Index m_rows; + Index m_cols; + + public: + EIGEN_DEVICE_FUNC DenseStorage() : m_rows(0), m_cols(0) {} + EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) : DenseStorage() {} + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) : m_rows(other.m_rows), m_cols(other.m_cols) {} + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) { + m_rows = other.m_rows; + m_cols = other.m_cols; + return *this; + } + EIGEN_DEVICE_FUNC DenseStorage(Index, Index rows, Index cols) : m_rows(rows), m_cols(cols) { + eigen_assert(m_rows * m_cols == 0 && "The number of rows times columns must equal the storage size."); + } + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { + numext::swap(m_rows, other.m_rows); + numext::swap(m_cols, other.m_cols); + } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_rows; } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_cols; } + EIGEN_DEVICE_FUNC void conservativeResize(Index, Index rows, Index cols) { + m_rows = rows; + m_cols = cols; + eigen_assert(m_rows * m_cols == 0 && "The number of rows times columns must equal the storage size."); + } + EIGEN_DEVICE_FUNC void resize(Index, Index rows, Index cols) { + m_rows = rows; + m_cols = cols; + eigen_assert(m_rows * m_cols == 0 && "The number of rows times columns must equal the storage size."); + } + EIGEN_DEVICE_FUNC const T* data() const { return nullptr; } + EIGEN_DEVICE_FUNC T* data() { return nullptr; } +}; -template class DenseStorage -: public DenseStorage { }; +template +class DenseStorage { + Index m_cols; + + public: + EIGEN_DEVICE_FUNC DenseStorage() : m_cols(0) {} + EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) : DenseStorage() {} + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) : m_cols(other.m_cols) {} + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) { + m_cols = other.m_cols; + return *this; + } + EIGEN_DEVICE_FUNC DenseStorage(Index, Index, Index cols) : m_cols(cols) { + eigen_assert(Rows_ * m_cols == 0 && "The number of rows times columns must equal the storage size."); + } + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { numext::swap(m_cols, other.m_cols); } + EIGEN_DEVICE_FUNC static EIGEN_CONSTEXPR Index rows(void) EIGEN_NOEXCEPT { return Rows_; } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index cols(void) const EIGEN_NOEXCEPT { return m_cols; } + EIGEN_DEVICE_FUNC void conservativeResize(Index, Index, Index cols) { + m_cols = cols; + eigen_assert(Rows_ * m_cols == 0 && "The number of rows times columns must equal the storage size."); + } + EIGEN_DEVICE_FUNC void resize(Index, Index, Index cols) { + m_cols = cols; + eigen_assert(Rows_ * m_cols == 0 && "The number of rows times columns must equal the storage size."); + } + EIGEN_DEVICE_FUNC const T* data() const { return nullptr; } + EIGEN_DEVICE_FUNC T* data() { return nullptr; } +}; -template class DenseStorage -: public DenseStorage { }; +template +class DenseStorage { + Index m_rows; + + public: + EIGEN_DEVICE_FUNC DenseStorage() : m_rows(0) {} + EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) : DenseStorage() {} + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) : m_rows(other.m_rows) {} + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) { + m_rows = other.m_rows; + return *this; + } + EIGEN_DEVICE_FUNC DenseStorage(Index, Index rows, Index) : m_rows(rows) { + eigen_assert(m_rows * Cols_ == 0 && "The number of rows times columns must equal the storage size."); + } + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { numext::swap(m_rows, other.m_rows); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index rows(void) const EIGEN_NOEXCEPT { return m_rows; } + EIGEN_DEVICE_FUNC static EIGEN_CONSTEXPR Index cols(void) EIGEN_NOEXCEPT { return Cols_; } + EIGEN_DEVICE_FUNC void conservativeResize(Index, Index rows, Index) { + m_rows = rows; + eigen_assert(m_rows * Cols_ == 0 && "The number of rows times columns must equal the storage size."); + } + EIGEN_DEVICE_FUNC void resize(Index, Index rows, Index) { + m_rows = rows; + eigen_assert(m_rows * Cols_ == 0 && "The number of rows times columns must equal the storage size."); + } + EIGEN_DEVICE_FUNC const T* data() const { return nullptr; } + EIGEN_DEVICE_FUNC T* data() { return nullptr; } +}; // dynamic-size matrix with fixed-size storage -template class DenseStorage -{ - internal::plain_array m_data; - Index m_rows; - Index m_cols; - public: - EIGEN_DEVICE_FUNC DenseStorage() : m_rows(0), m_cols(0) {} - EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) +template +class DenseStorage { + internal::plain_array m_data; + Index m_rows; + Index m_cols; + + public: + EIGEN_DEVICE_FUNC constexpr DenseStorage() : m_data(), m_rows(0), m_cols(0) {} + EIGEN_DEVICE_FUNC explicit constexpr DenseStorage(internal::constructor_without_unaligned_array_assert) : m_data(internal::constructor_without_unaligned_array_assert()), m_rows(0), m_cols(0) {} - EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) - : m_data(internal::constructor_without_unaligned_array_assert()), m_rows(other.m_rows), m_cols(other.m_cols) - { + EIGEN_DEVICE_FUNC constexpr DenseStorage(const DenseStorage& other) + : m_data(internal::constructor_without_unaligned_array_assert()), m_rows(other.m_rows), m_cols(other.m_cols) { + internal::plain_array_helper::copy(other.m_data, m_rows * m_cols, m_data); + } + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) { + if (this != &other) { + m_rows = other.m_rows; + m_cols = other.m_cols; internal::plain_array_helper::copy(other.m_data, m_rows * m_cols, m_data); } - EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) - { - if (this != &other) - { - m_rows = other.m_rows; - m_cols = other.m_cols; - internal::plain_array_helper::copy(other.m_data, m_rows * m_cols, m_data); - } - return *this; - } - EIGEN_DEVICE_FUNC DenseStorage(Index, Index rows, Index cols) : m_rows(rows), m_cols(cols) {} - EIGEN_DEVICE_FUNC void swap(DenseStorage& other) - { - internal::plain_array_helper::swap(m_data, m_rows * m_cols, other.m_data, other.m_rows * other.m_cols); - numext::swap(m_rows,other.m_rows); - numext::swap(m_cols,other.m_cols); - } - EIGEN_DEVICE_FUNC Index rows() const {return m_rows;} - EIGEN_DEVICE_FUNC Index cols() const {return m_cols;} - EIGEN_DEVICE_FUNC void conservativeResize(Index, Index rows, Index cols) { m_rows = rows; m_cols = cols; } - EIGEN_DEVICE_FUNC void resize(Index, Index rows, Index cols) { m_rows = rows; m_cols = cols; } - EIGEN_DEVICE_FUNC const T *data() const { return m_data.array; } - EIGEN_DEVICE_FUNC T *data() { return m_data.array; } + return *this; + } + EIGEN_DEVICE_FUNC constexpr DenseStorage(Index, Index rows, Index cols) : m_rows(rows), m_cols(cols) {} + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { + internal::plain_array_helper::swap(m_data, m_rows * m_cols, other.m_data, other.m_rows * other.m_cols); + numext::swap(m_rows, other.m_rows); + numext::swap(m_cols, other.m_cols); + } + EIGEN_DEVICE_FUNC constexpr Index rows() const { return m_rows; } + EIGEN_DEVICE_FUNC constexpr Index cols() const { return m_cols; } + EIGEN_DEVICE_FUNC constexpr void conservativeResize(Index, Index rows, Index cols) { + m_rows = rows; + m_cols = cols; + } + EIGEN_DEVICE_FUNC constexpr void resize(Index, Index rows, Index cols) { + m_rows = rows; + m_cols = cols; + } + EIGEN_DEVICE_FUNC constexpr const T* data() const { return m_data.array; } + EIGEN_DEVICE_FUNC constexpr T* data() { return m_data.array; } }; // dynamic-size matrix with fixed-size storage and fixed width -template class DenseStorage -{ - internal::plain_array m_data; - Index m_rows; - public: - EIGEN_DEVICE_FUNC DenseStorage() : m_rows(0) {} - EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) +template +class DenseStorage { + internal::plain_array m_data; + Index m_rows; + + public: + EIGEN_DEVICE_FUNC constexpr DenseStorage() : m_rows(0) {} + EIGEN_DEVICE_FUNC explicit constexpr DenseStorage(internal::constructor_without_unaligned_array_assert) : m_data(internal::constructor_without_unaligned_array_assert()), m_rows(0) {} - EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) - : m_data(internal::constructor_without_unaligned_array_assert()), m_rows(other.m_rows) - { - internal::plain_array_helper::copy(other.m_data, m_rows * _Cols, m_data); - } - - EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) - { - if (this != &other) - { - m_rows = other.m_rows; - internal::plain_array_helper::copy(other.m_data, m_rows * _Cols, m_data); - } - return *this; - } - EIGEN_DEVICE_FUNC DenseStorage(Index, Index rows, Index) : m_rows(rows) {} - EIGEN_DEVICE_FUNC void swap(DenseStorage& other) - { - internal::plain_array_helper::swap(m_data, m_rows * _Cols, other.m_data, other.m_rows * _Cols); - numext::swap(m_rows, other.m_rows); + EIGEN_DEVICE_FUNC constexpr DenseStorage(const DenseStorage& other) + : m_data(internal::constructor_without_unaligned_array_assert()), m_rows(other.m_rows) { + internal::plain_array_helper::copy(other.m_data, m_rows * Cols_, m_data); + } + + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) { + if (this != &other) { + m_rows = other.m_rows; + internal::plain_array_helper::copy(other.m_data, m_rows * Cols_, m_data); } - EIGEN_DEVICE_FUNC Index rows(void) const EIGEN_NOEXCEPT {return m_rows;} - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index cols(void) const EIGEN_NOEXCEPT {return _Cols;} - EIGEN_DEVICE_FUNC void conservativeResize(Index, Index rows, Index) { m_rows = rows; } - EIGEN_DEVICE_FUNC void resize(Index, Index rows, Index) { m_rows = rows; } - EIGEN_DEVICE_FUNC const T *data() const { return m_data.array; } - EIGEN_DEVICE_FUNC T *data() { return m_data.array; } + return *this; + } + EIGEN_DEVICE_FUNC constexpr DenseStorage(Index, Index rows, Index) : m_rows(rows) {} + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { + internal::plain_array_helper::swap(m_data, m_rows * Cols_, other.m_data, other.m_rows * Cols_); + numext::swap(m_rows, other.m_rows); + } + EIGEN_DEVICE_FUNC constexpr Index rows(void) const EIGEN_NOEXCEPT { return m_rows; } + EIGEN_DEVICE_FUNC constexpr Index cols(void) const EIGEN_NOEXCEPT { return Cols_; } + EIGEN_DEVICE_FUNC constexpr void conservativeResize(Index, Index rows, Index) { m_rows = rows; } + EIGEN_DEVICE_FUNC constexpr void resize(Index, Index rows, Index) { m_rows = rows; } + EIGEN_DEVICE_FUNC constexpr const T* data() const { return m_data.array; } + EIGEN_DEVICE_FUNC constexpr T* data() { return m_data.array; } }; // dynamic-size matrix with fixed-size storage and fixed height -template class DenseStorage -{ - internal::plain_array m_data; - Index m_cols; - public: - EIGEN_DEVICE_FUNC DenseStorage() : m_cols(0) {} - EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) +template +class DenseStorage { + internal::plain_array m_data; + Index m_cols; + + public: + EIGEN_DEVICE_FUNC constexpr DenseStorage() : m_cols(0) {} + EIGEN_DEVICE_FUNC explicit constexpr DenseStorage(internal::constructor_without_unaligned_array_assert) : m_data(internal::constructor_without_unaligned_array_assert()), m_cols(0) {} - EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) - : m_data(internal::constructor_without_unaligned_array_assert()), m_cols(other.m_cols) - { - internal::plain_array_helper::copy(other.m_data, _Rows * m_cols, m_data); - } - EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) - { - if (this != &other) - { - m_cols = other.m_cols; - internal::plain_array_helper::copy(other.m_data, _Rows * m_cols, m_data); - } - return *this; - } - EIGEN_DEVICE_FUNC DenseStorage(Index, Index, Index cols) : m_cols(cols) {} - EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { - internal::plain_array_helper::swap(m_data, _Rows * m_cols, other.m_data, _Rows * other.m_cols); - numext::swap(m_cols, other.m_cols); + EIGEN_DEVICE_FUNC constexpr DenseStorage(const DenseStorage& other) + : m_data(internal::constructor_without_unaligned_array_assert()), m_cols(other.m_cols) { + internal::plain_array_helper::copy(other.m_data, Rows_ * m_cols, m_data); + } + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) { + if (this != &other) { + m_cols = other.m_cols; + internal::plain_array_helper::copy(other.m_data, Rows_ * m_cols, m_data); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index rows(void) const EIGEN_NOEXCEPT {return _Rows;} - EIGEN_DEVICE_FUNC Index cols(void) const EIGEN_NOEXCEPT {return m_cols;} - EIGEN_DEVICE_FUNC void conservativeResize(Index, Index, Index cols) { m_cols = cols; } - EIGEN_DEVICE_FUNC void resize(Index, Index, Index cols) { m_cols = cols; } - EIGEN_DEVICE_FUNC const T *data() const { return m_data.array; } - EIGEN_DEVICE_FUNC T *data() { return m_data.array; } + return *this; + } + EIGEN_DEVICE_FUNC DenseStorage(Index, Index, Index cols) : m_cols(cols) {} + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { + internal::plain_array_helper::swap(m_data, Rows_ * m_cols, other.m_data, Rows_ * other.m_cols); + numext::swap(m_cols, other.m_cols); + } + EIGEN_DEVICE_FUNC constexpr Index rows(void) const EIGEN_NOEXCEPT { return Rows_; } + EIGEN_DEVICE_FUNC constexpr Index cols(void) const EIGEN_NOEXCEPT { return m_cols; } + EIGEN_DEVICE_FUNC constexpr void conservativeResize(Index, Index, Index cols) { m_cols = cols; } + EIGEN_DEVICE_FUNC constexpr void resize(Index, Index, Index cols) { m_cols = cols; } + EIGEN_DEVICE_FUNC constexpr const T* data() const { return m_data.array; } + EIGEN_DEVICE_FUNC constexpr T* data() { return m_data.array; } }; // purely dynamic matrix. -template class DenseStorage -{ - T *m_data; - Index m_rows; - Index m_cols; - public: - EIGEN_DEVICE_FUNC DenseStorage() : m_data(0), m_rows(0), m_cols(0) {} - EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) - : m_data(0), m_rows(0), m_cols(0) {} - EIGEN_DEVICE_FUNC DenseStorage(Index size, Index rows, Index cols) - : m_data(internal::conditional_aligned_new_auto(size)), m_rows(rows), m_cols(cols) - { - EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) - eigen_internal_assert(size==rows*cols && rows>=0 && cols >=0); - } - EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) - : m_data(internal::conditional_aligned_new_auto(other.m_rows*other.m_cols)) - , m_rows(other.m_rows) - , m_cols(other.m_cols) - { - EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = m_rows*m_cols) - internal::smart_copy(other.m_data, other.m_data+other.m_rows*other.m_cols, m_data); - } - EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) - { - if (this != &other) - { - DenseStorage tmp(other); - this->swap(tmp); - } - return *this; - } -#if EIGEN_HAS_RVALUE_REFERENCES - EIGEN_DEVICE_FUNC - DenseStorage(DenseStorage&& other) EIGEN_NOEXCEPT - : m_data(std::move(other.m_data)) - , m_rows(std::move(other.m_rows)) - , m_cols(std::move(other.m_cols)) - { - other.m_data = nullptr; - other.m_rows = 0; - other.m_cols = 0; - } - EIGEN_DEVICE_FUNC - DenseStorage& operator=(DenseStorage&& other) EIGEN_NOEXCEPT - { - numext::swap(m_data, other.m_data); - numext::swap(m_rows, other.m_rows); - numext::swap(m_cols, other.m_cols); - return *this; - } -#endif - EIGEN_DEVICE_FUNC ~DenseStorage() { internal::conditional_aligned_delete_auto(m_data, m_rows*m_cols); } - EIGEN_DEVICE_FUNC void swap(DenseStorage& other) - { - numext::swap(m_data,other.m_data); - numext::swap(m_rows,other.m_rows); - numext::swap(m_cols,other.m_cols); - } - EIGEN_DEVICE_FUNC Index rows(void) const EIGEN_NOEXCEPT {return m_rows;} - EIGEN_DEVICE_FUNC Index cols(void) const EIGEN_NOEXCEPT {return m_cols;} - void conservativeResize(Index size, Index rows, Index cols) - { - m_data = internal::conditional_aligned_realloc_new_auto(m_data, size, m_rows*m_cols); - m_rows = rows; - m_cols = cols; +template +class DenseStorage { + T* m_data; + Index m_rows; + Index m_cols; + + public: + EIGEN_DEVICE_FUNC constexpr DenseStorage() : m_data(0), m_rows(0), m_cols(0) {} + EIGEN_DEVICE_FUNC explicit constexpr DenseStorage(internal::constructor_without_unaligned_array_assert) + : m_data(0), m_rows(0), m_cols(0) {} + EIGEN_DEVICE_FUNC DenseStorage(Index size, Index rows, Index cols) + : m_data(internal::conditional_aligned_new_auto(size)), + m_rows(rows), + m_cols(cols) { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) + eigen_internal_assert(size == rows * cols && rows >= 0 && cols >= 0); + } + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) + : m_data(internal::conditional_aligned_new_auto(other.m_rows * other.m_cols)), + m_rows(other.m_rows), + m_cols(other.m_cols) { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = m_rows * m_cols) + internal::smart_copy(other.m_data, other.m_data + other.m_rows * other.m_cols, m_data); + } + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) { + if (this != &other) { + DenseStorage tmp(other); + this->swap(tmp); } - EIGEN_DEVICE_FUNC void resize(Index size, Index rows, Index cols) - { - if(size != m_rows*m_cols) - { - internal::conditional_aligned_delete_auto(m_data, m_rows*m_cols); - if (size>0) // >0 and not simply !=0 to let the compiler knows that size cannot be negative - m_data = internal::conditional_aligned_new_auto(size); - else - m_data = 0; - EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) - } - m_rows = rows; - m_cols = cols; + return *this; + } + EIGEN_DEVICE_FUNC DenseStorage(DenseStorage&& other) EIGEN_NOEXCEPT : m_data(std::move(other.m_data)), + m_rows(std::move(other.m_rows)), + m_cols(std::move(other.m_cols)) { + other.m_data = nullptr; + other.m_rows = 0; + other.m_cols = 0; + } + EIGEN_DEVICE_FUNC DenseStorage& operator=(DenseStorage&& other) EIGEN_NOEXCEPT { + numext::swap(m_data, other.m_data); + numext::swap(m_rows, other.m_rows); + numext::swap(m_cols, other.m_cols); + return *this; + } + EIGEN_DEVICE_FUNC ~DenseStorage() { + internal::conditional_aligned_delete_auto(m_data, m_rows * m_cols); + } + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { + numext::swap(m_data, other.m_data); + numext::swap(m_rows, other.m_rows); + numext::swap(m_cols, other.m_cols); + } + EIGEN_DEVICE_FUNC Index rows(void) const EIGEN_NOEXCEPT { return m_rows; } + EIGEN_DEVICE_FUNC Index cols(void) const EIGEN_NOEXCEPT { return m_cols; } + void conservativeResize(Index size, Index rows, Index cols) { + m_data = + internal::conditional_aligned_realloc_new_auto(m_data, size, m_rows * m_cols); + m_rows = rows; + m_cols = cols; + } + EIGEN_DEVICE_FUNC void resize(Index size, Index rows, Index cols) { + if (size != m_rows * m_cols) { + internal::conditional_aligned_delete_auto(m_data, m_rows * m_cols); + if (size > 0) // >0 and not simply !=0 to let the compiler knows that size cannot be negative + m_data = internal::conditional_aligned_new_auto(size); + else + m_data = 0; + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) } - EIGEN_DEVICE_FUNC const T *data() const { return m_data; } - EIGEN_DEVICE_FUNC T *data() { return m_data; } + m_rows = rows; + m_cols = cols; + } + EIGEN_DEVICE_FUNC const T* data() const { return m_data; } + EIGEN_DEVICE_FUNC T* data() { return m_data; } }; // matrix with dynamic width and fixed height (so that matrix has dynamic size). -template class DenseStorage -{ - T *m_data; - Index m_cols; - public: - EIGEN_DEVICE_FUNC DenseStorage() : m_data(0), m_cols(0) {} - explicit DenseStorage(internal::constructor_without_unaligned_array_assert) : m_data(0), m_cols(0) {} - EIGEN_DEVICE_FUNC DenseStorage(Index size, Index rows, Index cols) : m_data(internal::conditional_aligned_new_auto(size)), m_cols(cols) - { - EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) - eigen_internal_assert(size==rows*cols && rows==_Rows && cols >=0); - EIGEN_UNUSED_VARIABLE(rows); - } - EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) - : m_data(internal::conditional_aligned_new_auto(_Rows*other.m_cols)) - , m_cols(other.m_cols) - { - EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = m_cols*_Rows) - internal::smart_copy(other.m_data, other.m_data+_Rows*m_cols, m_data); - } - EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) - { - if (this != &other) - { - DenseStorage tmp(other); - this->swap(tmp); - } - return *this; - } -#if EIGEN_HAS_RVALUE_REFERENCES - EIGEN_DEVICE_FUNC - DenseStorage(DenseStorage&& other) EIGEN_NOEXCEPT - : m_data(std::move(other.m_data)) - , m_cols(std::move(other.m_cols)) - { - other.m_data = nullptr; - other.m_cols = 0; - } - EIGEN_DEVICE_FUNC - DenseStorage& operator=(DenseStorage&& other) EIGEN_NOEXCEPT - { - numext::swap(m_data, other.m_data); - numext::swap(m_cols, other.m_cols); - return *this; - } -#endif - EIGEN_DEVICE_FUNC ~DenseStorage() { internal::conditional_aligned_delete_auto(m_data, _Rows*m_cols); } - EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { - numext::swap(m_data,other.m_data); - numext::swap(m_cols,other.m_cols); - } - EIGEN_DEVICE_FUNC static EIGEN_CONSTEXPR Index rows(void) EIGEN_NOEXCEPT {return _Rows;} - EIGEN_DEVICE_FUNC Index cols(void) const EIGEN_NOEXCEPT {return m_cols;} - EIGEN_DEVICE_FUNC void conservativeResize(Index size, Index, Index cols) - { - m_data = internal::conditional_aligned_realloc_new_auto(m_data, size, _Rows*m_cols); - m_cols = cols; +template +class DenseStorage { + T* m_data; + Index m_cols; + + public: + EIGEN_DEVICE_FUNC constexpr DenseStorage() : m_data(0), m_cols(0) {} + explicit constexpr DenseStorage(internal::constructor_without_unaligned_array_assert) : m_data(0), m_cols(0) {} + EIGEN_DEVICE_FUNC DenseStorage(Index size, Index rows, Index cols) + : m_data(internal::conditional_aligned_new_auto(size)), m_cols(cols) { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) + eigen_internal_assert(size == rows * cols && rows == Rows_ && cols >= 0); + EIGEN_UNUSED_VARIABLE(rows); + } + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) + : m_data(internal::conditional_aligned_new_auto(Rows_ * other.m_cols)), + m_cols(other.m_cols) { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = m_cols * Rows_) + internal::smart_copy(other.m_data, other.m_data + Rows_ * m_cols, m_data); + } + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) { + if (this != &other) { + DenseStorage tmp(other); + this->swap(tmp); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resize(Index size, Index, Index cols) - { - if(size != _Rows*m_cols) - { - internal::conditional_aligned_delete_auto(m_data, _Rows*m_cols); - if (size>0) // >0 and not simply !=0 to let the compiler knows that size cannot be negative - m_data = internal::conditional_aligned_new_auto(size); - else - m_data = 0; - EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) - } - m_cols = cols; + return *this; + } + EIGEN_DEVICE_FUNC DenseStorage(DenseStorage&& other) EIGEN_NOEXCEPT : m_data(std::move(other.m_data)), + m_cols(std::move(other.m_cols)) { + other.m_data = nullptr; + other.m_cols = 0; + } + EIGEN_DEVICE_FUNC DenseStorage& operator=(DenseStorage&& other) EIGEN_NOEXCEPT { + numext::swap(m_data, other.m_data); + numext::swap(m_cols, other.m_cols); + return *this; + } + EIGEN_DEVICE_FUNC ~DenseStorage() { + internal::conditional_aligned_delete_auto(m_data, Rows_ * m_cols); + } + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { + numext::swap(m_data, other.m_data); + numext::swap(m_cols, other.m_cols); + } + EIGEN_DEVICE_FUNC static constexpr Index rows(void) EIGEN_NOEXCEPT { return Rows_; } + EIGEN_DEVICE_FUNC Index cols(void) const EIGEN_NOEXCEPT { return m_cols; } + EIGEN_DEVICE_FUNC void conservativeResize(Index size, Index, Index cols) { + m_data = + internal::conditional_aligned_realloc_new_auto(m_data, size, Rows_ * m_cols); + m_cols = cols; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resize(Index size, Index, Index cols) { + if (size != Rows_ * m_cols) { + internal::conditional_aligned_delete_auto(m_data, Rows_ * m_cols); + if (size > 0) // >0 and not simply !=0 to let the compiler knows that size cannot be negative + m_data = internal::conditional_aligned_new_auto(size); + else + m_data = 0; + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) } - EIGEN_DEVICE_FUNC const T *data() const { return m_data; } - EIGEN_DEVICE_FUNC T *data() { return m_data; } + m_cols = cols; + } + EIGEN_DEVICE_FUNC const T* data() const { return m_data; } + EIGEN_DEVICE_FUNC T* data() { return m_data; } }; // matrix with dynamic height and fixed width (so that matrix has dynamic size). -template class DenseStorage -{ - T *m_data; - Index m_rows; - public: - EIGEN_DEVICE_FUNC DenseStorage() : m_data(0), m_rows(0) {} - explicit DenseStorage(internal::constructor_without_unaligned_array_assert) : m_data(0), m_rows(0) {} - EIGEN_DEVICE_FUNC DenseStorage(Index size, Index rows, Index cols) : m_data(internal::conditional_aligned_new_auto(size)), m_rows(rows) - { - EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) - eigen_internal_assert(size==rows*cols && rows>=0 && cols == _Cols); - EIGEN_UNUSED_VARIABLE(cols); - } - EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) - : m_data(internal::conditional_aligned_new_auto(other.m_rows*_Cols)) - , m_rows(other.m_rows) - { - EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = m_rows*_Cols) - internal::smart_copy(other.m_data, other.m_data+other.m_rows*_Cols, m_data); - } - EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) - { - if (this != &other) - { - DenseStorage tmp(other); - this->swap(tmp); - } - return *this; - } -#if EIGEN_HAS_RVALUE_REFERENCES - EIGEN_DEVICE_FUNC - DenseStorage(DenseStorage&& other) EIGEN_NOEXCEPT - : m_data(std::move(other.m_data)) - , m_rows(std::move(other.m_rows)) - { - other.m_data = nullptr; - other.m_rows = 0; - } - EIGEN_DEVICE_FUNC - DenseStorage& operator=(DenseStorage&& other) EIGEN_NOEXCEPT - { - numext::swap(m_data, other.m_data); - numext::swap(m_rows, other.m_rows); - return *this; - } -#endif - EIGEN_DEVICE_FUNC ~DenseStorage() { internal::conditional_aligned_delete_auto(m_data, _Cols*m_rows); } - EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { - numext::swap(m_data,other.m_data); - numext::swap(m_rows,other.m_rows); - } - EIGEN_DEVICE_FUNC Index rows(void) const EIGEN_NOEXCEPT {return m_rows;} - EIGEN_DEVICE_FUNC static EIGEN_CONSTEXPR Index cols(void) {return _Cols;} - void conservativeResize(Index size, Index rows, Index) - { - m_data = internal::conditional_aligned_realloc_new_auto(m_data, size, m_rows*_Cols); - m_rows = rows; +template +class DenseStorage { + T* m_data; + Index m_rows; + + public: + EIGEN_DEVICE_FUNC constexpr DenseStorage() : m_data(0), m_rows(0) {} + explicit constexpr DenseStorage(internal::constructor_without_unaligned_array_assert) : m_data(0), m_rows(0) {} + EIGEN_DEVICE_FUNC constexpr DenseStorage(Index size, Index rows, Index cols) + : m_data(internal::conditional_aligned_new_auto(size)), m_rows(rows) { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) + eigen_internal_assert(size == rows * cols && rows >= 0 && cols == Cols_); + EIGEN_UNUSED_VARIABLE(cols); + } + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) + : m_data(internal::conditional_aligned_new_auto(other.m_rows * Cols_)), + m_rows(other.m_rows) { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = m_rows * Cols_) + internal::smart_copy(other.m_data, other.m_data + other.m_rows * Cols_, m_data); + } + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) { + if (this != &other) { + DenseStorage tmp(other); + this->swap(tmp); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resize(Index size, Index rows, Index) - { - if(size != m_rows*_Cols) - { - internal::conditional_aligned_delete_auto(m_data, _Cols*m_rows); - if (size>0) // >0 and not simply !=0 to let the compiler knows that size cannot be negative - m_data = internal::conditional_aligned_new_auto(size); - else - m_data = 0; - EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) - } - m_rows = rows; + return *this; + } + EIGEN_DEVICE_FUNC DenseStorage(DenseStorage&& other) EIGEN_NOEXCEPT : m_data(std::move(other.m_data)), + m_rows(std::move(other.m_rows)) { + other.m_data = nullptr; + other.m_rows = 0; + } + EIGEN_DEVICE_FUNC DenseStorage& operator=(DenseStorage&& other) EIGEN_NOEXCEPT { + numext::swap(m_data, other.m_data); + numext::swap(m_rows, other.m_rows); + return *this; + } + EIGEN_DEVICE_FUNC ~DenseStorage() { + internal::conditional_aligned_delete_auto(m_data, Cols_ * m_rows); + } + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { + numext::swap(m_data, other.m_data); + numext::swap(m_rows, other.m_rows); + } + EIGEN_DEVICE_FUNC Index rows(void) const EIGEN_NOEXCEPT { return m_rows; } + EIGEN_DEVICE_FUNC static constexpr Index cols(void) { return Cols_; } + void conservativeResize(Index size, Index rows, Index) { + m_data = + internal::conditional_aligned_realloc_new_auto(m_data, size, m_rows * Cols_); + m_rows = rows; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resize(Index size, Index rows, Index) { + if (size != m_rows * Cols_) { + internal::conditional_aligned_delete_auto(m_data, Cols_ * m_rows); + if (size > 0) // >0 and not simply !=0 to let the compiler knows that size cannot be negative + m_data = internal::conditional_aligned_new_auto(size); + else + m_data = 0; + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) } - EIGEN_DEVICE_FUNC const T *data() const { return m_data; } - EIGEN_DEVICE_FUNC T *data() { return m_data; } + m_rows = rows; + } + EIGEN_DEVICE_FUNC const T* data() const { return m_data; } + EIGEN_DEVICE_FUNC T* data() { return m_data; } }; -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_MATRIX_H +#endif // EIGEN_MATRIX_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Diagonal.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Diagonal.h index 3112d2c16a9..8d27857e050 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Diagonal.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Diagonal.h @@ -11,248 +11,211 @@ #ifndef EIGEN_DIAGONAL_H #define EIGEN_DIAGONAL_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { /** \class Diagonal - * \ingroup Core_Module - * - * \brief Expression of a diagonal/subdiagonal/superdiagonal in a matrix - * - * \param MatrixType the type of the object in which we are taking a sub/main/super diagonal - * \param DiagIndex the index of the sub/super diagonal. The default is 0 and it means the main diagonal. - * A positive value means a superdiagonal, a negative value means a subdiagonal. - * You can also use DynamicIndex so the index can be set at runtime. - * - * The matrix is not required to be square. - * - * This class represents an expression of the main diagonal, or any sub/super diagonal - * of a square matrix. It is the return type of MatrixBase::diagonal() and MatrixBase::diagonal(Index) and most of the - * time this is the only way it is used. - * - * \sa MatrixBase::diagonal(), MatrixBase::diagonal(Index) - */ + * \ingroup Core_Module + * + * \brief Expression of a diagonal/subdiagonal/superdiagonal in a matrix + * + * \tparam MatrixType the type of the object in which we are taking a sub/main/super diagonal + * \tparam DiagIndex the index of the sub/super diagonal. The default is 0 and it means the main diagonal. + * A positive value means a superdiagonal, a negative value means a subdiagonal. + * You can also use DynamicIndex so the index can be set at runtime. + * + * The matrix is not required to be square. + * + * This class represents an expression of the main diagonal, or any sub/super diagonal + * of a square matrix. It is the return type of MatrixBase::diagonal() and MatrixBase::diagonal(Index) and most of the + * time this is the only way it is used. + * + * \sa MatrixBase::diagonal(), MatrixBase::diagonal(Index) + */ namespace internal { -template -struct traits > - : traits -{ +template +struct traits > : traits { typedef typename ref_selector::type MatrixTypeNested; - typedef typename remove_reference::type _MatrixTypeNested; + typedef std::remove_reference_t MatrixTypeNested_; typedef typename MatrixType::StorageKind StorageKind; enum { - RowsAtCompileTime = (int(DiagIndex) == DynamicIndex || int(MatrixType::SizeAtCompileTime) == Dynamic) ? Dynamic - : (EIGEN_PLAIN_ENUM_MIN(MatrixType::RowsAtCompileTime - EIGEN_PLAIN_ENUM_MAX(-DiagIndex, 0), - MatrixType::ColsAtCompileTime - EIGEN_PLAIN_ENUM_MAX( DiagIndex, 0))), + RowsAtCompileTime = (int(DiagIndex) == DynamicIndex || int(MatrixType::SizeAtCompileTime) == Dynamic) + ? Dynamic + : (plain_enum_min(MatrixType::RowsAtCompileTime - plain_enum_max(-DiagIndex, 0), + MatrixType::ColsAtCompileTime - plain_enum_max(DiagIndex, 0))), ColsAtCompileTime = 1, - MaxRowsAtCompileTime = int(MatrixType::MaxSizeAtCompileTime) == Dynamic ? Dynamic - : DiagIndex == DynamicIndex ? EIGEN_SIZE_MIN_PREFER_FIXED(MatrixType::MaxRowsAtCompileTime, - MatrixType::MaxColsAtCompileTime) - : (EIGEN_PLAIN_ENUM_MIN(MatrixType::MaxRowsAtCompileTime - EIGEN_PLAIN_ENUM_MAX(-DiagIndex, 0), - MatrixType::MaxColsAtCompileTime - EIGEN_PLAIN_ENUM_MAX( DiagIndex, 0))), + MaxRowsAtCompileTime = + int(MatrixType::MaxSizeAtCompileTime) == Dynamic ? Dynamic + : DiagIndex == DynamicIndex + ? min_size_prefer_fixed(MatrixType::MaxRowsAtCompileTime, MatrixType::MaxColsAtCompileTime) + : (plain_enum_min(MatrixType::MaxRowsAtCompileTime - plain_enum_max(-DiagIndex, 0), + MatrixType::MaxColsAtCompileTime - plain_enum_max(DiagIndex, 0))), MaxColsAtCompileTime = 1, MaskLvalueBit = is_lvalue::value ? LvalueBit : 0, - Flags = (unsigned int)_MatrixTypeNested::Flags & (RowMajorBit | MaskLvalueBit | DirectAccessBit) & ~RowMajorBit, // FIXME DirectAccessBit should not be handled by expressions + Flags = (unsigned int)MatrixTypeNested_::Flags & (RowMajorBit | MaskLvalueBit | DirectAccessBit) & + ~RowMajorBit, // FIXME DirectAccessBit should not be handled by expressions MatrixTypeOuterStride = outer_stride_at_compile_time::ret, - InnerStrideAtCompileTime = MatrixTypeOuterStride == Dynamic ? Dynamic : MatrixTypeOuterStride+1, + InnerStrideAtCompileTime = MatrixTypeOuterStride == Dynamic ? Dynamic : MatrixTypeOuterStride + 1, OuterStrideAtCompileTime = 0 }; }; -} - -template class Diagonal - : public internal::dense_xpr_base< Diagonal >::type -{ - public: - - enum { DiagIndex = _DiagIndex }; - typedef typename internal::dense_xpr_base::type Base; - EIGEN_DENSE_PUBLIC_INTERFACE(Diagonal) - - EIGEN_DEVICE_FUNC - explicit inline Diagonal(MatrixType& matrix, Index a_index = DiagIndex) : m_matrix(matrix), m_index(a_index) - { - eigen_assert( a_index <= m_matrix.cols() && -a_index <= m_matrix.rows() ); - } - - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Diagonal) - - EIGEN_DEVICE_FUNC - inline Index rows() const - { - return m_index.value()<0 ? numext::mini(m_matrix.cols(),m_matrix.rows()+m_index.value()) - : numext::mini(m_matrix.rows(),m_matrix.cols()-m_index.value()); - } - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index cols() const EIGEN_NOEXCEPT { return 1; } - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index innerStride() const EIGEN_NOEXCEPT { - return m_matrix.outerStride() + 1; - } - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outerStride() const EIGEN_NOEXCEPT { return 0; } - - typedef typename internal::conditional< - internal::is_lvalue::value, - Scalar, - const Scalar - >::type ScalarWithConstIfNotLvalue; - - EIGEN_DEVICE_FUNC - inline ScalarWithConstIfNotLvalue* data() { return &(m_matrix.coeffRef(rowOffset(), colOffset())); } - EIGEN_DEVICE_FUNC - inline const Scalar* data() const { return &(m_matrix.coeffRef(rowOffset(), colOffset())); } - - EIGEN_DEVICE_FUNC - inline Scalar& coeffRef(Index row, Index) - { - EIGEN_STATIC_ASSERT_LVALUE(MatrixType) - return m_matrix.coeffRef(row+rowOffset(), row+colOffset()); - } - - EIGEN_DEVICE_FUNC - inline const Scalar& coeffRef(Index row, Index) const - { - return m_matrix.coeffRef(row+rowOffset(), row+colOffset()); - } - - EIGEN_DEVICE_FUNC - inline CoeffReturnType coeff(Index row, Index) const - { - return m_matrix.coeff(row+rowOffset(), row+colOffset()); - } - - EIGEN_DEVICE_FUNC - inline Scalar& coeffRef(Index idx) - { - EIGEN_STATIC_ASSERT_LVALUE(MatrixType) - return m_matrix.coeffRef(idx+rowOffset(), idx+colOffset()); - } - - EIGEN_DEVICE_FUNC - inline const Scalar& coeffRef(Index idx) const - { - return m_matrix.coeffRef(idx+rowOffset(), idx+colOffset()); - } - - EIGEN_DEVICE_FUNC - inline CoeffReturnType coeff(Index idx) const - { - return m_matrix.coeff(idx+rowOffset(), idx+colOffset()); - } - - EIGEN_DEVICE_FUNC - inline const typename internal::remove_all::type& - nestedExpression() const - { - return m_matrix; - } - - EIGEN_DEVICE_FUNC - inline Index index() const - { - return m_index.value(); - } - - protected: - typename internal::ref_selector::non_const_type m_matrix; - const internal::variable_if_dynamicindex m_index; - - private: - // some compilers may fail to optimize std::max etc in case of compile-time constants... - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index absDiagIndex() const EIGEN_NOEXCEPT { return m_index.value()>0 ? m_index.value() : -m_index.value(); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index rowOffset() const EIGEN_NOEXCEPT { return m_index.value()>0 ? 0 : -m_index.value(); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index colOffset() const EIGEN_NOEXCEPT { return m_index.value()>0 ? m_index.value() : 0; } - // trigger a compile-time error if someone try to call packet - template typename MatrixType::PacketReturnType packet(Index) const; - template typename MatrixType::PacketReturnType packet(Index,Index) const; +} // namespace internal + +template +class Diagonal : public internal::dense_xpr_base >::type { + public: + enum { DiagIndex = DiagIndex_ }; + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Diagonal) + + EIGEN_DEVICE_FUNC explicit inline Diagonal(MatrixType& matrix, Index a_index = DiagIndex) + : m_matrix(matrix), m_index(a_index) { + eigen_assert(a_index <= m_matrix.cols() && -a_index <= m_matrix.rows()); + } + + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Diagonal) + + EIGEN_DEVICE_FUNC inline Index rows() const { + return m_index.value() < 0 ? numext::mini(m_matrix.cols(), m_matrix.rows() + m_index.value()) + : numext::mini(m_matrix.rows(), m_matrix.cols() - m_index.value()); + } + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return 1; } + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const EIGEN_NOEXCEPT { + return m_matrix.outerStride() + 1; + } + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const EIGEN_NOEXCEPT { return 0; } + + typedef std::conditional_t::value, Scalar, const Scalar> ScalarWithConstIfNotLvalue; + + EIGEN_DEVICE_FUNC inline ScalarWithConstIfNotLvalue* data() { return &(m_matrix.coeffRef(rowOffset(), colOffset())); } + EIGEN_DEVICE_FUNC inline const Scalar* data() const { return &(m_matrix.coeffRef(rowOffset(), colOffset())); } + + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index row, Index) { + EIGEN_STATIC_ASSERT_LVALUE(MatrixType) + return m_matrix.coeffRef(row + rowOffset(), row + colOffset()); + } + + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index row, Index) const { + return m_matrix.coeffRef(row + rowOffset(), row + colOffset()); + } + + EIGEN_DEVICE_FUNC inline CoeffReturnType coeff(Index row, Index) const { + return m_matrix.coeff(row + rowOffset(), row + colOffset()); + } + + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index idx) { + EIGEN_STATIC_ASSERT_LVALUE(MatrixType) + return m_matrix.coeffRef(idx + rowOffset(), idx + colOffset()); + } + + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index idx) const { + return m_matrix.coeffRef(idx + rowOffset(), idx + colOffset()); + } + + EIGEN_DEVICE_FUNC inline CoeffReturnType coeff(Index idx) const { + return m_matrix.coeff(idx + rowOffset(), idx + colOffset()); + } + + EIGEN_DEVICE_FUNC inline const internal::remove_all_t& nestedExpression() const { + return m_matrix; + } + + EIGEN_DEVICE_FUNC inline Index index() const { return m_index.value(); } + + protected: + typename internal::ref_selector::non_const_type m_matrix; + const internal::variable_if_dynamicindex m_index; + + private: + // some compilers may fail to optimize std::max etc in case of compile-time constants... + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index absDiagIndex() const EIGEN_NOEXCEPT { + return m_index.value() > 0 ? m_index.value() : -m_index.value(); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index rowOffset() const EIGEN_NOEXCEPT { + return m_index.value() > 0 ? 0 : -m_index.value(); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index colOffset() const EIGEN_NOEXCEPT { + return m_index.value() > 0 ? m_index.value() : 0; + } + // trigger a compile-time error if someone try to call packet + template + typename MatrixType::PacketReturnType packet(Index) const; + template + typename MatrixType::PacketReturnType packet(Index, Index) const; }; /** \returns an expression of the main diagonal of the matrix \c *this - * - * \c *this is not required to be square. - * - * Example: \include MatrixBase_diagonal.cpp - * Output: \verbinclude MatrixBase_diagonal.out - * - * \sa class Diagonal */ -template -EIGEN_DEVICE_FUNC inline typename MatrixBase::DiagonalReturnType -MatrixBase::diagonal() -{ + * + * \c *this is not required to be square. + * + * Example: \include MatrixBase_diagonal.cpp + * Output: \verbinclude MatrixBase_diagonal.out + * + * \sa class Diagonal */ +template +EIGEN_DEVICE_FUNC inline typename MatrixBase::DiagonalReturnType MatrixBase::diagonal() { return DiagonalReturnType(derived()); } /** This is the const version of diagonal(). */ -template -EIGEN_DEVICE_FUNC inline typename MatrixBase::ConstDiagonalReturnType -MatrixBase::diagonal() const -{ +template +EIGEN_DEVICE_FUNC inline const typename MatrixBase::ConstDiagonalReturnType MatrixBase::diagonal() + const { return ConstDiagonalReturnType(derived()); } /** \returns an expression of the \a DiagIndex-th sub or super diagonal of the matrix \c *this - * - * \c *this is not required to be square. - * - * The template parameter \a DiagIndex represent a super diagonal if \a DiagIndex > 0 - * and a sub diagonal otherwise. \a DiagIndex == 0 is equivalent to the main diagonal. - * - * Example: \include MatrixBase_diagonal_int.cpp - * Output: \verbinclude MatrixBase_diagonal_int.out - * - * \sa MatrixBase::diagonal(), class Diagonal */ -template -EIGEN_DEVICE_FUNC inline typename MatrixBase::DiagonalDynamicIndexReturnType -MatrixBase::diagonal(Index index) -{ - return DiagonalDynamicIndexReturnType(derived(), index); + * + * \c *this is not required to be square. + * + * The template parameter \a DiagIndex represent a super diagonal if \a DiagIndex > 0 + * and a sub diagonal otherwise. \a DiagIndex == 0 is equivalent to the main diagonal. + * + * Example: \include MatrixBase_diagonal_int.cpp + * Output: \verbinclude MatrixBase_diagonal_int.out + * + * \sa MatrixBase::diagonal(), class Diagonal */ +template +EIGEN_DEVICE_FUNC inline Diagonal MatrixBase::diagonal(Index index) { + return Diagonal(derived(), index); } /** This is the const version of diagonal(Index). */ -template -EIGEN_DEVICE_FUNC inline typename MatrixBase::ConstDiagonalDynamicIndexReturnType -MatrixBase::diagonal(Index index) const -{ - return ConstDiagonalDynamicIndexReturnType(derived(), index); +template +EIGEN_DEVICE_FUNC inline const Diagonal MatrixBase::diagonal(Index index) const { + return Diagonal(derived(), index); } /** \returns an expression of the \a DiagIndex-th sub or super diagonal of the matrix \c *this - * - * \c *this is not required to be square. - * - * The template parameter \a DiagIndex represent a super diagonal if \a DiagIndex > 0 - * and a sub diagonal otherwise. \a DiagIndex == 0 is equivalent to the main diagonal. - * - * Example: \include MatrixBase_diagonal_template_int.cpp - * Output: \verbinclude MatrixBase_diagonal_template_int.out - * - * \sa MatrixBase::diagonal(), class Diagonal */ -template -template -EIGEN_DEVICE_FUNC -inline typename MatrixBase::template DiagonalIndexReturnType::Type -MatrixBase::diagonal() -{ - return typename DiagonalIndexReturnType::Type(derived()); + * + * \c *this is not required to be square. + * + * The template parameter \a DiagIndex represent a super diagonal if \a DiagIndex > 0 + * and a sub diagonal otherwise. \a DiagIndex == 0 is equivalent to the main diagonal. + * + * Example: \include MatrixBase_diagonal_template_int.cpp + * Output: \verbinclude MatrixBase_diagonal_template_int.out + * + * \sa MatrixBase::diagonal(), class Diagonal */ +template +template +EIGEN_DEVICE_FUNC inline Diagonal MatrixBase::diagonal() { + return Diagonal(derived()); } /** This is the const version of diagonal(). */ -template -template -EIGEN_DEVICE_FUNC -inline typename MatrixBase::template ConstDiagonalIndexReturnType::Type -MatrixBase::diagonal() const -{ - return typename ConstDiagonalIndexReturnType::Type(derived()); +template +template +EIGEN_DEVICE_FUNC inline const Diagonal MatrixBase::diagonal() const { + return Diagonal(derived()); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_DIAGONAL_H +#endif // EIGEN_DIAGONAL_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DiagonalMatrix.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DiagonalMatrix.h index 542685c6594..fd61bb7931c 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DiagonalMatrix.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DiagonalMatrix.h @@ -11,270 +11,294 @@ #ifndef EIGEN_DIAGONALMATRIX_H #define EIGEN_DIAGONALMATRIX_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class DiagonalBase + * \ingroup Core_Module + * + * \brief Base class for diagonal matrices and expressions + * + * This is the base class that is inherited by diagonal matrix and related expression + * types, which internally use a vector for storing the diagonal entries. Diagonal + * types always represent square matrices. + * + * \tparam Derived is the derived type, a DiagonalMatrix or DiagonalWrapper. + * + * \sa class DiagonalMatrix, class DiagonalWrapper + */ +template +class DiagonalBase : public EigenBase { + public: + typedef typename internal::traits::DiagonalVectorType DiagonalVectorType; + typedef typename DiagonalVectorType::Scalar Scalar; + typedef typename DiagonalVectorType::RealScalar RealScalar; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::StorageIndex StorageIndex; -#ifndef EIGEN_PARSED_BY_DOXYGEN -template -class DiagonalBase : public EigenBase -{ - public: - typedef typename internal::traits::DiagonalVectorType DiagonalVectorType; - typedef typename DiagonalVectorType::Scalar Scalar; - typedef typename DiagonalVectorType::RealScalar RealScalar; - typedef typename internal::traits::StorageKind StorageKind; - typedef typename internal::traits::StorageIndex StorageIndex; - - enum { - RowsAtCompileTime = DiagonalVectorType::SizeAtCompileTime, - ColsAtCompileTime = DiagonalVectorType::SizeAtCompileTime, - MaxRowsAtCompileTime = DiagonalVectorType::MaxSizeAtCompileTime, - MaxColsAtCompileTime = DiagonalVectorType::MaxSizeAtCompileTime, - IsVectorAtCompileTime = 0, - Flags = NoPreferredStorageOrderBit - }; - - typedef Matrix DenseMatrixType; - typedef DenseMatrixType DenseType; - typedef DiagonalMatrix PlainObject; - - EIGEN_DEVICE_FUNC - inline const Derived& derived() const { return *static_cast(this); } - EIGEN_DEVICE_FUNC - inline Derived& derived() { return *static_cast(this); } - - EIGEN_DEVICE_FUNC - DenseMatrixType toDenseMatrix() const { return derived(); } - - EIGEN_DEVICE_FUNC - inline const DiagonalVectorType& diagonal() const { return derived().diagonal(); } - EIGEN_DEVICE_FUNC - inline DiagonalVectorType& diagonal() { return derived().diagonal(); } - - EIGEN_DEVICE_FUNC - inline Index rows() const { return diagonal().size(); } - EIGEN_DEVICE_FUNC - inline Index cols() const { return diagonal().size(); } - - template - EIGEN_DEVICE_FUNC - const Product - operator*(const MatrixBase &matrix) const - { - return Product(derived(),matrix.derived()); - } + enum { + RowsAtCompileTime = DiagonalVectorType::SizeAtCompileTime, + ColsAtCompileTime = DiagonalVectorType::SizeAtCompileTime, + MaxRowsAtCompileTime = DiagonalVectorType::MaxSizeAtCompileTime, + MaxColsAtCompileTime = DiagonalVectorType::MaxSizeAtCompileTime, + IsVectorAtCompileTime = 0, + Flags = NoPreferredStorageOrderBit + }; - typedef DiagonalWrapper, const DiagonalVectorType> > InverseReturnType; - EIGEN_DEVICE_FUNC - inline const InverseReturnType - inverse() const - { - return InverseReturnType(diagonal().cwiseInverse()); - } - - EIGEN_DEVICE_FUNC - inline const DiagonalWrapper - operator*(const Scalar& scalar) const - { - return DiagonalWrapper(diagonal() * scalar); - } - EIGEN_DEVICE_FUNC - friend inline const DiagonalWrapper - operator*(const Scalar& scalar, const DiagonalBase& other) - { - return DiagonalWrapper(scalar * other.diagonal()); - } + typedef Matrix + DenseMatrixType; + typedef DenseMatrixType DenseType; + typedef DiagonalMatrix + PlainObject; + + /** \returns a reference to the derived object. */ + EIGEN_DEVICE_FUNC inline const Derived& derived() const { return *static_cast(this); } + /** \returns a const reference to the derived object. */ + EIGEN_DEVICE_FUNC inline Derived& derived() { return *static_cast(this); } + + /** + * Constructs a dense matrix from \c *this. Note, this directly returns a dense matrix type, + * not an expression. + * \returns A dense matrix, with its diagonal entries set from the the derived object. */ + EIGEN_DEVICE_FUNC DenseMatrixType toDenseMatrix() const { return derived(); } + + /** \returns a reference to the derived object's vector of diagonal coefficients. */ + EIGEN_DEVICE_FUNC inline const DiagonalVectorType& diagonal() const { return derived().diagonal(); } + /** \returns a const reference to the derived object's vector of diagonal coefficients. */ + EIGEN_DEVICE_FUNC inline DiagonalVectorType& diagonal() { return derived().diagonal(); } + + /** \returns the value of the coefficient as if \c *this was a dense matrix. */ + EIGEN_DEVICE_FUNC inline Scalar coeff(Index row, Index col) const { + eigen_assert(row >= 0 && col >= 0 && row < rows() && col <= cols()); + return row == col ? diagonal().coeff(row) : Scalar(0); + } - template - EIGEN_DEVICE_FUNC - #ifdef EIGEN_PARSED_BY_DOXYGEN - inline unspecified_expression_type - #else - inline const DiagonalWrapper - #endif - operator+(const DiagonalBase& other) const - { - return (diagonal() + other.diagonal()).asDiagonal(); - } + /** \returns the number of rows. */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const { return diagonal().size(); } + /** \returns the number of columns. */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const { return diagonal().size(); } - template - EIGEN_DEVICE_FUNC - #ifdef EIGEN_PARSED_BY_DOXYGEN - inline unspecified_expression_type - #else - inline const DiagonalWrapper - #endif - operator-(const DiagonalBase& other) const - { - return (diagonal() - other.diagonal()).asDiagonal(); - } -}; + /** \returns the diagonal matrix product of \c *this by the dense matrix, \a matrix */ + template + EIGEN_DEVICE_FUNC const Product operator*( + const MatrixBase& matrix) const { + return Product(derived(), matrix.derived()); + } -#endif + template + using DiagonalProductReturnType = DiagonalWrapper; + + /** \returns the diagonal matrix product of \c *this by the diagonal matrix \a other */ + template + EIGEN_DEVICE_FUNC const DiagonalProductReturnType operator*( + const DiagonalBase& other) const { + return diagonal().cwiseProduct(other.diagonal()).asDiagonal(); + } + + using DiagonalInverseReturnType = + DiagonalWrapper, const DiagonalVectorType>>; + + /** \returns the inverse \c *this. Computed as the coefficient-wise inverse of the diagonal. */ + EIGEN_DEVICE_FUNC inline const DiagonalInverseReturnType inverse() const { + return diagonal().cwiseInverse().asDiagonal(); + } + + using DiagonalScaleReturnType = + DiagonalWrapper; + + /** \returns the product of \c *this by the scalar \a scalar */ + EIGEN_DEVICE_FUNC inline const DiagonalScaleReturnType operator*(const Scalar& scalar) const { + return (diagonal() * scalar).asDiagonal(); + } + + using ScaleDiagonalReturnType = + DiagonalWrapper; + + /** \returns the product of a scalar and the diagonal matrix \a other */ + EIGEN_DEVICE_FUNC friend inline const ScaleDiagonalReturnType operator*(const Scalar& scalar, + const DiagonalBase& other) { + return (scalar * other.diagonal()).asDiagonal(); + } + + template + using DiagonalSumReturnType = DiagonalWrapper; + + /** \returns the sum of \c *this and the diagonal matrix \a other */ + template + EIGEN_DEVICE_FUNC inline const DiagonalSumReturnType operator+( + const DiagonalBase& other) const { + return (diagonal() + other.diagonal()).asDiagonal(); + } + + template + using DiagonalDifferenceReturnType = DiagonalWrapper; + + /** \returns the difference of \c *this and the diagonal matrix \a other */ + template + EIGEN_DEVICE_FUNC inline const DiagonalDifferenceReturnType operator-( + const DiagonalBase& other) const { + return (diagonal() - other.diagonal()).asDiagonal(); + } +}; /** \class DiagonalMatrix - * \ingroup Core_Module - * - * \brief Represents a diagonal matrix with its storage - * - * \param _Scalar the type of coefficients - * \param SizeAtCompileTime the dimension of the matrix, or Dynamic - * \param MaxSizeAtCompileTime the dimension of the matrix, or Dynamic. This parameter is optional and defaults - * to SizeAtCompileTime. Most of the time, you do not need to specify it. - * - * \sa class DiagonalWrapper - */ + * \ingroup Core_Module + * + * \brief Represents a diagonal matrix with its storage + * + * \tparam Scalar_ the type of coefficients + * \tparam SizeAtCompileTime the dimension of the matrix, or Dynamic + * \tparam MaxSizeAtCompileTime the dimension of the matrix, or Dynamic. This parameter is optional and defaults + * to SizeAtCompileTime. Most of the time, you do not need to specify it. + * + * \sa class DiagonalBase, class DiagonalWrapper + */ namespace internal { -template -struct traits > - : traits > -{ - typedef Matrix<_Scalar,SizeAtCompileTime,1,0,MaxSizeAtCompileTime,1> DiagonalVectorType; +template +struct traits> + : traits> { + typedef Matrix DiagonalVectorType; typedef DiagonalShape StorageKind; - enum { - Flags = LvalueBit | NoPreferredStorageOrderBit - }; + enum { Flags = LvalueBit | NoPreferredStorageOrderBit | NestByRefBit }; }; -} -template -class DiagonalMatrix - : public DiagonalBase > -{ - public: - #ifndef EIGEN_PARSED_BY_DOXYGEN - typedef typename internal::traits::DiagonalVectorType DiagonalVectorType; - typedef const DiagonalMatrix& Nested; - typedef _Scalar Scalar; - typedef typename internal::traits::StorageKind StorageKind; - typedef typename internal::traits::StorageIndex StorageIndex; - #endif - - protected: - - DiagonalVectorType m_diagonal; - - public: - - /** const version of diagonal(). */ - EIGEN_DEVICE_FUNC - inline const DiagonalVectorType& diagonal() const { return m_diagonal; } - /** \returns a reference to the stored vector of diagonal coefficients. */ - EIGEN_DEVICE_FUNC - inline DiagonalVectorType& diagonal() { return m_diagonal; } - - /** Default constructor without initialization */ - EIGEN_DEVICE_FUNC - inline DiagonalMatrix() {} - - /** Constructs a diagonal matrix with given dimension */ - EIGEN_DEVICE_FUNC - explicit inline DiagonalMatrix(Index dim) : m_diagonal(dim) {} - - /** 2D constructor. */ - EIGEN_DEVICE_FUNC - inline DiagonalMatrix(const Scalar& x, const Scalar& y) : m_diagonal(x,y) {} - - /** 3D constructor. */ - EIGEN_DEVICE_FUNC - inline DiagonalMatrix(const Scalar& x, const Scalar& y, const Scalar& z) : m_diagonal(x,y,z) {} - - #if EIGEN_HAS_CXX11 - /** \brief Construct a diagonal matrix with fixed size from an arbitrary number of coefficients. \cpp11 - * - * There exists C++98 anologue constructors for fixed-size diagonal matrices having 2 or 3 coefficients. - * - * \warning To construct a diagonal matrix of fixed size, the number of values passed to this - * constructor must match the fixed dimension of \c *this. - * - * \sa DiagonalMatrix(const Scalar&, const Scalar&) - * \sa DiagonalMatrix(const Scalar&, const Scalar&, const Scalar&) - */ - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - DiagonalMatrix(const Scalar& a0, const Scalar& a1, const Scalar& a2, const ArgTypes&... args) +} // namespace internal +template +class DiagonalMatrix : public DiagonalBase> { + public: +#ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename internal::traits::DiagonalVectorType DiagonalVectorType; + typedef const DiagonalMatrix& Nested; + typedef Scalar_ Scalar; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::StorageIndex StorageIndex; +#endif + + protected: + DiagonalVectorType m_diagonal; + + public: + /** const version of diagonal(). */ + EIGEN_DEVICE_FUNC inline const DiagonalVectorType& diagonal() const { return m_diagonal; } + /** \returns a reference to the stored vector of diagonal coefficients. */ + EIGEN_DEVICE_FUNC inline DiagonalVectorType& diagonal() { return m_diagonal; } + + /** Default constructor without initialization */ + EIGEN_DEVICE_FUNC inline DiagonalMatrix() {} + + /** Constructs a diagonal matrix with given dimension */ + EIGEN_DEVICE_FUNC explicit inline DiagonalMatrix(Index dim) : m_diagonal(dim) {} + + /** 2D constructor. */ + EIGEN_DEVICE_FUNC inline DiagonalMatrix(const Scalar& x, const Scalar& y) : m_diagonal(x, y) {} + + /** 3D constructor. */ + EIGEN_DEVICE_FUNC inline DiagonalMatrix(const Scalar& x, const Scalar& y, const Scalar& z) : m_diagonal(x, y, z) {} + + /** \brief Construct a diagonal matrix with fixed size from an arbitrary number of coefficients. + * + * \warning To construct a diagonal matrix of fixed size, the number of values passed to this + * constructor must match the fixed dimension of \c *this. + * + * \sa DiagonalMatrix(const Scalar&, const Scalar&) + * \sa DiagonalMatrix(const Scalar&, const Scalar&, const Scalar&) + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DiagonalMatrix(const Scalar& a0, const Scalar& a1, const Scalar& a2, + const ArgTypes&... args) : m_diagonal(a0, a1, a2, args...) {} - /** \brief Constructs a DiagonalMatrix and initializes it by elements given by an initializer list of initializer - * lists \cpp11 - */ - EIGEN_DEVICE_FUNC - explicit EIGEN_STRONG_INLINE DiagonalMatrix(const std::initializer_list>& list) + /** \brief Constructs a DiagonalMatrix and initializes it by elements given by an initializer list of initializer + * lists \cpp11 + */ + EIGEN_DEVICE_FUNC explicit EIGEN_STRONG_INLINE DiagonalMatrix( + const std::initializer_list>& list) : m_diagonal(list) {} - #endif // EIGEN_HAS_CXX11 - - /** Copy constructor. */ - template - EIGEN_DEVICE_FUNC - inline DiagonalMatrix(const DiagonalBase& other) : m_diagonal(other.diagonal()) {} - - #ifndef EIGEN_PARSED_BY_DOXYGEN - /** copy constructor. prevent a default copy constructor from hiding the other templated constructor */ - inline DiagonalMatrix(const DiagonalMatrix& other) : m_diagonal(other.diagonal()) {} - #endif - - /** generic constructor from expression of the diagonal coefficients */ - template - EIGEN_DEVICE_FUNC - explicit inline DiagonalMatrix(const MatrixBase& other) : m_diagonal(other) - {} - - /** Copy operator. */ - template - EIGEN_DEVICE_FUNC - DiagonalMatrix& operator=(const DiagonalBase& other) - { - m_diagonal = other.diagonal(); - return *this; - } - #ifndef EIGEN_PARSED_BY_DOXYGEN - /** This is a special case of the templated operator=. Its purpose is to - * prevent a default operator= from hiding the templated operator=. - */ - EIGEN_DEVICE_FUNC - DiagonalMatrix& operator=(const DiagonalMatrix& other) - { - m_diagonal = other.diagonal(); - return *this; - } - #endif - - /** Resizes to given size. */ - EIGEN_DEVICE_FUNC - inline void resize(Index size) { m_diagonal.resize(size); } - /** Sets all coefficients to zero. */ - EIGEN_DEVICE_FUNC - inline void setZero() { m_diagonal.setZero(); } - /** Resizes and sets all coefficients to zero. */ - EIGEN_DEVICE_FUNC - inline void setZero(Index size) { m_diagonal.setZero(size); } - /** Sets this matrix to be the identity matrix of the current size. */ - EIGEN_DEVICE_FUNC - inline void setIdentity() { m_diagonal.setOnes(); } - /** Sets this matrix to be the identity matrix of the given size. */ - EIGEN_DEVICE_FUNC - inline void setIdentity(Index size) { m_diagonal.setOnes(size); } + /** \brief Constructs a DiagonalMatrix from an r-value diagonal vector type */ + EIGEN_DEVICE_FUNC explicit inline DiagonalMatrix(DiagonalVectorType&& diag) : m_diagonal(std::move(diag)) {} + + /** Copy constructor. */ + template + EIGEN_DEVICE_FUNC inline DiagonalMatrix(const DiagonalBase& other) : m_diagonal(other.diagonal()) {} + +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** copy constructor. prevent a default copy constructor from hiding the other templated constructor */ + inline DiagonalMatrix(const DiagonalMatrix& other) : m_diagonal(other.diagonal()) {} +#endif + + /** generic constructor from expression of the diagonal coefficients */ + template + EIGEN_DEVICE_FUNC explicit inline DiagonalMatrix(const MatrixBase& other) : m_diagonal(other) {} + + /** Copy operator. */ + template + EIGEN_DEVICE_FUNC DiagonalMatrix& operator=(const DiagonalBase& other) { + m_diagonal = other.diagonal(); + return *this; + } + +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** This is a special case of the templated operator=. Its purpose is to + * prevent a default operator= from hiding the templated operator=. + */ + EIGEN_DEVICE_FUNC DiagonalMatrix& operator=(const DiagonalMatrix& other) { + m_diagonal = other.diagonal(); + return *this; + } +#endif + + typedef DiagonalWrapper, DiagonalVectorType>> + InitializeReturnType; + + /** Initializes a diagonal matrix of size SizeAtCompileTime with coefficients set to zero */ + EIGEN_DEVICE_FUNC static const InitializeReturnType Zero() { return DiagonalVectorType::Zero().asDiagonal(); } + /** Initializes a diagonal matrix of size dim with coefficients set to zero */ + EIGEN_DEVICE_FUNC static const InitializeReturnType Zero(Index size) { + return DiagonalVectorType::Zero(size).asDiagonal(); + } + /** Initializes a identity matrix of size SizeAtCompileTime */ + EIGEN_DEVICE_FUNC static const InitializeReturnType Identity() { return DiagonalVectorType::Ones().asDiagonal(); } + /** Initializes a identity matrix of size dim */ + EIGEN_DEVICE_FUNC static const InitializeReturnType Identity(Index size) { + return DiagonalVectorType::Ones(size).asDiagonal(); + } + + /** Resizes to given size. */ + EIGEN_DEVICE_FUNC inline void resize(Index size) { m_diagonal.resize(size); } + /** Sets all coefficients to zero. */ + EIGEN_DEVICE_FUNC inline void setZero() { m_diagonal.setZero(); } + /** Resizes and sets all coefficients to zero. */ + EIGEN_DEVICE_FUNC inline void setZero(Index size) { m_diagonal.setZero(size); } + /** Sets this matrix to be the identity matrix of the current size. */ + EIGEN_DEVICE_FUNC inline void setIdentity() { m_diagonal.setOnes(); } + /** Sets this matrix to be the identity matrix of the given size. */ + EIGEN_DEVICE_FUNC inline void setIdentity(Index size) { m_diagonal.setOnes(size); } }; /** \class DiagonalWrapper - * \ingroup Core_Module - * - * \brief Expression of a diagonal matrix - * - * \param _DiagonalVectorType the type of the vector of diagonal coefficients - * - * This class is an expression of a diagonal matrix, but not storing its own vector of diagonal coefficients, - * instead wrapping an existing vector expression. It is the return type of MatrixBase::asDiagonal() - * and most of the time this is the only way that it is used. - * - * \sa class DiagonalMatrix, class DiagonalBase, MatrixBase::asDiagonal() - */ + * \ingroup Core_Module + * + * \brief Expression of a diagonal matrix + * + * \tparam DiagonalVectorType_ the type of the vector of diagonal coefficients + * + * This class is an expression of a diagonal matrix, but not storing its own vector of diagonal coefficients, + * instead wrapping an existing vector expression. It is the return type of MatrixBase::asDiagonal() + * and most of the time this is the only way that it is used. + * + * \sa class DiagonalMatrix, class DiagonalBase, MatrixBase::asDiagonal() + */ namespace internal { -template -struct traits > -{ - typedef _DiagonalVectorType DiagonalVectorType; +template +struct traits> { + typedef DiagonalVectorType_ DiagonalVectorType; typedef typename DiagonalVectorType::Scalar Scalar; typedef typename DiagonalVectorType::StorageIndex StorageIndex; typedef DiagonalShape StorageKind; @@ -284,108 +308,107 @@ struct traits > ColsAtCompileTime = DiagonalVectorType::SizeAtCompileTime, MaxRowsAtCompileTime = DiagonalVectorType::MaxSizeAtCompileTime, MaxColsAtCompileTime = DiagonalVectorType::MaxSizeAtCompileTime, - Flags = (traits::Flags & LvalueBit) | NoPreferredStorageOrderBit + Flags = (traits::Flags & LvalueBit) | NoPreferredStorageOrderBit }; }; -} +} // namespace internal + +template +class DiagonalWrapper : public DiagonalBase>, internal::no_assignment_operator { + public: +#ifndef EIGEN_PARSED_BY_DOXYGEN + typedef DiagonalVectorType_ DiagonalVectorType; + typedef DiagonalWrapper Nested; +#endif -template -class DiagonalWrapper - : public DiagonalBase >, internal::no_assignment_operator -{ - public: - #ifndef EIGEN_PARSED_BY_DOXYGEN - typedef _DiagonalVectorType DiagonalVectorType; - typedef DiagonalWrapper Nested; - #endif - - /** Constructor from expression of diagonal coefficients to wrap. */ - EIGEN_DEVICE_FUNC - explicit inline DiagonalWrapper(DiagonalVectorType& a_diagonal) : m_diagonal(a_diagonal) {} - - /** \returns a const reference to the wrapped expression of diagonal coefficients. */ - EIGEN_DEVICE_FUNC - const DiagonalVectorType& diagonal() const { return m_diagonal; } - - protected: - typename DiagonalVectorType::Nested m_diagonal; + /** Constructor from expression of diagonal coefficients to wrap. */ + EIGEN_DEVICE_FUNC explicit inline DiagonalWrapper(DiagonalVectorType& a_diagonal) : m_diagonal(a_diagonal) {} + + /** \returns a const reference to the wrapped expression of diagonal coefficients. */ + EIGEN_DEVICE_FUNC const DiagonalVectorType& diagonal() const { return m_diagonal; } + + protected: + typename DiagonalVectorType::Nested m_diagonal; }; /** \returns a pseudo-expression of a diagonal matrix with *this as vector of diagonal coefficients - * - * \only_for_vectors - * - * Example: \include MatrixBase_asDiagonal.cpp - * Output: \verbinclude MatrixBase_asDiagonal.out - * - * \sa class DiagonalWrapper, class DiagonalMatrix, diagonal(), isDiagonal() - **/ -template -EIGEN_DEVICE_FUNC inline const DiagonalWrapper -MatrixBase::asDiagonal() const -{ + * + * \only_for_vectors + * + * Example: \include MatrixBase_asDiagonal.cpp + * Output: \verbinclude MatrixBase_asDiagonal.out + * + * \sa class DiagonalWrapper, class DiagonalMatrix, diagonal(), isDiagonal() + **/ +template +EIGEN_DEVICE_FUNC inline const DiagonalWrapper MatrixBase::asDiagonal() const { return DiagonalWrapper(derived()); } /** \returns true if *this is approximately equal to a diagonal matrix, - * within the precision given by \a prec. - * - * Example: \include MatrixBase_isDiagonal.cpp - * Output: \verbinclude MatrixBase_isDiagonal.out - * - * \sa asDiagonal() - */ -template -bool MatrixBase::isDiagonal(const RealScalar& prec) const -{ - if(cols() != rows()) return false; + * within the precision given by \a prec. + * + * Example: \include MatrixBase_isDiagonal.cpp + * Output: \verbinclude MatrixBase_isDiagonal.out + * + * \sa asDiagonal() + */ +template +bool MatrixBase::isDiagonal(const RealScalar& prec) const { + if (cols() != rows()) return false; RealScalar maxAbsOnDiagonal = static_cast(-1); - for(Index j = 0; j < cols(); ++j) - { - RealScalar absOnDiagonal = numext::abs(coeff(j,j)); - if(absOnDiagonal > maxAbsOnDiagonal) maxAbsOnDiagonal = absOnDiagonal; + for (Index j = 0; j < cols(); ++j) { + RealScalar absOnDiagonal = numext::abs(coeff(j, j)); + if (absOnDiagonal > maxAbsOnDiagonal) maxAbsOnDiagonal = absOnDiagonal; } - for(Index j = 0; j < cols(); ++j) - for(Index i = 0; i < j; ++i) - { - if(!internal::isMuchSmallerThan(coeff(i, j), maxAbsOnDiagonal, prec)) return false; - if(!internal::isMuchSmallerThan(coeff(j, i), maxAbsOnDiagonal, prec)) return false; + for (Index j = 0; j < cols(); ++j) + for (Index i = 0; i < j; ++i) { + if (!internal::isMuchSmallerThan(coeff(i, j), maxAbsOnDiagonal, prec)) return false; + if (!internal::isMuchSmallerThan(coeff(j, i), maxAbsOnDiagonal, prec)) return false; } return true; } namespace internal { -template<> struct storage_kind_to_shape { typedef DiagonalShape Shape; }; +template <> +struct storage_kind_to_shape { + typedef DiagonalShape Shape; +}; struct Diagonal2Dense {}; -template<> struct AssignmentKind { typedef Diagonal2Dense Kind; }; +template <> +struct AssignmentKind { + typedef Diagonal2Dense Kind; +}; // Diagonal matrix to Dense assignment -template< typename DstXprType, typename SrcXprType, typename Functor> -struct Assignment -{ - static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &/*func*/) - { +template +struct Assignment { + static void run(DstXprType& dst, const SrcXprType& src, + const internal::assign_op& /*func*/) { Index dstRows = src.rows(); Index dstCols = src.cols(); - if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) - dst.resize(dstRows, dstCols); - + if ((dst.rows() != dstRows) || (dst.cols() != dstCols)) dst.resize(dstRows, dstCols); + dst.setZero(); dst.diagonal() = src.diagonal(); } - - static void run(DstXprType &dst, const SrcXprType &src, const internal::add_assign_op &/*func*/) - { dst.diagonal() += src.diagonal(); } - - static void run(DstXprType &dst, const SrcXprType &src, const internal::sub_assign_op &/*func*/) - { dst.diagonal() -= src.diagonal(); } + + static void run(DstXprType& dst, const SrcXprType& src, + const internal::add_assign_op& /*func*/) { + dst.diagonal() += src.diagonal(); + } + + static void run(DstXprType& dst, const SrcXprType& src, + const internal::sub_assign_op& /*func*/) { + dst.diagonal() -= src.diagonal(); + } }; -} // namespace internal +} // namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_DIAGONALMATRIX_H +#endif // EIGEN_DIAGONALMATRIX_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DiagonalProduct.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DiagonalProduct.h index 7911d1cd174..bd0feeac7f0 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DiagonalProduct.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/DiagonalProduct.h @@ -11,18 +11,20 @@ #ifndef EIGEN_DIAGONALPRODUCT_H #define EIGEN_DIAGONALPRODUCT_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { /** \returns the diagonal matrix product of \c *this by the diagonal matrix \a diagonal. - */ -template -template -EIGEN_DEVICE_FUNC inline const Product -MatrixBase::operator*(const DiagonalBase &a_diagonal) const -{ - return Product(derived(),a_diagonal.derived()); + */ +template +template +EIGEN_DEVICE_FUNC inline const Product MatrixBase::operator*( + const DiagonalBase &a_diagonal) const { + return Product(derived(), a_diagonal.derived()); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_DIAGONALPRODUCT_H +#endif // EIGEN_DIAGONALPRODUCT_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Dot.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Dot.h index 5c3441b9266..82eb9c70969 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Dot.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Dot.h @@ -10,309 +10,280 @@ #ifndef EIGEN_DOT_H #define EIGEN_DOT_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { namespace internal { // helper function for dot(). The problem is that if we put that in the body of dot(), then upon calling dot // with mismatched types, the compiler emits errors about failing to instantiate cwiseProduct BEFORE // looking at the static assertions. Thus this is a trick to get better compile errors. -template -struct dot_nocheck -{ - typedef scalar_conj_product_op::Scalar,typename traits::Scalar> conj_prod; +template +struct dot_nocheck { + typedef scalar_conj_product_op::Scalar, typename traits::Scalar> conj_prod; typedef typename conj_prod::result_type ResScalar; - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE - static ResScalar run(const MatrixBase& a, const MatrixBase& b) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static ResScalar run(const MatrixBase& a, const MatrixBase& b) { return a.template binaryExpr(b).sum(); } }; -template -struct dot_nocheck -{ - typedef scalar_conj_product_op::Scalar,typename traits::Scalar> conj_prod; +template +struct dot_nocheck { + typedef scalar_conj_product_op::Scalar, typename traits::Scalar> conj_prod; typedef typename conj_prod::result_type ResScalar; - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE - static ResScalar run(const MatrixBase& a, const MatrixBase& b) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static ResScalar run(const MatrixBase& a, const MatrixBase& b) { return a.transpose().template binaryExpr(b).sum(); } }; -} // end namespace internal +} // end namespace internal /** \fn MatrixBase::dot - * \returns the dot product of *this with other. - * - * \only_for_vectors - * - * \note If the scalar type is complex numbers, then this function returns the hermitian - * (sesquilinear) dot product, conjugate-linear in the first variable and linear in the - * second variable. - * - * \sa squaredNorm(), norm() - */ -template -template -EIGEN_DEVICE_FUNC -EIGEN_STRONG_INLINE -typename ScalarBinaryOpTraits::Scalar,typename internal::traits::Scalar>::ReturnType -MatrixBase::dot(const MatrixBase& other) const -{ + * \returns the dot product of *this with other. + * + * \only_for_vectors + * + * \note If the scalar type is complex numbers, then this function returns the hermitian + * (sesquilinear) dot product, conjugate-linear in the first variable and linear in the + * second variable. + * + * \sa squaredNorm(), norm() + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + typename ScalarBinaryOpTraits::Scalar, + typename internal::traits::Scalar>::ReturnType + MatrixBase::dot(const MatrixBase& other) const { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived) - EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(Derived,OtherDerived) + EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(Derived, OtherDerived) #if !(defined(EIGEN_NO_STATIC_ASSERT) && defined(EIGEN_NO_DEBUG)) - typedef internal::scalar_conj_product_op func; - EIGEN_CHECK_BINARY_COMPATIBILIY(func,Scalar,typename OtherDerived::Scalar); + EIGEN_CHECK_BINARY_COMPATIBILIY( + Eigen::internal::scalar_conj_product_op, Scalar, + typename OtherDerived::Scalar); #endif - + eigen_assert(size() == other.size()); - return internal::dot_nocheck::run(*this, other); + return internal::dot_nocheck::run(*this, other); } //---------- implementation of L2 norm and related functions ---------- /** \returns, for vectors, the squared \em l2 norm of \c *this, and for matrices the squared Frobenius norm. - * In both cases, it consists in the sum of the square of all the matrix entries. - * For vectors, this is also equals to the dot product of \c *this with itself. - * - * \sa dot(), norm(), lpNorm() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename NumTraits::Scalar>::Real MatrixBase::squaredNorm() const -{ + * In both cases, it consists in the sum of the square of all the matrix entries. + * For vectors, this is also equals to the dot product of \c *this with itself. + * + * \sa dot(), norm(), lpNorm() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename NumTraits::Scalar>::Real +MatrixBase::squaredNorm() const { return numext::real((*this).cwiseAbs2().sum()); } /** \returns, for vectors, the \em l2 norm of \c *this, and for matrices the Frobenius norm. - * In both cases, it consists in the square root of the sum of the square of all the matrix entries. - * For vectors, this is also equals to the square root of the dot product of \c *this with itself. - * - * \sa lpNorm(), dot(), squaredNorm() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename NumTraits::Scalar>::Real MatrixBase::norm() const -{ + * In both cases, it consists in the square root of the sum of the square of all the matrix entries. + * For vectors, this is also equals to the square root of the dot product of \c *this with itself. + * + * \sa lpNorm(), dot(), squaredNorm() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename NumTraits::Scalar>::Real +MatrixBase::norm() const { return numext::sqrt(squaredNorm()); } /** \returns an expression of the quotient of \c *this by its own norm. - * - * \warning If the input vector is too small (i.e., this->norm()==0), - * then this function returns a copy of the input. - * - * \only_for_vectors - * - * \sa norm(), normalize() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::PlainObject -MatrixBase::normalized() const -{ - typedef typename internal::nested_eval::type _Nested; - _Nested n(derived()); + * + * \warning If the input vector is too small (i.e., this->norm()==0), + * then this function returns a copy of the input. + * + * \only_for_vectors + * + * \sa norm(), normalize() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::PlainObject MatrixBase::normalized() + const { + typedef typename internal::nested_eval::type Nested_; + Nested_ n(derived()); RealScalar z = n.squaredNorm(); // NOTE: after extensive benchmarking, this conditional does not impact performance, at least on recent x86 CPU - if(z>RealScalar(0)) + if (z > RealScalar(0)) return n / numext::sqrt(z); else return n; } /** Normalizes the vector, i.e. divides it by its own norm. - * - * \only_for_vectors - * - * \warning If the input vector is too small (i.e., this->norm()==0), then \c *this is left unchanged. - * - * \sa norm(), normalized() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void MatrixBase::normalize() -{ + * + * \only_for_vectors + * + * \warning If the input vector is too small (i.e., this->norm()==0), then \c *this is left unchanged. + * + * \sa norm(), normalized() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void MatrixBase::normalize() { RealScalar z = squaredNorm(); // NOTE: after extensive benchmarking, this conditional does not impact performance, at least on recent x86 CPU - if(z>RealScalar(0)) - derived() /= numext::sqrt(z); + if (z > RealScalar(0)) derived() /= numext::sqrt(z); } /** \returns an expression of the quotient of \c *this by its own norm while avoiding underflow and overflow. - * - * \only_for_vectors - * - * This method is analogue to the normalized() method, but it reduces the risk of - * underflow and overflow when computing the norm. - * - * \warning If the input vector is too small (i.e., this->norm()==0), - * then this function returns a copy of the input. - * - * \sa stableNorm(), stableNormalize(), normalized() - */ -template + * + * \only_for_vectors + * + * This method is analogue to the normalized() method, but it reduces the risk of + * underflow and overflow when computing the norm. + * + * \warning If the input vector is too small (i.e., this->norm()==0), + * then this function returns a copy of the input. + * + * \sa stableNorm(), stableNormalize(), normalized() + */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::PlainObject -MatrixBase::stableNormalized() const -{ - typedef typename internal::nested_eval::type _Nested; - _Nested n(derived()); +MatrixBase::stableNormalized() const { + typedef typename internal::nested_eval::type Nested_; + Nested_ n(derived()); RealScalar w = n.cwiseAbs().maxCoeff(); - RealScalar z = (n/w).squaredNorm(); - if(z>RealScalar(0)) - return n / (numext::sqrt(z)*w); + RealScalar z = (n / w).squaredNorm(); + if (z > RealScalar(0)) + return n / (numext::sqrt(z) * w); else return n; } /** Normalizes the vector while avoid underflow and overflow - * - * \only_for_vectors - * - * This method is analogue to the normalize() method, but it reduces the risk of - * underflow and overflow when computing the norm. - * - * \warning If the input vector is too small (i.e., this->norm()==0), then \c *this is left unchanged. - * - * \sa stableNorm(), stableNormalized(), normalize() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void MatrixBase::stableNormalize() -{ + * + * \only_for_vectors + * + * This method is analogue to the normalize() method, but it reduces the risk of + * underflow and overflow when computing the norm. + * + * \warning If the input vector is too small (i.e., this->norm()==0), then \c *this is left unchanged. + * + * \sa stableNorm(), stableNormalized(), normalize() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void MatrixBase::stableNormalize() { RealScalar w = cwiseAbs().maxCoeff(); - RealScalar z = (derived()/w).squaredNorm(); - if(z>RealScalar(0)) - derived() /= numext::sqrt(z)*w; + RealScalar z = (derived() / w).squaredNorm(); + if (z > RealScalar(0)) derived() /= numext::sqrt(z) * w; } //---------- implementation of other norms ---------- namespace internal { -template -struct lpNorm_selector -{ +template +struct lpNorm_selector { typedef typename NumTraits::Scalar>::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const MatrixBase& m) - { + EIGEN_DEVICE_FUNC static inline RealScalar run(const MatrixBase& m) { EIGEN_USING_STD(pow) - return pow(m.cwiseAbs().array().pow(p).sum(), RealScalar(1)/p); + return pow(m.cwiseAbs().array().pow(p).sum(), RealScalar(1) / p); } }; -template -struct lpNorm_selector -{ - EIGEN_DEVICE_FUNC - static inline typename NumTraits::Scalar>::Real run(const MatrixBase& m) - { +template +struct lpNorm_selector { + EIGEN_DEVICE_FUNC static inline typename NumTraits::Scalar>::Real run( + const MatrixBase& m) { return m.cwiseAbs().sum(); } }; -template -struct lpNorm_selector -{ - EIGEN_DEVICE_FUNC - static inline typename NumTraits::Scalar>::Real run(const MatrixBase& m) - { +template +struct lpNorm_selector { + EIGEN_DEVICE_FUNC static inline typename NumTraits::Scalar>::Real run( + const MatrixBase& m) { return m.norm(); } }; -template -struct lpNorm_selector -{ +template +struct lpNorm_selector { typedef typename NumTraits::Scalar>::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const MatrixBase& m) - { - if(Derived::SizeAtCompileTime==0 || (Derived::SizeAtCompileTime==Dynamic && m.size()==0)) + EIGEN_DEVICE_FUNC static inline RealScalar run(const MatrixBase& m) { + if (Derived::SizeAtCompileTime == 0 || (Derived::SizeAtCompileTime == Dynamic && m.size() == 0)) return RealScalar(0); return m.cwiseAbs().maxCoeff(); } }; -} // end namespace internal +} // end namespace internal -/** \returns the \b coefficient-wise \f$ \ell^p \f$ norm of \c *this, that is, returns the p-th root of the sum of the p-th powers of the absolute values - * of the coefficients of \c *this. If \a p is the special value \a Eigen::Infinity, this function returns the \f$ \ell^\infty \f$ - * norm, that is the maximum of the absolute values of the coefficients of \c *this. - * - * In all cases, if \c *this is empty, then the value 0 is returned. - * - * \note For matrices, this function does not compute the operator-norm. That is, if \c *this is a matrix, then its coefficients are interpreted as a 1D vector. Nonetheless, you can easily compute the 1-norm and \f$\infty\f$-norm matrix operator norms using \link TutorialReductionsVisitorsBroadcastingReductionsNorm partial reductions \endlink. - * - * \sa norm() - */ -template -template +/** \returns the \b coefficient-wise \f$ \ell^p \f$ norm of \c *this, that is, returns the p-th root of the sum of the + * p-th powers of the absolute values of the coefficients of \c *this. If \a p is the special value \a Eigen::Infinity, + * this function returns the \f$ \ell^\infty \f$ norm, that is the maximum of the absolute values of the coefficients of + * \c *this. + * + * In all cases, if \c *this is empty, then the value 0 is returned. + * + * \note For matrices, this function does not compute the operator-norm. That is, if \c *this is a matrix, then its + * coefficients are interpreted as a 1D vector. Nonetheless, you can easily compute the 1-norm and \f$\infty\f$-norm + * matrix operator norms using \link TutorialReductionsVisitorsBroadcastingReductionsNorm partial reductions \endlink. + * + * \sa norm() + */ +template +template #ifndef EIGEN_PARSED_BY_DOXYGEN EIGEN_DEVICE_FUNC inline typename NumTraits::Scalar>::Real #else EIGEN_DEVICE_FUNC MatrixBase::RealScalar #endif -MatrixBase::lpNorm() const -{ +MatrixBase::lpNorm() const { return internal::lpNorm_selector::run(*this); } //---------- implementation of isOrthogonal / isUnitary ---------- /** \returns true if *this is approximately orthogonal to \a other, - * within the precision given by \a prec. - * - * Example: \include MatrixBase_isOrthogonal.cpp - * Output: \verbinclude MatrixBase_isOrthogonal.out - */ -template -template -bool MatrixBase::isOrthogonal -(const MatrixBase& other, const RealScalar& prec) const -{ - typename internal::nested_eval::type nested(derived()); - typename internal::nested_eval::type otherNested(other.derived()); + * within the precision given by \a prec. + * + * Example: \include MatrixBase_isOrthogonal.cpp + * Output: \verbinclude MatrixBase_isOrthogonal.out + */ +template +template +bool MatrixBase::isOrthogonal(const MatrixBase& other, const RealScalar& prec) const { + typename internal::nested_eval::type nested(derived()); + typename internal::nested_eval::type otherNested(other.derived()); return numext::abs2(nested.dot(otherNested)) <= prec * prec * nested.squaredNorm() * otherNested.squaredNorm(); } /** \returns true if *this is approximately an unitary matrix, - * within the precision given by \a prec. In the case where the \a Scalar - * type is real numbers, a unitary matrix is an orthogonal matrix, whence the name. - * - * \note This can be used to check whether a family of vectors forms an orthonormal basis. - * Indeed, \c m.isUnitary() returns true if and only if the columns (equivalently, the rows) of m form an - * orthonormal basis. - * - * Example: \include MatrixBase_isUnitary.cpp - * Output: \verbinclude MatrixBase_isUnitary.out - */ -template -bool MatrixBase::isUnitary(const RealScalar& prec) const -{ - typename internal::nested_eval::type self(derived()); - for(Index i = 0; i < cols(); ++i) - { - if(!internal::isApprox(self.col(i).squaredNorm(), static_cast(1), prec)) - return false; - for(Index j = 0; j < i; ++j) - if(!internal::isMuchSmallerThan(self.col(i).dot(self.col(j)), static_cast(1), prec)) - return false; + * within the precision given by \a prec. In the case where the \a Scalar + * type is real numbers, a unitary matrix is an orthogonal matrix, whence the name. + * + * \note This can be used to check whether a family of vectors forms an orthonormal basis. + * Indeed, \c m.isUnitary() returns true if and only if the columns (equivalently, the rows) of m form an + * orthonormal basis. + * + * Example: \include MatrixBase_isUnitary.cpp + * Output: \verbinclude MatrixBase_isUnitary.out + */ +template +bool MatrixBase::isUnitary(const RealScalar& prec) const { + typename internal::nested_eval::type self(derived()); + for (Index i = 0; i < cols(); ++i) { + if (!internal::isApprox(self.col(i).squaredNorm(), static_cast(1), prec)) return false; + for (Index j = 0; j < i; ++j) + if (!internal::isMuchSmallerThan(self.col(i).dot(self.col(j)), static_cast(1), prec)) return false; } return true; } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_DOT_H +#endif // EIGEN_DOT_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/EigenBase.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/EigenBase.h index 6b3c7d3745e..f485016ac49 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/EigenBase.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/EigenBase.h @@ -11,150 +11,134 @@ #ifndef EIGEN_EIGENBASE_H #define EIGEN_EIGENBASE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { /** \class EigenBase - * \ingroup Core_Module - * - * Common base class for all classes T such that MatrixBase has an operator=(T) and a constructor MatrixBase(T). - * - * In other words, an EigenBase object is an object that can be copied into a MatrixBase. - * - * Besides MatrixBase-derived classes, this also includes special matrix classes such as diagonal matrices, etc. - * - * Notice that this class is trivial, it is only used to disambiguate overloaded functions. - * - * \sa \blank \ref TopicClassHierarchy - */ -template struct EigenBase -{ -// typedef typename internal::plain_matrix_type::type PlainObject; + * \ingroup Core_Module + * + * Common base class for all classes T such that MatrixBase has an operator=(T) and a constructor MatrixBase(T). + * + * In other words, an EigenBase object is an object that can be copied into a MatrixBase. + * + * Besides MatrixBase-derived classes, this also includes special matrix classes such as diagonal matrices, etc. + * + * Notice that this class is trivial, it is only used to disambiguate overloaded functions. + * + * \sa \blank \ref TopicClassHierarchy + */ +template +struct EigenBase { + // typedef typename internal::plain_matrix_type::type PlainObject; /** \brief The interface type of indices - * \details To change this, \c \#define the preprocessor symbol \c EIGEN_DEFAULT_DENSE_INDEX_TYPE. - * \sa StorageIndex, \ref TopicPreprocessorDirectives. - * DEPRECATED: Since Eigen 3.3, its usage is deprecated. Use Eigen::Index instead. - * Deprecation is not marked with a doxygen comment because there are too many existing usages to add the deprecation attribute. - */ + * \details To change this, \c \#define the preprocessor symbol \c EIGEN_DEFAULT_DENSE_INDEX_TYPE. + * \sa StorageIndex, \ref TopicPreprocessorDirectives. + * DEPRECATED: Since Eigen 3.3, its usage is deprecated. Use Eigen::Index instead. + * Deprecation is not marked with a doxygen comment because there are too many existing usages to add the deprecation + * attribute. + */ typedef Eigen::Index Index; // FIXME is it needed? typedef typename internal::traits::StorageKind StorageKind; /** \returns a reference to the derived object */ - EIGEN_DEVICE_FUNC - Derived& derived() { return *static_cast(this); } + EIGEN_DEVICE_FUNC Derived& derived() { return *static_cast(this); } /** \returns a const reference to the derived object */ - EIGEN_DEVICE_FUNC - const Derived& derived() const { return *static_cast(this); } + EIGEN_DEVICE_FUNC const Derived& derived() const { return *static_cast(this); } - EIGEN_DEVICE_FUNC - inline Derived& const_cast_derived() const - { return *static_cast(const_cast(this)); } - EIGEN_DEVICE_FUNC - inline const Derived& const_derived() const - { return *static_cast(this); } + EIGEN_DEVICE_FUNC inline Derived& const_cast_derived() const { + return *static_cast(const_cast(this)); + } + EIGEN_DEVICE_FUNC inline const Derived& const_derived() const { return *static_cast(this); } /** \returns the number of rows. \sa cols(), RowsAtCompileTime */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rows() const EIGEN_NOEXCEPT { return derived().rows(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { return derived().rows(); } /** \returns the number of columns. \sa rows(), ColsAtCompileTime*/ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index cols() const EIGEN_NOEXCEPT { return derived().cols(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return derived().cols(); } /** \returns the number of coefficients, which is rows()*cols(). - * \sa rows(), cols(), SizeAtCompileTime. */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index size() const EIGEN_NOEXCEPT { return rows() * cols(); } + * \sa rows(), cols(), SizeAtCompileTime. */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index size() const EIGEN_NOEXCEPT { return rows() * cols(); } /** \internal Don't use it, but do the equivalent: \code dst = *this; \endcode */ - template - EIGEN_DEVICE_FUNC - inline void evalTo(Dest& dst) const - { derived().evalTo(dst); } + template + EIGEN_DEVICE_FUNC inline void evalTo(Dest& dst) const { + derived().evalTo(dst); + } /** \internal Don't use it, but do the equivalent: \code dst += *this; \endcode */ - template - EIGEN_DEVICE_FUNC - inline void addTo(Dest& dst) const - { + template + EIGEN_DEVICE_FUNC inline void addTo(Dest& dst) const { // This is the default implementation, // derived class can reimplement it in a more optimized way. - typename Dest::PlainObject res(rows(),cols()); + typename Dest::PlainObject res(rows(), cols()); evalTo(res); dst += res; } /** \internal Don't use it, but do the equivalent: \code dst -= *this; \endcode */ - template - EIGEN_DEVICE_FUNC - inline void subTo(Dest& dst) const - { + template + EIGEN_DEVICE_FUNC inline void subTo(Dest& dst) const { // This is the default implementation, // derived class can reimplement it in a more optimized way. - typename Dest::PlainObject res(rows(),cols()); + typename Dest::PlainObject res(rows(), cols()); evalTo(res); dst -= res; } /** \internal Don't use it, but do the equivalent: \code dst.applyOnTheRight(*this); \endcode */ - template - EIGEN_DEVICE_FUNC inline void applyThisOnTheRight(Dest& dst) const - { + template + EIGEN_DEVICE_FUNC inline void applyThisOnTheRight(Dest& dst) const { // This is the default implementation, // derived class can reimplement it in a more optimized way. dst = dst * this->derived(); } /** \internal Don't use it, but do the equivalent: \code dst.applyOnTheLeft(*this); \endcode */ - template - EIGEN_DEVICE_FUNC inline void applyThisOnTheLeft(Dest& dst) const - { + template + EIGEN_DEVICE_FUNC inline void applyThisOnTheLeft(Dest& dst) const { // This is the default implementation, // derived class can reimplement it in a more optimized way. dst = this->derived() * dst; } - }; /*************************************************************************** -* Implementation of matrix base methods -***************************************************************************/ + * Implementation of matrix base methods + ***************************************************************************/ /** \brief Copies the generic expression \a other into *this. - * - * \details The expression must provide a (templated) evalTo(Derived& dst) const - * function which does the actual job. In practice, this allows any user to write - * its own special matrix without having to modify MatrixBase - * - * \returns a reference to *this. - */ -template -template -EIGEN_DEVICE_FUNC -Derived& DenseBase::operator=(const EigenBase &other) -{ + * + * \details The expression must provide a (templated) evalTo(Derived& dst) const + * function which does the actual job. In practice, this allows any user to write + * its own special matrix without having to modify MatrixBase + * + * \returns a reference to *this. + */ +template +template +EIGEN_DEVICE_FUNC Derived& DenseBase::operator=(const EigenBase& other) { call_assignment(derived(), other.derived()); return derived(); } -template -template -EIGEN_DEVICE_FUNC -Derived& DenseBase::operator+=(const EigenBase &other) -{ - call_assignment(derived(), other.derived(), internal::add_assign_op()); +template +template +EIGEN_DEVICE_FUNC Derived& DenseBase::operator+=(const EigenBase& other) { + call_assignment(derived(), other.derived(), internal::add_assign_op()); return derived(); } -template -template -EIGEN_DEVICE_FUNC -Derived& DenseBase::operator-=(const EigenBase &other) -{ - call_assignment(derived(), other.derived(), internal::sub_assign_op()); +template +template +EIGEN_DEVICE_FUNC Derived& DenseBase::operator-=(const EigenBase& other) { + call_assignment(derived(), other.derived(), internal::sub_assign_op()); return derived(); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_EIGENBASE_H +#endif // EIGEN_EIGENBASE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ForceAlignedAccess.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ForceAlignedAccess.h index 817a43afced..a91b0da6a35 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ForceAlignedAccess.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ForceAlignedAccess.h @@ -10,141 +10,122 @@ #ifndef EIGEN_FORCEALIGNEDACCESS_H #define EIGEN_FORCEALIGNEDACCESS_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { /** \class ForceAlignedAccess - * \ingroup Core_Module - * - * \brief Enforce aligned packet loads and stores regardless of what is requested - * - * \param ExpressionType the type of the object of which we are forcing aligned packet access - * - * This class is the return type of MatrixBase::forceAlignedAccess() - * and most of the time this is the only way it is used. - * - * \sa MatrixBase::forceAlignedAccess() - */ + * \ingroup Core_Module + * + * \brief Enforce aligned packet loads and stores regardless of what is requested + * + * \param ExpressionType the type of the object of which we are forcing aligned packet access + * + * This class is the return type of MatrixBase::forceAlignedAccess() + * and most of the time this is the only way it is used. + * + * \sa MatrixBase::forceAlignedAccess() + */ namespace internal { -template -struct traits > : public traits -{}; -} - -template class ForceAlignedAccess - : public internal::dense_xpr_base< ForceAlignedAccess >::type -{ - public: - - typedef typename internal::dense_xpr_base::type Base; - EIGEN_DENSE_PUBLIC_INTERFACE(ForceAlignedAccess) - - EIGEN_DEVICE_FUNC explicit inline ForceAlignedAccess(const ExpressionType& matrix) : m_expression(matrix) {} - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rows() const EIGEN_NOEXCEPT { return m_expression.rows(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index cols() const EIGEN_NOEXCEPT { return m_expression.cols(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outerStride() const EIGEN_NOEXCEPT { return m_expression.outerStride(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index innerStride() const EIGEN_NOEXCEPT { return m_expression.innerStride(); } - - EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index row, Index col) const - { - return m_expression.coeff(row, col); - } - - EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index row, Index col) - { - return m_expression.const_cast_derived().coeffRef(row, col); - } - - EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index index) const - { - return m_expression.coeff(index); - } - - EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index index) - { - return m_expression.const_cast_derived().coeffRef(index); - } - - template - inline const PacketScalar packet(Index row, Index col) const - { - return m_expression.template packet(row, col); - } - - template - inline void writePacket(Index row, Index col, const PacketScalar& x) - { - m_expression.const_cast_derived().template writePacket(row, col, x); - } - - template - inline const PacketScalar packet(Index index) const - { - return m_expression.template packet(index); - } - - template - inline void writePacket(Index index, const PacketScalar& x) - { - m_expression.const_cast_derived().template writePacket(index, x); - } - - EIGEN_DEVICE_FUNC operator const ExpressionType&() const { return m_expression; } - - protected: - const ExpressionType& m_expression; - - private: - ForceAlignedAccess& operator=(const ForceAlignedAccess&); +template +struct traits> : public traits {}; +} // namespace internal + +template +class ForceAlignedAccess : public internal::dense_xpr_base>::type { + public: + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(ForceAlignedAccess) + + EIGEN_DEVICE_FUNC explicit inline ForceAlignedAccess(const ExpressionType& matrix) : m_expression(matrix) {} + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { return m_expression.rows(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return m_expression.cols(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const EIGEN_NOEXCEPT { + return m_expression.outerStride(); + } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const EIGEN_NOEXCEPT { + return m_expression.innerStride(); + } + + EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index row, Index col) const { + return m_expression.coeff(row, col); + } + + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index row, Index col) { + return m_expression.const_cast_derived().coeffRef(row, col); + } + + EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index index) const { return m_expression.coeff(index); } + + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index index) { return m_expression.const_cast_derived().coeffRef(index); } + + template + inline const PacketScalar packet(Index row, Index col) const { + return m_expression.template packet(row, col); + } + + template + inline void writePacket(Index row, Index col, const PacketScalar& x) { + m_expression.const_cast_derived().template writePacket(row, col, x); + } + + template + inline const PacketScalar packet(Index index) const { + return m_expression.template packet(index); + } + + template + inline void writePacket(Index index, const PacketScalar& x) { + m_expression.const_cast_derived().template writePacket(index, x); + } + + EIGEN_DEVICE_FUNC operator const ExpressionType&() const { return m_expression; } + + protected: + const ExpressionType& m_expression; + + private: + ForceAlignedAccess& operator=(const ForceAlignedAccess&); }; /** \returns an expression of *this with forced aligned access - * \sa forceAlignedAccessIf(),class ForceAlignedAccess - */ -template -inline const ForceAlignedAccess -MatrixBase::forceAlignedAccess() const -{ + * \sa forceAlignedAccessIf(),class ForceAlignedAccess + */ +template +inline const ForceAlignedAccess MatrixBase::forceAlignedAccess() const { return ForceAlignedAccess(derived()); } /** \returns an expression of *this with forced aligned access - * \sa forceAlignedAccessIf(), class ForceAlignedAccess - */ -template -inline ForceAlignedAccess -MatrixBase::forceAlignedAccess() -{ + * \sa forceAlignedAccessIf(), class ForceAlignedAccess + */ +template +inline ForceAlignedAccess MatrixBase::forceAlignedAccess() { return ForceAlignedAccess(derived()); } /** \returns an expression of *this with forced aligned access if \a Enable is true. - * \sa forceAlignedAccess(), class ForceAlignedAccess - */ -template -template -inline typename internal::add_const_on_value_type,Derived&>::type>::type -MatrixBase::forceAlignedAccessIf() const -{ + * \sa forceAlignedAccess(), class ForceAlignedAccess + */ +template +template +inline add_const_on_value_type_t, Derived&>> +MatrixBase::forceAlignedAccessIf() const { return derived(); // FIXME This should not work but apparently is never used } /** \returns an expression of *this with forced aligned access if \a Enable is true. - * \sa forceAlignedAccess(), class ForceAlignedAccess - */ -template -template -inline typename internal::conditional,Derived&>::type -MatrixBase::forceAlignedAccessIf() -{ + * \sa forceAlignedAccess(), class ForceAlignedAccess + */ +template +template +inline std::conditional_t, Derived&> MatrixBase::forceAlignedAccessIf() { return derived(); // FIXME This should not work but apparently is never used } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_FORCEALIGNEDACCESS_H +#endif // EIGEN_FORCEALIGNEDACCESS_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Fuzzy.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Fuzzy.h index 43aa49b2bc2..ed6b4ffead7 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Fuzzy.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Fuzzy.h @@ -11,145 +11,122 @@ #ifndef EIGEN_FUZZY_H #define EIGEN_FUZZY_H -namespace Eigen { - -namespace internal -{ - -template::IsInteger> -struct isApprox_selector -{ - EIGEN_DEVICE_FUNC - static bool run(const Derived& x, const OtherDerived& y, const typename Derived::RealScalar& prec) - { - typename internal::nested_eval::type nested(x); - typename internal::nested_eval::type otherNested(y); - return (nested - otherNested).cwiseAbs2().sum() <= prec * prec * numext::mini(nested.cwiseAbs2().sum(), otherNested.cwiseAbs2().sum()); +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template ::IsInteger> +struct isApprox_selector { + EIGEN_DEVICE_FUNC static bool run(const Derived& x, const OtherDerived& y, const typename Derived::RealScalar& prec) { + typename internal::nested_eval::type nested(x); + typename internal::nested_eval::type otherNested(y); + return (nested.matrix() - otherNested.matrix()).cwiseAbs2().sum() <= + prec * prec * numext::mini(nested.cwiseAbs2().sum(), otherNested.cwiseAbs2().sum()); } }; -template -struct isApprox_selector -{ - EIGEN_DEVICE_FUNC - static bool run(const Derived& x, const OtherDerived& y, const typename Derived::RealScalar&) - { +template +struct isApprox_selector { + EIGEN_DEVICE_FUNC static bool run(const Derived& x, const OtherDerived& y, const typename Derived::RealScalar&) { return x.matrix() == y.matrix(); } }; -template::IsInteger> -struct isMuchSmallerThan_object_selector -{ - EIGEN_DEVICE_FUNC - static bool run(const Derived& x, const OtherDerived& y, const typename Derived::RealScalar& prec) - { +template ::IsInteger> +struct isMuchSmallerThan_object_selector { + EIGEN_DEVICE_FUNC static bool run(const Derived& x, const OtherDerived& y, const typename Derived::RealScalar& prec) { return x.cwiseAbs2().sum() <= numext::abs2(prec) * y.cwiseAbs2().sum(); } }; -template -struct isMuchSmallerThan_object_selector -{ - EIGEN_DEVICE_FUNC - static bool run(const Derived& x, const OtherDerived&, const typename Derived::RealScalar&) - { +template +struct isMuchSmallerThan_object_selector { + EIGEN_DEVICE_FUNC static bool run(const Derived& x, const OtherDerived&, const typename Derived::RealScalar&) { return x.matrix() == Derived::Zero(x.rows(), x.cols()).matrix(); } }; -template::IsInteger> -struct isMuchSmallerThan_scalar_selector -{ - EIGEN_DEVICE_FUNC - static bool run(const Derived& x, const typename Derived::RealScalar& y, const typename Derived::RealScalar& prec) - { +template ::IsInteger> +struct isMuchSmallerThan_scalar_selector { + EIGEN_DEVICE_FUNC static bool run(const Derived& x, const typename Derived::RealScalar& y, + const typename Derived::RealScalar& prec) { return x.cwiseAbs2().sum() <= numext::abs2(prec * y); } }; -template -struct isMuchSmallerThan_scalar_selector -{ - EIGEN_DEVICE_FUNC - static bool run(const Derived& x, const typename Derived::RealScalar&, const typename Derived::RealScalar&) - { +template +struct isMuchSmallerThan_scalar_selector { + EIGEN_DEVICE_FUNC static bool run(const Derived& x, const typename Derived::RealScalar&, + const typename Derived::RealScalar&) { return x.matrix() == Derived::Zero(x.rows(), x.cols()).matrix(); } }; -} // end namespace internal - +} // end namespace internal /** \returns \c true if \c *this is approximately equal to \a other, within the precision - * determined by \a prec. - * - * \note The fuzzy compares are done multiplicatively. Two vectors \f$ v \f$ and \f$ w \f$ - * are considered to be approximately equal within precision \f$ p \f$ if - * \f[ \Vert v - w \Vert \leqslant p\,\min(\Vert v\Vert, \Vert w\Vert). \f] - * For matrices, the comparison is done using the Hilbert-Schmidt norm (aka Frobenius norm - * L2 norm). - * - * \note Because of the multiplicativeness of this comparison, one can't use this function - * to check whether \c *this is approximately equal to the zero matrix or vector. - * Indeed, \c isApprox(zero) returns false unless \c *this itself is exactly the zero matrix - * or vector. If you want to test whether \c *this is zero, use internal::isMuchSmallerThan(const - * RealScalar&, RealScalar) instead. - * - * \sa internal::isMuchSmallerThan(const RealScalar&, RealScalar) const - */ -template -template -EIGEN_DEVICE_FUNC bool DenseBase::isApprox( - const DenseBase& other, - const RealScalar& prec -) const -{ + * determined by \a prec. + * + * \note The fuzzy compares are done multiplicatively. Two vectors \f$ v \f$ and \f$ w \f$ + * are considered to be approximately equal within precision \f$ p \f$ if + * \f[ \Vert v - w \Vert \leqslant p\,\min(\Vert v\Vert, \Vert w\Vert). \f] + * For matrices, the comparison is done using the Hilbert-Schmidt norm (aka Frobenius norm + * L2 norm). + * + * \note Because of the multiplicativeness of this comparison, one can't use this function + * to check whether \c *this is approximately equal to the zero matrix or vector. + * Indeed, \c isApprox(zero) returns false unless \c *this itself is exactly the zero matrix + * or vector. If you want to test whether \c *this is zero, use internal::isMuchSmallerThan(const + * RealScalar&, RealScalar) instead. + * + * \sa internal::isMuchSmallerThan(const RealScalar&, RealScalar) const + */ +template +template +EIGEN_DEVICE_FUNC bool DenseBase::isApprox(const DenseBase& other, + const RealScalar& prec) const { return internal::isApprox_selector::run(derived(), other.derived(), prec); } /** \returns \c true if the norm of \c *this is much smaller than \a other, - * within the precision determined by \a prec. - * - * \note The fuzzy compares are done multiplicatively. A vector \f$ v \f$ is - * considered to be much smaller than \f$ x \f$ within precision \f$ p \f$ if - * \f[ \Vert v \Vert \leqslant p\,\vert x\vert. \f] - * - * For matrices, the comparison is done using the Hilbert-Schmidt norm. For this reason, - * the value of the reference scalar \a other should come from the Hilbert-Schmidt norm - * of a reference matrix of same dimensions. - * - * \sa isApprox(), isMuchSmallerThan(const DenseBase&, RealScalar) const - */ -template -EIGEN_DEVICE_FUNC bool DenseBase::isMuchSmallerThan( - const typename NumTraits::Real& other, - const RealScalar& prec -) const -{ + * within the precision determined by \a prec. + * + * \note The fuzzy compares are done multiplicatively. A vector \f$ v \f$ is + * considered to be much smaller than \f$ x \f$ within precision \f$ p \f$ if + * \f[ \Vert v \Vert \leqslant p\,\vert x\vert. \f] + * + * For matrices, the comparison is done using the Hilbert-Schmidt norm. For this reason, + * the value of the reference scalar \a other should come from the Hilbert-Schmidt norm + * of a reference matrix of same dimensions. + * + * \sa isApprox(), isMuchSmallerThan(const DenseBase&, RealScalar) const + */ +template +EIGEN_DEVICE_FUNC bool DenseBase::isMuchSmallerThan(const typename NumTraits::Real& other, + const RealScalar& prec) const { return internal::isMuchSmallerThan_scalar_selector::run(derived(), other, prec); } /** \returns \c true if the norm of \c *this is much smaller than the norm of \a other, - * within the precision determined by \a prec. - * - * \note The fuzzy compares are done multiplicatively. A vector \f$ v \f$ is - * considered to be much smaller than a vector \f$ w \f$ within precision \f$ p \f$ if - * \f[ \Vert v \Vert \leqslant p\,\Vert w\Vert. \f] - * For matrices, the comparison is done using the Hilbert-Schmidt norm. - * - * \sa isApprox(), isMuchSmallerThan(const RealScalar&, RealScalar) const - */ -template -template -EIGEN_DEVICE_FUNC bool DenseBase::isMuchSmallerThan( - const DenseBase& other, - const RealScalar& prec -) const -{ + * within the precision determined by \a prec. + * + * \note The fuzzy compares are done multiplicatively. A vector \f$ v \f$ is + * considered to be much smaller than a vector \f$ w \f$ within precision \f$ p \f$ if + * \f[ \Vert v \Vert \leqslant p\,\Vert w\Vert. \f] + * For matrices, the comparison is done using the Hilbert-Schmidt norm. + * + * \sa isApprox(), isMuchSmallerThan(const RealScalar&, RealScalar) const + */ +template +template +EIGEN_DEVICE_FUNC bool DenseBase::isMuchSmallerThan(const DenseBase& other, + const RealScalar& prec) const { return internal::isMuchSmallerThan_object_selector::run(derived(), other.derived(), prec); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_FUZZY_H +#endif // EIGEN_FUZZY_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/GeneralProduct.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/GeneralProduct.h index 6906aa75d10..1220073a8c1 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/GeneralProduct.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/GeneralProduct.h @@ -11,12 +11,12 @@ #ifndef EIGEN_GENERAL_PRODUCT_H #define EIGEN_GENERAL_PRODUCT_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { -enum { - Large = 2, - Small = 3 -}; +enum { Large = 2, Small = 3 }; // Define the threshold value to fallback from the generic matrix-matrix product // implementation (heavy) to the lightweight coeff-based product one. @@ -30,64 +30,58 @@ enum { namespace internal { -template struct product_type_selector; +template +struct product_type_selector; -template struct product_size_category -{ +template +struct product_size_category { enum { - #ifndef EIGEN_GPU_COMPILE_PHASE - is_large = MaxSize == Dynamic || - Size >= EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD || - (Size==Dynamic && MaxSize>=EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD), - #else +#ifndef EIGEN_GPU_COMPILE_PHASE + is_large = MaxSize == Dynamic || Size >= EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD || + (Size == Dynamic && MaxSize >= EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD), +#else is_large = 0, - #endif - value = is_large ? Large - : Size == 1 ? 1 - : Small +#endif + value = is_large ? Large + : Size == 1 ? 1 + : Small }; }; -template struct product_type -{ - typedef typename remove_all::type _Lhs; - typedef typename remove_all::type _Rhs; +template +struct product_type { + typedef remove_all_t Lhs_; + typedef remove_all_t Rhs_; enum { - MaxRows = traits<_Lhs>::MaxRowsAtCompileTime, - Rows = traits<_Lhs>::RowsAtCompileTime, - MaxCols = traits<_Rhs>::MaxColsAtCompileTime, - Cols = traits<_Rhs>::ColsAtCompileTime, - MaxDepth = EIGEN_SIZE_MIN_PREFER_FIXED(traits<_Lhs>::MaxColsAtCompileTime, - traits<_Rhs>::MaxRowsAtCompileTime), - Depth = EIGEN_SIZE_MIN_PREFER_FIXED(traits<_Lhs>::ColsAtCompileTime, - traits<_Rhs>::RowsAtCompileTime) + MaxRows = traits::MaxRowsAtCompileTime, + Rows = traits::RowsAtCompileTime, + MaxCols = traits::MaxColsAtCompileTime, + Cols = traits::ColsAtCompileTime, + MaxDepth = min_size_prefer_fixed(traits::MaxColsAtCompileTime, traits::MaxRowsAtCompileTime), + Depth = min_size_prefer_fixed(traits::ColsAtCompileTime, traits::RowsAtCompileTime) }; // the splitting into different lines of code here, introducing the _select enums and the typedef below, // is to work around an internal compiler error with gcc 4.1 and 4.2. -private: + private: enum { - rows_select = product_size_category::value, - cols_select = product_size_category::value, - depth_select = product_size_category::value + rows_select = product_size_category::value, + cols_select = product_size_category::value, + depth_select = product_size_category::value }; typedef product_type_selector selector; -public: - enum { - value = selector::ret, - ret = selector::ret - }; + public: + enum { value = selector::ret, ret = selector::ret }; #ifdef EIGEN_DEBUG_PRODUCT - static void debug() - { - EIGEN_DEBUG_VAR(Rows); - EIGEN_DEBUG_VAR(Cols); - EIGEN_DEBUG_VAR(Depth); - EIGEN_DEBUG_VAR(rows_select); - EIGEN_DEBUG_VAR(cols_select); - EIGEN_DEBUG_VAR(depth_select); - EIGEN_DEBUG_VAR(value); + static void debug() { + EIGEN_DEBUG_VAR(Rows); + EIGEN_DEBUG_VAR(Cols); + EIGEN_DEBUG_VAR(Depth); + EIGEN_DEBUG_VAR(rows_select); + EIGEN_DEBUG_VAR(cols_select); + EIGEN_DEBUG_VAR(depth_select); + EIGEN_DEBUG_VAR(value); } #endif }; @@ -96,36 +90,108 @@ template struct product_type * based on the three dimensions of the product. * This is a compile time mapping from {1,Small,Large}^3 -> {product types} */ // FIXME I'm not sure the current mapping is the ideal one. -template struct product_type_selector { enum { ret = OuterProduct }; }; -template struct product_type_selector { enum { ret = LazyCoeffBasedProductMode }; }; -template struct product_type_selector<1, N, 1> { enum { ret = LazyCoeffBasedProductMode }; }; -template struct product_type_selector<1, 1, Depth> { enum { ret = InnerProduct }; }; -template<> struct product_type_selector<1, 1, 1> { enum { ret = InnerProduct }; }; -template<> struct product_type_selector { enum { ret = CoeffBasedProductMode }; }; -template<> struct product_type_selector<1, Small,Small> { enum { ret = CoeffBasedProductMode }; }; -template<> struct product_type_selector { enum { ret = CoeffBasedProductMode }; }; -template<> struct product_type_selector { enum { ret = LazyCoeffBasedProductMode }; }; -template<> struct product_type_selector { enum { ret = LazyCoeffBasedProductMode }; }; -template<> struct product_type_selector { enum { ret = LazyCoeffBasedProductMode }; }; -template<> struct product_type_selector<1, Large,Small> { enum { ret = CoeffBasedProductMode }; }; -template<> struct product_type_selector<1, Large,Large> { enum { ret = GemvProduct }; }; -template<> struct product_type_selector<1, Small,Large> { enum { ret = CoeffBasedProductMode }; }; -template<> struct product_type_selector { enum { ret = CoeffBasedProductMode }; }; -template<> struct product_type_selector { enum { ret = GemvProduct }; }; -template<> struct product_type_selector { enum { ret = CoeffBasedProductMode }; }; -template<> struct product_type_selector { enum { ret = GemmProduct }; }; -template<> struct product_type_selector { enum { ret = GemmProduct }; }; -template<> struct product_type_selector { enum { ret = GemmProduct }; }; -template<> struct product_type_selector { enum { ret = GemmProduct }; }; -template<> struct product_type_selector { enum { ret = CoeffBasedProductMode }; }; -template<> struct product_type_selector { enum { ret = CoeffBasedProductMode }; }; -template<> struct product_type_selector { enum { ret = GemmProduct }; }; - -} // end namespace internal +template +struct product_type_selector { + enum { ret = OuterProduct }; +}; +template +struct product_type_selector { + enum { ret = LazyCoeffBasedProductMode }; +}; +template +struct product_type_selector<1, N, 1> { + enum { ret = LazyCoeffBasedProductMode }; +}; +template +struct product_type_selector<1, 1, Depth> { + enum { ret = InnerProduct }; +}; +template <> +struct product_type_selector<1, 1, 1> { + enum { ret = InnerProduct }; +}; +template <> +struct product_type_selector { + enum { ret = CoeffBasedProductMode }; +}; +template <> +struct product_type_selector<1, Small, Small> { + enum { ret = CoeffBasedProductMode }; +}; +template <> +struct product_type_selector { + enum { ret = CoeffBasedProductMode }; +}; +template <> +struct product_type_selector { + enum { ret = LazyCoeffBasedProductMode }; +}; +template <> +struct product_type_selector { + enum { ret = LazyCoeffBasedProductMode }; +}; +template <> +struct product_type_selector { + enum { ret = LazyCoeffBasedProductMode }; +}; +template <> +struct product_type_selector<1, Large, Small> { + enum { ret = CoeffBasedProductMode }; +}; +template <> +struct product_type_selector<1, Large, Large> { + enum { ret = GemvProduct }; +}; +template <> +struct product_type_selector<1, Small, Large> { + enum { ret = CoeffBasedProductMode }; +}; +template <> +struct product_type_selector { + enum { ret = CoeffBasedProductMode }; +}; +template <> +struct product_type_selector { + enum { ret = GemvProduct }; +}; +template <> +struct product_type_selector { + enum { ret = CoeffBasedProductMode }; +}; +template <> +struct product_type_selector { + enum { ret = GemmProduct }; +}; +template <> +struct product_type_selector { + enum { ret = GemmProduct }; +}; +template <> +struct product_type_selector { + enum { ret = GemmProduct }; +}; +template <> +struct product_type_selector { + enum { ret = GemmProduct }; +}; +template <> +struct product_type_selector { + enum { ret = CoeffBasedProductMode }; +}; +template <> +struct product_type_selector { + enum { ret = CoeffBasedProductMode }; +}; +template <> +struct product_type_selector { + enum { ret = GemmProduct }; +}; + +} // end namespace internal /*********************************************************************** -* Implementation of Inner Vector Vector Product -***********************************************************************/ + * Implementation of Inner Vector Vector Product + ***********************************************************************/ // FIXME : maybe the "inner product" could return a Scalar // instead of a 1x1 matrix ?? @@ -135,12 +201,12 @@ template<> struct product_type_selector { enum // case, we could have a specialization for Block with: operator=(Scalar x); /*********************************************************************** -* Implementation of Outer Vector Vector Product -***********************************************************************/ + * Implementation of Outer Vector Vector Product + ***********************************************************************/ /*********************************************************************** -* Implementation of General Matrix Vector Product -***********************************************************************/ + * Implementation of General Matrix Vector Product + ***********************************************************************/ /* According to the shape/flags of the matrix we have to distinghish 3 different cases: * 1 - the matrix is col-major, BLAS compatible and M is large => call fast BLAS-like colmajor routine @@ -151,79 +217,74 @@ template<> struct product_type_selector { enum */ namespace internal { -template +template struct gemv_dense_selector; -} // end namespace internal +} // end namespace internal namespace internal { -template struct gemv_static_vector_if; +template +struct gemv_static_vector_if; -template -struct gemv_static_vector_if -{ - EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Scalar* data() { eigen_internal_assert(false && "should never be called"); return 0; } +template +struct gemv_static_vector_if { + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Scalar* data() { + eigen_internal_assert(false && "should never be called"); + return 0; + } }; -template -struct gemv_static_vector_if -{ +template +struct gemv_static_vector_if { EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Scalar* data() { return 0; } }; -template -struct gemv_static_vector_if -{ - enum { - ForceAlignment = internal::packet_traits::Vectorizable, - PacketSize = internal::packet_traits::size - }; - #if EIGEN_MAX_STATIC_ALIGN_BYTES!=0 - internal::plain_array m_data; +template +struct gemv_static_vector_if { +#if EIGEN_MAX_STATIC_ALIGN_BYTES != 0 + internal::plain_array + m_data; EIGEN_STRONG_INLINE Scalar* data() { return m_data.array; } - #else +#else // Some architectures cannot align on the stack, // => let's manually enforce alignment by allocating more data and return the address of the first aligned element. - internal::plain_array m_data; + internal::plain_array< + Scalar, internal::min_size_prefer_fixed(Size, MaxSize) + EIGEN_MAX_ALIGN_BYTES, 0> + m_data; EIGEN_STRONG_INLINE Scalar* data() { - return ForceAlignment - ? reinterpret_cast((internal::UIntPtr(m_data.array) & ~(std::size_t(EIGEN_MAX_ALIGN_BYTES-1))) + EIGEN_MAX_ALIGN_BYTES) - : m_data.array; + return reinterpret_cast((std::uintptr_t(m_data.array) & ~(std::size_t(EIGEN_MAX_ALIGN_BYTES - 1))) + EIGEN_MAX_ALIGN_BYTES); } - #endif +#endif }; // The vector is on the left => transposition -template -struct gemv_dense_selector -{ - template - static void run(const Lhs &lhs, const Rhs &rhs, Dest& dest, const typename Dest::Scalar& alpha) - { +template +struct gemv_dense_selector { + template + static void run(const Lhs& lhs, const Rhs& rhs, Dest& dest, const typename Dest::Scalar& alpha) { Transpose destT(dest); enum { OtherStorageOrder = StorageOrder == RowMajor ? ColMajor : RowMajor }; - gemv_dense_selector - ::run(rhs.transpose(), lhs.transpose(), destT, alpha); + gemv_dense_selector::run(rhs.transpose(), lhs.transpose(), destT, + alpha); } }; -template<> struct gemv_dense_selector -{ - template - static inline void run(const Lhs &lhs, const Rhs &rhs, Dest& dest, const typename Dest::Scalar& alpha) - { - typedef typename Lhs::Scalar LhsScalar; - typedef typename Rhs::Scalar RhsScalar; - typedef typename Dest::Scalar ResScalar; - typedef typename Dest::RealScalar RealScalar; - +template <> +struct gemv_dense_selector { + template + static inline void run(const Lhs& lhs, const Rhs& rhs, Dest& dest, const typename Dest::Scalar& alpha) { + typedef typename Lhs::Scalar LhsScalar; + typedef typename Rhs::Scalar RhsScalar; + typedef typename Dest::Scalar ResScalar; + typedef internal::blas_traits LhsBlasTraits; typedef typename LhsBlasTraits::DirectLinearAccessType ActualLhsType; typedef internal::blas_traits RhsBlasTraits; typedef typename RhsBlasTraits::DirectLinearAccessType ActualRhsType; - - typedef Map, EIGEN_PLAIN_ENUM_MIN(AlignedMax,internal::packet_traits::size)> MappedDest; + + typedef Map, plain_enum_min(AlignedMax, internal::packet_traits::size)> + MappedDest; ActualLhsType actualLhs = LhsBlasTraits::extract(lhs); ActualRhsType actualRhs = RhsBlasTraits::extract(rhs); @@ -231,68 +292,63 @@ template<> struct gemv_dense_selector ResScalar actualAlpha = combine_scalar_factors(alpha, lhs, rhs); // make sure Dest is a compile-time vector type (bug 1166) - typedef typename conditional::type ActualDest; + typedef std::conditional_t ActualDest; enum { // FIXME find a way to allow an inner stride on the result if packet_traits::size==1 // on, the other hand it is good for the cache to pack the vector anyways... - EvalToDestAtCompileTime = (ActualDest::InnerStrideAtCompileTime==1), + EvalToDestAtCompileTime = (ActualDest::InnerStrideAtCompileTime == 1), ComplexByReal = (NumTraits::IsComplex) && (!NumTraits::IsComplex), - MightCannotUseDest = ((!EvalToDestAtCompileTime) || ComplexByReal) && (ActualDest::MaxSizeAtCompileTime!=0) + MightCannotUseDest = ((!EvalToDestAtCompileTime) || ComplexByReal) && (ActualDest::MaxSizeAtCompileTime != 0) }; - typedef const_blas_data_mapper LhsMapper; - typedef const_blas_data_mapper RhsMapper; - RhsScalar compatibleAlpha = get_factor::run(actualAlpha); + typedef const_blas_data_mapper LhsMapper; + typedef const_blas_data_mapper RhsMapper; + RhsScalar compatibleAlpha = get_factor::run(actualAlpha); - if(!MightCannotUseDest) - { + if (!MightCannotUseDest) { // shortcut if we are sure to be able to use dest directly, // this ease the compiler to generate cleaner and more optimzized code for most common cases - general_matrix_vector_product - ::run( - actualLhs.rows(), actualLhs.cols(), - LhsMapper(actualLhs.data(), actualLhs.outerStride()), - RhsMapper(actualRhs.data(), actualRhs.innerStride()), - dest.data(), 1, - compatibleAlpha); - } - else - { - gemv_static_vector_if static_dest; - - const bool alphaIsCompatible = (!ComplexByReal) || (numext::imag(actualAlpha)==RealScalar(0)); + general_matrix_vector_product::run(actualLhs.rows(), actualLhs.cols(), + LhsMapper(actualLhs.data(), + actualLhs.outerStride()), + RhsMapper(actualRhs.data(), + actualRhs.innerStride()), + dest.data(), 1, compatibleAlpha); + } else { + gemv_static_vector_if + static_dest; + + const bool alphaIsCompatible = (!ComplexByReal) || (numext::is_exactly_zero(numext::imag(actualAlpha))); const bool evalToDest = EvalToDestAtCompileTime && alphaIsCompatible; - ei_declare_aligned_stack_constructed_variable(ResScalar,actualDestPtr,dest.size(), + ei_declare_aligned_stack_constructed_variable(ResScalar, actualDestPtr, dest.size(), evalToDest ? dest.data() : static_dest.data()); - if(!evalToDest) - { - #ifdef EIGEN_DENSE_STORAGE_CTOR_PLUGIN + if (!evalToDest) { +#ifdef EIGEN_DENSE_STORAGE_CTOR_PLUGIN Index size = dest.size(); EIGEN_DENSE_STORAGE_CTOR_PLUGIN - #endif - if(!alphaIsCompatible) - { +#endif + if (!alphaIsCompatible) { MappedDest(actualDestPtr, dest.size()).setZero(); compatibleAlpha = RhsScalar(1); - } - else + } else MappedDest(actualDestPtr, dest.size()) = dest; } - general_matrix_vector_product - ::run( - actualLhs.rows(), actualLhs.cols(), - LhsMapper(actualLhs.data(), actualLhs.outerStride()), - RhsMapper(actualRhs.data(), actualRhs.innerStride()), - actualDestPtr, 1, - compatibleAlpha); - - if (!evalToDest) - { - if(!alphaIsCompatible) + general_matrix_vector_product::run(actualLhs.rows(), actualLhs.cols(), + LhsMapper(actualLhs.data(), + actualLhs.outerStride()), + RhsMapper(actualRhs.data(), + actualRhs.innerStride()), + actualDestPtr, 1, compatibleAlpha); + + if (!evalToDest) { + if (!alphaIsCompatible) dest.matrix() += actualAlpha * MappedDest(actualDestPtr, dest.size()); else dest = MappedDest(actualDestPtr, dest.size()); @@ -301,165 +357,163 @@ template<> struct gemv_dense_selector } }; -template<> struct gemv_dense_selector -{ - template - static void run(const Lhs &lhs, const Rhs &rhs, Dest& dest, const typename Dest::Scalar& alpha) - { - typedef typename Lhs::Scalar LhsScalar; - typedef typename Rhs::Scalar RhsScalar; - typedef typename Dest::Scalar ResScalar; - +template <> +struct gemv_dense_selector { + template + static void run(const Lhs& lhs, const Rhs& rhs, Dest& dest, const typename Dest::Scalar& alpha) { + typedef typename Lhs::Scalar LhsScalar; + typedef typename Rhs::Scalar RhsScalar; + typedef typename Dest::Scalar ResScalar; + typedef internal::blas_traits LhsBlasTraits; typedef typename LhsBlasTraits::DirectLinearAccessType ActualLhsType; typedef internal::blas_traits RhsBlasTraits; typedef typename RhsBlasTraits::DirectLinearAccessType ActualRhsType; - typedef typename internal::remove_all::type ActualRhsTypeCleaned; + typedef internal::remove_all_t ActualRhsTypeCleaned; - typename add_const::type actualLhs = LhsBlasTraits::extract(lhs); - typename add_const::type actualRhs = RhsBlasTraits::extract(rhs); + std::add_const_t actualLhs = LhsBlasTraits::extract(lhs); + std::add_const_t actualRhs = RhsBlasTraits::extract(rhs); ResScalar actualAlpha = combine_scalar_factors(alpha, lhs, rhs); enum { // FIXME find a way to allow an inner stride on the result if packet_traits::size==1 // on, the other hand it is good for the cache to pack the vector anyways... - DirectlyUseRhs = ActualRhsTypeCleaned::InnerStrideAtCompileTime==1 || ActualRhsTypeCleaned::MaxSizeAtCompileTime==0 + DirectlyUseRhs = + ActualRhsTypeCleaned::InnerStrideAtCompileTime == 1 || ActualRhsTypeCleaned::MaxSizeAtCompileTime == 0 }; - gemv_static_vector_if static_rhs; + gemv_static_vector_if + static_rhs; - ei_declare_aligned_stack_constructed_variable(RhsScalar,actualRhsPtr,actualRhs.size(), + ei_declare_aligned_stack_constructed_variable( + RhsScalar, actualRhsPtr, actualRhs.size(), DirectlyUseRhs ? const_cast(actualRhs.data()) : static_rhs.data()); - if(!DirectlyUseRhs) - { - #ifdef EIGEN_DENSE_STORAGE_CTOR_PLUGIN + if (!DirectlyUseRhs) { +#ifdef EIGEN_DENSE_STORAGE_CTOR_PLUGIN Index size = actualRhs.size(); EIGEN_DENSE_STORAGE_CTOR_PLUGIN - #endif +#endif Map(actualRhsPtr, actualRhs.size()) = actualRhs; } - typedef const_blas_data_mapper LhsMapper; - typedef const_blas_data_mapper RhsMapper; - general_matrix_vector_product - ::run( - actualLhs.rows(), actualLhs.cols(), - LhsMapper(actualLhs.data(), actualLhs.outerStride()), - RhsMapper(actualRhsPtr, 1), - dest.data(), dest.col(0).innerStride(), //NOTE if dest is not a vector at compile-time, then dest.innerStride() might be wrong. (bug 1166) - actualAlpha); + typedef const_blas_data_mapper LhsMapper; + typedef const_blas_data_mapper RhsMapper; + general_matrix_vector_product:: + run(actualLhs.rows(), actualLhs.cols(), LhsMapper(actualLhs.data(), actualLhs.outerStride()), + RhsMapper(actualRhsPtr, 1), dest.data(), + dest.col(0).innerStride(), // NOTE if dest is not a vector at compile-time, then dest.innerStride() might + // be wrong. (bug 1166) + actualAlpha); } }; -template<> struct gemv_dense_selector -{ - template - static void run(const Lhs &lhs, const Rhs &rhs, Dest& dest, const typename Dest::Scalar& alpha) - { - EIGEN_STATIC_ASSERT((!nested_eval::Evaluate),EIGEN_INTERNAL_COMPILATION_ERROR_OR_YOU_MADE_A_PROGRAMMING_MISTAKE); - // TODO if rhs is large enough it might be beneficial to make sure that dest is sequentially stored in memory, otherwise use a temp - typename nested_eval::type actual_rhs(rhs); +template <> +struct gemv_dense_selector { + template + static void run(const Lhs& lhs, const Rhs& rhs, Dest& dest, const typename Dest::Scalar& alpha) { + EIGEN_STATIC_ASSERT((!nested_eval::Evaluate), + EIGEN_INTERNAL_COMPILATION_ERROR_OR_YOU_MADE_A_PROGRAMMING_MISTAKE); + // TODO if rhs is large enough it might be beneficial to make sure that dest is sequentially stored in memory, + // otherwise use a temp + typename nested_eval::type actual_rhs(rhs); const Index size = rhs.rows(); - for(Index k=0; k struct gemv_dense_selector -{ - template - static void run(const Lhs &lhs, const Rhs &rhs, Dest& dest, const typename Dest::Scalar& alpha) - { - EIGEN_STATIC_ASSERT((!nested_eval::Evaluate),EIGEN_INTERNAL_COMPILATION_ERROR_OR_YOU_MADE_A_PROGRAMMING_MISTAKE); - typename nested_eval::type actual_rhs(rhs); +template <> +struct gemv_dense_selector { + template + static void run(const Lhs& lhs, const Rhs& rhs, Dest& dest, const typename Dest::Scalar& alpha) { + EIGEN_STATIC_ASSERT((!nested_eval::Evaluate), + EIGEN_INTERNAL_COMPILATION_ERROR_OR_YOU_MADE_A_PROGRAMMING_MISTAKE); + typename nested_eval::type actual_rhs(rhs); const Index rows = dest.rows(); - for(Index i=0; i -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -const Product -MatrixBase::operator*(const MatrixBase &other) const -{ + * + * \note If instead of the matrix product you want the coefficient-wise product, see Cwise::operator*(). + * + * \sa lazyProduct(), operator*=(const MatrixBase&), Cwise::operator*() + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Product MatrixBase::operator*( + const MatrixBase& other) const { // A note regarding the function declaration: In MSVC, this function will sometimes // not be inlined since DenseStorage is an unwindable object for dynamic // matrices and product types are holding a member to store the result. // Thus it does not help tagging this function with EIGEN_STRONG_INLINE. enum { - ProductIsValid = Derived::ColsAtCompileTime==Dynamic - || OtherDerived::RowsAtCompileTime==Dynamic - || int(Derived::ColsAtCompileTime)==int(OtherDerived::RowsAtCompileTime), + ProductIsValid = Derived::ColsAtCompileTime == Dynamic || OtherDerived::RowsAtCompileTime == Dynamic || + int(Derived::ColsAtCompileTime) == int(OtherDerived::RowsAtCompileTime), AreVectors = Derived::IsVectorAtCompileTime && OtherDerived::IsVectorAtCompileTime, - SameSizes = EIGEN_PREDICATE_SAME_MATRIX_SIZE(Derived,OtherDerived) + SameSizes = EIGEN_PREDICATE_SAME_MATRIX_SIZE(Derived, OtherDerived) }; // note to the lost user: // * for a dot product use: v1.dot(v2) // * for a coeff-wise product use: v1.cwiseProduct(v2) - EIGEN_STATIC_ASSERT(ProductIsValid || !(AreVectors && SameSizes), - INVALID_VECTOR_VECTOR_PRODUCT__IF_YOU_WANTED_A_DOT_OR_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTIONS) + EIGEN_STATIC_ASSERT( + ProductIsValid || !(AreVectors && SameSizes), + INVALID_VECTOR_VECTOR_PRODUCT__IF_YOU_WANTED_A_DOT_OR_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTIONS) EIGEN_STATIC_ASSERT(ProductIsValid || !(SameSizes && !AreVectors), - INVALID_MATRIX_PRODUCT__IF_YOU_WANTED_A_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTION) + INVALID_MATRIX_PRODUCT__IF_YOU_WANTED_A_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTION) EIGEN_STATIC_ASSERT(ProductIsValid || SameSizes, INVALID_MATRIX_PRODUCT) #ifdef EIGEN_DEBUG_PRODUCT - internal::product_type::debug(); + internal::product_type::debug(); #endif return Product(derived(), other.derived()); } /** \returns an expression of the matrix product of \c *this and \a other without implicit evaluation. - * - * The returned product will behave like any other expressions: the coefficients of the product will be - * computed once at a time as requested. This might be useful in some extremely rare cases when only - * a small and no coherent fraction of the result's coefficients have to be computed. - * - * \warning This version of the matrix product can be much much slower. So use it only if you know - * what you are doing and that you measured a true speed improvement. - * - * \sa operator*(const MatrixBase&) - */ -template -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -const Product -MatrixBase::lazyProduct(const MatrixBase &other) const -{ + * + * The returned product will behave like any other expressions: the coefficients of the product will be + * computed once at a time as requested. This might be useful in some extremely rare cases when only + * a small and no coherent fraction of the result's coefficients have to be computed. + * + * \warning This version of the matrix product can be much much slower. So use it only if you know + * what you are doing and that you measured a true speed improvement. + * + * \sa operator*(const MatrixBase&) + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Product +MatrixBase::lazyProduct(const MatrixBase& other) const { enum { - ProductIsValid = Derived::ColsAtCompileTime==Dynamic - || OtherDerived::RowsAtCompileTime==Dynamic - || int(Derived::ColsAtCompileTime)==int(OtherDerived::RowsAtCompileTime), + ProductIsValid = Derived::ColsAtCompileTime == Dynamic || OtherDerived::RowsAtCompileTime == Dynamic || + int(Derived::ColsAtCompileTime) == int(OtherDerived::RowsAtCompileTime), AreVectors = Derived::IsVectorAtCompileTime && OtherDerived::IsVectorAtCompileTime, - SameSizes = EIGEN_PREDICATE_SAME_MATRIX_SIZE(Derived,OtherDerived) + SameSizes = EIGEN_PREDICATE_SAME_MATRIX_SIZE(Derived, OtherDerived) }; // note to the lost user: // * for a dot product use: v1.dot(v2) // * for a coeff-wise product use: v1.cwiseProduct(v2) - EIGEN_STATIC_ASSERT(ProductIsValid || !(AreVectors && SameSizes), - INVALID_VECTOR_VECTOR_PRODUCT__IF_YOU_WANTED_A_DOT_OR_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTIONS) + EIGEN_STATIC_ASSERT( + ProductIsValid || !(AreVectors && SameSizes), + INVALID_VECTOR_VECTOR_PRODUCT__IF_YOU_WANTED_A_DOT_OR_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTIONS) EIGEN_STATIC_ASSERT(ProductIsValid || !(SameSizes && !AreVectors), - INVALID_MATRIX_PRODUCT__IF_YOU_WANTED_A_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTION) + INVALID_MATRIX_PRODUCT__IF_YOU_WANTED_A_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTION) EIGEN_STATIC_ASSERT(ProductIsValid || SameSizes, INVALID_MATRIX_PRODUCT) - return Product(derived(), other.derived()); + return Product(derived(), other.derived()); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_PRODUCT_H +#endif // EIGEN_PRODUCT_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/GenericPacketMath.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/GenericPacketMath.h index cf677a1905f..8a07d50fe3a 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/GenericPacketMath.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/GenericPacketMath.h @@ -11,17 +11,20 @@ #ifndef EIGEN_GENERIC_PACKET_MATH_H #define EIGEN_GENERIC_PACKET_MATH_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { /** \internal - * \file GenericPacketMath.h - * - * Default implementation for types not supported by the vectorization. - * In practice these functions are provided to make easier the writing - * of generic vectorized code. - */ + * \file GenericPacketMath.h + * + * Default implementation for types not supported by the vectorization. + * In practice these functions are provided to make easier the writing + * of generic vectorized code. + */ #ifndef EIGEN_DEBUG_ALIGNED_LOAD #define EIGEN_DEBUG_ALIGNED_LOAD @@ -39,48 +42,52 @@ namespace internal { #define EIGEN_DEBUG_UNALIGNED_STORE #endif -struct default_packet_traits -{ +struct default_packet_traits { enum { - HasHalfPacket = 0, - - HasAdd = 1, - HasSub = 1, - HasShift = 1, - HasMul = 1, - HasNegate = 1, - HasAbs = 1, - HasArg = 0, - HasAbs2 = 1, - HasAbsDiff = 0, - HasMin = 1, - HasMax = 1, - HasConj = 1, + // Ops that are implemented for most types. + HasAdd = 1, + HasSub = 1, + HasShift = 1, + HasMul = 1, + HasNegate = 1, + HasAbs = 1, + HasAbs2 = 1, + HasMin = 1, + HasMax = 1, + HasConj = 1, HasSetLinear = 1, - HasBlend = 0, + HasSign = 1, + // By default, the nearest integer functions (rint, round, floor, ceil, trunc) are enabled for all scalar and packet + // types + HasRound = 1, + + HasArg = 0, + HasAbsDiff = 0, + HasBlend = 0, // This flag is used to indicate whether packet comparison is supported. // pcmp_eq, pcmp_lt and pcmp_le should be defined for it to be true. - HasCmp = 0, - - HasDiv = 0, - HasSqrt = 0, - HasRsqrt = 0, - HasExp = 0, - HasExpm1 = 0, - HasLog = 0, - HasLog1p = 0, - HasLog10 = 0, - HasPow = 0, - - HasSin = 0, - HasCos = 0, - HasTan = 0, - HasASin = 0, - HasACos = 0, - HasATan = 0, - HasSinh = 0, - HasCosh = 0, - HasTanh = 0, + HasCmp = 0, + + HasDiv = 0, + HasReciprocal = 0, + HasSqrt = 0, + HasRsqrt = 0, + HasExp = 0, + HasExpm1 = 0, + HasLog = 0, + HasLog1p = 0, + HasLog10 = 0, + HasPow = 0, + HasSin = 0, + HasCos = 0, + HasTan = 0, + HasASin = 0, + HasACos = 0, + HasATan = 0, + HasATanh = 0, + HasSinh = 0, + HasCosh = 0, + HasTanh = 0, HasLGamma = 0, HasDiGamma = 0, HasZeta = 0, @@ -93,76 +100,134 @@ struct default_packet_traits HasIGammaDerA = 0, HasGammaSampleDerAlpha = 0, HasIGammac = 0, - HasBetaInc = 0, - - HasRound = 0, - HasRint = 0, - HasFloor = 0, - HasCeil = 0, - HasSign = 0 + HasBetaInc = 0 }; }; -template struct packet_traits : default_packet_traits -{ +template +struct packet_traits : default_packet_traits { typedef T type; typedef T half; enum { Vectorizable = 0, size = 1, AlignedOnScalar = 0, - HasHalfPacket = 0 }; enum { - HasAdd = 0, - HasSub = 0, - HasMul = 0, + HasAdd = 0, + HasSub = 0, + HasMul = 0, HasNegate = 0, - HasAbs = 0, - HasAbs2 = 0, - HasMin = 0, - HasMax = 0, - HasConj = 0, + HasAbs = 0, + HasAbs2 = 0, + HasMin = 0, + HasMax = 0, + HasConj = 0, HasSetLinear = 0 }; }; -template struct packet_traits : packet_traits { }; +template +struct packet_traits : packet_traits {}; -template struct unpacket_traits -{ +template +struct unpacket_traits { typedef T type; typedef T half; - enum - { + typedef typename numext::get_integer_by_size::signed_type integer_packet; + enum { size = 1, - alignment = 1, + alignment = alignof(T), vectorizable = false, - masked_load_available=false, - masked_store_available=false + masked_load_available = false, + masked_store_available = false }; }; -template struct unpacket_traits : unpacket_traits { }; +template +struct unpacket_traits : unpacket_traits {}; + +/** \internal A convenience utility for determining if the type is a scalar. + * This is used to enable some generic packet implementations. + */ +template +struct is_scalar { + using Scalar = typename unpacket_traits::type; + enum { value = internal::is_same::value }; +}; + +// automatically and succinctly define combinations of pcast when +// 1) the packets are the same type, or +// 2) the packets differ only in sign. +// In both of these cases, preinterpret (bit_cast) is equivalent to pcast (static_cast) +template ::value && is_scalar::value> +struct is_degenerate_helper : is_same {}; +template <> +struct is_degenerate_helper : std::true_type {}; +template <> +struct is_degenerate_helper : std::true_type {}; +template <> +struct is_degenerate_helper : std::true_type {}; +template <> +struct is_degenerate_helper : std::true_type {}; + +template +struct is_degenerate_helper { + using SrcScalar = typename unpacket_traits::type; + static constexpr int SrcSize = unpacket_traits::size; + using TgtScalar = typename unpacket_traits::type; + static constexpr int TgtSize = unpacket_traits::size; + static constexpr bool value = is_degenerate_helper::value && (SrcSize == TgtSize); +}; -template struct type_casting_traits { +// is_degenerate::value == is_degenerate::value +template +struct is_degenerate { + static constexpr bool value = + is_degenerate_helper::value || is_degenerate_helper::value; +}; + +template +struct is_half { + using Scalar = typename unpacket_traits::type; + static constexpr int Size = unpacket_traits::size; + using DefaultPacket = typename packet_traits::type; + static constexpr int DefaultSize = unpacket_traits::size; + static constexpr bool value = Size < DefaultSize; +}; + +template +struct type_casting_traits { enum { - VectorizedCast = 0, + VectorizedCast = + is_degenerate::value && packet_traits::Vectorizable && packet_traits::Vectorizable, SrcCoeffRatio = 1, TgtCoeffRatio = 1 }; }; +// provides a succint template to define vectorized casting traits with respect to the largest accessible packet types +template +struct vectorized_type_casting_traits { + enum : int { + DefaultSrcPacketSize = packet_traits::size, + DefaultTgtPacketSize = packet_traits::size, + VectorizedCast = 1, + SrcCoeffRatio = plain_enum_max(DefaultTgtPacketSize / DefaultSrcPacketSize, 1), + TgtCoeffRatio = plain_enum_max(DefaultSrcPacketSize / DefaultTgtPacketSize, 1) + }; +}; + /** \internal Wrapper to ensure that multiple packet types can map to the same same underlying vector type. */ -template -struct eigen_packet_wrapper -{ +template +struct eigen_packet_wrapper { EIGEN_ALWAYS_INLINE operator T&() { return m_val; } EIGEN_ALWAYS_INLINE operator const T&() const { return m_val; } - EIGEN_ALWAYS_INLINE eigen_packet_wrapper() {} - EIGEN_ALWAYS_INLINE eigen_packet_wrapper(const T &v) : m_val(v) {} - EIGEN_ALWAYS_INLINE eigen_packet_wrapper& operator=(const T &v) { + EIGEN_ALWAYS_INLINE eigen_packet_wrapper() = default; + EIGEN_ALWAYS_INLINE eigen_packet_wrapper(const T& v) : m_val(v) {} + EIGEN_ALWAYS_INLINE eigen_packet_wrapper& operator=(const T& v) { m_val = v; return *this; } @@ -170,109 +235,173 @@ struct eigen_packet_wrapper T m_val; }; +template ::value> +struct preinterpret_generic; -/** \internal A convenience utility for determining if the type is a scalar. - * This is used to enable some generic packet implementations. - */ -template -struct is_scalar { - typedef typename unpacket_traits::type Scalar; - enum { - value = internal::is_same::value - }; +template +struct preinterpret_generic { + // the packets are not the same, attempt scalar bit_cast + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Target run(const Packet& a) { + return numext::bit_cast(a); + } +}; + +template +struct preinterpret_generic { + // the packets are the same type: do nothing + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run(const Packet& a) { return a; } +}; + +/** \internal \returns reinterpret_cast(a) */ +template +EIGEN_DEVICE_FUNC inline Target preinterpret(const Packet& a) { + return preinterpret_generic::run(a); +} + +template ::value, + bool TgtIsHalf = is_half::value> +struct pcast_generic; + +template +struct pcast_generic { + // the packets are not degenerate: attempt scalar static_cast + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket run(const SrcPacket& a) { + return cast_impl::run(a); + } +}; + +template +struct pcast_generic { + // the packets are the same: do nothing + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run(const Packet& a) { return a; } +}; + +template +struct pcast_generic { + // the packets are degenerate: preinterpret is equivalent to pcast + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket run(const SrcPacket& a) { return preinterpret(a); } }; /** \internal \returns static_cast(a) (coeff-wise) */ template -EIGEN_DEVICE_FUNC inline TgtPacket -pcast(const SrcPacket& a) { - return static_cast(a); +EIGEN_DEVICE_FUNC inline TgtPacket pcast(const SrcPacket& a) { + return pcast_generic::run(a); } template -EIGEN_DEVICE_FUNC inline TgtPacket -pcast(const SrcPacket& a, const SrcPacket& /*b*/) { - return static_cast(a); +EIGEN_DEVICE_FUNC inline TgtPacket pcast(const SrcPacket& a, const SrcPacket& b) { + return pcast_generic::run(a, b); } template -EIGEN_DEVICE_FUNC inline TgtPacket -pcast(const SrcPacket& a, const SrcPacket& /*b*/, const SrcPacket& /*c*/, const SrcPacket& /*d*/) { - return static_cast(a); +EIGEN_DEVICE_FUNC inline TgtPacket pcast(const SrcPacket& a, const SrcPacket& b, const SrcPacket& c, + const SrcPacket& d) { + return pcast_generic::run(a, b, c, d); } template -EIGEN_DEVICE_FUNC inline TgtPacket -pcast(const SrcPacket& a, const SrcPacket& /*b*/, const SrcPacket& /*c*/, const SrcPacket& /*d*/, - const SrcPacket& /*e*/, const SrcPacket& /*f*/, const SrcPacket& /*g*/, const SrcPacket& /*h*/) { - return static_cast(a); +EIGEN_DEVICE_FUNC inline TgtPacket pcast(const SrcPacket& a, const SrcPacket& b, const SrcPacket& c, const SrcPacket& d, + const SrcPacket& e, const SrcPacket& f, const SrcPacket& g, + const SrcPacket& h) { + return pcast_generic::run(a, b, c, d, e, f, g, h); } -/** \internal \returns reinterpret_cast(a) */ -template -EIGEN_DEVICE_FUNC inline Target -preinterpret(const Packet& a); /* { return reinterpret_cast(a); } */ +template +struct pcast_generic { + // TgtPacket is a half packet of some other type + // perform cast and truncate result + using DefaultTgtPacket = typename is_half::DefaultPacket; + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket run(const SrcPacket& a) { + return preinterpret(pcast(a)); + } +}; /** \internal \returns a + b (coeff-wise) */ -template EIGEN_DEVICE_FUNC inline Packet -padd(const Packet& a, const Packet& b) { return a+b; } +template +EIGEN_DEVICE_FUNC inline Packet padd(const Packet& a, const Packet& b) { + return a + b; +} // Avoid compiler warning for boolean algebra. -template<> EIGEN_DEVICE_FUNC inline bool -padd(const bool& a, const bool& b) { return a || b; } +template <> +EIGEN_DEVICE_FUNC inline bool padd(const bool& a, const bool& b) { + return a || b; +} + +/** \internal \returns a packet version of \a *from, (un-aligned masked add) + * There is no generic implementation. We only have implementations for specialized + * cases. Generic case should not be called. + */ +template +EIGEN_DEVICE_FUNC inline std::enable_if_t::masked_fpops_available, Packet> padd( + const Packet& a, const Packet& b, typename unpacket_traits::mask_t umask); /** \internal \returns a - b (coeff-wise) */ -template EIGEN_DEVICE_FUNC inline Packet -psub(const Packet& a, const Packet& b) { return a-b; } +template +EIGEN_DEVICE_FUNC inline Packet psub(const Packet& a, const Packet& b) { + return a - b; +} /** \internal \returns -a (coeff-wise) */ -template EIGEN_DEVICE_FUNC inline Packet -pnegate(const Packet& a) { return -a; } - -template<> EIGEN_DEVICE_FUNC inline bool -pnegate(const bool& a) { return !a; } +template +EIGEN_DEVICE_FUNC inline Packet pnegate(const Packet& a) { + EIGEN_STATIC_ASSERT((!is_same::type, bool>::value), + NEGATE IS NOT DEFINED FOR BOOLEAN TYPES) + return numext::negate(a); +} /** \internal \returns conj(a) (coeff-wise) */ -template EIGEN_DEVICE_FUNC inline Packet -pconj(const Packet& a) { return numext::conj(a); } +template +EIGEN_DEVICE_FUNC inline Packet pconj(const Packet& a) { + return numext::conj(a); +} /** \internal \returns a * b (coeff-wise) */ -template EIGEN_DEVICE_FUNC inline Packet -pmul(const Packet& a, const Packet& b) { return a*b; } +template +EIGEN_DEVICE_FUNC inline Packet pmul(const Packet& a, const Packet& b) { + return a * b; +} // Avoid compiler warning for boolean algebra. -template<> EIGEN_DEVICE_FUNC inline bool -pmul(const bool& a, const bool& b) { return a && b; } +template <> +EIGEN_DEVICE_FUNC inline bool pmul(const bool& a, const bool& b) { + return a && b; +} /** \internal \returns a / b (coeff-wise) */ -template EIGEN_DEVICE_FUNC inline Packet -pdiv(const Packet& a, const Packet& b) { return a/b; } +template +EIGEN_DEVICE_FUNC inline Packet pdiv(const Packet& a, const Packet& b) { + return a / b; +} // In the generic case, memset to all one bits. -template +template struct ptrue_impl { - static EIGEN_DEVICE_FUNC inline Packet run(const Packet& /*a*/){ + static EIGEN_DEVICE_FUNC inline Packet run(const Packet& /*a*/) { Packet b; memset(static_cast(&b), 0xff, sizeof(Packet)); return b; } }; +// For booleans, we can only directly set a valid `bool` value to avoid UB. +template <> +struct ptrue_impl { + static EIGEN_DEVICE_FUNC inline bool run(const bool& /*a*/) { return true; } +}; + // For non-trivial scalars, set to Scalar(1) (i.e. a non-zero value). // Although this is technically not a valid bitmask, the scalar path for pselect // uses a comparison to zero, so this should still work in most cases. We don't // have another option, since the scalar type requires initialization. -template -struct ptrue_impl::value && NumTraits::RequireInitialization>::type > { - static EIGEN_DEVICE_FUNC inline T run(const T& /*a*/){ - return T(1); - } +template +struct ptrue_impl::value && NumTraits::RequireInitialization>> { + static EIGEN_DEVICE_FUNC inline T run(const T& /*a*/) { return T(1); } }; /** \internal \returns one bits. */ -template EIGEN_DEVICE_FUNC inline Packet -ptrue(const Packet& a) { +template +EIGEN_DEVICE_FUNC inline Packet ptrue(const Packet& a) { return ptrue_impl::run(a); } // In the general case, memset to zero. -template +template struct pzero_impl { static EIGEN_DEVICE_FUNC inline Packet run(const Packet& /*a*/) { Packet b; @@ -283,66 +412,89 @@ struct pzero_impl { // For scalars, explicitly set to Scalar(0), since the underlying representation // for zero may not consist of all-zero bits. -template -struct pzero_impl::value>::type> { - static EIGEN_DEVICE_FUNC inline T run(const T& /*a*/) { - return T(0); - } +template +struct pzero_impl::value>> { + static EIGEN_DEVICE_FUNC inline T run(const T& /*a*/) { return T(0); } }; /** \internal \returns packet of zeros */ -template EIGEN_DEVICE_FUNC inline Packet -pzero(const Packet& a) { +template +EIGEN_DEVICE_FUNC inline Packet pzero(const Packet& a) { return pzero_impl::run(a); } /** \internal \returns a <= b as a bit mask */ -template EIGEN_DEVICE_FUNC inline Packet -pcmp_le(const Packet& a, const Packet& b) { return a<=b ? ptrue(a) : pzero(a); } +template +EIGEN_DEVICE_FUNC inline Packet pcmp_le(const Packet& a, const Packet& b) { + return a <= b ? ptrue(a) : pzero(a); +} /** \internal \returns a < b as a bit mask */ -template EIGEN_DEVICE_FUNC inline Packet -pcmp_lt(const Packet& a, const Packet& b) { return a +EIGEN_DEVICE_FUNC inline Packet pcmp_lt(const Packet& a, const Packet& b) { + return a < b ? ptrue(a) : pzero(a); +} /** \internal \returns a == b as a bit mask */ -template EIGEN_DEVICE_FUNC inline Packet -pcmp_eq(const Packet& a, const Packet& b) { return a==b ? ptrue(a) : pzero(a); } +template +EIGEN_DEVICE_FUNC inline Packet pcmp_eq(const Packet& a, const Packet& b) { + return a == b ? ptrue(a) : pzero(a); +} /** \internal \returns a < b or a==NaN or b==NaN as a bit mask */ -template EIGEN_DEVICE_FUNC inline Packet -pcmp_lt_or_nan(const Packet& a, const Packet& b) { return a>=b ? pzero(a) : ptrue(a); } +template +EIGEN_DEVICE_FUNC inline Packet pcmp_lt_or_nan(const Packet& a, const Packet& b) { + return a >= b ? pzero(a) : ptrue(a); +} -template +template struct bit_and { - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE T operator()(const T& a, const T& b) const { - return a & b; - } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE T operator()(const T& a, const T& b) const { return a & b; } }; -template +template struct bit_or { - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE T operator()(const T& a, const T& b) const { - return a | b; - } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE T operator()(const T& a, const T& b) const { return a | b; } }; -template +template struct bit_xor { - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE T operator()(const T& a, const T& b) const { - return a ^ b; - } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE T operator()(const T& a, const T& b) const { return a ^ b; } }; -template +template struct bit_not { - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE T operator()(const T& a) const { - return ~a; + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE T operator()(const T& a) const { return ~a; } +}; + +template <> +struct bit_and { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE bool operator()(const bool& a, const bool& b) const { + return a && b; } }; +template <> +struct bit_or { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE bool operator()(const bool& a, const bool& b) const { + return a || b; + } +}; + +template <> +struct bit_xor { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE bool operator()(const bool& a, const bool& b) const { + return a != b; + } +}; + +template <> +struct bit_not { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR EIGEN_ALWAYS_INLINE bool operator()(const bool& a) const { return !a; } +}; + // Use operators &, |, ^, ~. -template +template struct operator_bitwise_helper { EIGEN_DEVICE_FUNC static inline T bitwise_and(const T& a, const T& b) { return bit_and()(a, b); } EIGEN_DEVICE_FUNC static inline T bitwise_or(const T& a, const T& b) { return bit_or()(a, b); } @@ -351,23 +503,19 @@ struct operator_bitwise_helper { }; // Apply binary operations byte-by-byte -template +template struct bytewise_bitwise_helper { EIGEN_DEVICE_FUNC static inline T bitwise_and(const T& a, const T& b) { return binary(a, b, bit_and()); } - EIGEN_DEVICE_FUNC static inline T bitwise_or(const T& a, const T& b) { - return binary(a, b, bit_or()); - } + EIGEN_DEVICE_FUNC static inline T bitwise_or(const T& a, const T& b) { return binary(a, b, bit_or()); } EIGEN_DEVICE_FUNC static inline T bitwise_xor(const T& a, const T& b) { return binary(a, b, bit_xor()); } - EIGEN_DEVICE_FUNC static inline T bitwise_not(const T& a) { - return unary(a,bit_not()); - } - + EIGEN_DEVICE_FUNC static inline T bitwise_not(const T& a) { return unary(a, bit_not()); } + private: - template + template EIGEN_DEVICE_FUNC static inline T unary(const T& a, Op op) { const unsigned char* a_ptr = reinterpret_cast(&a); T c; @@ -378,7 +526,7 @@ struct bytewise_bitwise_helper { return c; } - template + template EIGEN_DEVICE_FUNC static inline T binary(const T& a, const T& b, Op op) { const unsigned char* a_ptr = reinterpret_cast(&a); const unsigned char* b_ptr = reinterpret_cast(&b); @@ -392,124 +540,121 @@ struct bytewise_bitwise_helper { }; // In the general case, use byte-by-byte manipulation. -template +template struct bitwise_helper : public bytewise_bitwise_helper {}; // For integers or non-trivial scalars, use binary operators. -template -struct bitwise_helper::value && (NumTraits::IsInteger || NumTraits::RequireInitialization)>::type - > : public operator_bitwise_helper {}; +template +struct bitwise_helper::value && + (NumTraits::IsInteger || NumTraits::RequireInitialization)>> + : public operator_bitwise_helper {}; /** \internal \returns the bitwise and of \a a and \a b */ -template EIGEN_DEVICE_FUNC inline Packet -pand(const Packet& a, const Packet& b) { +template +EIGEN_DEVICE_FUNC inline Packet pand(const Packet& a, const Packet& b) { return bitwise_helper::bitwise_and(a, b); } /** \internal \returns the bitwise or of \a a and \a b */ -template EIGEN_DEVICE_FUNC inline Packet -por(const Packet& a, const Packet& b) { +template +EIGEN_DEVICE_FUNC inline Packet por(const Packet& a, const Packet& b) { return bitwise_helper::bitwise_or(a, b); } /** \internal \returns the bitwise xor of \a a and \a b */ -template EIGEN_DEVICE_FUNC inline Packet -pxor(const Packet& a, const Packet& b) { +template +EIGEN_DEVICE_FUNC inline Packet pxor(const Packet& a, const Packet& b) { return bitwise_helper::bitwise_xor(a, b); } /** \internal \returns the bitwise not of \a a */ -template EIGEN_DEVICE_FUNC inline Packet -pnot(const Packet& a) { +template +EIGEN_DEVICE_FUNC inline Packet pnot(const Packet& a) { return bitwise_helper::bitwise_not(a); } /** \internal \returns the bitwise and of \a a and not \a b */ -template EIGEN_DEVICE_FUNC inline Packet -pandnot(const Packet& a, const Packet& b) { return pand(a, pnot(b)); } +template +EIGEN_DEVICE_FUNC inline Packet pandnot(const Packet& a, const Packet& b) { + return pand(a, pnot(b)); +} + +/** \internal \returns isnan(a) */ +template +EIGEN_DEVICE_FUNC inline Packet pisnan(const Packet& a) { + return pandnot(ptrue(a), pcmp_eq(a, a)); +} // In the general case, use bitwise select. -template +template struct pselect_impl { static EIGEN_DEVICE_FUNC inline Packet run(const Packet& mask, const Packet& a, const Packet& b) { - return por(pand(a,mask),pandnot(b,mask)); + return por(pand(a, mask), pandnot(b, mask)); } }; // For scalars, use ternary select. -template -struct pselect_impl::value>::type > { +template +struct pselect_impl::value>> { static EIGEN_DEVICE_FUNC inline Packet run(const Packet& mask, const Packet& a, const Packet& b) { return numext::equal_strict(mask, Packet(0)) ? b : a; } }; /** \internal \returns \a or \b for each field in packet according to \mask */ -template EIGEN_DEVICE_FUNC inline Packet -pselect(const Packet& mask, const Packet& a, const Packet& b) { +template +EIGEN_DEVICE_FUNC inline Packet pselect(const Packet& mask, const Packet& a, const Packet& b) { return pselect_impl::run(mask, a, b); } -template<> EIGEN_DEVICE_FUNC inline bool pselect( - const bool& cond, const bool& a, const bool& b) { +template <> +EIGEN_DEVICE_FUNC inline bool pselect(const bool& cond, const bool& a, const bool& b) { return cond ? a : b; } /** \internal \returns the min or of \a a and \a b (coeff-wise) If either \a a or \a b are NaN, the result is implementation defined. */ -template +template struct pminmax_impl { template static EIGEN_DEVICE_FUNC inline Packet run(const Packet& a, const Packet& b, Op op) { - return op(a,b); + return op(a, b); } }; /** \internal \returns the min or max of \a a and \a b (coeff-wise) If either \a a or \a b are NaN, NaN is returned. */ -template<> +template <> struct pminmax_impl { template static EIGEN_DEVICE_FUNC inline Packet run(const Packet& a, const Packet& b, Op op) { - Packet not_nan_mask_a = pcmp_eq(a, a); - Packet not_nan_mask_b = pcmp_eq(b, b); - return pselect(not_nan_mask_a, - pselect(not_nan_mask_b, op(a, b), b), - a); + Packet not_nan_mask_a = pcmp_eq(a, a); + Packet not_nan_mask_b = pcmp_eq(b, b); + return pselect(not_nan_mask_a, pselect(not_nan_mask_b, op(a, b), b), a); } }; /** \internal \returns the min or max of \a a and \a b (coeff-wise) If both \a a and \a b are NaN, NaN is returned. Equivalent to std::fmin(a, b). */ -template<> +template <> struct pminmax_impl { template static EIGEN_DEVICE_FUNC inline Packet run(const Packet& a, const Packet& b, Op op) { - Packet not_nan_mask_a = pcmp_eq(a, a); - Packet not_nan_mask_b = pcmp_eq(b, b); - return pselect(not_nan_mask_a, - pselect(not_nan_mask_b, op(a, b), a), - b); + Packet not_nan_mask_a = pcmp_eq(a, a); + Packet not_nan_mask_b = pcmp_eq(b, b); + return pselect(not_nan_mask_a, pselect(not_nan_mask_b, op(a, b), a), b); } }; - -#ifndef SYCL_DEVICE_ONLY -#define EIGEN_BINARY_OP_NAN_PROPAGATION(Type, Func) Func -#else -#define EIGEN_BINARY_OP_NAN_PROPAGATION(Type, Func) \ -[](const Type& a, const Type& b) { \ - return Func(a, b);} -#endif +#define EIGEN_BINARY_OP_NAN_PROPAGATION(Type, Func) [](const Type& a, const Type& b) { return Func(a, b); } /** \internal \returns the min of \a a and \a b (coeff-wise). If \a a or \b b is NaN, the return value is implementation defined. */ -template EIGEN_DEVICE_FUNC inline Packet -pmin(const Packet& a, const Packet& b) { return numext::mini(a,b); } +template +EIGEN_DEVICE_FUNC inline Packet pmin(const Packet& a, const Packet& b) { + return numext::mini(a, b); +} /** \internal \returns the min of \a a and \a b (coeff-wise). NaNPropagation determines the NaN propagation semantics. */ @@ -520,58 +665,70 @@ EIGEN_DEVICE_FUNC inline Packet pmin(const Packet& a, const Packet& b) { /** \internal \returns the max of \a a and \a b (coeff-wise) If \a a or \b b is NaN, the return value is implementation defined. */ -template EIGEN_DEVICE_FUNC inline Packet -pmax(const Packet& a, const Packet& b) { return numext::maxi(a, b); } +template +EIGEN_DEVICE_FUNC inline Packet pmax(const Packet& a, const Packet& b) { + return numext::maxi(a, b); +} /** \internal \returns the max of \a a and \a b (coeff-wise). NaNPropagation determines the NaN propagation semantics. */ template EIGEN_DEVICE_FUNC inline Packet pmax(const Packet& a, const Packet& b) { - return pminmax_impl::run(a, b, EIGEN_BINARY_OP_NAN_PROPAGATION(Packet,(pmax))); + return pminmax_impl::run(a, b, EIGEN_BINARY_OP_NAN_PROPAGATION(Packet, (pmax))); } /** \internal \returns the absolute value of \a a */ -template EIGEN_DEVICE_FUNC inline Packet -pabs(const Packet& a) { return numext::abs(a); } -template<> EIGEN_DEVICE_FUNC inline unsigned int -pabs(const unsigned int& a) { return a; } -template<> EIGEN_DEVICE_FUNC inline unsigned long -pabs(const unsigned long& a) { return a; } -template<> EIGEN_DEVICE_FUNC inline unsigned long long -pabs(const unsigned long long& a) { return a; } +template +EIGEN_DEVICE_FUNC inline Packet pabs(const Packet& a) { + return numext::abs(a); +} +template <> +EIGEN_DEVICE_FUNC inline unsigned int pabs(const unsigned int& a) { + return a; +} +template <> +EIGEN_DEVICE_FUNC inline unsigned long pabs(const unsigned long& a) { + return a; +} +template <> +EIGEN_DEVICE_FUNC inline unsigned long long pabs(const unsigned long long& a) { + return a; +} /** \internal \returns the addsub value of \a a,b */ -template EIGEN_DEVICE_FUNC inline Packet -paddsub(const Packet& a, const Packet& b) { +template +EIGEN_DEVICE_FUNC inline Packet paddsub(const Packet& a, const Packet& b) { return pselect(peven_mask(a), padd(a, b), psub(a, b)); - } +} /** \internal \returns the phase angle of \a a */ -template EIGEN_DEVICE_FUNC inline Packet -parg(const Packet& a) { using numext::arg; return arg(a); } +template +EIGEN_DEVICE_FUNC inline Packet parg(const Packet& a) { + using numext::arg; + return arg(a); +} +/** \internal \returns \a a arithmetically shifted by N bits to the right */ +template +EIGEN_DEVICE_FUNC inline T parithmetic_shift_right(const T& a) { + return numext::arithmetic_shift_right(a, N); +} /** \internal \returns \a a logically shifted by N bits to the right */ -template EIGEN_DEVICE_FUNC inline int -parithmetic_shift_right(const int& a) { return a >> N; } -template EIGEN_DEVICE_FUNC inline long int -parithmetic_shift_right(const long int& a) { return a >> N; } - -/** \internal \returns \a a arithmetically shifted by N bits to the right */ -template EIGEN_DEVICE_FUNC inline int -plogical_shift_right(const int& a) { return static_cast(static_cast(a) >> N); } -template EIGEN_DEVICE_FUNC inline long int -plogical_shift_right(const long int& a) { return static_cast(static_cast(a) >> N); } +template +EIGEN_DEVICE_FUNC inline T plogical_shift_right(const T& a) { + return numext::logical_shift_right(a, N); +} /** \internal \returns \a a shifted by N bits to the left */ -template EIGEN_DEVICE_FUNC inline int -plogical_shift_left(const int& a) { return a << N; } -template EIGEN_DEVICE_FUNC inline long int -plogical_shift_left(const long int& a) { return a << N; } +template +EIGEN_DEVICE_FUNC inline T plogical_shift_left(const T& a) { + return numext::logical_shift_left(a, N); +} /** \internal \returns the significant and exponent of the underlying floating point numbers - * See https://en.cppreference.com/w/cpp/numeric/math/frexp - */ + * See https://en.cppreference.com/w/cpp/numeric/math/frexp + */ template EIGEN_DEVICE_FUNC inline Packet pfrexp(const Packet& a, Packet& exponent) { int exp; @@ -582,142 +739,238 @@ EIGEN_DEVICE_FUNC inline Packet pfrexp(const Packet& a, Packet& exponent) { } /** \internal \returns a * 2^((int)exponent) - * See https://en.cppreference.com/w/cpp/numeric/math/ldexp - */ -template EIGEN_DEVICE_FUNC inline Packet -pldexp(const Packet &a, const Packet &exponent) { + * See https://en.cppreference.com/w/cpp/numeric/math/ldexp + */ +template +EIGEN_DEVICE_FUNC inline Packet pldexp(const Packet& a, const Packet& exponent) { EIGEN_USING_STD(ldexp) return static_cast(ldexp(a, static_cast(exponent))); } /** \internal \returns the min of \a a and \a b (coeff-wise) */ -template EIGEN_DEVICE_FUNC inline Packet -pabsdiff(const Packet& a, const Packet& b) { return pselect(pcmp_lt(a, b), psub(b, a), psub(a, b)); } +template +EIGEN_DEVICE_FUNC inline Packet pabsdiff(const Packet& a, const Packet& b) { + return pselect(pcmp_lt(a, b), psub(b, a), psub(a, b)); +} + +/** \internal \returns a packet version of \a *from, from must be properly aligned */ +template +EIGEN_DEVICE_FUNC inline Packet pload(const typename unpacket_traits::type* from) { + return *from; +} -/** \internal \returns a packet version of \a *from, from must be 16 bytes aligned */ -template EIGEN_DEVICE_FUNC inline Packet -pload(const typename unpacket_traits::type* from) { return *from; } +/** \internal \returns n elements of a packet version of \a *from, from must be properly aligned + * offset indicates the starting element in which to load and + * offset + n <= unpacket_traits::size + * All elements before offset and after the last element loaded will initialized with zero */ +template +EIGEN_DEVICE_FUNC inline Packet pload_partial(const typename unpacket_traits::type* from, const Index n, + const Index offset = 0) { + const Index packet_size = unpacket_traits::size; + eigen_assert(n + offset <= packet_size && "number of elements plus offset will read past end of packet"); + typedef typename unpacket_traits::type Scalar; + EIGEN_ALIGN_MAX Scalar elements[packet_size] = {Scalar(0)}; + for (Index i = offset; i < numext::mini(n + offset, packet_size); i++) { + elements[i] = from[i - offset]; + } + return pload(elements); +} /** \internal \returns a packet version of \a *from, (un-aligned load) */ -template EIGEN_DEVICE_FUNC inline Packet -ploadu(const typename unpacket_traits::type* from) { return *from; } +template +EIGEN_DEVICE_FUNC inline Packet ploadu(const typename unpacket_traits::type* from) { + return *from; +} + +/** \internal \returns n elements of a packet version of \a *from, (un-aligned load) + * All elements after the last element loaded will initialized with zero */ +template +EIGEN_DEVICE_FUNC inline Packet ploadu_partial(const typename unpacket_traits::type* from, const Index n, + const Index offset = 0) { + const Index packet_size = unpacket_traits::size; + eigen_assert(n + offset <= packet_size && "number of elements plus offset will read past end of packet"); + typedef typename unpacket_traits::type Scalar; + EIGEN_ALIGN_MAX Scalar elements[packet_size] = {Scalar(0)}; + for (Index i = offset; i < numext::mini(n + offset, packet_size); i++) { + elements[i] = from[i - offset]; + } + return pload(elements); +} /** \internal \returns a packet version of \a *from, (un-aligned masked load) * There is no generic implementation. We only have implementations for specialized * cases. Generic case should not be called. */ -template EIGEN_DEVICE_FUNC inline -typename enable_if::masked_load_available, Packet>::type -ploadu(const typename unpacket_traits::type* from, typename unpacket_traits::mask_t umask); +template +EIGEN_DEVICE_FUNC inline std::enable_if_t::masked_load_available, Packet> ploadu( + const typename unpacket_traits::type* from, typename unpacket_traits::mask_t umask); /** \internal \returns a packet with constant coefficients \a a, e.g.: (a,a,a,a) */ -template EIGEN_DEVICE_FUNC inline Packet -pset1(const typename unpacket_traits::type& a) { return a; } +template +EIGEN_DEVICE_FUNC inline Packet pset1(const typename unpacket_traits::type& a) { + return a; +} /** \internal \returns a packet with constant coefficients set from bits */ -template EIGEN_DEVICE_FUNC inline Packet -pset1frombits(BitsType a); +template +EIGEN_DEVICE_FUNC inline Packet pset1frombits(BitsType a); /** \internal \returns a packet with constant coefficients \a a[0], e.g.: (a[0],a[0],a[0],a[0]) */ -template EIGEN_DEVICE_FUNC inline Packet -pload1(const typename unpacket_traits::type *a) { return pset1(*a); } +template +EIGEN_DEVICE_FUNC inline Packet pload1(const typename unpacket_traits::type* a) { + return pset1(*a); +} /** \internal \returns a packet with elements of \a *from duplicated. - * For instance, for a packet of 8 elements, 4 scalars will be read from \a *from and - * duplicated to form: {from[0],from[0],from[1],from[1],from[2],from[2],from[3],from[3]} - * Currently, this function is only used for scalar * complex products. - */ -template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet -ploaddup(const typename unpacket_traits::type* from) { return *from; } + * For instance, for a packet of 8 elements, 4 scalars will be read from \a *from and + * duplicated to form: {from[0],from[0],from[1],from[1],from[2],from[2],from[3],from[3]} + * Currently, this function is only used for scalar * complex products. + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet ploaddup(const typename unpacket_traits::type* from) { + return *from; +} /** \internal \returns a packet with elements of \a *from quadrupled. - * For instance, for a packet of 8 elements, 2 scalars will be read from \a *from and - * replicated to form: {from[0],from[0],from[0],from[0],from[1],from[1],from[1],from[1]} - * Currently, this function is only used in matrix products. - * For packet-size smaller or equal to 4, this function is equivalent to pload1 - */ -template EIGEN_DEVICE_FUNC inline Packet -ploadquad(const typename unpacket_traits::type* from) -{ return pload1(from); } + * For instance, for a packet of 8 elements, 2 scalars will be read from \a *from and + * replicated to form: {from[0],from[0],from[0],from[0],from[1],from[1],from[1],from[1]} + * Currently, this function is only used in matrix products. + * For packet-size smaller or equal to 4, this function is equivalent to pload1 + */ +template +EIGEN_DEVICE_FUNC inline Packet ploadquad(const typename unpacket_traits::type* from) { + return pload1(from); +} /** \internal equivalent to - * \code - * a0 = pload1(a+0); - * a1 = pload1(a+1); - * a2 = pload1(a+2); - * a3 = pload1(a+3); - * \endcode - * \sa pset1, pload1, ploaddup, pbroadcast2 - */ -template EIGEN_DEVICE_FUNC -inline void pbroadcast4(const typename unpacket_traits::type *a, - Packet& a0, Packet& a1, Packet& a2, Packet& a3) -{ - a0 = pload1(a+0); - a1 = pload1(a+1); - a2 = pload1(a+2); - a3 = pload1(a+3); + * \code + * a0 = pload1(a+0); + * a1 = pload1(a+1); + * a2 = pload1(a+2); + * a3 = pload1(a+3); + * \endcode + * \sa pset1, pload1, ploaddup, pbroadcast2 + */ +template +EIGEN_DEVICE_FUNC inline void pbroadcast4(const typename unpacket_traits::type* a, Packet& a0, Packet& a1, + Packet& a2, Packet& a3) { + a0 = pload1(a + 0); + a1 = pload1(a + 1); + a2 = pload1(a + 2); + a3 = pload1(a + 3); } /** \internal equivalent to - * \code - * a0 = pload1(a+0); - * a1 = pload1(a+1); - * \endcode - * \sa pset1, pload1, ploaddup, pbroadcast4 - */ -template EIGEN_DEVICE_FUNC -inline void pbroadcast2(const typename unpacket_traits::type *a, - Packet& a0, Packet& a1) -{ - a0 = pload1(a+0); - a1 = pload1(a+1); + * \code + * a0 = pload1(a+0); + * a1 = pload1(a+1); + * \endcode + * \sa pset1, pload1, ploaddup, pbroadcast4 + */ +template +EIGEN_DEVICE_FUNC inline void pbroadcast2(const typename unpacket_traits::type* a, Packet& a0, Packet& a1) { + a0 = pload1(a + 0); + a1 = pload1(a + 1); } /** \internal \brief Returns a packet with coefficients (a,a+1,...,a+packet_size-1). */ -template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet -plset(const typename unpacket_traits::type& a) { return a; } +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet plset(const typename unpacket_traits::type& a) { + return a; +} /** \internal \returns a packet with constant coefficients \a a, e.g.: (x, 0, x, 0), where x is the value of all 1-bits. */ -template EIGEN_DEVICE_FUNC inline Packet -peven_mask(const Packet& /*a*/) { +template +EIGEN_DEVICE_FUNC inline Packet peven_mask(const Packet& /*a*/) { typedef typename unpacket_traits::type Scalar; const size_t n = unpacket_traits::size; EIGEN_ALIGN_TO_BOUNDARY(sizeof(Packet)) Scalar elements[n]; - for(size_t i = 0; i < n; ++i) { - memset(elements+i, ((i & 1) == 0 ? 0xff : 0), sizeof(Scalar)); + for (size_t i = 0; i < n; ++i) { + memset(elements + i, ((i & 1) == 0 ? 0xff : 0), sizeof(Scalar)); } return ploadu(elements); } +/** \internal copy the packet \a from to \a *to, \a to must be properly aligned */ +template +EIGEN_DEVICE_FUNC inline void pstore(Scalar* to, const Packet& from) { + (*to) = from; +} -/** \internal copy the packet \a from to \a *to, \a to must be 16 bytes aligned */ -template EIGEN_DEVICE_FUNC inline void pstore(Scalar* to, const Packet& from) -{ (*to) = from; } +/** \internal copy n elements of the packet \a from to \a *to, \a to must be properly aligned + * offset indicates the starting element in which to store and + * offset + n <= unpacket_traits::size */ +template +EIGEN_DEVICE_FUNC inline void pstore_partial(Scalar* to, const Packet& from, const Index n, const Index offset = 0) { + const Index packet_size = unpacket_traits::size; + eigen_assert(n + offset <= packet_size && "number of elements plus offset will write past end of packet"); + EIGEN_ALIGN_MAX Scalar elements[packet_size]; + pstore(elements, from); + for (Index i = 0; i < numext::mini(n, packet_size - offset); i++) { + to[i] = elements[i + offset]; + } +} /** \internal copy the packet \a from to \a *to, (un-aligned store) */ -template EIGEN_DEVICE_FUNC inline void pstoreu(Scalar* to, const Packet& from) -{ (*to) = from; } +template +EIGEN_DEVICE_FUNC inline void pstoreu(Scalar* to, const Packet& from) { + (*to) = from; +} + +/** \internal copy n elements of the packet \a from to \a *to, (un-aligned store) */ +template +EIGEN_DEVICE_FUNC inline void pstoreu_partial(Scalar* to, const Packet& from, const Index n, const Index offset = 0) { + const Index packet_size = unpacket_traits::size; + eigen_assert(n + offset <= packet_size && "number of elements plus offset will write past end of packet"); + EIGEN_ALIGN_MAX Scalar elements[packet_size]; + pstore(elements, from); + for (Index i = 0; i < numext::mini(n, packet_size - offset); i++) { + to[i] = elements[i + offset]; + } +} /** \internal copy the packet \a from to \a *to, (un-aligned store with a mask) * There is no generic implementation. We only have implementations for specialized * cases. Generic case should not be called. */ -template -EIGEN_DEVICE_FUNC inline -typename enable_if::masked_store_available, void>::type -pstoreu(Scalar* to, const Packet& from, typename unpacket_traits::mask_t umask); +template +EIGEN_DEVICE_FUNC inline std::enable_if_t::masked_store_available, void> pstoreu( + Scalar* to, const Packet& from, typename unpacket_traits::mask_t umask); - template EIGEN_DEVICE_FUNC inline Packet pgather(const Scalar* from, Index /*stride*/) - { return ploadu(from); } +template +EIGEN_DEVICE_FUNC inline Packet pgather(const Scalar* from, Index /*stride*/) { + return ploadu(from); +} - template EIGEN_DEVICE_FUNC inline void pscatter(Scalar* to, const Packet& from, Index /*stride*/) - { pstore(to, from); } +template +EIGEN_DEVICE_FUNC inline Packet pgather_partial(const Scalar* from, Index stride, const Index n) { + const Index packet_size = unpacket_traits::size; + EIGEN_ALIGN_MAX Scalar elements[packet_size] = {Scalar(0)}; + for (Index i = 0; i < numext::mini(n, packet_size); i++) { + elements[i] = from[i * stride]; + } + return pload(elements); +} + +template +EIGEN_DEVICE_FUNC inline void pscatter(Scalar* to, const Packet& from, Index /*stride*/) { + pstore(to, from); +} + +template +EIGEN_DEVICE_FUNC inline void pscatter_partial(Scalar* to, const Packet& from, Index stride, const Index n) { + const Index packet_size = unpacket_traits::size; + EIGEN_ALIGN_MAX Scalar elements[packet_size]; + pstore(elements, from); + for (Index i = 0; i < numext::mini(n, packet_size); i++) { + to[i * stride] = elements[i]; + } +} /** \internal tries to do cache prefetching of \a addr */ -template EIGEN_DEVICE_FUNC inline void prefetch(const Scalar* addr) -{ +template +EIGEN_DEVICE_FUNC inline void prefetch(const Scalar* addr) { #if defined(EIGEN_HIP_DEVICE_COMPILE) // do nothing #elif defined(EIGEN_CUDA_ARCH) @@ -734,135 +987,227 @@ template EIGEN_DEVICE_FUNC inline void prefetch(const Scalar* a } /** \internal \returns the reversed elements of \a a*/ -template EIGEN_DEVICE_FUNC inline Packet preverse(const Packet& a) -{ return a; } +template +EIGEN_DEVICE_FUNC inline Packet preverse(const Packet& a) { + return a; +} /** \internal \returns \a a with real and imaginary part flipped (for complex type only) */ -template EIGEN_DEVICE_FUNC inline Packet pcplxflip(const Packet& a) -{ - return Packet(numext::imag(a),numext::real(a)); +template +EIGEN_DEVICE_FUNC inline Packet pcplxflip(const Packet& a) { + return Packet(numext::imag(a), numext::real(a)); } /************************** -* Special math functions -***************************/ + * Special math functions + ***************************/ /** \internal \returns the sine of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet psin(const Packet& a) { EIGEN_USING_STD(sin); return sin(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet psin(const Packet& a) { + EIGEN_USING_STD(sin); + return sin(a); +} /** \internal \returns the cosine of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet pcos(const Packet& a) { EIGEN_USING_STD(cos); return cos(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet pcos(const Packet& a) { + EIGEN_USING_STD(cos); + return cos(a); +} /** \internal \returns the tan of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet ptan(const Packet& a) { EIGEN_USING_STD(tan); return tan(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet ptan(const Packet& a) { + EIGEN_USING_STD(tan); + return tan(a); +} /** \internal \returns the arc sine of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet pasin(const Packet& a) { EIGEN_USING_STD(asin); return asin(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet pasin(const Packet& a) { + EIGEN_USING_STD(asin); + return asin(a); +} /** \internal \returns the arc cosine of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet pacos(const Packet& a) { EIGEN_USING_STD(acos); return acos(a); } - -/** \internal \returns the arc tangent of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet patan(const Packet& a) { EIGEN_USING_STD(atan); return atan(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet pacos(const Packet& a) { + EIGEN_USING_STD(acos); + return acos(a); +} /** \internal \returns the hyperbolic sine of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet psinh(const Packet& a) { EIGEN_USING_STD(sinh); return sinh(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet psinh(const Packet& a) { + EIGEN_USING_STD(sinh); + return sinh(a); +} /** \internal \returns the hyperbolic cosine of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet pcosh(const Packet& a) { EIGEN_USING_STD(cosh); return cosh(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet pcosh(const Packet& a) { + EIGEN_USING_STD(cosh); + return cosh(a); +} + +/** \internal \returns the arc tangent of \a a (coeff-wise) */ +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet patan(const Packet& a) { + EIGEN_USING_STD(atan); + return atan(a); +} /** \internal \returns the hyperbolic tan of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet ptanh(const Packet& a) { EIGEN_USING_STD(tanh); return tanh(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet ptanh(const Packet& a) { + EIGEN_USING_STD(tanh); + return tanh(a); +} + +/** \internal \returns the arc tangent of \a a (coeff-wise) */ +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet patanh(const Packet& a) { + EIGEN_USING_STD(atanh); + return atanh(a); +} /** \internal \returns the exp of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet pexp(const Packet& a) { EIGEN_USING_STD(exp); return exp(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet pexp(const Packet& a) { + EIGEN_USING_STD(exp); + return exp(a); +} /** \internal \returns the expm1 of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet pexpm1(const Packet& a) { return numext::expm1(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet pexpm1(const Packet& a) { + return numext::expm1(a); +} /** \internal \returns the log of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet plog(const Packet& a) { EIGEN_USING_STD(log); return log(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet plog(const Packet& a) { + EIGEN_USING_STD(log); + return log(a); +} /** \internal \returns the log1p of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet plog1p(const Packet& a) { return numext::log1p(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet plog1p(const Packet& a) { + return numext::log1p(a); +} /** \internal \returns the log10 of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet plog10(const Packet& a) { EIGEN_USING_STD(log10); return log10(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet plog10(const Packet& a) { + EIGEN_USING_STD(log10); + return log10(a); +} /** \internal \returns the log10 of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet plog2(const Packet& a) { - typedef typename internal::unpacket_traits::type Scalar; - return pmul(pset1(Scalar(EIGEN_LOG2E)), plog(a)); +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet plog2(const Packet& a) { + using Scalar = typename internal::unpacket_traits::type; + using RealScalar = typename NumTraits::Real; + return pmul(pset1(Scalar(RealScalar(EIGEN_LOG2E))), plog(a)); } /** \internal \returns the square-root of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet psqrt(const Packet& a) { return numext::sqrt(a); } +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet psqrt(const Packet& a) { + return numext::sqrt(a); +} -/** \internal \returns the reciprocal square-root of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet prsqrt(const Packet& a) { - typedef typename internal::unpacket_traits::type Scalar; - return pdiv(pset1(Scalar(1)), psqrt(a)); +/** \internal \returns the cube-root of \a a (coeff-wise) */ +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet pcbrt(const Packet& a) { + return numext::cbrt(a); } +template ::value, + bool IsInteger = NumTraits::type>::IsInteger> +struct nearest_integer_packetop_impl { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_floor(const Packet& x) { return numext::floor(x); } + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_ceil(const Packet& x) { return numext::ceil(x); } + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_rint(const Packet& x) { return numext::rint(x); } + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_round(const Packet& x) { return numext::round(x); } + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet run_trunc(const Packet& x) { return numext::trunc(x); } +}; + /** \internal \returns the rounded value of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet pround(const Packet& a) { using numext::round; return round(a); } +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet pround(const Packet& a) { + return nearest_integer_packetop_impl::run_round(a); +} /** \internal \returns the floor of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet pfloor(const Packet& a) { using numext::floor; return floor(a); } +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet pfloor(const Packet& a) { + return nearest_integer_packetop_impl::run_floor(a); +} /** \internal \returns the rounded value of \a a (coeff-wise) with current * rounding mode */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet print(const Packet& a) { using numext::rint; return rint(a); } +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet print(const Packet& a) { + return nearest_integer_packetop_impl::run_rint(a); +} /** \internal \returns the ceil of \a a (coeff-wise) */ -template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS -Packet pceil(const Packet& a) { using numext::ceil; return ceil(a); } +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet pceil(const Packet& a) { + return nearest_integer_packetop_impl::run_ceil(a); +} + +/** \internal \returns the truncation of \a a (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet ptrunc(const Packet& a) { + return nearest_integer_packetop_impl::run_trunc(a); +} + +template +struct psign_impl { + static EIGEN_DEVICE_FUNC inline Packet run(const Packet& a) { return numext::sign(a); } +}; + +/** \internal \returns the sign of \a a (coeff-wise) */ +template +EIGEN_DEVICE_FUNC inline Packet psign(const Packet& a) { + return psign_impl::run(a); +} + +template <> +EIGEN_DEVICE_FUNC inline bool psign(const bool& a) { + return a; +} /** \internal \returns the first element of a packet */ -template -EIGEN_DEVICE_FUNC inline typename unpacket_traits::type -pfirst(const Packet& a) -{ return a; } +template +EIGEN_DEVICE_FUNC inline typename unpacket_traits::type pfirst(const Packet& a) { + return a; +} /** \internal \returns the sum of the elements of upper and lower half of \a a if \a a is larger than 4. - * For a packet {a0, a1, a2, a3, a4, a5, a6, a7}, it returns a half packet {a0+a4, a1+a5, a2+a6, a3+a7} - * For packet-size smaller or equal to 4, this boils down to a noop. - */ -template -EIGEN_DEVICE_FUNC inline typename conditional<(unpacket_traits::size%8)==0,typename unpacket_traits::half,Packet>::type -predux_half_dowto4(const Packet& a) -{ return a; } + * For a packet {a0, a1, a2, a3, a4, a5, a6, a7}, it returns a half packet {a0+a4, a1+a5, a2+a6, a3+a7} + * For packet-size smaller or equal to 4, this boils down to a noop. + */ +template +EIGEN_DEVICE_FUNC inline std::conditional_t<(unpacket_traits::size % 8) == 0, + typename unpacket_traits::half, Packet> +predux_half_dowto4(const Packet& a) { + return a; +} // Slow generic implementation of Packet reduction. template -EIGEN_DEVICE_FUNC inline typename unpacket_traits::type -predux_helper(const Packet& a, Op op) { +EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_helper(const Packet& a, Op op) { typedef typename unpacket_traits::type Scalar; const size_t n = unpacket_traits::size; EIGEN_ALIGN_TO_BOUNDARY(sizeof(Packet)) Scalar elements[n]; pstoreu(elements, a); - for(size_t k = n / 2; k > 0; k /= 2) { - for(size_t i = 0; i < k; ++i) { + for (size_t k = n / 2; k > 0; k /= 2) { + for (size_t i = 0; i < k; ++i) { elements[i] = op(elements[i], elements[i + k]); } } @@ -870,65 +1215,58 @@ predux_helper(const Packet& a, Op op) { } /** \internal \returns the sum of the elements of \a a*/ -template -EIGEN_DEVICE_FUNC inline typename unpacket_traits::type -predux(const Packet& a) -{ +template +EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux(const Packet& a) { return a; } /** \internal \returns the product of the elements of \a a */ template -EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_mul( - const Packet& a) { - typedef typename unpacket_traits::type Scalar; +EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_mul(const Packet& a) { + typedef typename unpacket_traits::type Scalar; return predux_helper(a, EIGEN_BINARY_OP_NAN_PROPAGATION(Scalar, (pmul))); } /** \internal \returns the min of the elements of \a a */ template -EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_min( - const Packet &a) { - typedef typename unpacket_traits::type Scalar; +EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_min(const Packet& a) { + typedef typename unpacket_traits::type Scalar; return predux_helper(a, EIGEN_BINARY_OP_NAN_PROPAGATION(Scalar, (pmin))); } template -EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_min( - const Packet& a) { - typedef typename unpacket_traits::type Scalar; +EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_min(const Packet& a) { + typedef typename unpacket_traits::type Scalar; return predux_helper(a, EIGEN_BINARY_OP_NAN_PROPAGATION(Scalar, (pmin))); } /** \internal \returns the min of the elements of \a a */ template -EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_max( - const Packet &a) { - typedef typename unpacket_traits::type Scalar; +EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_max(const Packet& a) { + typedef typename unpacket_traits::type Scalar; return predux_helper(a, EIGEN_BINARY_OP_NAN_PROPAGATION(Scalar, (pmax))); } template -EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_max( - const Packet& a) { - typedef typename unpacket_traits::type Scalar; +EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_max(const Packet& a) { + typedef typename unpacket_traits::type Scalar; return predux_helper(a, EIGEN_BINARY_OP_NAN_PROPAGATION(Scalar, (pmax))); } #undef EIGEN_BINARY_OP_NAN_PROPAGATION /** \internal \returns true if all coeffs of \a a means "true" - * It is supposed to be called on values returned by pcmp_*. - */ + * It is supposed to be called on values returned by pcmp_*. + */ // not needed yet // template EIGEN_DEVICE_FUNC inline bool predux_all(const Packet& a) // { return bool(a); } /** \internal \returns true if any coeffs of \a a means "true" - * It is supposed to be called on values returned by pcmp_*. - */ -template EIGEN_DEVICE_FUNC inline bool predux_any(const Packet& a) -{ + * It is supposed to be called on values returned by pcmp_*. + */ +template +EIGEN_DEVICE_FUNC inline bool predux_any(const Packet& a) { // Dirty but generic implementation where "true" is assumed to be non 0 and all the sames. // It is expected that "true" is either: // - Scalar(1) @@ -940,101 +1278,242 @@ template EIGEN_DEVICE_FUNC inline bool predux_any(const Packet& } /*************************************************************************** -* The following functions might not have to be overwritten for vectorized types -***************************************************************************/ - -/** \internal copy a packet with constant coefficient \a a (e.g., [a,a,a,a]) to \a *to. \a to must be 16 bytes aligned */ -// NOTE: this function must really be templated on the packet type (think about different packet types for the same scalar type) -template -inline void pstore1(typename unpacket_traits::type* to, const typename unpacket_traits::type& a) -{ - pstore(to, pset1(a)); -} + * The following functions might not have to be overwritten for vectorized types + ***************************************************************************/ +// FMA instructions. /** \internal \returns a * b + c (coeff-wise) */ -template EIGEN_DEVICE_FUNC inline Packet -pmadd(const Packet& a, - const Packet& b, - const Packet& c) -{ return padd(pmul(a, b),c); } +template +EIGEN_DEVICE_FUNC inline Packet pmadd(const Packet& a, const Packet& b, const Packet& c) { + return padd(pmul(a, b), c); +} + +/** \internal \returns a * b - c (coeff-wise) */ +template +EIGEN_DEVICE_FUNC inline Packet pmsub(const Packet& a, const Packet& b, const Packet& c) { + return psub(pmul(a, b), c); +} + +/** \internal \returns -(a * b) + c (coeff-wise) */ +template +EIGEN_DEVICE_FUNC inline Packet pnmadd(const Packet& a, const Packet& b, const Packet& c) { + return psub(c, pmul(a, b)); +} + +/** \internal \returns -((a * b + c) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC inline Packet pnmsub(const Packet& a, const Packet& b, const Packet& c) { + return pnegate(pmadd(a, b, c)); +} + +/** \internal copy a packet with constant coefficient \a a (e.g., [a,a,a,a]) to \a *to. \a to must be 16 bytes aligned + */ +// NOTE: this function must really be templated on the packet type (think about different packet types for the same +// scalar type) +template +inline void pstore1(typename unpacket_traits::type* to, const typename unpacket_traits::type& a) { + pstore(to, pset1(a)); +} /** \internal \returns a packet version of \a *from. - * The pointer \a from must be aligned on a \a Alignment bytes boundary. */ -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet ploadt(const typename unpacket_traits::type* from) -{ - if(Alignment >= unpacket_traits::alignment) + * The pointer \a from must be aligned on a \a Alignment bytes boundary. */ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet ploadt(const typename unpacket_traits::type* from) { + if (Alignment >= unpacket_traits::alignment) return pload(from); else return ploadu(from); } +/** \internal \returns n elements of a packet version of \a *from. + * The pointer \a from must be aligned on a \a Alignment bytes boundary. */ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet ploadt_partial(const typename unpacket_traits::type* from, + const Index n, const Index offset = 0) { + if (Alignment >= unpacket_traits::alignment) + return pload_partial(from, n, offset); + else + return ploadu_partial(from, n, offset); +} + /** \internal copy the packet \a from to \a *to. - * The pointer \a from must be aligned on a \a Alignment bytes boundary. */ -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void pstoret(Scalar* to, const Packet& from) -{ - if(Alignment >= unpacket_traits::alignment) + * The pointer \a from must be aligned on a \a Alignment bytes boundary. */ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void pstoret(Scalar* to, const Packet& from) { + if (Alignment >= unpacket_traits::alignment) pstore(to, from); else pstoreu(to, from); } +/** \internal copy n elements of the packet \a from to \a *to. + * The pointer \a from must be aligned on a \a Alignment bytes boundary. */ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void pstoret_partial(Scalar* to, const Packet& from, const Index n, + const Index offset = 0) { + if (Alignment >= unpacket_traits::alignment) + pstore_partial(to, from, n, offset); + else + pstoreu_partial(to, from, n, offset); +} + /** \internal \returns a packet version of \a *from. - * Unlike ploadt, ploadt_ro takes advantage of the read-only memory path on the - * hardware if available to speedup the loading of data that won't be modified - * by the current computation. - */ -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet ploadt_ro(const typename unpacket_traits::type* from) -{ + * Unlike ploadt, ploadt_ro takes advantage of the read-only memory path on the + * hardware if available to speedup the loading of data that won't be modified + * by the current computation. + */ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet ploadt_ro(const typename unpacket_traits::type* from) { return ploadt(from); } /*************************************************************************** -* Fast complex products (GCC generates a function call which is very slow) -***************************************************************************/ + * Fast complex products (GCC generates a function call which is very slow) + ***************************************************************************/ // Eigen+CUDA does not support complexes. #if !defined(EIGEN_GPUCC) -template<> inline std::complex pmul(const std::complex& a, const std::complex& b) -{ return std::complex(a.real()*b.real() - a.imag()*b.imag(), a.imag()*b.real() + a.real()*b.imag()); } +template <> +inline std::complex pmul(const std::complex& a, const std::complex& b) { + return std::complex(a.real() * b.real() - a.imag() * b.imag(), a.imag() * b.real() + a.real() * b.imag()); +} -template<> inline std::complex pmul(const std::complex& a, const std::complex& b) -{ return std::complex(a.real()*b.real() - a.imag()*b.imag(), a.imag()*b.real() + a.real()*b.imag()); } +template <> +inline std::complex pmul(const std::complex& a, const std::complex& b) { + return std::complex(a.real() * b.real() - a.imag() * b.imag(), a.imag() * b.real() + a.real() * b.imag()); +} #endif - /*************************************************************************** * PacketBlock, that is a collection of N packets where the number of words * in the packet is a multiple of N. -***************************************************************************/ -template ::size> struct PacketBlock { + ***************************************************************************/ +template ::size> +struct PacketBlock { Packet packet[N]; }; -template EIGEN_DEVICE_FUNC inline void -ptranspose(PacketBlock& /*kernel*/) { +template +EIGEN_DEVICE_FUNC inline void ptranspose(PacketBlock& /*kernel*/) { // Nothing to do in the scalar case, i.e. a 1x1 matrix. } /*************************************************************************** * Selector, i.e. vector of N boolean values used to select (i.e. blend) * words from 2 packets. -***************************************************************************/ -template struct Selector { + ***************************************************************************/ +template +struct Selector { bool select[N]; }; -template EIGEN_DEVICE_FUNC inline Packet -pblend(const Selector::size>& ifPacket, const Packet& thenPacket, const Packet& elsePacket) { +template +EIGEN_DEVICE_FUNC inline Packet pblend(const Selector::size>& ifPacket, + const Packet& thenPacket, const Packet& elsePacket) { return ifPacket.select[0] ? thenPacket : elsePacket; } -} // end namespace internal +/** \internal \returns 1 / a (coeff-wise) */ +template +EIGEN_DEVICE_FUNC inline Packet preciprocal(const Packet& a) { + using Scalar = typename unpacket_traits::type; + return pdiv(pset1(Scalar(1)), a); +} + +/** \internal \returns the reciprocal square-root of \a a (coeff-wise) */ +template +EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet prsqrt(const Packet& a) { + return preciprocal(psqrt(a)); +} + +template ::value, + bool IsInteger = NumTraits::type>::IsInteger> +struct psignbit_impl; +template +struct psignbit_impl { + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static constexpr Packet run(const Packet& a) { return numext::signbit(a); } +}; +template +struct psignbit_impl { + // generic implementation if not specialized in PacketMath.h + // slower than arithmetic shift + typedef typename unpacket_traits::type Scalar; + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static Packet run(const Packet& a) { + const Packet cst_pos_one = pset1(Scalar(1)); + const Packet cst_neg_one = pset1(Scalar(-1)); + return pcmp_eq(por(pand(a, cst_neg_one), cst_pos_one), cst_neg_one); + } +}; +template +struct psignbit_impl { + // generic implementation for integer packets + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static constexpr Packet run(const Packet& a) { return pcmp_lt(a, pzero(a)); } +}; +/** \internal \returns the sign bit of \a a as a bitmask*/ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE constexpr Packet psignbit(const Packet& a) { + return psignbit_impl::run(a); +} + +/** \internal \returns the 2-argument arc tangent of \a y and \a x (coeff-wise) */ +template ::value, int> = 0> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet patan2(const Packet& y, const Packet& x) { + return numext::atan2(y, x); +} + +/** \internal \returns the 2-argument arc tangent of \a y and \a x (coeff-wise) */ +template ::value, int> = 0> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet patan2(const Packet& y, const Packet& x) { + typedef typename internal::unpacket_traits::type Scalar; + + // See https://en.cppreference.com/w/cpp/numeric/math/atan2 + // for how corner cases are supposed to be handled according to the + // IEEE floating-point standard (IEC 60559). + const Packet kSignMask = pset1(-Scalar(0)); + const Packet kZero = pzero(x); + const Packet kOne = pset1(Scalar(1)); + const Packet kPi = pset1(Scalar(EIGEN_PI)); + + const Packet x_has_signbit = psignbit(x); + const Packet y_signmask = pand(y, kSignMask); + const Packet x_signmask = pand(x, kSignMask); + const Packet result_signmask = pxor(y_signmask, x_signmask); + const Packet shift = por(pand(x_has_signbit, kPi), y_signmask); + + const Packet x_and_y_are_same = pcmp_eq(pabs(x), pabs(y)); + const Packet x_and_y_are_zero = pcmp_eq(por(x, y), kZero); + + Packet arg = pdiv(y, x); + arg = pselect(x_and_y_are_same, por(kOne, result_signmask), arg); + arg = pselect(x_and_y_are_zero, result_signmask, arg); + + Packet result = patan(arg); + result = padd(result, shift); + return result; +} + +/** \internal \returns the argument of \a a as a complex number */ +template ::value, int> = 0> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet pcarg(const Packet& a) { + return Packet(numext::arg(a)); +} + +/** \internal \returns the argument of \a a as a complex number */ +template ::value, int> = 0> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet pcarg(const Packet& a) { + EIGEN_STATIC_ASSERT(NumTraits::type>::IsComplex, + THIS METHOD IS FOR COMPLEX TYPES ONLY) + using RealPacket = typename unpacket_traits::as_real; + // a // r i r i ... + RealPacket aflip = pcplxflip(a).v; // i r i r ... + RealPacket result = patan2(aflip, a.v); // atan2 crap atan2 crap ... + return (Packet)pand(result, peven_mask(result)); // atan2 0 atan2 0 ... +} + +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_GENERIC_PACKET_MATH_H +#endif // EIGEN_GENERIC_PACKET_MATH_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/GlobalFunctions.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/GlobalFunctions.h index 629af94b994..3f147b8f6fb 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/GlobalFunctions.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/GlobalFunctions.h @@ -13,182 +13,217 @@ #ifdef EIGEN_PARSED_BY_DOXYGEN -#define EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(NAME,FUNCTOR,DOC_OP,DOC_DETAILS) \ - /** \returns an expression of the coefficient-wise DOC_OP of \a x - - DOC_DETAILS - - \sa Math functions, class CwiseUnaryOp - */ \ - template \ - inline const Eigen::CwiseUnaryOp, const Derived> \ - NAME(const Eigen::ArrayBase& x); +#define EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(NAME, FUNCTOR, DOC_OP, DOC_DETAILS) \ + /** \returns an expression of the coefficient-wise DOC_OP of \a x \ + \ \ + DOC_DETAILS \ + \ \ + \sa Math functions, class CwiseUnaryOp \ + */ \ + template \ + inline const Eigen::CwiseUnaryOp, const Derived> NAME( \ + const Eigen::ArrayBase& x); #else -#define EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(NAME,FUNCTOR,DOC_OP,DOC_DETAILS) \ - template \ - inline const Eigen::CwiseUnaryOp, const Derived> \ - (NAME)(const Eigen::ArrayBase& x) { \ +#define EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(NAME, FUNCTOR, DOC_OP, DOC_DETAILS) \ + template \ + inline const Eigen::CwiseUnaryOp, const Derived>(NAME)( \ + const Eigen::ArrayBase& x) { \ return Eigen::CwiseUnaryOp, const Derived>(x.derived()); \ } -#endif // EIGEN_PARSED_BY_DOXYGEN +#endif // EIGEN_PARSED_BY_DOXYGEN -#define EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(NAME,FUNCTOR) \ - \ - template \ - struct NAME##_retval > \ - { \ +#define EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(NAME, FUNCTOR) \ + \ + template \ + struct NAME##_retval > { \ typedef const Eigen::CwiseUnaryOp, const Derived> type; \ - }; \ - template \ - struct NAME##_impl > \ - { \ - static inline typename NAME##_retval >::type run(const Eigen::ArrayBase& x) \ - { \ - return typename NAME##_retval >::type(x.derived()); \ - } \ + }; \ + template \ + struct NAME##_impl > { \ + static inline typename NAME##_retval >::type run(const Eigen::ArrayBase& x) { \ + return typename NAME##_retval >::type(x.derived()); \ + } \ }; -namespace Eigen -{ - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(real,scalar_real_op,real part,\sa ArrayBase::real) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(imag,scalar_imag_op,imaginary part,\sa ArrayBase::imag) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(conj,scalar_conjugate_op,complex conjugate,\sa ArrayBase::conjugate) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(inverse,scalar_inverse_op,inverse,\sa ArrayBase::inverse) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(sin,scalar_sin_op,sine,\sa ArrayBase::sin) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(cos,scalar_cos_op,cosine,\sa ArrayBase::cos) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(tan,scalar_tan_op,tangent,\sa ArrayBase::tan) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(atan,scalar_atan_op,arc-tangent,\sa ArrayBase::atan) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(asin,scalar_asin_op,arc-sine,\sa ArrayBase::asin) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(acos,scalar_acos_op,arc-consine,\sa ArrayBase::acos) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(sinh,scalar_sinh_op,hyperbolic sine,\sa ArrayBase::sinh) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(cosh,scalar_cosh_op,hyperbolic cosine,\sa ArrayBase::cosh) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(tanh,scalar_tanh_op,hyperbolic tangent,\sa ArrayBase::tanh) -#if EIGEN_HAS_CXX11_MATH - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(asinh,scalar_asinh_op,inverse hyperbolic sine,\sa ArrayBase::asinh) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(acosh,scalar_acosh_op,inverse hyperbolic cosine,\sa ArrayBase::acosh) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(atanh,scalar_atanh_op,inverse hyperbolic tangent,\sa ArrayBase::atanh) -#endif - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(logistic,scalar_logistic_op,logistic function,\sa ArrayBase::logistic) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(lgamma,scalar_lgamma_op,natural logarithm of the gamma function,\sa ArrayBase::lgamma) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(digamma,scalar_digamma_op,derivative of lgamma,\sa ArrayBase::digamma) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(erf,scalar_erf_op,error function,\sa ArrayBase::erf) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(erfc,scalar_erfc_op,complement error function,\sa ArrayBase::erfc) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(ndtri,scalar_ndtri_op,inverse normal distribution function,\sa ArrayBase::ndtri) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(exp,scalar_exp_op,exponential,\sa ArrayBase::exp) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(expm1,scalar_expm1_op,exponential of a value minus 1,\sa ArrayBase::expm1) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(log,scalar_log_op,natural logarithm,\sa Eigen::log10 DOXCOMMA ArrayBase::log) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(log1p,scalar_log1p_op,natural logarithm of 1 plus the value,\sa ArrayBase::log1p) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(log10,scalar_log10_op,base 10 logarithm,\sa Eigen::log DOXCOMMA ArrayBase::log10) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(log2,scalar_log2_op,base 2 logarithm,\sa Eigen::log DOXCOMMA ArrayBase::log2) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(abs,scalar_abs_op,absolute value,\sa ArrayBase::abs DOXCOMMA MatrixBase::cwiseAbs) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(abs2,scalar_abs2_op,squared absolute value,\sa ArrayBase::abs2 DOXCOMMA MatrixBase::cwiseAbs2) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(arg,scalar_arg_op,complex argument,\sa ArrayBase::arg DOXCOMMA MatrixBase::cwiseArg) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(sqrt,scalar_sqrt_op,square root,\sa ArrayBase::sqrt DOXCOMMA MatrixBase::cwiseSqrt) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(rsqrt,scalar_rsqrt_op,reciprocal square root,\sa ArrayBase::rsqrt) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(square,scalar_square_op,square (power 2),\sa Eigen::abs2 DOXCOMMA Eigen::pow DOXCOMMA ArrayBase::square) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(cube,scalar_cube_op,cube (power 3),\sa Eigen::pow DOXCOMMA ArrayBase::cube) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(rint,scalar_rint_op,nearest integer,\sa Eigen::floor DOXCOMMA Eigen::ceil DOXCOMMA ArrayBase::round) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(round,scalar_round_op,nearest integer,\sa Eigen::floor DOXCOMMA Eigen::ceil DOXCOMMA ArrayBase::round) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(floor,scalar_floor_op,nearest integer not greater than the giben value,\sa Eigen::ceil DOXCOMMA ArrayBase::floor) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(ceil,scalar_ceil_op,nearest integer not less than the giben value,\sa Eigen::floor DOXCOMMA ArrayBase::ceil) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(isnan,scalar_isnan_op,not-a-number test,\sa Eigen::isinf DOXCOMMA Eigen::isfinite DOXCOMMA ArrayBase::isnan) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(isinf,scalar_isinf_op,infinite value test,\sa Eigen::isnan DOXCOMMA Eigen::isfinite DOXCOMMA ArrayBase::isinf) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(isfinite,scalar_isfinite_op,finite value test,\sa Eigen::isinf DOXCOMMA Eigen::isnan DOXCOMMA ArrayBase::isfinite) - EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(sign,scalar_sign_op,sign (or 0),\sa ArrayBase::sign) - - /** \returns an expression of the coefficient-wise power of \a x to the given constant \a exponent. - * - * \tparam ScalarExponent is the scalar type of \a exponent. It must be compatible with the scalar type of the given expression (\c Derived::Scalar). - * - * \sa ArrayBase::pow() - * - * \relates ArrayBase - */ +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(real, scalar_real_op, real part,\sa ArrayBase::real) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(imag, scalar_imag_op, imaginary part,\sa ArrayBase::imag) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(conj, scalar_conjugate_op, complex conjugate,\sa ArrayBase::conjugate) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(inverse, scalar_inverse_op, inverse,\sa ArrayBase::inverse) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(sin, scalar_sin_op, sine,\sa ArrayBase::sin) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(cos, scalar_cos_op, cosine,\sa ArrayBase::cos) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(tan, scalar_tan_op, tangent,\sa ArrayBase::tan) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(atan, scalar_atan_op, arc - tangent,\sa ArrayBase::atan) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(asin, scalar_asin_op, arc - sine,\sa ArrayBase::asin) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(acos, scalar_acos_op, arc - consine,\sa ArrayBase::acos) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(sinh, scalar_sinh_op, hyperbolic sine,\sa ArrayBase::sinh) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(cosh, scalar_cosh_op, hyperbolic cosine,\sa ArrayBase::cosh) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(tanh, scalar_tanh_op, hyperbolic tangent,\sa ArrayBase::tanh) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(asinh, scalar_asinh_op, inverse hyperbolic sine,\sa ArrayBase::asinh) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(acosh, scalar_acosh_op, inverse hyperbolic cosine,\sa ArrayBase::acosh) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(atanh, scalar_atanh_op, inverse hyperbolic tangent,\sa ArrayBase::atanh) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(logistic, scalar_logistic_op, logistic function,\sa ArrayBase::logistic) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(lgamma, scalar_lgamma_op, + natural logarithm of the gamma function,\sa ArrayBase::lgamma) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(digamma, scalar_digamma_op, derivative of lgamma,\sa ArrayBase::digamma) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(erf, scalar_erf_op, error function,\sa ArrayBase::erf) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(erfc, scalar_erfc_op, complement error function,\sa ArrayBase::erfc) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(ndtri, scalar_ndtri_op, inverse normal distribution function,\sa ArrayBase::ndtri) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(exp, scalar_exp_op, exponential,\sa ArrayBase::exp) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(expm1, scalar_expm1_op, exponential of a value minus 1,\sa ArrayBase::expm1) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(log, scalar_log_op, natural logarithm,\sa Eigen::log10 DOXCOMMA ArrayBase::log) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(log1p, scalar_log1p_op, natural logarithm of 1 plus the value,\sa ArrayBase::log1p) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(log10, scalar_log10_op, base 10 logarithm,\sa Eigen::log DOXCOMMA ArrayBase::log10) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(log2, scalar_log2_op, base 2 logarithm,\sa Eigen::log DOXCOMMA ArrayBase::log2) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(abs, scalar_abs_op, absolute value,\sa ArrayBase::abs DOXCOMMA MatrixBase::cwiseAbs) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(abs2, scalar_abs2_op, + squared absolute value,\sa ArrayBase::abs2 DOXCOMMA MatrixBase::cwiseAbs2) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(arg, scalar_arg_op, complex argument,\sa ArrayBase::arg DOXCOMMA MatrixBase::cwiseArg) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(carg, scalar_carg_op, + complex argument, \sa ArrayBase::carg DOXCOMMA MatrixBase::cwiseCArg) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(sqrt, scalar_sqrt_op, square root,\sa ArrayBase::sqrt DOXCOMMA MatrixBase::cwiseSqrt) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(cbrt, scalar_cbrt_op, cube root,\sa ArrayBase::cbrt DOXCOMMA MatrixBase::cwiseCbrt) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(rsqrt, scalar_rsqrt_op, reciprocal square root,\sa ArrayBase::rsqrt) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(square, scalar_square_op, + square(power 2),\sa Eigen::abs2 DOXCOMMA Eigen::pow DOXCOMMA ArrayBase::square) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(cube, scalar_cube_op, cube(power 3),\sa Eigen::pow DOXCOMMA ArrayBase::cube) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(rint, scalar_rint_op, + nearest integer,\sa Eigen::floor DOXCOMMA Eigen::ceil DOXCOMMA ArrayBase::round) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(round, scalar_round_op, + nearest integer,\sa Eigen::floor DOXCOMMA Eigen::ceil DOXCOMMA ArrayBase::round) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY( + floor, scalar_floor_op, nearest integer not greater than the given value,\sa Eigen::ceil DOXCOMMA ArrayBase::floor) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY( + ceil, scalar_ceil_op, nearest integer not less than the given value,\sa Eigen::floor DOXCOMMA ArrayBase::ceil) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(trunc, scalar_trunc_op, + nearest integer not greater in magnitude than the given value,\sa Eigen::trunc DOXCOMMA + ArrayBase::trunc) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY( + isnan, scalar_isnan_op, not -a - number test,\sa Eigen::isinf DOXCOMMA Eigen::isfinite DOXCOMMA ArrayBase::isnan) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY( + isinf, scalar_isinf_op, infinite value test,\sa Eigen::isnan DOXCOMMA Eigen::isfinite DOXCOMMA ArrayBase::isinf) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(isfinite, scalar_isfinite_op, + finite value test,\sa Eigen::isinf DOXCOMMA Eigen::isnan DOXCOMMA ArrayBase::isfinite) +EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(sign, scalar_sign_op, sign(or 0),\sa ArrayBase::sign) + +template +using GlobalUnaryPowReturnType = std::enable_if_t< + !internal::is_arithmetic::Real>::value && + internal::is_arithmetic::Real>::value, + CwiseUnaryOp, const Derived> >; + +/** \returns an expression of the coefficient-wise power of \a x to the given constant \a exponent. + * + * \tparam ScalarExponent is the scalar type of \a exponent. It must be compatible with the scalar type of the given + * expression (\c Derived::Scalar). + * + * \sa ArrayBase::pow() + * + * \relates ArrayBase + */ #ifdef EIGEN_PARSED_BY_DOXYGEN - template - inline const CwiseBinaryOp,Derived,Constant > - pow(const Eigen::ArrayBase& x, const ScalarExponent& exponent); +template +EIGEN_DEVICE_FUNC inline const GlobalUnaryPowReturnType pow(const Eigen::ArrayBase& x, + const ScalarExponent& exponent); #else - template - EIGEN_DEVICE_FUNC inline - EIGEN_MSVC10_WORKAROUND_BINARYOP_RETURN_TYPE( - const EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(Derived,typename internal::promote_scalar_arg::type,pow)) - pow(const Eigen::ArrayBase& x, const ScalarExponent& exponent) - { - typedef typename internal::promote_scalar_arg::type PromotedExponent; - return EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(Derived,PromotedExponent,pow)(x.derived(), - typename internal::plain_constant_type::type(x.derived().rows(), x.derived().cols(), internal::scalar_constant_op(exponent))); - } +template +EIGEN_DEVICE_FUNC inline const GlobalUnaryPowReturnType pow(const Eigen::ArrayBase& x, + const ScalarExponent& exponent) { + return GlobalUnaryPowReturnType( + x.derived(), internal::scalar_unary_pow_op(exponent)); +} #endif - /** \returns an expression of the coefficient-wise power of \a x to the given array of \a exponents. - * - * This function computes the coefficient-wise power. - * - * Example: \include Cwise_array_power_array.cpp - * Output: \verbinclude Cwise_array_power_array.out - * - * \sa ArrayBase::pow() - * - * \relates ArrayBase - */ - template - inline const Eigen::CwiseBinaryOp, const Derived, const ExponentDerived> - pow(const Eigen::ArrayBase& x, const Eigen::ArrayBase& exponents) - { - return Eigen::CwiseBinaryOp, const Derived, const ExponentDerived>( - x.derived(), - exponents.derived() - ); - } +/** \returns an expression of the coefficient-wise power of \a x to the given array of \a exponents. + * + * This function computes the coefficient-wise power. + * + * Example: \include Cwise_array_power_array.cpp + * Output: \verbinclude Cwise_array_power_array.out + * + * \sa ArrayBase::pow() + * + * \relates ArrayBase + */ +template +inline const Eigen::CwiseBinaryOp< + Eigen::internal::scalar_pow_op, const Derived, + const ExponentDerived> +pow(const Eigen::ArrayBase& x, const Eigen::ArrayBase& exponents) { + return Eigen::CwiseBinaryOp< + Eigen::internal::scalar_pow_op, const Derived, + const ExponentDerived>(x.derived(), exponents.derived()); +} - /** \returns an expression of the coefficient-wise power of the scalar \a x to the given array of \a exponents. - * - * This function computes the coefficient-wise power between a scalar and an array of exponents. - * - * \tparam Scalar is the scalar type of \a x. It must be compatible with the scalar type of the given array expression (\c Derived::Scalar). - * - * Example: \include Cwise_scalar_power_array.cpp - * Output: \verbinclude Cwise_scalar_power_array.out - * - * \sa ArrayBase::pow() - * - * \relates ArrayBase - */ +/** \returns an expression of the coefficient-wise power of the scalar \a x to the given array of \a exponents. + * + * This function computes the coefficient-wise power between a scalar and an array of exponents. + * + * \tparam Scalar is the scalar type of \a x. It must be compatible with the scalar type of the given array expression + * (\c Derived::Scalar). + * + * Example: \include Cwise_scalar_power_array.cpp + * Output: \verbinclude Cwise_scalar_power_array.out + * + * \sa ArrayBase::pow() + * + * \relates ArrayBase + */ #ifdef EIGEN_PARSED_BY_DOXYGEN - template - inline const CwiseBinaryOp,Constant,Derived> - pow(const Scalar& x,const Eigen::ArrayBase& x); +template +inline const CwiseBinaryOp, Constant, Derived> pow( + const Scalar& x, const Eigen::ArrayBase& x); #else - template - EIGEN_DEVICE_FUNC inline - EIGEN_MSVC10_WORKAROUND_BINARYOP_RETURN_TYPE( - const EIGEN_SCALAR_BINARYOP_EXPR_RETURN_TYPE(typename internal::promote_scalar_arg::type,Derived,pow)) - pow(const Scalar& x, const Eigen::ArrayBase& exponents) { - typedef typename internal::promote_scalar_arg::type PromotedScalar; - return EIGEN_SCALAR_BINARYOP_EXPR_RETURN_TYPE(PromotedScalar,Derived,pow)( - typename internal::plain_constant_type::type(exponents.derived().rows(), exponents.derived().cols(), internal::scalar_constant_op(x)), exponents.derived()); - } +template +EIGEN_DEVICE_FUNC inline const EIGEN_SCALAR_BINARYOP_EXPR_RETURN_TYPE( + typename internal::promote_scalar_arg::type, + Derived, pow) pow(const Scalar& x, const Eigen::ArrayBase& exponents) { + typedef + typename internal::promote_scalar_arg::type + PromotedScalar; + return EIGEN_SCALAR_BINARYOP_EXPR_RETURN_TYPE(PromotedScalar, Derived, pow)( + typename internal::plain_constant_type::type( + exponents.derived().rows(), exponents.derived().cols(), internal::scalar_constant_op(x)), + exponents.derived()); +} #endif - - namespace internal - { - EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(real,scalar_real_op) - EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(imag,scalar_imag_op) - EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(abs2,scalar_abs2_op) - } +/** \returns an expression of the coefficient-wise atan2(\a x, \a y). \a x and \a y must be of the same type. + * + * This function computes the coefficient-wise atan2(). + * + * \sa ArrayBase::atan2() + * + * \relates ArrayBase + */ +template +inline const std::enable_if_t< + std::is_same::value, + Eigen::CwiseBinaryOp, + const LhsDerived, const RhsDerived> > +atan2(const Eigen::ArrayBase& x, const Eigen::ArrayBase& exponents) { + return Eigen::CwiseBinaryOp< + Eigen::internal::scalar_atan2_op, const LhsDerived, + const RhsDerived>(x.derived(), exponents.derived()); } -// TODO: cleanly disable those functions that are not supported on Array (numext::real_ref, internal::random, internal::isApprox...) +namespace internal { +EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(real, scalar_real_op) +EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(imag, scalar_imag_op) +EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(abs2, scalar_abs2_op) +} // namespace internal +} // namespace Eigen + +// TODO: cleanly disable those functions that are not supported on Array (numext::real_ref, internal::random, +// internal::isApprox...) -#endif // EIGEN_GLOBAL_FUNCTIONS_H +#endif // EIGEN_GLOBAL_FUNCTIONS_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/IO.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/IO.h index e81c3152168..ca5f247ede0 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/IO.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/IO.h @@ -11,60 +11,65 @@ #ifndef EIGEN_IO_H #define EIGEN_IO_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { enum { DontAlignCols = 1 }; -enum { StreamPrecision = -1, - FullPrecision = -2 }; +enum { StreamPrecision = -1, FullPrecision = -2 }; namespace internal { -template -std::ostream & print_matrix(std::ostream & s, const Derived& _m, const IOFormat& fmt); +template +std::ostream& print_matrix(std::ostream& s, const Derived& _m, const IOFormat& fmt); } /** \class IOFormat - * \ingroup Core_Module - * - * \brief Stores a set of parameters controlling the way matrices are printed - * - * List of available parameters: - * - \b precision number of digits for floating point values, or one of the special constants \c StreamPrecision and \c FullPrecision. - * The default is the special value \c StreamPrecision which means to use the - * stream's own precision setting, as set for instance using \c cout.precision(3). The other special value - * \c FullPrecision means that the number of digits will be computed to match the full precision of each floating-point - * type. - * - \b flags an OR-ed combination of flags, the default value is 0, the only currently available flag is \c DontAlignCols which - * allows to disable the alignment of columns, resulting in faster code. - * - \b coeffSeparator string printed between two coefficients of the same row - * - \b rowSeparator string printed between two rows - * - \b rowPrefix string printed at the beginning of each row - * - \b rowSuffix string printed at the end of each row - * - \b matPrefix string printed at the beginning of the matrix - * - \b matSuffix string printed at the end of the matrix - * - \b fill character printed to fill the empty space in aligned columns - * - * Example: \include IOFormat.cpp - * Output: \verbinclude IOFormat.out - * - * \sa DenseBase::format(), class WithFormat - */ -struct IOFormat -{ + * \ingroup Core_Module + * + * \brief Stores a set of parameters controlling the way matrices are printed + * + * List of available parameters: + * - \b precision number of digits for floating point values, or one of the special constants \c StreamPrecision and \c + * FullPrecision. The default is the special value \c StreamPrecision which means to use the stream's own precision + * setting, as set for instance using \c cout.precision(3). The other special value \c FullPrecision means that the + * number of digits will be computed to match the full precision of each floating-point type. + * - \b flags an OR-ed combination of flags, the default value is 0, the only currently available flag is \c + * DontAlignCols which allows to disable the alignment of columns, resulting in faster code. + * - \b coeffSeparator string printed between two coefficients of the same row + * - \b rowSeparator string printed between two rows + * - \b rowPrefix string printed at the beginning of each row + * - \b rowSuffix string printed at the end of each row + * - \b matPrefix string printed at the beginning of the matrix + * - \b matSuffix string printed at the end of the matrix + * - \b fill character printed to fill the empty space in aligned columns + * + * Example: \include IOFormat.cpp + * Output: \verbinclude IOFormat.out + * + * \sa DenseBase::format(), class WithFormat + */ +struct IOFormat { /** Default constructor, see class IOFormat for the meaning of the parameters */ - IOFormat(int _precision = StreamPrecision, int _flags = 0, - const std::string& _coeffSeparator = " ", - const std::string& _rowSeparator = "\n", const std::string& _rowPrefix="", const std::string& _rowSuffix="", - const std::string& _matPrefix="", const std::string& _matSuffix="", const char _fill=' ') - : matPrefix(_matPrefix), matSuffix(_matSuffix), rowPrefix(_rowPrefix), rowSuffix(_rowSuffix), rowSeparator(_rowSeparator), - rowSpacer(""), coeffSeparator(_coeffSeparator), fill(_fill), precision(_precision), flags(_flags) - { + IOFormat(int _precision = StreamPrecision, int _flags = 0, const std::string& _coeffSeparator = " ", + const std::string& _rowSeparator = "\n", const std::string& _rowPrefix = "", + const std::string& _rowSuffix = "", const std::string& _matPrefix = "", const std::string& _matSuffix = "", + const char _fill = ' ') + : matPrefix(_matPrefix), + matSuffix(_matSuffix), + rowPrefix(_rowPrefix), + rowSuffix(_rowSuffix), + rowSeparator(_rowSeparator), + rowSpacer(""), + coeffSeparator(_coeffSeparator), + fill(_fill), + precision(_precision), + flags(_flags) { // TODO check if rowPrefix, rowSuffix or rowSeparator contains a newline // don't add rowSpacer if columns are not to be aligned - if((flags & DontAlignCols)) - return; - int i = int(matSuffix.length())-1; - while (i>=0 && matSuffix[i]!='\n') - { + if ((flags & DontAlignCols)) return; + int i = int(matSuffix.length()) - 1; + while (i >= 0 && matSuffix[i] != '\n') { rowSpacer += ' '; i--; } @@ -78,181 +83,151 @@ struct IOFormat }; /** \class WithFormat - * \ingroup Core_Module - * - * \brief Pseudo expression providing matrix output with given format - * - * \tparam ExpressionType the type of the object on which IO stream operations are performed - * - * This class represents an expression with stream operators controlled by a given IOFormat. - * It is the return type of DenseBase::format() - * and most of the time this is the only way it is used. - * - * See class IOFormat for some examples. - * - * \sa DenseBase::format(), class IOFormat - */ -template -class WithFormat -{ - public: - - WithFormat(const ExpressionType& matrix, const IOFormat& format) - : m_matrix(matrix), m_format(format) - {} - - friend std::ostream & operator << (std::ostream & s, const WithFormat& wf) - { - return internal::print_matrix(s, wf.m_matrix.eval(), wf.m_format); - } + * \ingroup Core_Module + * + * \brief Pseudo expression providing matrix output with given format + * + * \tparam ExpressionType the type of the object on which IO stream operations are performed + * + * This class represents an expression with stream operators controlled by a given IOFormat. + * It is the return type of DenseBase::format() + * and most of the time this is the only way it is used. + * + * See class IOFormat for some examples. + * + * \sa DenseBase::format(), class IOFormat + */ +template +class WithFormat { + public: + WithFormat(const ExpressionType& matrix, const IOFormat& format) : m_matrix(matrix), m_format(format) {} + + friend std::ostream& operator<<(std::ostream& s, const WithFormat& wf) { + return internal::print_matrix(s, wf.m_matrix.eval(), wf.m_format); + } - protected: - typename ExpressionType::Nested m_matrix; - IOFormat m_format; + protected: + typename ExpressionType::Nested m_matrix; + IOFormat m_format; }; namespace internal { // NOTE: This helper is kept for backward compatibility with previous code specializing // this internal::significant_decimals_impl structure. In the future we should directly -// call digits10() which has been introduced in July 2016 in 3.3. -template -struct significant_decimals_impl -{ - static inline int run() - { - return NumTraits::digits10(); - } +// call max_digits10(). +template +struct significant_decimals_impl { + static inline int run() { return NumTraits::max_digits10(); } }; /** \internal - * print the matrix \a _m to the output stream \a s using the output format \a fmt */ -template -std::ostream & print_matrix(std::ostream & s, const Derived& _m, const IOFormat& fmt) -{ + * print the matrix \a _m to the output stream \a s using the output format \a fmt */ +template +std::ostream& print_matrix(std::ostream& s, const Derived& _m, const IOFormat& fmt) { using internal::is_same; - using internal::conditional; - if(_m.size() == 0) - { + if (_m.size() == 0) { s << fmt.matPrefix << fmt.matSuffix; return s; } - + typename Derived::Nested m = _m; typedef typename Derived::Scalar Scalar; - typedef typename - conditional< - is_same::value || - is_same::value || - is_same::value || - is_same::value, - int, - typename conditional< - is_same >::value || - is_same >::value || - is_same >::value || - is_same >::value, - std::complex, - const Scalar& - >::type - >::type PrintType; + typedef std::conditional_t::value || is_same::value || + is_same::value || is_same::value, + int, + std::conditional_t >::value || + is_same >::value || + is_same >::value || + is_same >::value, + std::complex, const Scalar&> > + PrintType; Index width = 0; std::streamsize explicit_precision; - if(fmt.precision == StreamPrecision) - { + if (fmt.precision == StreamPrecision) { explicit_precision = 0; - } - else if(fmt.precision == FullPrecision) - { - if (NumTraits::IsInteger) - { + } else if (fmt.precision == FullPrecision) { + if (NumTraits::IsInteger) { explicit_precision = 0; - } - else - { + } else { explicit_precision = significant_decimals_impl::run(); } - } - else - { + } else { explicit_precision = fmt.precision; } std::streamsize old_precision = 0; - if(explicit_precision) old_precision = s.precision(explicit_precision); + if (explicit_precision) old_precision = s.precision(explicit_precision); bool align_cols = !(fmt.flags & DontAlignCols); - if(align_cols) - { + if (align_cols) { // compute the largest width - for(Index j = 0; j < m.cols(); ++j) - for(Index i = 0; i < m.rows(); ++i) - { + for (Index j = 0; j < m.cols(); ++j) + for (Index i = 0; i < m.rows(); ++i) { std::stringstream sstr; sstr.copyfmt(s); - sstr << static_cast(m.coeff(i,j)); + sstr << static_cast(m.coeff(i, j)); width = std::max(width, Index(sstr.str().length())); } } std::streamsize old_width = s.width(); char old_fill_character = s.fill(); s << fmt.matPrefix; - for(Index i = 0; i < m.rows(); ++i) - { - if (i) - s << fmt.rowSpacer; + for (Index i = 0; i < m.rows(); ++i) { + if (i) s << fmt.rowSpacer; s << fmt.rowPrefix; - if(width) { + if (width) { s.fill(fmt.fill); s.width(width); } s << static_cast(m.coeff(i, 0)); - for(Index j = 1; j < m.cols(); ++j) - { + for (Index j = 1; j < m.cols(); ++j) { s << fmt.coeffSeparator; - if(width) { + if (width) { s.fill(fmt.fill); s.width(width); } s << static_cast(m.coeff(i, j)); } s << fmt.rowSuffix; - if( i < m.rows() - 1) - s << fmt.rowSeparator; + if (i < m.rows() - 1) s << fmt.rowSeparator; } s << fmt.matSuffix; - if(explicit_precision) s.precision(old_precision); - if(width) { + if (explicit_precision) s.precision(old_precision); + if (width) { s.fill(old_fill_character); s.width(old_width); } return s; } -} // end namespace internal +} // end namespace internal /** \relates DenseBase - * - * Outputs the matrix, to the given stream. - * - * If you wish to print the matrix with a format different than the default, use DenseBase::format(). - * - * It is also possible to change the default format by defining EIGEN_DEFAULT_IO_FORMAT before including Eigen headers. - * If not defined, this will automatically be defined to Eigen::IOFormat(), that is the Eigen::IOFormat with default parameters. - * - * \sa DenseBase::format() - */ -template -std::ostream & operator << -(std::ostream & s, - const DenseBase & m) -{ + * + * Outputs the matrix, to the given stream. + * + * If you wish to print the matrix with a format different than the default, use DenseBase::format(). + * + * It is also possible to change the default format by defining EIGEN_DEFAULT_IO_FORMAT before including Eigen headers. + * If not defined, this will automatically be defined to Eigen::IOFormat(), that is the Eigen::IOFormat with default + * parameters. + * + * \sa DenseBase::format() + */ +template +std::ostream& operator<<(std::ostream& s, const DenseBase& m) { return internal::print_matrix(s, m.eval(), EIGEN_DEFAULT_IO_FORMAT); } -} // end namespace Eigen +template +std::ostream& operator<<(std::ostream& s, const DiagonalBase& m) { + return internal::print_matrix(s, m.derived(), EIGEN_DEFAULT_IO_FORMAT); +} + +} // end namespace Eigen -#endif // EIGEN_IO_H +#endif // EIGEN_IO_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/IndexedView.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/IndexedView.h index 08476251d32..454e560e4b9 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/IndexedView.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/IndexedView.h @@ -10,130 +10,158 @@ #ifndef EIGEN_INDEXED_VIEW_H #define EIGEN_INDEXED_VIEW_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > - : traits -{ +template +struct traits> : traits { enum { - RowsAtCompileTime = int(array_size::value), - ColsAtCompileTime = int(array_size::value), - MaxRowsAtCompileTime = RowsAtCompileTime != Dynamic ? int(RowsAtCompileTime) : Dynamic, - MaxColsAtCompileTime = ColsAtCompileTime != Dynamic ? int(ColsAtCompileTime) : Dynamic, - - XprTypeIsRowMajor = (int(traits::Flags)&RowMajorBit) != 0, - IsRowMajor = (MaxRowsAtCompileTime==1&&MaxColsAtCompileTime!=1) ? 1 - : (MaxColsAtCompileTime==1&&MaxRowsAtCompileTime!=1) ? 0 - : XprTypeIsRowMajor, - - RowIncr = int(get_compile_time_incr::value), - ColIncr = int(get_compile_time_incr::value), + RowsAtCompileTime = int(IndexedViewHelper::SizeAtCompileTime), + ColsAtCompileTime = int(IndexedViewHelper::SizeAtCompileTime), + MaxRowsAtCompileTime = RowsAtCompileTime, + MaxColsAtCompileTime = ColsAtCompileTime, + + XprTypeIsRowMajor = (int(traits::Flags) & RowMajorBit) != 0, + IsRowMajor = (MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1) ? 1 + : (MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1) ? 0 + : XprTypeIsRowMajor, + + RowIncr = int(IndexedViewHelper::IncrAtCompileTime), + ColIncr = int(IndexedViewHelper::IncrAtCompileTime), InnerIncr = IsRowMajor ? ColIncr : RowIncr, OuterIncr = IsRowMajor ? RowIncr : ColIncr, HasSameStorageOrderAsXprType = (IsRowMajor == XprTypeIsRowMajor), - XprInnerStride = HasSameStorageOrderAsXprType ? int(inner_stride_at_compile_time::ret) : int(outer_stride_at_compile_time::ret), - XprOuterstride = HasSameStorageOrderAsXprType ? int(outer_stride_at_compile_time::ret) : int(inner_stride_at_compile_time::ret), + XprInnerStride = HasSameStorageOrderAsXprType ? int(inner_stride_at_compile_time::ret) + : int(outer_stride_at_compile_time::ret), + XprOuterstride = HasSameStorageOrderAsXprType ? int(outer_stride_at_compile_time::ret) + : int(inner_stride_at_compile_time::ret), InnerSize = XprTypeIsRowMajor ? ColsAtCompileTime : RowsAtCompileTime, - IsBlockAlike = InnerIncr==1 && OuterIncr==1, - IsInnerPannel = HasSameStorageOrderAsXprType && is_same,typename conditional::type>::value, - - InnerStrideAtCompileTime = InnerIncr<0 || InnerIncr==DynamicIndex || XprInnerStride==Dynamic ? Dynamic : XprInnerStride * InnerIncr, - OuterStrideAtCompileTime = OuterIncr<0 || OuterIncr==DynamicIndex || XprOuterstride==Dynamic ? Dynamic : XprOuterstride * OuterIncr, - - ReturnAsScalar = is_same::value && is_same::value, + IsBlockAlike = InnerIncr == 1 && OuterIncr == 1, + IsInnerPannel = HasSameStorageOrderAsXprType && + is_same, std::conditional_t>::value, + + InnerStrideAtCompileTime = + InnerIncr < 0 || InnerIncr == DynamicIndex || XprInnerStride == Dynamic || InnerIncr == Undefined + ? Dynamic + : XprInnerStride * InnerIncr, + OuterStrideAtCompileTime = + OuterIncr < 0 || OuterIncr == DynamicIndex || XprOuterstride == Dynamic || OuterIncr == Undefined + ? Dynamic + : XprOuterstride * OuterIncr, + + ReturnAsScalar = is_single_range::value && is_single_range::value, ReturnAsBlock = (!ReturnAsScalar) && IsBlockAlike, ReturnAsIndexedView = (!ReturnAsScalar) && (!ReturnAsBlock), // FIXME we deal with compile-time strides if and only if we have DirectAccessBit flag, // but this is too strict regarding negative strides... - DirectAccessMask = (int(InnerIncr)!=UndefinedIncr && int(OuterIncr)!=UndefinedIncr && InnerIncr>=0 && OuterIncr>=0) ? DirectAccessBit : 0, + DirectAccessMask = (int(InnerIncr) != Undefined && int(OuterIncr) != Undefined && InnerIncr >= 0 && OuterIncr >= 0) + ? DirectAccessBit + : 0, FlagsRowMajorBit = IsRowMajor ? RowMajorBit : 0, FlagsLvalueBit = is_lvalue::value ? LvalueBit : 0, FlagsLinearAccessBit = (RowsAtCompileTime == 1 || ColsAtCompileTime == 1) ? LinearAccessBit : 0, - Flags = (traits::Flags & (HereditaryBits | DirectAccessMask )) | FlagsLvalueBit | FlagsRowMajorBit | FlagsLinearAccessBit + Flags = (traits::Flags & (HereditaryBits | DirectAccessMask)) | FlagsLvalueBit | FlagsRowMajorBit | + FlagsLinearAccessBit }; - typedef Block BlockType; + typedef Block BlockType; }; -} - -template +template class IndexedViewImpl; +} // namespace internal /** \class IndexedView - * \ingroup Core_Module - * - * \brief Expression of a non-sequential sub-matrix defined by arbitrary sequences of row and column indices - * - * \tparam XprType the type of the expression in which we are taking the intersections of sub-rows and sub-columns - * \tparam RowIndices the type of the object defining the sequence of row indices - * \tparam ColIndices the type of the object defining the sequence of column indices - * - * This class represents an expression of a sub-matrix (or sub-vector) defined as the intersection - * of sub-sets of rows and columns, that are themself defined by generic sequences of row indices \f$ \{r_0,r_1,..r_{m-1}\} \f$ - * and column indices \f$ \{c_0,c_1,..c_{n-1} \}\f$. Let \f$ A \f$ be the nested matrix, then the resulting matrix \f$ B \f$ has \c m - * rows and \c n columns, and its entries are given by: \f$ B(i,j) = A(r_i,c_j) \f$. - * - * The \c RowIndices and \c ColIndices types must be compatible with the following API: - * \code - * operator[](Index) const; - * Index size() const; - * \endcode - * - * Typical supported types thus include: - * - std::vector - * - std::valarray - * - std::array - * - Plain C arrays: int[N] - * - Eigen::ArrayXi - * - decltype(ArrayXi::LinSpaced(...)) - * - Any view/expressions of the previous types - * - Eigen::ArithmeticSequence - * - Eigen::internal::AllRange (helper for Eigen::all) - * - Eigen::internal::SingleRange (helper for single index) - * - etc. - * - * In typical usages of %Eigen, this class should never be used directly. It is the return type of - * DenseBase::operator()(const RowIndices&, const ColIndices&). - * - * \sa class Block - */ -template -class IndexedView : public IndexedViewImpl::StorageKind> -{ -public: - typedef typename IndexedViewImpl::StorageKind>::Base Base; + * \ingroup Core_Module + * + * \brief Expression of a non-sequential sub-matrix defined by arbitrary sequences of row and column indices + * + * \tparam XprType the type of the expression in which we are taking the intersections of sub-rows and sub-columns + * \tparam RowIndices the type of the object defining the sequence of row indices + * \tparam ColIndices the type of the object defining the sequence of column indices + * + * This class represents an expression of a sub-matrix (or sub-vector) defined as the intersection + * of sub-sets of rows and columns, that are themself defined by generic sequences of row indices \f$ + * \{r_0,r_1,..r_{m-1}\} \f$ and column indices \f$ \{c_0,c_1,..c_{n-1} \}\f$. Let \f$ A \f$ be the nested matrix, then + * the resulting matrix \f$ B \f$ has \c m rows and \c n columns, and its entries are given by: \f$ B(i,j) = A(r_i,c_j) + * \f$. + * + * The \c RowIndices and \c ColIndices types must be compatible with the following API: + * \code + * operator[](Index) const; + * Index size() const; + * \endcode + * + * Typical supported types thus include: + * - std::vector + * - std::valarray + * - std::array + * - Eigen::ArrayXi + * - decltype(ArrayXi::LinSpaced(...)) + * - Any view/expressions of the previous types + * - Eigen::ArithmeticSequence + * - Eigen::internal::AllRange (helper for Eigen::placeholders::all) + * - Eigen::internal::SingleRange (helper for single index) + * - etc. + * + * In typical usages of %Eigen, this class should never be used directly. It is the return type of + * DenseBase::operator()(const RowIndices&, const ColIndices&). + * + * \sa class Block + */ +template +class IndexedView + : public internal::IndexedViewImpl::StorageKind, + (internal::traits>::Flags & + DirectAccessBit) != 0> { + public: + typedef typename internal::IndexedViewImpl< + XprType, RowIndices, ColIndices, typename internal::traits::StorageKind, + (internal::traits>::Flags & DirectAccessBit) != 0> + Base; EIGEN_GENERIC_PUBLIC_INTERFACE(IndexedView) EIGEN_INHERIT_ASSIGNMENT_OPERATORS(IndexedView) + template + IndexedView(XprType& xpr, const T0& rowIndices, const T1& colIndices) : Base(xpr, rowIndices, colIndices) {} +}; + +namespace internal { + +// Generic API dispatcher +template +class IndexedViewImpl : public internal::generic_xpr_base>::type { + public: + typedef typename internal::generic_xpr_base>::type Base; typedef typename internal::ref_selector::non_const_type MatrixTypeNested; - typedef typename internal::remove_all::type NestedExpression; + typedef internal::remove_all_t NestedExpression; + typedef typename XprType::Scalar Scalar; + + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(IndexedViewImpl) - template - IndexedView(XprType& xpr, const T0& rowIndices, const T1& colIndices) - : m_xpr(xpr), m_rowIndices(rowIndices), m_colIndices(colIndices) - {} + template + IndexedViewImpl(XprType& xpr, const T0& rowIndices, const T1& colIndices) + : m_xpr(xpr), m_rowIndices(rowIndices), m_colIndices(colIndices) {} /** \returns number of rows */ - Index rows() const { return internal::size(m_rowIndices); } + Index rows() const { return IndexedViewHelper::size(m_rowIndices); } /** \returns number of columns */ - Index cols() const { return internal::size(m_colIndices); } + Index cols() const { return IndexedViewHelper::size(m_colIndices); } /** \returns the nested expression */ - const typename internal::remove_all::type& - nestedExpression() const { return m_xpr; } + const internal::remove_all_t& nestedExpression() const { return m_xpr; } /** \returns the nested expression */ - typename internal::remove_reference::type& - nestedExpression() { return m_xpr; } + std::remove_reference_t& nestedExpression() { return m_xpr; } /** \returns a const reference to the object storing/generating the row indices */ const RowIndices& rowIndices() const { return m_rowIndices; } @@ -141,97 +169,147 @@ class IndexedView : public IndexedViewImpl +class IndexedViewImpl + : public IndexedViewImpl { + public: + using Base = internal::IndexedViewImpl::StorageKind, false>; + using Derived = IndexedView; -// Generic API dispatcher -template -class IndexedViewImpl - : public internal::generic_xpr_base >::type -{ -public: - typedef typename internal::generic_xpr_base >::type Base; -}; + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(IndexedViewImpl) -namespace internal { + template + IndexedViewImpl(XprType& xpr, const T0& rowIndices, const T1& colIndices) : Base(xpr, rowIndices, colIndices) {} + Index rowIncrement() const { + if (traits::RowIncr != DynamicIndex && traits::RowIncr != Undefined) { + return traits::RowIncr; + } + return IndexedViewHelper::incr(this->rowIndices()); + } + Index colIncrement() const { + if (traits::ColIncr != DynamicIndex && traits::ColIncr != Undefined) { + return traits::ColIncr; + } + return IndexedViewHelper::incr(this->colIndices()); + } + + Index innerIncrement() const { return traits::IsRowMajor ? colIncrement() : rowIncrement(); } + + Index outerIncrement() const { return traits::IsRowMajor ? rowIncrement() : colIncrement(); } + + std::decay_t* data() { + Index row_offset = this->rowIndices()[0] * this->nestedExpression().rowStride(); + Index col_offset = this->colIndices()[0] * this->nestedExpression().colStride(); + return this->nestedExpression().data() + row_offset + col_offset; + } + + const std::decay_t* data() const { + Index row_offset = this->rowIndices()[0] * this->nestedExpression().rowStride(); + Index col_offset = this->colIndices()[0] * this->nestedExpression().colStride(); + return this->nestedExpression().data() + row_offset + col_offset; + } + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const EIGEN_NOEXCEPT { + if (traits::InnerStrideAtCompileTime != Dynamic) { + return traits::InnerStrideAtCompileTime; + } + return innerIncrement() * this->nestedExpression().innerStride(); + } -template + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const EIGEN_NOEXCEPT { + if (traits::OuterStrideAtCompileTime != Dynamic) { + return traits::OuterStrideAtCompileTime; + } + return outerIncrement() * this->nestedExpression().outerStride(); + } +}; + +template struct unary_evaluator, IndexBased> - : evaluator_base > -{ + : evaluator_base> { typedef IndexedView XprType; enum { CoeffReadCost = evaluator::CoeffReadCost /* TODO + cost of row/col index */, - FlagsLinearAccessBit = (traits::RowsAtCompileTime == 1 || traits::ColsAtCompileTime == 1) ? LinearAccessBit : 0, + FlagsLinearAccessBit = + (traits::RowsAtCompileTime == 1 || traits::ColsAtCompileTime == 1) ? LinearAccessBit : 0, - FlagsRowMajorBit = traits::FlagsRowMajorBit, + FlagsRowMajorBit = traits::FlagsRowMajorBit, - Flags = (evaluator::Flags & (HereditaryBits & ~RowMajorBit /*| LinearAccessBit | DirectAccessBit*/)) | FlagsLinearAccessBit | FlagsRowMajorBit, + Flags = (evaluator::Flags & (HereditaryBits & ~RowMajorBit /*| LinearAccessBit | DirectAccessBit*/)) | + FlagsLinearAccessBit | FlagsRowMajorBit, Alignment = 0 }; - EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& xpr) : m_argImpl(xpr.nestedExpression()), m_xpr(xpr) - { + EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& xpr) : m_argImpl(xpr.nestedExpression()), m_xpr(xpr) { EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } typedef typename XprType::Scalar Scalar; typedef typename XprType::CoeffReturnType CoeffReturnType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const { + eigen_assert(m_xpr.rowIndices()[row] >= 0 && m_xpr.rowIndices()[row] < m_xpr.nestedExpression().rows() && + m_xpr.colIndices()[col] >= 0 && m_xpr.colIndices()[col] < m_xpr.nestedExpression().cols()); return m_argImpl.coeff(m_xpr.rowIndices()[row], m_xpr.colIndices()[col]); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index row, Index col) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col) { + eigen_assert(m_xpr.rowIndices()[row] >= 0 && m_xpr.rowIndices()[row] < m_xpr.nestedExpression().rows() && + m_xpr.colIndices()[col] >= 0 && m_xpr.colIndices()[col] < m_xpr.nestedExpression().cols()); return m_argImpl.coeffRef(m_xpr.rowIndices()[row], m_xpr.colIndices()[col]); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Scalar& coeffRef(Index index) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { EIGEN_STATIC_ASSERT_LVALUE(XprType) Index row = XprType::RowsAtCompileTime == 1 ? 0 : index; Index col = XprType::RowsAtCompileTime == 1 ? index : 0; - return m_argImpl.coeffRef( m_xpr.rowIndices()[row], m_xpr.colIndices()[col]); + eigen_assert(m_xpr.rowIndices()[row] >= 0 && m_xpr.rowIndices()[row] < m_xpr.nestedExpression().rows() && + m_xpr.colIndices()[col] >= 0 && m_xpr.colIndices()[col] < m_xpr.nestedExpression().cols()); + return m_argImpl.coeffRef(m_xpr.rowIndices()[row], m_xpr.colIndices()[col]); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const Scalar& coeffRef(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeffRef(Index index) const { Index row = XprType::RowsAtCompileTime == 1 ? 0 : index; Index col = XprType::RowsAtCompileTime == 1 ? index : 0; - return m_argImpl.coeffRef( m_xpr.rowIndices()[row], m_xpr.colIndices()[col]); + eigen_assert(m_xpr.rowIndices()[row] >= 0 && m_xpr.rowIndices()[row] < m_xpr.nestedExpression().rows() && + m_xpr.colIndices()[col] >= 0 && m_xpr.colIndices()[col] < m_xpr.nestedExpression().cols()); + return m_argImpl.coeffRef(m_xpr.rowIndices()[row], m_xpr.colIndices()[col]); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const CoeffReturnType coeff(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index index) const { Index row = XprType::RowsAtCompileTime == 1 ? 0 : index; Index col = XprType::RowsAtCompileTime == 1 ? index : 0; - return m_argImpl.coeff( m_xpr.rowIndices()[row], m_xpr.colIndices()[col]); + eigen_assert(m_xpr.rowIndices()[row] >= 0 && m_xpr.rowIndices()[row] < m_xpr.nestedExpression().rows() && + m_xpr.colIndices()[col] >= 0 && m_xpr.colIndices()[col] < m_xpr.nestedExpression().cols()); + return m_argImpl.coeff(m_xpr.rowIndices()[row], m_xpr.colIndices()[col]); } -protected: - + protected: evaluator m_argImpl; const XprType& m_xpr; - }; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_INDEXED_VIEW_H +#endif // EIGEN_INDEXED_VIEW_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/InternalHeaderCheck.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/InternalHeaderCheck.h new file mode 100644 index 00000000000..1cea572dcf9 --- /dev/null +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_CORE_MODULE_H +#error "Please include Eigen/Core instead of including headers inside the src directory directly." +#endif diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Inverse.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Inverse.h index c514438c45e..cfb3b20e5a2 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Inverse.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Inverse.h @@ -10,69 +10,64 @@ #ifndef EIGEN_INVERSE_H #define EIGEN_INVERSE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { -template class InverseImpl; +template +class InverseImpl; namespace internal { -template -struct traits > - : traits -{ +template +struct traits > : traits { typedef typename XprType::PlainObject PlainObject; typedef traits BaseTraits; - enum { - Flags = BaseTraits::Flags & RowMajorBit - }; + enum { Flags = BaseTraits::Flags & RowMajorBit }; }; -} // end namespace internal +} // end namespace internal /** \class Inverse - * - * \brief Expression of the inverse of another expression - * - * \tparam XprType the type of the expression we are taking the inverse - * - * This class represents an abstract expression of A.inverse() - * and most of the time this is the only way it is used. - * - */ -template -class Inverse : public InverseImpl::StorageKind> -{ -public: + * + * \brief Expression of the inverse of another expression + * + * \tparam XprType the type of the expression we are taking the inverse + * + * This class represents an abstract expression of A.inverse() + * and most of the time this is the only way it is used. + * + */ +template +class Inverse : public InverseImpl::StorageKind> { + public: typedef typename XprType::StorageIndex StorageIndex; - typedef typename XprType::Scalar Scalar; - typedef typename internal::ref_selector::type XprTypeNested; - typedef typename internal::remove_all::type XprTypeNestedCleaned; + typedef typename XprType::Scalar Scalar; + typedef typename internal::ref_selector::type XprTypeNested; + typedef internal::remove_all_t XprTypeNestedCleaned; typedef typename internal::ref_selector::type Nested; - typedef typename internal::remove_all::type NestedExpression; + typedef internal::remove_all_t NestedExpression; - explicit EIGEN_DEVICE_FUNC Inverse(const XprType &xpr) - : m_xpr(xpr) - {} + explicit EIGEN_DEVICE_FUNC Inverse(const XprType& xpr) : m_xpr(xpr) {} - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_xpr.cols(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_xpr.rows(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_xpr.cols(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_xpr.rows(); } EIGEN_DEVICE_FUNC const XprTypeNestedCleaned& nestedExpression() const { return m_xpr; } -protected: + protected: XprTypeNested m_xpr; }; // Generic API dispatcher -template -class InverseImpl - : public internal::generic_xpr_base >::type -{ -public: +template +class InverseImpl : public internal::generic_xpr_base >::type { + public: typedef typename internal::generic_xpr_base >::type Base; typedef typename XprType::Scalar Scalar; -private: + private: Scalar coeff(Index row, Index col) const; Scalar coeff(Index i) const; }; @@ -80,38 +75,34 @@ class InverseImpl namespace internal { /** \internal - * \brief Default evaluator for Inverse expression. - * - * This default evaluator for Inverse expression simply evaluate the inverse into a temporary - * by a call to internal::call_assignment_no_alias. - * Therefore, inverse implementers only have to specialize Assignment, ...> for - * there own nested expression. - * - * \sa class Inverse - */ -template -struct unary_evaluator > - : public evaluator::PlainObject> -{ + * \brief Default evaluator for Inverse expression. + * + * This default evaluator for Inverse expression simply evaluate the inverse into a temporary + * by a call to internal::call_assignment_no_alias. + * Therefore, inverse implementers only have to specialize Assignment, ...> for + * there own nested expression. + * + * \sa class Inverse + */ +template +struct unary_evaluator > : public evaluator::PlainObject> { typedef Inverse InverseType; typedef typename InverseType::PlainObject PlainObject; typedef evaluator Base; enum { Flags = Base::Flags | EvalBeforeNestingBit }; - unary_evaluator(const InverseType& inv_xpr) - : m_result(inv_xpr.rows(), inv_xpr.cols()) - { - ::new (static_cast(this)) Base(m_result); + unary_evaluator(const InverseType& inv_xpr) : m_result(inv_xpr.rows(), inv_xpr.cols()) { + internal::construct_at(this, m_result); internal::call_assignment_no_alias(m_result, inv_xpr); } -protected: + protected: PlainObject m_result; }; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_INVERSE_H +#endif // EIGEN_INVERSE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Map.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Map.h index 218cc157f38..df7b7ca7781 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Map.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Map.h @@ -11,161 +11,143 @@ #ifndef EIGEN_MAP_H #define EIGEN_MAP_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > - : public traits -{ +template +struct traits > : public traits { typedef traits TraitsBase; enum { - PlainObjectTypeInnerSize = ((traits::Flags&RowMajorBit)==RowMajorBit) - ? PlainObjectType::ColsAtCompileTime - : PlainObjectType::RowsAtCompileTime, + PlainObjectTypeInnerSize = ((traits::Flags & RowMajorBit) == RowMajorBit) + ? PlainObjectType::ColsAtCompileTime + : PlainObjectType::RowsAtCompileTime, InnerStrideAtCompileTime = StrideType::InnerStrideAtCompileTime == 0 - ? int(PlainObjectType::InnerStrideAtCompileTime) - : int(StrideType::InnerStrideAtCompileTime), + ? int(PlainObjectType::InnerStrideAtCompileTime) + : int(StrideType::InnerStrideAtCompileTime), OuterStrideAtCompileTime = StrideType::OuterStrideAtCompileTime == 0 - ? (InnerStrideAtCompileTime==Dynamic || PlainObjectTypeInnerSize==Dynamic - ? Dynamic - : int(InnerStrideAtCompileTime) * int(PlainObjectTypeInnerSize)) - : int(StrideType::OuterStrideAtCompileTime), - Alignment = int(MapOptions)&int(AlignedMask), + ? (InnerStrideAtCompileTime == Dynamic || PlainObjectTypeInnerSize == Dynamic + ? Dynamic + : int(InnerStrideAtCompileTime) * int(PlainObjectTypeInnerSize)) + : int(StrideType::OuterStrideAtCompileTime), + Alignment = int(MapOptions) & int(AlignedMask), Flags0 = TraitsBase::Flags & (~NestByRefBit), Flags = is_lvalue::value ? int(Flags0) : (int(Flags0) & ~LvalueBit) }; -private: - enum { Options }; // Expressions don't have Options + + private: + enum { Options }; // Expressions don't have Options }; -} +} // namespace internal /** \class Map - * \ingroup Core_Module - * - * \brief A matrix or vector expression mapping an existing array of data. - * - * \tparam PlainObjectType the equivalent matrix type of the mapped data - * \tparam MapOptions specifies the pointer alignment in bytes. It can be: \c #Aligned128, \c #Aligned64, \c #Aligned32, \c #Aligned16, \c #Aligned8 or \c #Unaligned. - * The default is \c #Unaligned. - * \tparam StrideType optionally specifies strides. By default, Map assumes the memory layout - * of an ordinary, contiguous array. This can be overridden by specifying strides. - * The type passed here must be a specialization of the Stride template, see examples below. - * - * This class represents a matrix or vector expression mapping an existing array of data. - * It can be used to let Eigen interface without any overhead with non-Eigen data structures, - * such as plain C arrays or structures from other libraries. By default, it assumes that the - * data is laid out contiguously in memory. You can however override this by explicitly specifying - * inner and outer strides. - * - * Here's an example of simply mapping a contiguous array as a \ref TopicStorageOrders "column-major" matrix: - * \include Map_simple.cpp - * Output: \verbinclude Map_simple.out - * - * If you need to map non-contiguous arrays, you can do so by specifying strides: - * - * Here's an example of mapping an array as a vector, specifying an inner stride, that is, the pointer - * increment between two consecutive coefficients. Here, we're specifying the inner stride as a compile-time - * fixed value. - * \include Map_inner_stride.cpp - * Output: \verbinclude Map_inner_stride.out - * - * Here's an example of mapping an array while specifying an outer stride. Here, since we're mapping - * as a column-major matrix, 'outer stride' means the pointer increment between two consecutive columns. - * Here, we're specifying the outer stride as a runtime parameter. Note that here \c OuterStride<> is - * a short version of \c OuterStride because the default template parameter of OuterStride - * is \c Dynamic - * \include Map_outer_stride.cpp - * Output: \verbinclude Map_outer_stride.out - * - * For more details and for an example of specifying both an inner and an outer stride, see class Stride. - * - * \b Tip: to change the array of data mapped by a Map object, you can use the C++ - * placement new syntax: - * - * Example: \include Map_placement_new.cpp - * Output: \verbinclude Map_placement_new.out - * - * This class is the return type of PlainObjectBase::Map() but can also be used directly. - * - * \sa PlainObjectBase::Map(), \ref TopicStorageOrders - */ -template class Map - : public MapBase > -{ - public: - - typedef MapBase Base; - EIGEN_DENSE_PUBLIC_INTERFACE(Map) - - typedef typename Base::PointerType PointerType; - typedef PointerType PointerArgType; - EIGEN_DEVICE_FUNC - inline PointerType cast_to_pointer_type(PointerArgType ptr) { return ptr; } - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index innerStride() const - { - return StrideType::InnerStrideAtCompileTime != 0 ? m_stride.inner() : 1; - } - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outerStride() const - { - return StrideType::OuterStrideAtCompileTime != 0 ? m_stride.outer() - : internal::traits::OuterStrideAtCompileTime != Dynamic ? Index(internal::traits::OuterStrideAtCompileTime) - : IsVectorAtCompileTime ? (this->size() * innerStride()) - : int(Flags)&RowMajorBit ? (this->cols() * innerStride()) - : (this->rows() * innerStride()); - } - - /** Constructor in the fixed-size case. - * - * \param dataPtr pointer to the array to map - * \param stride optional Stride object, passing the strides. - */ - EIGEN_DEVICE_FUNC - explicit inline Map(PointerArgType dataPtr, const StrideType& stride = StrideType()) - : Base(cast_to_pointer_type(dataPtr)), m_stride(stride) - { - PlainObjectType::Base::_check_template_params(); - } - - /** Constructor in the dynamic-size vector case. - * - * \param dataPtr pointer to the array to map - * \param size the size of the vector expression - * \param stride optional Stride object, passing the strides. - */ - EIGEN_DEVICE_FUNC - inline Map(PointerArgType dataPtr, Index size, const StrideType& stride = StrideType()) - : Base(cast_to_pointer_type(dataPtr), size), m_stride(stride) - { - PlainObjectType::Base::_check_template_params(); - } - - /** Constructor in the dynamic-size matrix case. - * - * \param dataPtr pointer to the array to map - * \param rows the number of rows of the matrix expression - * \param cols the number of columns of the matrix expression - * \param stride optional Stride object, passing the strides. - */ - EIGEN_DEVICE_FUNC - inline Map(PointerArgType dataPtr, Index rows, Index cols, const StrideType& stride = StrideType()) - : Base(cast_to_pointer_type(dataPtr), rows, cols), m_stride(stride) - { - PlainObjectType::Base::_check_template_params(); - } - - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Map) - - protected: - StrideType m_stride; + * \ingroup Core_Module + * + * \brief A matrix or vector expression mapping an existing array of data. + * + * \tparam PlainObjectType the equivalent matrix type of the mapped data + * \tparam MapOptions specifies the pointer alignment in bytes. It can be: \c #Aligned128, \c #Aligned64, \c #Aligned32, + * \c #Aligned16, \c #Aligned8 or \c #Unaligned. The default is \c #Unaligned. \tparam StrideType optionally specifies + * strides. By default, Map assumes the memory layout of an ordinary, contiguous array. This can be overridden by + * specifying strides. The type passed here must be a specialization of the Stride template, see examples below. + * + * This class represents a matrix or vector expression mapping an existing array of data. + * It can be used to let Eigen interface without any overhead with non-Eigen data structures, + * such as plain C arrays or structures from other libraries. By default, it assumes that the + * data is laid out contiguously in memory. You can however override this by explicitly specifying + * inner and outer strides. + * + * Here's an example of simply mapping a contiguous array as a \ref TopicStorageOrders "column-major" matrix: + * \include Map_simple.cpp + * Output: \verbinclude Map_simple.out + * + * If you need to map non-contiguous arrays, you can do so by specifying strides: + * + * Here's an example of mapping an array as a vector, specifying an inner stride, that is, the pointer + * increment between two consecutive coefficients. Here, we're specifying the inner stride as a compile-time + * fixed value. + * \include Map_inner_stride.cpp + * Output: \verbinclude Map_inner_stride.out + * + * Here's an example of mapping an array while specifying an outer stride. Here, since we're mapping + * as a column-major matrix, 'outer stride' means the pointer increment between two consecutive columns. + * Here, we're specifying the outer stride as a runtime parameter. Note that here \c OuterStride<> is + * a short version of \c OuterStride because the default template parameter of OuterStride + * is \c Dynamic + * \include Map_outer_stride.cpp + * Output: \verbinclude Map_outer_stride.out + * + * For more details and for an example of specifying both an inner and an outer stride, see class Stride. + * + * \b Tip: to change the array of data mapped by a Map object, you can use the C++ + * placement new syntax: + * + * Example: \include Map_placement_new.cpp + * Output: \verbinclude Map_placement_new.out + * + * This class is the return type of PlainObjectBase::Map() but can also be used directly. + * + * \sa PlainObjectBase::Map(), \ref TopicStorageOrders + */ +template +class Map : public MapBase > { + public: + typedef MapBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Map) + + typedef typename Base::PointerType PointerType; + typedef PointerType PointerArgType; + EIGEN_DEVICE_FUNC inline PointerType cast_to_pointer_type(PointerArgType ptr) { return ptr; } + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const { + return StrideType::InnerStrideAtCompileTime != 0 ? m_stride.inner() : 1; + } + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const { + return StrideType::OuterStrideAtCompileTime != 0 ? m_stride.outer() + : internal::traits::OuterStrideAtCompileTime != Dynamic + ? Index(internal::traits::OuterStrideAtCompileTime) + : IsVectorAtCompileTime ? (this->size() * innerStride()) + : int(Flags) & RowMajorBit ? (this->cols() * innerStride()) + : (this->rows() * innerStride()); + } + + /** Constructor in the fixed-size case. + * + * \param dataPtr pointer to the array to map + * \param stride optional Stride object, passing the strides. + */ + EIGEN_DEVICE_FUNC explicit inline Map(PointerArgType dataPtr, const StrideType& stride = StrideType()) + : Base(cast_to_pointer_type(dataPtr)), m_stride(stride) {} + + /** Constructor in the dynamic-size vector case. + * + * \param dataPtr pointer to the array to map + * \param size the size of the vector expression + * \param stride optional Stride object, passing the strides. + */ + EIGEN_DEVICE_FUNC inline Map(PointerArgType dataPtr, Index size, const StrideType& stride = StrideType()) + : Base(cast_to_pointer_type(dataPtr), size), m_stride(stride) {} + + /** Constructor in the dynamic-size matrix case. + * + * \param dataPtr pointer to the array to map + * \param rows the number of rows of the matrix expression + * \param cols the number of columns of the matrix expression + * \param stride optional Stride object, passing the strides. + */ + EIGEN_DEVICE_FUNC inline Map(PointerArgType dataPtr, Index rows, Index cols, const StrideType& stride = StrideType()) + : Base(cast_to_pointer_type(dataPtr), rows, cols), m_stride(stride) {} + + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Map) + + protected: + StrideType m_stride; }; +} // end namespace Eigen -} // end namespace Eigen - -#endif // EIGEN_MAP_H +#endif // EIGEN_MAP_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MapBase.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MapBase.h index d856447f03e..da95b5c4007 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MapBase.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MapBase.h @@ -11,300 +11,273 @@ #ifndef EIGEN_MAPBASE_H #define EIGEN_MAPBASE_H -#define EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) \ - EIGEN_STATIC_ASSERT((int(internal::evaluator::Flags) & LinearAccessBit) || Derived::IsVectorAtCompileTime, \ - YOU_ARE_TRYING_TO_USE_AN_INDEX_BASED_ACCESSOR_ON_AN_EXPRESSION_THAT_DOES_NOT_SUPPORT_THAT) +#define EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) \ + EIGEN_STATIC_ASSERT((int(internal::evaluator::Flags) & LinearAccessBit) || Derived::IsVectorAtCompileTime, \ + YOU_ARE_TRYING_TO_USE_AN_INDEX_BASED_ACCESSOR_ON_AN_EXPRESSION_THAT_DOES_NOT_SUPPORT_THAT) + +// IWYU pragma: private +#include "./InternalHeaderCheck.h" namespace Eigen { /** \ingroup Core_Module - * - * \brief Base class for dense Map and Block expression with direct access - * - * This base class provides the const low-level accessors (e.g. coeff, coeffRef) of dense - * Map and Block objects with direct access. - * Typical users do not have to directly deal with this class. - * - * This class can be extended by through the macro plugin \c EIGEN_MAPBASE_PLUGIN. - * See \link TopicCustomizing_Plugins customizing Eigen \endlink for details. - * - * The \c Derived class has to provide the following two methods describing the memory layout: - * \code Index innerStride() const; \endcode - * \code Index outerStride() const; \endcode - * - * \sa class Map, class Block - */ -template class MapBase - : public internal::dense_xpr_base::type -{ - public: - - typedef typename internal::dense_xpr_base::type Base; - enum { - RowsAtCompileTime = internal::traits::RowsAtCompileTime, - ColsAtCompileTime = internal::traits::ColsAtCompileTime, - InnerStrideAtCompileTime = internal::traits::InnerStrideAtCompileTime, - SizeAtCompileTime = Base::SizeAtCompileTime - }; - - typedef typename internal::traits::StorageKind StorageKind; - typedef typename internal::traits::Scalar Scalar; - typedef typename internal::packet_traits::type PacketScalar; - typedef typename NumTraits::Real RealScalar; - typedef typename internal::conditional< - bool(internal::is_lvalue::value), - Scalar *, - const Scalar *>::type - PointerType; - - using Base::derived; -// using Base::RowsAtCompileTime; -// using Base::ColsAtCompileTime; -// using Base::SizeAtCompileTime; - using Base::MaxRowsAtCompileTime; - using Base::MaxColsAtCompileTime; - using Base::MaxSizeAtCompileTime; - using Base::IsVectorAtCompileTime; - using Base::Flags; - using Base::IsRowMajor; - - using Base::rows; - using Base::cols; - using Base::size; - using Base::coeff; - using Base::coeffRef; - using Base::lazyAssign; - using Base::eval; - - using Base::innerStride; - using Base::outerStride; - using Base::rowStride; - using Base::colStride; - - // bug 217 - compile error on ICC 11.1 - using Base::operator=; - - typedef typename Base::CoeffReturnType CoeffReturnType; - - /** \copydoc DenseBase::rows() */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rows() const EIGEN_NOEXCEPT { return m_rows.value(); } - /** \copydoc DenseBase::cols() */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index cols() const EIGEN_NOEXCEPT { return m_cols.value(); } - - /** Returns a pointer to the first coefficient of the matrix or vector. - * - * \note When addressing this data, make sure to honor the strides returned by innerStride() and outerStride(). - * - * \sa innerStride(), outerStride() - */ - EIGEN_DEVICE_FUNC inline const Scalar* data() const { return m_data; } - - /** \copydoc PlainObjectBase::coeff(Index,Index) const */ - EIGEN_DEVICE_FUNC - inline const Scalar& coeff(Index rowId, Index colId) const - { - return m_data[colId * colStride() + rowId * rowStride()]; - } - - /** \copydoc PlainObjectBase::coeff(Index) const */ - EIGEN_DEVICE_FUNC - inline const Scalar& coeff(Index index) const - { - EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) - return m_data[index * innerStride()]; - } - - /** \copydoc PlainObjectBase::coeffRef(Index,Index) const */ - EIGEN_DEVICE_FUNC - inline const Scalar& coeffRef(Index rowId, Index colId) const - { - return this->m_data[colId * colStride() + rowId * rowStride()]; - } - - /** \copydoc PlainObjectBase::coeffRef(Index) const */ - EIGEN_DEVICE_FUNC - inline const Scalar& coeffRef(Index index) const - { - EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) - return this->m_data[index * innerStride()]; - } - - /** \internal */ - template - inline PacketScalar packet(Index rowId, Index colId) const - { - return internal::ploadt - (m_data + (colId * colStride() + rowId * rowStride())); - } - - /** \internal */ - template - inline PacketScalar packet(Index index) const - { - EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) - return internal::ploadt(m_data + index * innerStride()); - } - - /** \internal Constructor for fixed size matrices or vectors */ - EIGEN_DEVICE_FUNC - explicit inline MapBase(PointerType dataPtr) : m_data(dataPtr), m_rows(RowsAtCompileTime), m_cols(ColsAtCompileTime) - { - EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) - checkSanity(); - } - - /** \internal Constructor for dynamically sized vectors */ - EIGEN_DEVICE_FUNC - inline MapBase(PointerType dataPtr, Index vecSize) - : m_data(dataPtr), - m_rows(RowsAtCompileTime == Dynamic ? vecSize : Index(RowsAtCompileTime)), - m_cols(ColsAtCompileTime == Dynamic ? vecSize : Index(ColsAtCompileTime)) - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) - eigen_assert(vecSize >= 0); - eigen_assert(dataPtr == 0 || SizeAtCompileTime == Dynamic || SizeAtCompileTime == vecSize); - checkSanity(); - } - - /** \internal Constructor for dynamically sized matrices */ - EIGEN_DEVICE_FUNC - inline MapBase(PointerType dataPtr, Index rows, Index cols) - : m_data(dataPtr), m_rows(rows), m_cols(cols) - { - eigen_assert( (dataPtr == 0) - || ( rows >= 0 && (RowsAtCompileTime == Dynamic || RowsAtCompileTime == rows) - && cols >= 0 && (ColsAtCompileTime == Dynamic || ColsAtCompileTime == cols))); - checkSanity(); - } - - #ifdef EIGEN_MAPBASE_PLUGIN - #include EIGEN_MAPBASE_PLUGIN - #endif - - protected: - EIGEN_DEFAULT_COPY_CONSTRUCTOR(MapBase) - EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(MapBase) - - template - EIGEN_DEVICE_FUNC - void checkSanity(typename internal::enable_if<(internal::traits::Alignment>0),void*>::type = 0) const - { -#if EIGEN_MAX_ALIGN_BYTES>0 - // innerStride() is not set yet when this function is called, so we optimistically assume the lowest plausible value: - const Index minInnerStride = InnerStrideAtCompileTime == Dynamic ? 1 : Index(InnerStrideAtCompileTime); - EIGEN_ONLY_USED_FOR_DEBUG(minInnerStride); - eigen_assert(( ((internal::UIntPtr(m_data) % internal::traits::Alignment) == 0) - || (cols() * rows() * minInnerStride * sizeof(Scalar)) < internal::traits::Alignment ) && "data is not aligned"); + * + * \brief Base class for dense Map and Block expression with direct access + * + * This base class provides the const low-level accessors (e.g. coeff, coeffRef) of dense + * Map and Block objects with direct access. + * Typical users do not have to directly deal with this class. + * + * This class can be extended by through the macro plugin \c EIGEN_MAPBASE_PLUGIN. + * See \link TopicCustomizing_Plugins customizing Eigen \endlink for details. + * + * The \c Derived class has to provide the following two methods describing the memory layout: + * \code Index innerStride() const; \endcode + * \code Index outerStride() const; \endcode + * + * \sa class Map, class Block + */ +template +class MapBase : public internal::dense_xpr_base::type { + public: + typedef typename internal::dense_xpr_base::type Base; + enum { + RowsAtCompileTime = internal::traits::RowsAtCompileTime, + ColsAtCompileTime = internal::traits::ColsAtCompileTime, + InnerStrideAtCompileTime = internal::traits::InnerStrideAtCompileTime, + SizeAtCompileTime = Base::SizeAtCompileTime + }; + + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::packet_traits::type PacketScalar; + typedef typename NumTraits::Real RealScalar; + typedef std::conditional_t::value), Scalar*, const Scalar*> PointerType; + + using Base::derived; + // using Base::RowsAtCompileTime; + // using Base::ColsAtCompileTime; + // using Base::SizeAtCompileTime; + using Base::Flags; + using Base::IsRowMajor; + using Base::IsVectorAtCompileTime; + using Base::MaxColsAtCompileTime; + using Base::MaxRowsAtCompileTime; + using Base::MaxSizeAtCompileTime; + + using Base::coeff; + using Base::coeffRef; + using Base::cols; + using Base::eval; + using Base::lazyAssign; + using Base::rows; + using Base::size; + + using Base::colStride; + using Base::innerStride; + using Base::outerStride; + using Base::rowStride; + + // bug 217 - compile error on ICC 11.1 + using Base::operator=; + + typedef typename Base::CoeffReturnType CoeffReturnType; + + /** \copydoc DenseBase::rows() */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { return m_rows.value(); } + /** \copydoc DenseBase::cols() */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return m_cols.value(); } + + /** Returns a pointer to the first coefficient of the matrix or vector. + * + * \note When addressing this data, make sure to honor the strides returned by innerStride() and outerStride(). + * + * \sa innerStride(), outerStride() + */ + EIGEN_DEVICE_FUNC inline const Scalar* data() const { return m_data; } + + /** \copydoc PlainObjectBase::coeff(Index,Index) const */ + EIGEN_DEVICE_FUNC inline const Scalar& coeff(Index rowId, Index colId) const { + return m_data[colId * colStride() + rowId * rowStride()]; + } + + /** \copydoc PlainObjectBase::coeff(Index) const */ + EIGEN_DEVICE_FUNC inline const Scalar& coeff(Index index) const { + EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) + return m_data[index * innerStride()]; + } + + /** \copydoc PlainObjectBase::coeffRef(Index,Index) const */ + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index rowId, Index colId) const { + return this->m_data[colId * colStride() + rowId * rowStride()]; + } + + /** \copydoc PlainObjectBase::coeffRef(Index) const */ + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index index) const { + EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) + return this->m_data[index * innerStride()]; + } + + /** \internal */ + template + inline PacketScalar packet(Index rowId, Index colId) const { + return internal::ploadt(m_data + (colId * colStride() + rowId * rowStride())); + } + + /** \internal */ + template + inline PacketScalar packet(Index index) const { + EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) + return internal::ploadt(m_data + index * innerStride()); + } + + /** \internal Constructor for fixed size matrices or vectors */ + EIGEN_DEVICE_FUNC explicit inline MapBase(PointerType dataPtr) + : m_data(dataPtr), m_rows(RowsAtCompileTime), m_cols(ColsAtCompileTime) { + EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) + checkSanity(); + } + + /** \internal Constructor for dynamically sized vectors */ + EIGEN_DEVICE_FUNC inline MapBase(PointerType dataPtr, Index vecSize) + : m_data(dataPtr), + m_rows(RowsAtCompileTime == Dynamic ? vecSize : Index(RowsAtCompileTime)), + m_cols(ColsAtCompileTime == Dynamic ? vecSize : Index(ColsAtCompileTime)) { + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + eigen_assert(vecSize >= 0); + eigen_assert(dataPtr == 0 || SizeAtCompileTime == Dynamic || SizeAtCompileTime == vecSize); + checkSanity(); + } + + /** \internal Constructor for dynamically sized matrices */ + EIGEN_DEVICE_FUNC inline MapBase(PointerType dataPtr, Index rows, Index cols) + : m_data(dataPtr), m_rows(rows), m_cols(cols) { + eigen_assert((dataPtr == 0) || (rows >= 0 && (RowsAtCompileTime == Dynamic || RowsAtCompileTime == rows) && + cols >= 0 && (ColsAtCompileTime == Dynamic || ColsAtCompileTime == cols))); + checkSanity(); + } + +#ifdef EIGEN_MAPBASE_PLUGIN +#include EIGEN_MAPBASE_PLUGIN #endif - } - template - EIGEN_DEVICE_FUNC - void checkSanity(typename internal::enable_if::Alignment==0,void*>::type = 0) const - {} + protected: + EIGEN_DEFAULT_COPY_CONSTRUCTOR(MapBase) + EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(MapBase) + + template + EIGEN_DEVICE_FUNC void checkSanity(std::enable_if_t<(internal::traits::Alignment > 0), void*> = 0) const { +// Temporary macro to allow scalars to not be properly aligned. This is while we sort out failures +// in TensorFlow Lite that are currently relying on this UB. +#ifndef EIGEN_ALLOW_UNALIGNED_SCALARS + // Pointer must be aligned to the Scalar type, otherwise we get UB. + eigen_assert((std::uintptr_t(m_data) % alignof(Scalar) == 0) && "data is not scalar-aligned"); +#endif +#if EIGEN_MAX_ALIGN_BYTES > 0 + // innerStride() is not set yet when this function is called, so we optimistically assume the lowest plausible + // value: + const Index minInnerStride = InnerStrideAtCompileTime == Dynamic ? 1 : Index(InnerStrideAtCompileTime); + EIGEN_ONLY_USED_FOR_DEBUG(minInnerStride); + eigen_assert((((std::uintptr_t(m_data) % internal::traits::Alignment) == 0) || + (cols() * rows() * minInnerStride * sizeof(Scalar)) < internal::traits::Alignment) && + "data is not aligned"); +#endif + } + + template + EIGEN_DEVICE_FUNC void checkSanity(std::enable_if_t::Alignment == 0, void*> = 0) const { +#ifndef EIGEN_ALLOW_UNALIGNED_SCALARS + // Pointer must be aligned to the Scalar type, otherwise we get UB. + eigen_assert((std::uintptr_t(m_data) % alignof(Scalar) == 0) && "data is not scalar-aligned"); +#endif + } - PointerType m_data; - const internal::variable_if_dynamic m_rows; - const internal::variable_if_dynamic m_cols; + PointerType m_data; + const internal::variable_if_dynamic m_rows; + const internal::variable_if_dynamic m_cols; }; /** \ingroup Core_Module - * - * \brief Base class for non-const dense Map and Block expression with direct access - * - * This base class provides the non-const low-level accessors (e.g. coeff and coeffRef) of - * dense Map and Block objects with direct access. - * It inherits MapBase which defines the const variant for reading specific entries. - * - * \sa class Map, class Block - */ -template class MapBase - : public MapBase -{ - typedef MapBase ReadOnlyMapBase; - public: - - typedef MapBase Base; - - typedef typename Base::Scalar Scalar; - typedef typename Base::PacketScalar PacketScalar; - typedef typename Base::StorageIndex StorageIndex; - typedef typename Base::PointerType PointerType; - - using Base::derived; - using Base::rows; - using Base::cols; - using Base::size; - using Base::coeff; - using Base::coeffRef; - - using Base::innerStride; - using Base::outerStride; - using Base::rowStride; - using Base::colStride; - - typedef typename internal::conditional< - internal::is_lvalue::value, - Scalar, - const Scalar - >::type ScalarWithConstIfNotLvalue; - - EIGEN_DEVICE_FUNC - inline const Scalar* data() const { return this->m_data; } - EIGEN_DEVICE_FUNC - inline ScalarWithConstIfNotLvalue* data() { return this->m_data; } // no const-cast here so non-const-correct code will give a compile error - - EIGEN_DEVICE_FUNC - inline ScalarWithConstIfNotLvalue& coeffRef(Index row, Index col) - { - return this->m_data[col * colStride() + row * rowStride()]; - } - - EIGEN_DEVICE_FUNC - inline ScalarWithConstIfNotLvalue& coeffRef(Index index) - { - EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) - return this->m_data[index * innerStride()]; - } - - template - inline void writePacket(Index row, Index col, const PacketScalar& val) - { - internal::pstoret - (this->m_data + (col * colStride() + row * rowStride()), val); - } - - template - inline void writePacket(Index index, const PacketScalar& val) - { - EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) - internal::pstoret - (this->m_data + index * innerStride(), val); - } - - EIGEN_DEVICE_FUNC explicit inline MapBase(PointerType dataPtr) : Base(dataPtr) {} - EIGEN_DEVICE_FUNC inline MapBase(PointerType dataPtr, Index vecSize) : Base(dataPtr, vecSize) {} - EIGEN_DEVICE_FUNC inline MapBase(PointerType dataPtr, Index rows, Index cols) : Base(dataPtr, rows, cols) {} - - EIGEN_DEVICE_FUNC - Derived& operator=(const MapBase& other) - { - ReadOnlyMapBase::Base::operator=(other); - return derived(); - } - - // In theory we could simply refer to Base:Base::operator=, but MSVC does not like Base::Base, - // see bugs 821 and 920. - using ReadOnlyMapBase::Base::operator=; - protected: - EIGEN_DEFAULT_COPY_CONSTRUCTOR(MapBase) - EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(MapBase) + * + * \brief Base class for non-const dense Map and Block expression with direct access + * + * This base class provides the non-const low-level accessors (e.g. coeff and coeffRef) of + * dense Map and Block objects with direct access. + * It inherits MapBase which defines the const variant for reading specific entries. + * + * \sa class Map, class Block + */ +template +class MapBase : public MapBase { + typedef MapBase ReadOnlyMapBase; + + public: + typedef MapBase Base; + + typedef typename Base::Scalar Scalar; + typedef typename Base::PacketScalar PacketScalar; + typedef typename Base::StorageIndex StorageIndex; + typedef typename Base::PointerType PointerType; + + using Base::coeff; + using Base::coeffRef; + using Base::cols; + using Base::derived; + using Base::rows; + using Base::size; + + using Base::colStride; + using Base::innerStride; + using Base::outerStride; + using Base::rowStride; + + typedef std::conditional_t::value, Scalar, const Scalar> ScalarWithConstIfNotLvalue; + + EIGEN_DEVICE_FUNC inline const Scalar* data() const { return this->m_data; } + EIGEN_DEVICE_FUNC inline ScalarWithConstIfNotLvalue* data() { + return this->m_data; + } // no const-cast here so non-const-correct code will give a compile error + + EIGEN_DEVICE_FUNC inline ScalarWithConstIfNotLvalue& coeffRef(Index row, Index col) { + return this->m_data[col * colStride() + row * rowStride()]; + } + + EIGEN_DEVICE_FUNC inline ScalarWithConstIfNotLvalue& coeffRef(Index index) { + EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) + return this->m_data[index * innerStride()]; + } + + template + inline void writePacket(Index row, Index col, const PacketScalar& val) { + internal::pstoret(this->m_data + (col * colStride() + row * rowStride()), val); + } + + template + inline void writePacket(Index index, const PacketScalar& val) { + EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) + internal::pstoret(this->m_data + index * innerStride(), val); + } + + EIGEN_DEVICE_FUNC explicit inline MapBase(PointerType dataPtr) : Base(dataPtr) {} + EIGEN_DEVICE_FUNC inline MapBase(PointerType dataPtr, Index vecSize) : Base(dataPtr, vecSize) {} + EIGEN_DEVICE_FUNC inline MapBase(PointerType dataPtr, Index rows, Index cols) : Base(dataPtr, rows, cols) {} + + EIGEN_DEVICE_FUNC Derived& operator=(const MapBase& other) { + ReadOnlyMapBase::Base::operator=(other); + return derived(); + } + + // In theory we could simply refer to Base:Base::operator=, but MSVC does not like Base::Base, + // see bugs 821 and 920. + using ReadOnlyMapBase::Base::operator=; + + protected: + EIGEN_DEFAULT_COPY_CONSTRUCTOR(MapBase) + EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(MapBase) }; #undef EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_MAPBASE_H +#endif // EIGEN_MAPBASE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MathFunctions.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MathFunctions.h index 61b78f4f20a..d42fc93cc96 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MathFunctions.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MathFunctions.h @@ -13,441 +13,344 @@ // TODO this should better be moved to NumTraits // Source: WolframAlpha -#define EIGEN_PI 3.141592653589793238462643383279502884197169399375105820974944592307816406L +#define EIGEN_PI 3.141592653589793238462643383279502884197169399375105820974944592307816406L #define EIGEN_LOG2E 1.442695040888963407359924681001892137426645954152985934135449406931109219L -#define EIGEN_LN2 0.693147180559945309417232121458176568075500134360255254120680009493393621L +#define EIGEN_LN2 0.693147180559945309417232121458176568075500134360255254120680009493393621L -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" -// On WINCE, std::abs is defined for int only, so let's defined our own overloads: -// This issue has been confirmed with MSVC 2008 only, but the issue might exist for more recent versions too. -#if EIGEN_OS_WINCE && EIGEN_COMP_MSVC && EIGEN_COMP_MSVC<=1500 -long abs(long x) { return (labs(x)); } -double abs(double x) { return (fabs(x)); } -float abs(float x) { return (fabsf(x)); } -long double abs(long double x) { return (fabsl(x)); } -#endif +namespace Eigen { namespace internal { /** \internal \class global_math_functions_filtering_base - * - * What it does: - * Defines a typedef 'type' as follows: - * - if type T has a member typedef Eigen_BaseClassForSpecializationOfGlobalMathFuncImpl, then - * global_math_functions_filtering_base::type is a typedef for it. - * - otherwise, global_math_functions_filtering_base::type is a typedef for T. - * - * How it's used: - * To allow to defined the global math functions (like sin...) in certain cases, like the Array expressions. - * When you do sin(array1+array2), the object array1+array2 has a complicated expression type, all what you want to know - * is that it inherits ArrayBase. So we implement a partial specialization of sin_impl for ArrayBase. - * So we must make sure to use sin_impl > and not sin_impl, otherwise our partial specialization - * won't be used. How does sin know that? That's exactly what global_math_functions_filtering_base tells it. - * - * How it's implemented: - * SFINAE in the style of enable_if. Highly susceptible of breaking compilers. With GCC, it sure does work, but if you replace - * the typename dummy by an integer template parameter, it doesn't work anymore! - */ - -template -struct global_math_functions_filtering_base -{ + * + * What it does: + * Defines a typedef 'type' as follows: + * - if type T has a member typedef Eigen_BaseClassForSpecializationOfGlobalMathFuncImpl, then + * global_math_functions_filtering_base::type is a typedef for it. + * - otherwise, global_math_functions_filtering_base::type is a typedef for T. + * + * How it's used: + * To allow to defined the global math functions (like sin...) in certain cases, like the Array expressions. + * When you do sin(array1+array2), the object array1+array2 has a complicated expression type, all what you want to know + * is that it inherits ArrayBase. So we implement a partial specialization of sin_impl for ArrayBase. + * So we must make sure to use sin_impl > and not sin_impl, otherwise our partial + * specialization won't be used. How does sin know that? That's exactly what global_math_functions_filtering_base tells + * it. + * + * How it's implemented: + * SFINAE in the style of enable_if. Highly susceptible of breaking compilers. With GCC, it sure does work, but if you + * replace the typename dummy by an integer template parameter, it doesn't work anymore! + */ + +template +struct global_math_functions_filtering_base { typedef T type; }; -template struct always_void { typedef void type; }; +template +struct always_void { + typedef void type; +}; -template -struct global_math_functions_filtering_base - ::type - > -{ +template +struct global_math_functions_filtering_base< + T, typename always_void::type> { typedef typename T::Eigen_BaseClassForSpecializationOfGlobalMathFuncImpl type; }; -#define EIGEN_MATHFUNC_IMPL(func, scalar) Eigen::internal::func##_impl::type> -#define EIGEN_MATHFUNC_RETVAL(func, scalar) typename Eigen::internal::func##_retval::type>::type +#define EIGEN_MATHFUNC_IMPL(func, scalar) \ + Eigen::internal::func##_impl::type> +#define EIGEN_MATHFUNC_RETVAL(func, scalar) \ + typename Eigen::internal::func##_retval< \ + typename Eigen::internal::global_math_functions_filtering_base::type>::type /**************************************************************************** -* Implementation of real * -****************************************************************************/ + * Implementation of real * + ****************************************************************************/ -template::IsComplex> -struct real_default_impl -{ +template ::IsComplex> +struct real_default_impl { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const Scalar& x) - { - return x; - } + EIGEN_DEVICE_FUNC static inline RealScalar run(const Scalar& x) { return x; } }; -template -struct real_default_impl -{ +template +struct real_default_impl { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const Scalar& x) - { + EIGEN_DEVICE_FUNC static inline RealScalar run(const Scalar& x) { using std::real; return real(x); } }; -template struct real_impl : real_default_impl {}; +template +struct real_impl : real_default_impl {}; #if defined(EIGEN_GPU_COMPILE_PHASE) -template -struct real_impl > -{ +template +struct real_impl> { typedef T RealScalar; - EIGEN_DEVICE_FUNC - static inline T run(const std::complex& x) - { - return x.real(); - } + EIGEN_DEVICE_FUNC static inline T run(const std::complex& x) { return x.real(); } }; #endif -template -struct real_retval -{ +template +struct real_retval { typedef typename NumTraits::Real type; }; /**************************************************************************** -* Implementation of imag * -****************************************************************************/ + * Implementation of imag * + ****************************************************************************/ -template::IsComplex> -struct imag_default_impl -{ +template ::IsComplex> +struct imag_default_impl { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const Scalar&) - { - return RealScalar(0); - } + EIGEN_DEVICE_FUNC static inline RealScalar run(const Scalar&) { return RealScalar(0); } }; -template -struct imag_default_impl -{ +template +struct imag_default_impl { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const Scalar& x) - { + EIGEN_DEVICE_FUNC static inline RealScalar run(const Scalar& x) { using std::imag; return imag(x); } }; -template struct imag_impl : imag_default_impl {}; +template +struct imag_impl : imag_default_impl {}; #if defined(EIGEN_GPU_COMPILE_PHASE) -template -struct imag_impl > -{ +template +struct imag_impl> { typedef T RealScalar; - EIGEN_DEVICE_FUNC - static inline T run(const std::complex& x) - { - return x.imag(); - } + EIGEN_DEVICE_FUNC static inline T run(const std::complex& x) { return x.imag(); } }; #endif -template -struct imag_retval -{ +template +struct imag_retval { typedef typename NumTraits::Real type; }; /**************************************************************************** -* Implementation of real_ref * -****************************************************************************/ + * Implementation of real_ref * + ****************************************************************************/ -template -struct real_ref_impl -{ +template +struct real_ref_impl { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar& run(Scalar& x) - { - return reinterpret_cast(&x)[0]; - } - EIGEN_DEVICE_FUNC - static inline const RealScalar& run(const Scalar& x) - { + EIGEN_DEVICE_FUNC static inline RealScalar& run(Scalar& x) { return reinterpret_cast(&x)[0]; } + EIGEN_DEVICE_FUNC static inline const RealScalar& run(const Scalar& x) { return reinterpret_cast(&x)[0]; } }; -template -struct real_ref_retval -{ - typedef typename NumTraits::Real & type; +template +struct real_ref_retval { + typedef typename NumTraits::Real& type; }; /**************************************************************************** -* Implementation of imag_ref * -****************************************************************************/ + * Implementation of imag_ref * + ****************************************************************************/ -template -struct imag_ref_default_impl -{ +template +struct imag_ref_default_impl { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar& run(Scalar& x) - { - return reinterpret_cast(&x)[1]; - } - EIGEN_DEVICE_FUNC - static inline const RealScalar& run(const Scalar& x) - { - return reinterpret_cast(&x)[1]; + EIGEN_DEVICE_FUNC static inline RealScalar& run(Scalar& x) { return reinterpret_cast(&x)[1]; } + EIGEN_DEVICE_FUNC static inline const RealScalar& run(const Scalar& x) { + return reinterpret_cast(&x)[1]; } }; -template -struct imag_ref_default_impl -{ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline Scalar run(Scalar&) - { - return Scalar(0); - } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline const Scalar run(const Scalar&) - { - return Scalar(0); - } +template +struct imag_ref_default_impl { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline Scalar run(Scalar&) { return Scalar(0); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline const Scalar run(const Scalar&) { return Scalar(0); } }; -template +template struct imag_ref_impl : imag_ref_default_impl::IsComplex> {}; -template -struct imag_ref_retval -{ - typedef typename NumTraits::Real & type; +template +struct imag_ref_retval { + typedef typename NumTraits::Real& type; }; /**************************************************************************** -* Implementation of conj * -****************************************************************************/ + * Implementation of conj * + ****************************************************************************/ -template::IsComplex> -struct conj_default_impl -{ - EIGEN_DEVICE_FUNC - static inline Scalar run(const Scalar& x) - { - return x; - } +template ::IsComplex> +struct conj_default_impl { + EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& x) { return x; } }; -template -struct conj_default_impl -{ - EIGEN_DEVICE_FUNC - static inline Scalar run(const Scalar& x) - { +template +struct conj_default_impl { + EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& x) { using std::conj; return conj(x); } }; -template::IsComplex> +template ::IsComplex> struct conj_impl : conj_default_impl {}; -template -struct conj_retval -{ +template +struct conj_retval { typedef Scalar type; }; /**************************************************************************** -* Implementation of abs2 * -****************************************************************************/ + * Implementation of abs2 * + ****************************************************************************/ -template -struct abs2_impl_default -{ +template +struct abs2_impl_default { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const Scalar& x) - { - return x*x; - } + EIGEN_DEVICE_FUNC static inline RealScalar run(const Scalar& x) { return x * x; } }; -template -struct abs2_impl_default // IsComplex +template +struct abs2_impl_default // IsComplex { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const Scalar& x) - { - return x.real()*x.real() + x.imag()*x.imag(); - } + EIGEN_DEVICE_FUNC static inline RealScalar run(const Scalar& x) { return x.real() * x.real() + x.imag() * x.imag(); } }; -template -struct abs2_impl -{ +template +struct abs2_impl { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const Scalar& x) - { - return abs2_impl_default::IsComplex>::run(x); + EIGEN_DEVICE_FUNC static inline RealScalar run(const Scalar& x) { + return abs2_impl_default::IsComplex>::run(x); } }; -template -struct abs2_retval -{ +template +struct abs2_retval { typedef typename NumTraits::Real type; }; /**************************************************************************** -* Implementation of sqrt/rsqrt * -****************************************************************************/ + * Implementation of sqrt/rsqrt * + ****************************************************************************/ -template -struct sqrt_impl -{ - EIGEN_DEVICE_FUNC - static EIGEN_ALWAYS_INLINE Scalar run(const Scalar& x) - { +template +struct sqrt_impl { + EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE Scalar run(const Scalar& x) { EIGEN_USING_STD(sqrt); return sqrt(x); } }; // Complex sqrt defined in MathFunctionsImpl.h. -template EIGEN_DEVICE_FUNC std::complex complex_sqrt(const std::complex& a_x); +template +EIGEN_DEVICE_FUNC std::complex complex_sqrt(const std::complex& a_x); // Custom implementation is faster than `std::sqrt`, works on // GPU, and correctly handles special cases (unlike MSVC). -template -struct sqrt_impl > -{ - EIGEN_DEVICE_FUNC - static EIGEN_ALWAYS_INLINE std::complex run(const std::complex& x) - { +template +struct sqrt_impl> { + EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE std::complex run(const std::complex& x) { return complex_sqrt(x); } }; -template -struct sqrt_retval -{ +template +struct sqrt_retval { typedef Scalar type; }; // Default implementation relies on numext::sqrt, at bottom of file. -template +template struct rsqrt_impl; // Complex rsqrt defined in MathFunctionsImpl.h. -template EIGEN_DEVICE_FUNC std::complex complex_rsqrt(const std::complex& a_x); +template +EIGEN_DEVICE_FUNC std::complex complex_rsqrt(const std::complex& a_x); -template -struct rsqrt_impl > -{ - EIGEN_DEVICE_FUNC - static EIGEN_ALWAYS_INLINE std::complex run(const std::complex& x) - { +template +struct rsqrt_impl> { + EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE std::complex run(const std::complex& x) { return complex_rsqrt(x); } }; -template -struct rsqrt_retval -{ +template +struct rsqrt_retval { typedef Scalar type; }; /**************************************************************************** -* Implementation of norm1 * -****************************************************************************/ + * Implementation of norm1 * + ****************************************************************************/ -template +template struct norm1_default_impl; -template -struct norm1_default_impl -{ +template +struct norm1_default_impl { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const Scalar& x) - { + EIGEN_DEVICE_FUNC static inline RealScalar run(const Scalar& x) { EIGEN_USING_STD(abs); return abs(x.real()) + abs(x.imag()); } }; -template -struct norm1_default_impl -{ - EIGEN_DEVICE_FUNC - static inline Scalar run(const Scalar& x) - { +template +struct norm1_default_impl { + EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& x) { EIGEN_USING_STD(abs); return abs(x); } }; -template +template struct norm1_impl : norm1_default_impl::IsComplex> {}; -template -struct norm1_retval -{ +template +struct norm1_retval { typedef typename NumTraits::Real type; }; /**************************************************************************** -* Implementation of hypot * -****************************************************************************/ + * Implementation of hypot * + ****************************************************************************/ -template struct hypot_impl; +template +struct hypot_impl; -template -struct hypot_retval -{ +template +struct hypot_retval { typedef typename NumTraits::Real type; }; /**************************************************************************** -* Implementation of cast * -****************************************************************************/ + * Implementation of cast * + ****************************************************************************/ -template -struct cast_impl -{ - EIGEN_DEVICE_FUNC - static inline NewType run(const OldType& x) - { - return static_cast(x); - } +template +struct cast_impl { + EIGEN_DEVICE_FUNC static inline NewType run(const OldType& x) { return static_cast(x); } +}; + +template +struct cast_impl { + EIGEN_DEVICE_FUNC static inline bool run(const OldType& x) { return x != OldType(0); } }; // Casting from S -> Complex leads to an implicit conversion from S to T, // generating warnings on clang. Here we explicitly cast the real component. -template +template struct cast_impl::IsComplex && NumTraits::IsComplex - >::type> -{ - EIGEN_DEVICE_FUNC - static inline NewType run(const OldType& x) - { + typename std::enable_if_t::IsComplex && NumTraits::IsComplex>> { + EIGEN_DEVICE_FUNC static inline NewType run(const OldType& x) { typedef typename NumTraits::Real NewReal; return static_cast(static_cast(x)); } @@ -455,667 +358,592 @@ struct cast_impl -EIGEN_DEVICE_FUNC -inline NewType cast(const OldType& x) -{ +template +EIGEN_DEVICE_FUNC inline NewType cast(const OldType& x) { return cast_impl::run(x); } /**************************************************************************** -* Implementation of round * -****************************************************************************/ - -template -struct round_impl -{ - EIGEN_DEVICE_FUNC - static inline Scalar run(const Scalar& x) - { - EIGEN_STATIC_ASSERT((!NumTraits::IsComplex), NUMERIC_TYPE_MUST_BE_REAL) -#if EIGEN_HAS_CXX11_MATH - EIGEN_USING_STD(round); -#endif - return Scalar(round(x)); - } -}; - -#if !EIGEN_HAS_CXX11_MATH -#if EIGEN_HAS_C99_MATH -// Use ::roundf for float. -template<> -struct round_impl { - EIGEN_DEVICE_FUNC - static inline float run(const float& x) - { - return ::roundf(x); - } -}; -#else -template -struct round_using_floor_ceil_impl -{ - EIGEN_DEVICE_FUNC - static inline Scalar run(const Scalar& x) - { - EIGEN_STATIC_ASSERT((!NumTraits::IsComplex), NUMERIC_TYPE_MUST_BE_REAL) - // Without C99 round/roundf, resort to floor/ceil. - EIGEN_USING_STD(floor); - EIGEN_USING_STD(ceil); - // If not enough precision to resolve a decimal at all, return the input. - // Otherwise, adding 0.5 can trigger an increment by 1. - const Scalar limit = Scalar(1ull << (NumTraits::digits() - 1)); - if (x >= limit || x <= -limit) { - return x; - } - return (x > Scalar(0)) ? Scalar(floor(x + Scalar(0.5))) : Scalar(ceil(x - Scalar(0.5))); - } -}; - -template<> -struct round_impl : round_using_floor_ceil_impl {}; - -template<> -struct round_impl : round_using_floor_ceil_impl {}; -#endif // EIGEN_HAS_C99_MATH -#endif // !EIGEN_HAS_CXX11_MATH - -template -struct round_retval -{ - typedef Scalar type; -}; - -/**************************************************************************** -* Implementation of rint * -****************************************************************************/ - -template -struct rint_impl { - EIGEN_DEVICE_FUNC - static inline Scalar run(const Scalar& x) - { - EIGEN_STATIC_ASSERT((!NumTraits::IsComplex), NUMERIC_TYPE_MUST_BE_REAL) -#if EIGEN_HAS_CXX11_MATH - EIGEN_USING_STD(rint); -#endif - return rint(x); - } -}; - -#if !EIGEN_HAS_CXX11_MATH -template<> -struct rint_impl { - EIGEN_DEVICE_FUNC - static inline double run(const double& x) - { - return ::rint(x); - } -}; -template<> -struct rint_impl { - EIGEN_DEVICE_FUNC - static inline float run(const float& x) - { - return ::rintf(x); - } -}; -#endif - -template -struct rint_retval -{ - typedef Scalar type; -}; - -/**************************************************************************** -* Implementation of arg * -****************************************************************************/ + * Implementation of arg * + ****************************************************************************/ // Visual Studio 2017 has a bug where arg(float) returns 0 for negative inputs. // This seems to be fixed in VS 2019. -#if EIGEN_HAS_CXX11_MATH && (!EIGEN_COMP_MSVC || EIGEN_COMP_MSVC >= 1920) +#if (!EIGEN_COMP_MSVC || EIGEN_COMP_MSVC >= 1920) // std::arg is only defined for types of std::complex, or integer types or float/double/long double -template::IsComplex || is_integral::value - || is_same::value || is_same::value - || is_same::value > +template ::IsComplex || is_integral::value || + is_same::value || is_same::value || + is_same::value> struct arg_default_impl; -template +template struct arg_default_impl { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const Scalar& x) - { - #if defined(EIGEN_HIP_DEVICE_COMPILE) - // HIP does not seem to have a native device side implementation for the math routine "arg" + EIGEN_DEVICE_FUNC static inline RealScalar run(const Scalar& x) { + // There is no official ::arg on device in CUDA/HIP, so we always need to use std::arg. using std::arg; - #else - EIGEN_USING_STD(arg); - #endif return static_cast(arg(x)); } }; // Must be non-complex floating-point type (e.g. half/bfloat16). -template +template struct arg_default_impl { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const Scalar& x) - { + EIGEN_DEVICE_FUNC static inline RealScalar run(const Scalar& x) { return (x < Scalar(0)) ? RealScalar(EIGEN_PI) : RealScalar(0); } }; #else -template::IsComplex> -struct arg_default_impl -{ +template ::IsComplex> +struct arg_default_impl { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const Scalar& x) - { + EIGEN_DEVICE_FUNC static inline RealScalar run(const Scalar& x) { return (x < RealScalar(0)) ? RealScalar(EIGEN_PI) : RealScalar(0); } }; -template -struct arg_default_impl -{ +template +struct arg_default_impl { typedef typename NumTraits::Real RealScalar; - EIGEN_DEVICE_FUNC - static inline RealScalar run(const Scalar& x) - { + EIGEN_DEVICE_FUNC static inline RealScalar run(const Scalar& x) { EIGEN_USING_STD(arg); return arg(x); } }; #endif -template struct arg_impl : arg_default_impl {}; +template +struct arg_impl : arg_default_impl {}; -template -struct arg_retval -{ +template +struct arg_retval { typedef typename NumTraits::Real type; }; /**************************************************************************** -* Implementation of expm1 * -****************************************************************************/ + * Implementation of expm1 * + ****************************************************************************/ // This implementation is based on GSL Math's expm1. namespace std_fallback { - // fallback expm1 implementation in case there is no expm1(Scalar) function in namespace of Scalar, - // or that there is no suitable std::expm1 function available. Implementation - // attributed to Kahan. See: http://www.plunk.org/~hatch/rightway.php. - template - EIGEN_DEVICE_FUNC inline Scalar expm1(const Scalar& x) { - EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar) - typedef typename NumTraits::Real RealScalar; - - EIGEN_USING_STD(exp); - Scalar u = exp(x); - if (numext::equal_strict(u, Scalar(1))) { - return x; - } - Scalar um1 = u - RealScalar(1); - if (numext::equal_strict(um1, Scalar(-1))) { - return RealScalar(-1); - } +// fallback expm1 implementation in case there is no expm1(Scalar) function in namespace of Scalar, +// or that there is no suitable std::expm1 function available. Implementation +// attributed to Kahan. See: http://www.plunk.org/~hatch/rightway.php. +template +EIGEN_DEVICE_FUNC inline Scalar expm1(const Scalar& x) { + EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar) + typedef typename NumTraits::Real RealScalar; - EIGEN_USING_STD(log); - Scalar logu = log(u); - return numext::equal_strict(u, logu) ? u : (u - RealScalar(1)) * x / logu; + EIGEN_USING_STD(exp); + Scalar u = exp(x); + if (numext::equal_strict(u, Scalar(1))) { + return x; + } + Scalar um1 = u - RealScalar(1); + if (numext::equal_strict(um1, Scalar(-1))) { + return RealScalar(-1); } + + EIGEN_USING_STD(log); + Scalar logu = log(u); + return numext::equal_strict(u, logu) ? u : (u - RealScalar(1)) * x / logu; } +} // namespace std_fallback -template +template struct expm1_impl { - EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& x) - { + EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& x) { EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar) - #if EIGEN_HAS_CXX11_MATH - using std::expm1; - #else - using std_fallback::expm1; - #endif + EIGEN_USING_STD(expm1); return expm1(x); } }; -template -struct expm1_retval -{ +template +struct expm1_retval { typedef Scalar type; }; /**************************************************************************** -* Implementation of log * -****************************************************************************/ + * Implementation of log * + ****************************************************************************/ // Complex log defined in MathFunctionsImpl.h. -template EIGEN_DEVICE_FUNC std::complex complex_log(const std::complex& z); +template +EIGEN_DEVICE_FUNC std::complex complex_log(const std::complex& z); -template +template struct log_impl { - EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& x) - { + EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& x) { EIGEN_USING_STD(log); return static_cast(log(x)); } }; -template -struct log_impl > { - EIGEN_DEVICE_FUNC static inline std::complex run(const std::complex& z) - { - return complex_log(z); - } +template +struct log_impl> { + EIGEN_DEVICE_FUNC static inline std::complex run(const std::complex& z) { return complex_log(z); } }; /**************************************************************************** -* Implementation of log1p * -****************************************************************************/ + * Implementation of log1p * + ****************************************************************************/ namespace std_fallback { - // fallback log1p implementation in case there is no log1p(Scalar) function in namespace of Scalar, - // or that there is no suitable std::log1p function available - template - EIGEN_DEVICE_FUNC inline Scalar log1p(const Scalar& x) { - EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar) - typedef typename NumTraits::Real RealScalar; - EIGEN_USING_STD(log); - Scalar x1p = RealScalar(1) + x; - Scalar log_1p = log_impl::run(x1p); - const bool is_small = numext::equal_strict(x1p, Scalar(1)); - const bool is_inf = numext::equal_strict(x1p, log_1p); - return (is_small || is_inf) ? x : x * (log_1p / (x1p - RealScalar(1))); - } +// fallback log1p implementation in case there is no log1p(Scalar) function in namespace of Scalar, +// or that there is no suitable std::log1p function available +template +EIGEN_DEVICE_FUNC inline Scalar log1p(const Scalar& x) { + EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar) + typedef typename NumTraits::Real RealScalar; + EIGEN_USING_STD(log); + Scalar x1p = RealScalar(1) + x; + Scalar log_1p = log_impl::run(x1p); + const bool is_small = numext::equal_strict(x1p, Scalar(1)); + const bool is_inf = numext::equal_strict(x1p, log_1p); + return (is_small || is_inf) ? x : x * (log_1p / (x1p - RealScalar(1))); } +} // namespace std_fallback -template +template struct log1p_impl { - EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& x) - { - EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar) - #if EIGEN_HAS_CXX11_MATH - using std::log1p; - #else - using std_fallback::log1p; - #endif + EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar) + + EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& x) { + EIGEN_USING_STD(log1p); return log1p(x); } }; // Specialization for complex types that are not supported by std::log1p. template -struct log1p_impl > { - EIGEN_DEVICE_FUNC static inline std::complex run( - const std::complex& x) { - EIGEN_STATIC_ASSERT_NON_INTEGER(RealScalar) +struct log1p_impl> { + EIGEN_STATIC_ASSERT_NON_INTEGER(RealScalar) + + EIGEN_DEVICE_FUNC static inline std::complex run(const std::complex& x) { return std_fallback::log1p(x); } }; -template -struct log1p_retval -{ +template +struct log1p_retval { typedef Scalar type; }; /**************************************************************************** -* Implementation of pow * -****************************************************************************/ - -template::IsInteger&&NumTraits::IsInteger> -struct pow_impl -{ - //typedef Scalar retval; - typedef typename ScalarBinaryOpTraits >::ReturnType result_type; - static EIGEN_DEVICE_FUNC inline result_type run(const ScalarX& x, const ScalarY& y) - { + * Implementation of pow * + ****************************************************************************/ + +template ::IsInteger && NumTraits::IsInteger> +struct pow_impl { + // typedef Scalar retval; + typedef typename ScalarBinaryOpTraits>::ReturnType + result_type; + static EIGEN_DEVICE_FUNC inline result_type run(const ScalarX& x, const ScalarY& y) { EIGEN_USING_STD(pow); return pow(x, y); } }; -template -struct pow_impl -{ +template +struct pow_impl { typedef ScalarX result_type; - static EIGEN_DEVICE_FUNC inline ScalarX run(ScalarX x, ScalarY y) - { + static EIGEN_DEVICE_FUNC inline ScalarX run(ScalarX x, ScalarY y) { ScalarX res(1); eigen_assert(!NumTraits::IsSigned || y >= 0); - if(y & 1) res *= x; + if (y & 1) res *= x; y >>= 1; - while(y) - { + while (y) { x *= x; - if(y&1) res *= x; + if (y & 1) res *= x; y >>= 1; } return res; } }; -/**************************************************************************** -* Implementation of random * -****************************************************************************/ +enum { meta_floor_log2_terminate, meta_floor_log2_move_up, meta_floor_log2_move_down, meta_floor_log2_bogus }; -template -struct random_default_impl {}; +template +struct meta_floor_log2_selector { + enum { + middle = (lower + upper) / 2, + value = (upper <= lower + 1) ? int(meta_floor_log2_terminate) + : (n < (1 << middle)) ? int(meta_floor_log2_move_down) + : (n == 0) ? int(meta_floor_log2_bogus) + : int(meta_floor_log2_move_up) + }; +}; -template -struct random_impl : random_default_impl::IsComplex, NumTraits::IsInteger> {}; +template ::value> +struct meta_floor_log2 {}; -template -struct random_retval -{ - typedef Scalar type; +template +struct meta_floor_log2 { + enum { value = meta_floor_log2::middle>::value }; }; -template inline EIGEN_MATHFUNC_RETVAL(random, Scalar) random(const Scalar& x, const Scalar& y); -template inline EIGEN_MATHFUNC_RETVAL(random, Scalar) random(); +template +struct meta_floor_log2 { + enum { value = meta_floor_log2::middle, upper>::value }; +}; -template -struct random_default_impl -{ - static inline Scalar run(const Scalar& x, const Scalar& y) - { - return x + (y-x) * Scalar(std::rand()) / Scalar(RAND_MAX); - } - static inline Scalar run() - { - return run(Scalar(NumTraits::IsSigned ? -1 : 0), Scalar(1)); - } +template +struct meta_floor_log2 { + enum { value = (n >= ((unsigned int)(1) << (lower + 1))) ? lower + 1 : lower }; }; -enum { - meta_floor_log2_terminate, - meta_floor_log2_move_up, - meta_floor_log2_move_down, - meta_floor_log2_bogus +template +struct meta_floor_log2 { + // no value, error at compile time }; -template struct meta_floor_log2_selector -{ - enum { middle = (lower + upper) / 2, - value = (upper <= lower + 1) ? int(meta_floor_log2_terminate) - : (n < (1 << middle)) ? int(meta_floor_log2_move_down) - : (n==0) ? int(meta_floor_log2_bogus) - : int(meta_floor_log2_move_up) - }; +template +struct count_bits_impl { + static_assert(std::is_integral::value && std::is_unsigned::value, + "BitsType must be an unsigned integer"); + static EIGEN_DEVICE_FUNC inline int clz(BitsType bits) { + int n = CHAR_BIT * sizeof(BitsType); + int shift = n / 2; + while (bits > 0 && shift > 0) { + BitsType y = bits >> shift; + if (y > 0) { + n -= shift; + bits = y; + } + shift /= 2; + } + if (shift == 0) { + --n; + } + return n; + } + + static EIGEN_DEVICE_FUNC inline int ctz(BitsType bits) { + int n = CHAR_BIT * sizeof(BitsType); + int shift = n / 2; + while (bits > 0 && shift > 0) { + BitsType y = bits << shift; + if (y > 0) { + n -= shift; + bits = y; + } + shift /= 2; + } + if (shift == 0) { + --n; + } + return n; + } }; -template::value> -struct meta_floor_log2 {}; +// Count leading zeros. +template +EIGEN_DEVICE_FUNC inline int clz(BitsType bits) { + return count_bits_impl::clz(bits); +} -template -struct meta_floor_log2 -{ - enum { value = meta_floor_log2::middle>::value }; +// Count trailing zeros. +template +EIGEN_DEVICE_FUNC inline int ctz(BitsType bits) { + return count_bits_impl::ctz(bits); +} + +#if EIGEN_COMP_GNUC || EIGEN_COMP_CLANG + +template +struct count_bits_impl< + BitsType, std::enable_if_t::value && sizeof(BitsType) <= sizeof(unsigned int)>> { + static constexpr int kNumBits = static_cast(sizeof(BitsType) * CHAR_BIT); + static EIGEN_DEVICE_FUNC inline int clz(BitsType bits) { + static constexpr int kLeadingBitsOffset = (sizeof(unsigned int) - sizeof(BitsType)) * CHAR_BIT; + return bits == 0 ? kNumBits : __builtin_clz(static_cast(bits)) - kLeadingBitsOffset; + } + + static EIGEN_DEVICE_FUNC inline int ctz(BitsType bits) { + return bits == 0 ? kNumBits : __builtin_ctz(static_cast(bits)); + } }; -template -struct meta_floor_log2 -{ - enum { value = meta_floor_log2::middle, upper>::value }; +template +struct count_bits_impl::value && sizeof(unsigned int) < sizeof(BitsType) && + sizeof(BitsType) <= sizeof(unsigned long)>> { + static constexpr int kNumBits = static_cast(sizeof(BitsType) * CHAR_BIT); + static EIGEN_DEVICE_FUNC inline int clz(BitsType bits) { + static constexpr int kLeadingBitsOffset = (sizeof(unsigned long) - sizeof(BitsType)) * CHAR_BIT; + return bits == 0 ? kNumBits : __builtin_clzl(static_cast(bits)) - kLeadingBitsOffset; + } + + static EIGEN_DEVICE_FUNC inline int ctz(BitsType bits) { + return bits == 0 ? kNumBits : __builtin_ctzl(static_cast(bits)); + } }; -template -struct meta_floor_log2 -{ - enum { value = (n >= ((unsigned int)(1) << (lower+1))) ? lower+1 : lower }; +template +struct count_bits_impl::value && sizeof(unsigned long) < sizeof(BitsType) && + sizeof(BitsType) <= sizeof(unsigned long long)>> { + static constexpr int kNumBits = static_cast(sizeof(BitsType) * CHAR_BIT); + static EIGEN_DEVICE_FUNC inline int clz(BitsType bits) { + static constexpr int kLeadingBitsOffset = (sizeof(unsigned long long) - sizeof(BitsType)) * CHAR_BIT; + return bits == 0 ? kNumBits : __builtin_clzll(static_cast(bits)) - kLeadingBitsOffset; + } + + static EIGEN_DEVICE_FUNC inline int ctz(BitsType bits) { + return bits == 0 ? kNumBits : __builtin_ctzll(static_cast(bits)); + } }; -template -struct meta_floor_log2 -{ - // no value, error at compile time +#elif EIGEN_COMP_MSVC + +template +struct count_bits_impl< + BitsType, std::enable_if_t::value && sizeof(BitsType) <= sizeof(unsigned long)>> { + static constexpr int kNumBits = static_cast(sizeof(BitsType) * CHAR_BIT); + static EIGEN_DEVICE_FUNC inline int clz(BitsType bits) { + unsigned long out; + _BitScanReverse(&out, static_cast(bits)); + return bits == 0 ? kNumBits : (kNumBits - 1) - static_cast(out); + } + + static EIGEN_DEVICE_FUNC inline int ctz(BitsType bits) { + unsigned long out; + _BitScanForward(&out, static_cast(bits)); + return bits == 0 ? kNumBits : static_cast(out); + } }; -template -struct random_default_impl -{ - static inline Scalar run(const Scalar& x, const Scalar& y) - { - if (y <= x) - return x; - // ScalarU is the unsigned counterpart of Scalar, possibly Scalar itself. - typedef typename make_unsigned::type ScalarU; - // ScalarX is the widest of ScalarU and unsigned int. - // We'll deal only with ScalarX and unsigned int below thus avoiding signed - // types and arithmetic and signed overflows (which are undefined behavior). - typedef typename conditional<(ScalarU(-1) > unsigned(-1)), ScalarU, unsigned>::type ScalarX; - // The following difference doesn't overflow, provided our integer types are two's - // complement and have the same number of padding bits in signed and unsigned variants. - // This is the case in most modern implementations of C++. - ScalarX range = ScalarX(y) - ScalarX(x); - ScalarX offset = 0; - ScalarX divisor = 1; - ScalarX multiplier = 1; - const unsigned rand_max = RAND_MAX; - if (range <= rand_max) divisor = (rand_max + 1) / (range + 1); - else multiplier = 1 + range / (rand_max + 1); - // Rejection sampling. - do { - offset = (unsigned(std::rand()) * multiplier) / divisor; - } while (offset > range); - return Scalar(ScalarX(x) + offset); +#ifdef _WIN64 + +template +struct count_bits_impl::value && sizeof(unsigned long) < sizeof(BitsType) && + sizeof(BitsType) <= sizeof(__int64)>> { + static constexpr int kNumBits = static_cast(sizeof(BitsType) * CHAR_BIT); + static EIGEN_DEVICE_FUNC inline int clz(BitsType bits) { + unsigned long out; + _BitScanReverse64(&out, static_cast(bits)); + return bits == 0 ? kNumBits : (kNumBits - 1) - static_cast(out); } - static inline Scalar run() - { -#ifdef EIGEN_MAKING_DOCS - return run(Scalar(NumTraits::IsSigned ? -10 : 0), Scalar(10)); -#else - enum { rand_bits = meta_floor_log2<(unsigned int)(RAND_MAX)+1>::value, - scalar_bits = sizeof(Scalar) * CHAR_BIT, - shift = EIGEN_PLAIN_ENUM_MAX(0, int(rand_bits) - int(scalar_bits)), - offset = NumTraits::IsSigned ? (1 << (EIGEN_PLAIN_ENUM_MIN(rand_bits,scalar_bits)-1)) : 0 - }; - return Scalar((std::rand() >> shift) - offset); -#endif + static EIGEN_DEVICE_FUNC inline int ctz(BitsType bits) { + unsigned long out; + _BitScanForward64(&out, static_cast(bits)); + return bits == 0 ? kNumBits : static_cast(out); } }; -template -struct random_default_impl -{ - static inline Scalar run(const Scalar& x, const Scalar& y) - { - return Scalar(random(x.real(), y.real()), - random(x.imag(), y.imag())); +#endif // _WIN64 + +#endif // EIGEN_COMP_GNUC || EIGEN_COMP_CLANG + +template +struct log_2_impl { + static constexpr int kTotalBits = sizeof(BitsType) * CHAR_BIT; + static EIGEN_DEVICE_FUNC inline int run_ceil(const BitsType& x) { + const int n = kTotalBits - clz(x); + bool power_of_two = (x & (x - 1)) == 0; + return x == 0 ? 0 : power_of_two ? (n - 1) : n; } - static inline Scalar run() - { - typedef typename NumTraits::Real RealScalar; - return Scalar(random(), random()); + static EIGEN_DEVICE_FUNC inline int run_floor(const BitsType& x) { + const int n = kTotalBits - clz(x); + return x == 0 ? 0 : n - 1; } }; -template -inline EIGEN_MATHFUNC_RETVAL(random, Scalar) random(const Scalar& x, const Scalar& y) -{ - return EIGEN_MATHFUNC_IMPL(random, Scalar)::run(x, y); +template +int log2_ceil(const BitsType& x) { + return log_2_impl::run_ceil(x); } -template -inline EIGEN_MATHFUNC_RETVAL(random, Scalar) random() -{ - return EIGEN_MATHFUNC_IMPL(random, Scalar)::run(); +template +int log2_floor(const BitsType& x) { + return log_2_impl::run_floor(x); } // Implementation of is* functions -// std::is* do not work with fast-math and gcc, std::is* are available on MSVC 2013 and newer, as well as in clang. -#if (EIGEN_HAS_CXX11_MATH && !(EIGEN_COMP_GNUC_STRICT && __FINITE_MATH_ONLY__)) || (EIGEN_COMP_MSVC>=1800) || (EIGEN_COMP_CLANG) -#define EIGEN_USE_STD_FPCLASSIFY 1 -#else -#define EIGEN_USE_STD_FPCLASSIFY 0 -#endif - -template -EIGEN_DEVICE_FUNC -typename internal::enable_if::value,bool>::type -isnan_impl(const T&) { return false; } - -template -EIGEN_DEVICE_FUNC -typename internal::enable_if::value,bool>::type -isinf_impl(const T&) { return false; } +template +EIGEN_DEVICE_FUNC std::enable_if_t::has_infinity || std::numeric_limits::has_quiet_NaN || + std::numeric_limits::has_signaling_NaN), + bool> +isfinite_impl(const T&) { + return true; +} -template -EIGEN_DEVICE_FUNC -typename internal::enable_if::value,bool>::type -isfinite_impl(const T&) { return true; } +template +EIGEN_DEVICE_FUNC std::enable_if_t<(std::numeric_limits::has_infinity || std::numeric_limits::has_quiet_NaN || + std::numeric_limits::has_signaling_NaN) && + (!NumTraits::IsComplex), + bool> +isfinite_impl(const T& x) { + EIGEN_USING_STD(isfinite); + return isfinite EIGEN_NOT_A_MACRO(x); +} -template -EIGEN_DEVICE_FUNC -typename internal::enable_if<(!internal::is_integral::value)&&(!NumTraits::IsComplex),bool>::type -isfinite_impl(const T& x) -{ - #if defined(EIGEN_GPU_COMPILE_PHASE) - return (::isfinite)(x); - #elif EIGEN_USE_STD_FPCLASSIFY - using std::isfinite; - return isfinite EIGEN_NOT_A_MACRO (x); - #else - return x<=NumTraits::highest() && x>=NumTraits::lowest(); - #endif +template +EIGEN_DEVICE_FUNC std::enable_if_t::has_infinity, bool> isinf_impl(const T&) { + return false; } -template -EIGEN_DEVICE_FUNC -typename internal::enable_if<(!internal::is_integral::value)&&(!NumTraits::IsComplex),bool>::type -isinf_impl(const T& x) -{ - #if defined(EIGEN_GPU_COMPILE_PHASE) - return (::isinf)(x); - #elif EIGEN_USE_STD_FPCLASSIFY - using std::isinf; - return isinf EIGEN_NOT_A_MACRO (x); - #else - return x>NumTraits::highest() || x::lowest(); - #endif +template +EIGEN_DEVICE_FUNC std::enable_if_t<(std::numeric_limits::has_infinity && !NumTraits::IsComplex), bool> isinf_impl( + const T& x) { + EIGEN_USING_STD(isinf); + return isinf EIGEN_NOT_A_MACRO(x); } -template +template EIGEN_DEVICE_FUNC -typename internal::enable_if<(!internal::is_integral::value)&&(!NumTraits::IsComplex),bool>::type -isnan_impl(const T& x) -{ - #if defined(EIGEN_GPU_COMPILE_PHASE) - return (::isnan)(x); - #elif EIGEN_USE_STD_FPCLASSIFY - using std::isnan; - return isnan EIGEN_NOT_A_MACRO (x); - #else - return x != x; - #endif + std::enable_if_t::has_quiet_NaN || std::numeric_limits::has_signaling_NaN), bool> + isnan_impl(const T&) { + return false; } -#if (!EIGEN_USE_STD_FPCLASSIFY) +template +EIGEN_DEVICE_FUNC std::enable_if_t< + (std::numeric_limits::has_quiet_NaN || std::numeric_limits::has_signaling_NaN) && (!NumTraits::IsComplex), + bool> +isnan_impl(const T& x) { + EIGEN_USING_STD(isnan); + return isnan EIGEN_NOT_A_MACRO(x); +} -#if EIGEN_COMP_MSVC +// The following overload are defined at the end of this file +template +EIGEN_DEVICE_FUNC bool isfinite_impl(const std::complex& x); +template +EIGEN_DEVICE_FUNC bool isnan_impl(const std::complex& x); +template +EIGEN_DEVICE_FUNC bool isinf_impl(const std::complex& x); +template +EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS T ptanh_float(const T& a_x); -template EIGEN_DEVICE_FUNC bool isinf_msvc_helper(T x) -{ - return _fpclass(x)==_FPCLASS_NINF || _fpclass(x)==_FPCLASS_PINF; -} +/**************************************************************************** + * Implementation of sign * + ****************************************************************************/ +template ::IsComplex != 0), + bool IsInteger = (NumTraits::IsInteger != 0)> +struct sign_impl { + EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& a) { return Scalar((a > Scalar(0)) - (a < Scalar(0))); } +}; -//MSVC defines a _isnan builtin function, but for double only -EIGEN_DEVICE_FUNC inline bool isnan_impl(const long double& x) { return _isnan(x)!=0; } -EIGEN_DEVICE_FUNC inline bool isnan_impl(const double& x) { return _isnan(x)!=0; } -EIGEN_DEVICE_FUNC inline bool isnan_impl(const float& x) { return _isnan(x)!=0; } +template +struct sign_impl { + EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& a) { + return (isnan_impl)(a) ? a : Scalar((a > Scalar(0)) - (a < Scalar(0))); + } +}; -EIGEN_DEVICE_FUNC inline bool isinf_impl(const long double& x) { return isinf_msvc_helper(x); } -EIGEN_DEVICE_FUNC inline bool isinf_impl(const double& x) { return isinf_msvc_helper(x); } -EIGEN_DEVICE_FUNC inline bool isinf_impl(const float& x) { return isinf_msvc_helper(x); } +template +struct sign_impl { + EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& a) { + using real_type = typename NumTraits::Real; + EIGEN_USING_STD(abs); + real_type aa = abs(a); + if (aa == real_type(0)) return Scalar(0); + aa = real_type(1) / aa; + return Scalar(a.real() * aa, a.imag() * aa); + } +}; -#elif (defined __FINITE_MATH_ONLY__ && __FINITE_MATH_ONLY__ && EIGEN_COMP_GNUC) +// The sign function for bool is the identity. +template <> +struct sign_impl { + EIGEN_DEVICE_FUNC static inline bool run(const bool& a) { return a; } +}; -#if EIGEN_GNUC_AT_LEAST(5,0) - #define EIGEN_TMP_NOOPT_ATTRIB EIGEN_DEVICE_FUNC inline __attribute__((optimize("no-finite-math-only"))) -#else - // NOTE the inline qualifier and noinline attribute are both needed: the former is to avoid linking issue (duplicate symbol), - // while the second prevent too aggressive optimizations in fast-math mode: - #define EIGEN_TMP_NOOPT_ATTRIB EIGEN_DEVICE_FUNC inline __attribute__((noinline,optimize("no-finite-math-only"))) -#endif +template +struct sign_retval { + typedef Scalar type; +}; -template<> EIGEN_TMP_NOOPT_ATTRIB bool isnan_impl(const long double& x) { return __builtin_isnan(x); } -template<> EIGEN_TMP_NOOPT_ATTRIB bool isnan_impl(const double& x) { return __builtin_isnan(x); } -template<> EIGEN_TMP_NOOPT_ATTRIB bool isnan_impl(const float& x) { return __builtin_isnan(x); } -template<> EIGEN_TMP_NOOPT_ATTRIB bool isinf_impl(const double& x) { return __builtin_isinf(x); } -template<> EIGEN_TMP_NOOPT_ATTRIB bool isinf_impl(const float& x) { return __builtin_isinf(x); } -template<> EIGEN_TMP_NOOPT_ATTRIB bool isinf_impl(const long double& x) { return __builtin_isinf(x); } +// suppress "unary minus operator applied to unsigned type, result still unsigned" warnings on MSVC +// note: `0 - a` is distinct from `-a` when Scalar is a floating point type and `a` is zero -#undef EIGEN_TMP_NOOPT_ATTRIB +template ::IsInteger> +struct negate_impl { + static EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Scalar run(const Scalar& a) { return -a; } +}; -#endif +template +struct negate_impl { + EIGEN_STATIC_ASSERT((!is_same::value), NEGATE IS NOT DEFINED FOR BOOLEAN TYPES) + static EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Scalar run(const Scalar& a) { return Scalar(0) - a; } +}; -#endif +template +struct negate_retval { + typedef Scalar type; +}; -// The following overload are defined at the end of this file -template EIGEN_DEVICE_FUNC bool isfinite_impl(const std::complex& x); -template EIGEN_DEVICE_FUNC bool isnan_impl(const std::complex& x); -template EIGEN_DEVICE_FUNC bool isinf_impl(const std::complex& x); +template ::type>::IsInteger> +struct nearest_integer_impl { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar run_floor(const Scalar& x) { + EIGEN_USING_STD(floor) return floor(x); + } + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar run_ceil(const Scalar& x) { + EIGEN_USING_STD(ceil) return ceil(x); + } + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar run_rint(const Scalar& x) { + EIGEN_USING_STD(rint) return rint(x); + } + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar run_round(const Scalar& x) { + EIGEN_USING_STD(round) return round(x); + } + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar run_trunc(const Scalar& x) { + EIGEN_USING_STD(trunc) return trunc(x); + } +}; +template +struct nearest_integer_impl { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar run_floor(const Scalar& x) { return x; } + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar run_ceil(const Scalar& x) { return x; } + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar run_rint(const Scalar& x) { return x; } + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar run_round(const Scalar& x) { return x; } + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar run_trunc(const Scalar& x) { return x; } +}; -template T generic_fast_tanh_float(const T& a_x); -} // end namespace internal +} // end namespace internal /**************************************************************************** -* Generic math functions * -****************************************************************************/ + * Generic math functions * + ****************************************************************************/ namespace numext { #if (!defined(EIGEN_GPUCC) || defined(EIGEN_CONSTEXPR_ARE_DEVICE_FUNC)) -template -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE T mini(const T& x, const T& y) -{ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T mini(const T& x, const T& y) { EIGEN_USING_STD(min) - return min EIGEN_NOT_A_MACRO (x,y); + return min EIGEN_NOT_A_MACRO(x, y); } -template -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE T maxi(const T& x, const T& y) -{ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T maxi(const T& x, const T& y) { EIGEN_USING_STD(max) - return max EIGEN_NOT_A_MACRO (x,y); + return max EIGEN_NOT_A_MACRO(x, y); } #else -template -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE T mini(const T& x, const T& y) -{ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T mini(const T& x, const T& y) { return y < x ? y : x; } -template<> -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE float mini(const float& x, const float& y) -{ +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float mini(const float& x, const float& y) { return fminf(x, y); } -template<> -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE double mini(const double& x, const double& y) -{ +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double mini(const double& x, const double& y) { return fmin(x, y); } -template<> -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE long double mini(const long double& x, const long double& y) -{ + +#ifndef EIGEN_GPU_COMPILE_PHASE +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE long double mini(const long double& x, const long double& y) { #if defined(EIGEN_HIPCC) // no "fminl" on HIP yet return (x < y) ? x : y; @@ -1123,29 +951,23 @@ EIGEN_ALWAYS_INLINE long double mini(const long double& x, const long double& y) return fminl(x, y); #endif } +#endif -template -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE T maxi(const T& x, const T& y) -{ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T maxi(const T& x, const T& y) { return x < y ? y : x; } -template<> -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE float maxi(const float& x, const float& y) -{ +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float maxi(const float& x, const float& y) { return fmaxf(x, y); -} -template<> -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE double maxi(const double& x, const double& y) -{ +} +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double maxi(const double& x, const double& y) { return fmax(x, y); } -template<> -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE long double maxi(const long double& x, const long double& y) -{ +#ifndef EIGEN_GPU_COMPILE_PHASE +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE long double maxi(const long double& x, const long double& y) { #if defined(EIGEN_HIPCC) // no "fmaxl" on HIP yet return (x > y) ? x : y; @@ -1154,68 +976,64 @@ EIGEN_ALWAYS_INLINE long double maxi(const long double& x, const long double& y) #endif } #endif +#endif #if defined(SYCL_DEVICE_ONLY) - #define SYCL_SPECIALIZE_SIGNED_INTEGER_TYPES_BINARY(NAME, FUNC) \ - SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_char) \ - SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_short) \ - SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_int) \ + SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_char) \ + SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_short) \ + SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_int) \ SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_long) #define SYCL_SPECIALIZE_SIGNED_INTEGER_TYPES_UNARY(NAME, FUNC) \ - SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_char) \ - SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_short) \ - SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_int) \ + SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_char) \ + SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_short) \ + SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_int) \ SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_long) #define SYCL_SPECIALIZE_UNSIGNED_INTEGER_TYPES_BINARY(NAME, FUNC) \ - SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_uchar) \ - SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_ushort) \ - SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_uint) \ + SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_uchar) \ + SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_ushort) \ + SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_uint) \ SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_ulong) #define SYCL_SPECIALIZE_UNSIGNED_INTEGER_TYPES_UNARY(NAME, FUNC) \ - SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_uchar) \ - SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_ushort) \ - SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_uint) \ + SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_uchar) \ + SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_ushort) \ + SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_uint) \ SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_ulong) -#define SYCL_SPECIALIZE_INTEGER_TYPES_BINARY(NAME, FUNC) \ +#define SYCL_SPECIALIZE_INTEGER_TYPES_BINARY(NAME, FUNC) \ SYCL_SPECIALIZE_SIGNED_INTEGER_TYPES_BINARY(NAME, FUNC) \ SYCL_SPECIALIZE_UNSIGNED_INTEGER_TYPES_BINARY(NAME, FUNC) -#define SYCL_SPECIALIZE_INTEGER_TYPES_UNARY(NAME, FUNC) \ +#define SYCL_SPECIALIZE_INTEGER_TYPES_UNARY(NAME, FUNC) \ SYCL_SPECIALIZE_SIGNED_INTEGER_TYPES_UNARY(NAME, FUNC) \ SYCL_SPECIALIZE_UNSIGNED_INTEGER_TYPES_UNARY(NAME, FUNC) -#define SYCL_SPECIALIZE_FLOATING_TYPES_BINARY(NAME, FUNC) \ +#define SYCL_SPECIALIZE_FLOATING_TYPES_BINARY(NAME, FUNC) \ SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_float) \ - SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC,cl::sycl::cl_double) -#define SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(NAME, FUNC) \ + SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, cl::sycl::cl_double) +#define SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(NAME, FUNC) \ SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_float) \ - SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC,cl::sycl::cl_double) + SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, cl::sycl::cl_double) #define SYCL_SPECIALIZE_FLOATING_TYPES_UNARY_FUNC_RET_TYPE(NAME, FUNC, RET_TYPE) \ - SYCL_SPECIALIZE_GEN_UNARY_FUNC(NAME, FUNC, RET_TYPE, cl::sycl::cl_float) \ + SYCL_SPECIALIZE_GEN_UNARY_FUNC(NAME, FUNC, RET_TYPE, cl::sycl::cl_float) \ SYCL_SPECIALIZE_GEN_UNARY_FUNC(NAME, FUNC, RET_TYPE, cl::sycl::cl_double) -#define SYCL_SPECIALIZE_GEN_UNARY_FUNC(NAME, FUNC, RET_TYPE, ARG_TYPE) \ -template<> \ - EIGEN_DEVICE_FUNC \ - EIGEN_ALWAYS_INLINE RET_TYPE NAME(const ARG_TYPE& x) { \ - return cl::sycl::FUNC(x); \ +#define SYCL_SPECIALIZE_GEN_UNARY_FUNC(NAME, FUNC, RET_TYPE, ARG_TYPE) \ + template <> \ + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE RET_TYPE NAME(const ARG_TYPE& x) { \ + return cl::sycl::FUNC(x); \ } -#define SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, TYPE) \ - SYCL_SPECIALIZE_GEN_UNARY_FUNC(NAME, FUNC, TYPE, TYPE) +#define SYCL_SPECIALIZE_UNARY_FUNC(NAME, FUNC, TYPE) SYCL_SPECIALIZE_GEN_UNARY_FUNC(NAME, FUNC, TYPE, TYPE) -#define SYCL_SPECIALIZE_GEN1_BINARY_FUNC(NAME, FUNC, RET_TYPE, ARG_TYPE1, ARG_TYPE2) \ - template<> \ - EIGEN_DEVICE_FUNC \ - EIGEN_ALWAYS_INLINE RET_TYPE NAME(const ARG_TYPE1& x, const ARG_TYPE2& y) { \ - return cl::sycl::FUNC(x, y); \ +#define SYCL_SPECIALIZE_GEN1_BINARY_FUNC(NAME, FUNC, RET_TYPE, ARG_TYPE1, ARG_TYPE2) \ + template <> \ + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE RET_TYPE NAME(const ARG_TYPE1& x, const ARG_TYPE2& y) { \ + return cl::sycl::FUNC(x, y); \ } #define SYCL_SPECIALIZE_GEN2_BINARY_FUNC(NAME, FUNC, RET_TYPE, ARG_TYPE) \ SYCL_SPECIALIZE_GEN1_BINARY_FUNC(NAME, FUNC, RET_TYPE, ARG_TYPE, ARG_TYPE) -#define SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, TYPE) \ - SYCL_SPECIALIZE_GEN2_BINARY_FUNC(NAME, FUNC, TYPE, TYPE) +#define SYCL_SPECIALIZE_BINARY_FUNC(NAME, FUNC, TYPE) SYCL_SPECIALIZE_GEN2_BINARY_FUNC(NAME, FUNC, TYPE, TYPE) SYCL_SPECIALIZE_INTEGER_TYPES_BINARY(mini, min) SYCL_SPECIALIZE_FLOATING_TYPES_BINARY(mini, fmin) @@ -1224,123 +1042,102 @@ SYCL_SPECIALIZE_FLOATING_TYPES_BINARY(maxi, fmax) #endif - -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(real, Scalar) real(const Scalar& x) -{ +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(real, Scalar) real(const Scalar& x) { return EIGEN_MATHFUNC_IMPL(real, Scalar)::run(x); } -template -EIGEN_DEVICE_FUNC -inline typename internal::add_const_on_value_type< EIGEN_MATHFUNC_RETVAL(real_ref, Scalar) >::type real_ref(const Scalar& x) -{ +template +EIGEN_DEVICE_FUNC inline internal::add_const_on_value_type_t real_ref( + const Scalar& x) { return internal::real_ref_impl::run(x); } -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(real_ref, Scalar) real_ref(Scalar& x) -{ +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(real_ref, Scalar) real_ref(Scalar& x) { return EIGEN_MATHFUNC_IMPL(real_ref, Scalar)::run(x); } -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(imag, Scalar) imag(const Scalar& x) -{ +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(imag, Scalar) imag(const Scalar& x) { return EIGEN_MATHFUNC_IMPL(imag, Scalar)::run(x); } -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(arg, Scalar) arg(const Scalar& x) -{ +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(arg, Scalar) arg(const Scalar& x) { return EIGEN_MATHFUNC_IMPL(arg, Scalar)::run(x); } -template -EIGEN_DEVICE_FUNC -inline typename internal::add_const_on_value_type< EIGEN_MATHFUNC_RETVAL(imag_ref, Scalar) >::type imag_ref(const Scalar& x) -{ +template +EIGEN_DEVICE_FUNC inline internal::add_const_on_value_type_t imag_ref( + const Scalar& x) { return internal::imag_ref_impl::run(x); } -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(imag_ref, Scalar) imag_ref(Scalar& x) -{ +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(imag_ref, Scalar) imag_ref(Scalar& x) { return EIGEN_MATHFUNC_IMPL(imag_ref, Scalar)::run(x); } -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(conj, Scalar) conj(const Scalar& x) -{ +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(conj, Scalar) conj(const Scalar& x) { return EIGEN_MATHFUNC_IMPL(conj, Scalar)::run(x); } -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(abs2, Scalar) abs2(const Scalar& x) -{ +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(sign, Scalar) sign(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(sign, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(negate, Scalar) negate(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(negate, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(abs2, Scalar) abs2(const Scalar& x) { return EIGEN_MATHFUNC_IMPL(abs2, Scalar)::run(x); } -EIGEN_DEVICE_FUNC -inline bool abs2(bool x) { return x; } +EIGEN_DEVICE_FUNC inline bool abs2(bool x) { return x; } -template -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE T absdiff(const T& x, const T& y) -{ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T absdiff(const T& x, const T& y) { return x > y ? x - y : y - x; } -template<> -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE float absdiff(const float& x, const float& y) -{ +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float absdiff(const float& x, const float& y) { return fabsf(x - y); } -template<> -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE double absdiff(const double& x, const double& y) -{ +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double absdiff(const double& x, const double& y) { return fabs(x - y); } -#if !defined(EIGEN_GPUCC) // HIP and CUDA do not support long double. -template<> -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE long double absdiff(const long double& x, const long double& y) { +#ifndef EIGEN_GPU_COMPILE_PHASE +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE long double absdiff(const long double& x, const long double& y) { return fabsl(x - y); } #endif -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(norm1, Scalar) norm1(const Scalar& x) -{ +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(norm1, Scalar) norm1(const Scalar& x) { return EIGEN_MATHFUNC_IMPL(norm1, Scalar)::run(x); } -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(hypot, Scalar) hypot(const Scalar& x, const Scalar& y) -{ +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(hypot, Scalar) hypot(const Scalar& x, const Scalar& y) { return EIGEN_MATHFUNC_IMPL(hypot, Scalar)::run(x, y); } #if defined(SYCL_DEVICE_ONLY) - SYCL_SPECIALIZE_FLOATING_TYPES_BINARY(hypot, hypot) +SYCL_SPECIALIZE_FLOATING_TYPES_BINARY(hypot, hypot) #endif -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(log1p, Scalar) log1p(const Scalar& x) -{ +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(log1p, Scalar) log1p(const Scalar& x) { return EIGEN_MATHFUNC_IMPL(log1p, Scalar)::run(x); } @@ -1349,27 +1146,39 @@ SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(log1p, log1p) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float log1p(const float &x) { return ::log1pf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float log1p(const float& x) { + return ::log1pf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double log1p(const double &x) { return ::log1p(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double log1p(const double& x) { + return ::log1p(x); +} #endif -template -EIGEN_DEVICE_FUNC -inline typename internal::pow_impl::result_type pow(const ScalarX& x, const ScalarY& y) -{ - return internal::pow_impl::run(x, y); +template +EIGEN_DEVICE_FUNC inline typename internal::pow_impl::result_type pow(const ScalarX& x, + const ScalarY& y) { + return internal::pow_impl::run(x, y); } #if defined(SYCL_DEVICE_ONLY) SYCL_SPECIALIZE_FLOATING_TYPES_BINARY(pow, pow) #endif -template EIGEN_DEVICE_FUNC bool (isnan) (const T &x) { return internal::isnan_impl(x); } -template EIGEN_DEVICE_FUNC bool (isinf) (const T &x) { return internal::isinf_impl(x); } -template EIGEN_DEVICE_FUNC bool (isfinite)(const T &x) { return internal::isfinite_impl(x); } +template +EIGEN_DEVICE_FUNC bool(isnan)(const T& x) { + return internal::isnan_impl(x); +} +template +EIGEN_DEVICE_FUNC bool(isinf)(const T& x) { + return internal::isinf_impl(x); +} +template +EIGEN_DEVICE_FUNC bool(isfinite)(const T& x) { + return internal::isfinite_impl(x); +} #if defined(SYCL_DEVICE_ONLY) SYCL_SPECIALIZE_FLOATING_TYPES_UNARY_FUNC_RET_TYPE(isnan, isnan, bool) @@ -1377,72 +1186,83 @@ SYCL_SPECIALIZE_FLOATING_TYPES_UNARY_FUNC_RET_TYPE(isinf, isinf, bool) SYCL_SPECIALIZE_FLOATING_TYPES_UNARY_FUNC_RET_TYPE(isfinite, isfinite, bool) #endif -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(rint, Scalar) rint(const Scalar& x) -{ - return EIGEN_MATHFUNC_IMPL(rint, Scalar)::run(x); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar rint(const Scalar& x) { + return internal::nearest_integer_impl::run_rint(x); } -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(round, Scalar) round(const Scalar& x) -{ - return EIGEN_MATHFUNC_IMPL(round, Scalar)::run(x); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar round(const Scalar& x) { + return internal::nearest_integer_impl::run_round(x); } -#if defined(SYCL_DEVICE_ONLY) -SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(round, round) -#endif - -template -EIGEN_DEVICE_FUNC -T (floor)(const T& x) -{ - EIGEN_USING_STD(floor) - return floor(x); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar(floor)(const Scalar& x) { + return internal::nearest_integer_impl::run_floor(x); } -#if defined(SYCL_DEVICE_ONLY) -SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(floor, floor) -#endif - -#if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float floor(const float &x) { return ::floorf(x); } - -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double floor(const double &x) { return ::floor(x); } -#endif +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar(ceil)(const Scalar& x) { + return internal::nearest_integer_impl::run_ceil(x); +} -template -EIGEN_DEVICE_FUNC -T (ceil)(const T& x) -{ - EIGEN_USING_STD(ceil); - return ceil(x); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar(trunc)(const Scalar& x) { + return internal::nearest_integer_impl::run_trunc(x); } #if defined(SYCL_DEVICE_ONLY) +SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(round, round) +SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(floor, floor) SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(ceil, ceil) +SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(trunc, trunc) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float ceil(const float &x) { return ::ceilf(x); } - -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double ceil(const double &x) { return ::ceil(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float floor(const float& x) { + return ::floorf(x); +} +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double floor(const double& x) { + return ::floor(x); +} +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float ceil(const float& x) { + return ::ceilf(x); +} +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double ceil(const double& x) { + return ::ceil(x); +} +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float trunc(const float& x) { + return ::truncf(x); +} +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double trunc(const double& x) { + return ::trunc(x); +} #endif +// Integer division with rounding up. +// T is assumed to be an integer type with a>=0, and b>0 +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE EIGEN_CONSTEXPR T div_ceil(T a, T b) { + EIGEN_STATIC_ASSERT((NumTraits::IsInteger), THIS FUNCTION IS FOR INTEGER TYPES) + eigen_assert(a >= 0); + eigen_assert(b > 0); + // Note: This form is used because it cannot overflow. + return a == 0 ? 0 : (a - 1) / b + 1; +} /** Log base 2 for 32 bits positive integers. - * Conveniently returns 0 for x==0. */ -inline int log2(int x) -{ - eigen_assert(x>=0); + * Conveniently returns 0 for x==0. */ +inline int log2(int x) { + eigen_assert(x >= 0); unsigned int v(x); - static const int table[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; + static const int table[32] = {0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, + 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31}; v |= v >> 1; v |= v >> 2; v |= v >> 4; @@ -1452,41 +1272,44 @@ inline int log2(int x) } /** \returns the square root of \a x. - * - * It is essentially equivalent to - * \code using std::sqrt; return sqrt(x); \endcode - * but slightly faster for float/double and some compilers (e.g., gcc), thanks to - * specializations when SSE is enabled. - * - * It's usage is justified in performance critical functions, like norm/normalize. - */ -template -EIGEN_DEVICE_FUNC -EIGEN_ALWAYS_INLINE EIGEN_MATHFUNC_RETVAL(sqrt, Scalar) sqrt(const Scalar& x) -{ + * + * It is essentially equivalent to + * \code using std::sqrt; return sqrt(x); \endcode + * but slightly faster for float/double and some compilers (e.g., gcc), thanks to + * specializations when SSE is enabled. + * + * It's usage is justified in performance critical functions, like norm/normalize. + */ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE EIGEN_MATHFUNC_RETVAL(sqrt, Scalar) sqrt(const Scalar& x) { return EIGEN_MATHFUNC_IMPL(sqrt, Scalar)::run(x); } // Boolean specialization, avoids implicit float to bool conversion (-Wimplicit-conversion-floating-point-to-bool). -template<> -EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_DEVICE_FUNC -bool sqrt(const bool &x) { return x; } +template <> +EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_DEVICE_FUNC bool sqrt(const bool& x) { + return x; +} #if defined(SYCL_DEVICE_ONLY) SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(sqrt, sqrt) #endif +/** \returns the cube root of \a x. **/ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T cbrt(const T& x) { + EIGEN_USING_STD(cbrt); + return static_cast(cbrt(x)); +} + /** \returns the reciprocal square root of \a x. **/ -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T rsqrt(const T& x) -{ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T rsqrt(const T& x) { return internal::rsqrt_impl::run(x); } -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T log(const T &x) { +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T log(const T& x) { return internal::log_impl::run(x); } @@ -1494,27 +1317,30 @@ T log(const T &x) { SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(log, log) #endif - #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float log(const float &x) { return ::logf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float log(const float& x) { + return ::logf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double log(const double &x) { return ::log(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double log(const double& x) { + return ::log(x); +} #endif -template +template EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -typename internal::enable_if::IsSigned || NumTraits::IsComplex,typename NumTraits::Real>::type -abs(const T &x) { + std::enable_if_t::IsSigned || NumTraits::IsComplex, typename NumTraits::Real> + abs(const T& x) { EIGEN_USING_STD(abs); return abs(x); } -template +template EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -typename internal::enable_if::IsSigned || NumTraits::IsComplex),typename NumTraits::Real>::type -abs(const T &x) { + std::enable_if_t::IsSigned || NumTraits::IsComplex), typename NumTraits::Real> + abs(const T& x) { return x; } @@ -1524,51 +1350,106 @@ SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(abs, fabs) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float abs(const float &x) { return ::fabsf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float abs(const float& x) { + return ::fabsf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double abs(const double &x) { return ::fabs(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double abs(const double& x) { + return ::fabs(x); +} -template <> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float abs(const std::complex& x) { +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float abs(const std::complex& x) { return ::hypotf(x.real(), x.imag()); } -template <> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double abs(const std::complex& x) { +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double abs(const std::complex& x) { return ::hypot(x.real(), x.imag()); } #endif -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T exp(const T &x) { +template ::IsInteger, bool IsSigned = NumTraits::IsSigned> +struct signbit_impl; +template +struct signbit_impl { + static constexpr size_t Size = sizeof(Scalar); + static constexpr size_t Shift = (CHAR_BIT * Size) - 1; + using intSize_t = typename get_integer_by_size::signed_type; + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static Scalar run(const Scalar& x) { + intSize_t a = bit_cast(x); + a = a >> Shift; + Scalar result = bit_cast(a); + return result; + } +}; +template +struct signbit_impl { + static constexpr size_t Size = sizeof(Scalar); + static constexpr size_t Shift = (CHAR_BIT * Size) - 1; + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static constexpr Scalar run(const Scalar& x) { return x >> Shift; } +}; +template +struct signbit_impl { + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static constexpr Scalar run(const Scalar&) { return Scalar(0); } +}; +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static constexpr Scalar signbit(const Scalar& x) { + return signbit_impl::run(x); +} + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T exp(const T& x) { + EIGEN_USING_STD(exp); + return exp(x); +} + +// MSVC screws up some edge-cases for std::exp(complex). +#ifdef EIGEN_COMP_MSVC +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE std::complex exp(const std::complex& x) { EIGEN_USING_STD(exp); + // If z is (x,±∞) (for any finite x), the result is (NaN,NaN) and FE_INVALID is raised. + // If z is (x,NaN) (for any finite x), the result is (NaN,NaN) and FE_INVALID may be raised. + if ((isfinite)(real_ref(x)) && !(isfinite)(imag_ref(x))) { + return std::complex(NumTraits::quiet_NaN(), NumTraits::quiet_NaN()); + } + // If z is (+∞,±∞), the result is (±∞,NaN) and FE_INVALID is raised (the sign of the real part is unspecified) + // If z is (+∞,NaN), the result is (±∞,NaN) (the sign of the real part is unspecified) + if ((real_ref(x) == NumTraits::infinity() && !(isfinite)(imag_ref(x)))) { + return std::complex(NumTraits::infinity(), NumTraits::quiet_NaN()); + } return exp(x); } +#endif #if defined(SYCL_DEVICE_ONLY) SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(exp, exp) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float exp(const float &x) { return ::expf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float exp(const float& x) { + return ::expf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double exp(const double &x) { return ::exp(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double exp(const double& x) { + return ::exp(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -std::complex exp(const std::complex& x) { +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE std::complex exp(const std::complex& x) { float com = ::expf(x.real()); float res_real = com * ::cosf(x.imag()); float res_imag = com * ::sinf(x.imag()); return std::complex(res_real, res_imag); } -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -std::complex exp(const std::complex& x) { +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE std::complex exp(const std::complex& x) { double com = ::exp(x.real()); double res_real = com * ::cos(x.imag()); double res_imag = com * ::sin(x.imag()); @@ -1576,10 +1457,8 @@ std::complex exp(const std::complex& x) { } #endif -template -EIGEN_DEVICE_FUNC -inline EIGEN_MATHFUNC_RETVAL(expm1, Scalar) expm1(const Scalar& x) -{ +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(expm1, Scalar) expm1(const Scalar& x) { return EIGEN_MATHFUNC_IMPL(expm1, Scalar)::run(x); } @@ -1588,35 +1467,41 @@ SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(expm1, expm1) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float expm1(const float &x) { return ::expm1f(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float expm1(const float& x) { + return ::expm1f(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double expm1(const double &x) { return ::expm1(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double expm1(const double& x) { + return ::expm1(x); +} #endif -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T cos(const T &x) { +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T cos(const T& x) { EIGEN_USING_STD(cos); return cos(x); } #if defined(SYCL_DEVICE_ONLY) -SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(cos,cos) +SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(cos, cos) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float cos(const float &x) { return ::cosf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float cos(const float& x) { + return ::cosf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double cos(const double &x) { return ::cos(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double cos(const double& x) { + return ::cos(x); +} #endif -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T sin(const T &x) { +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T sin(const T& x) { EIGEN_USING_STD(sin); return sin(x); } @@ -1626,16 +1511,19 @@ SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(sin, sin) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float sin(const float &x) { return ::sinf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float sin(const float& x) { + return ::sinf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double sin(const double &x) { return ::sin(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double sin(const double& x) { + return ::sin(x); +} #endif -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T tan(const T &x) { +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T tan(const T& x) { EIGEN_USING_STD(tan); return tan(x); } @@ -1645,28 +1533,28 @@ SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(tan, tan) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float tan(const float &x) { return ::tanf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float tan(const float& x) { + return ::tanf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double tan(const double &x) { return ::tan(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double tan(const double& x) { + return ::tan(x); +} #endif -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T acos(const T &x) { +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T acos(const T& x) { EIGEN_USING_STD(acos); return acos(x); } -#if EIGEN_HAS_CXX11_MATH -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T acosh(const T &x) { +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T acosh(const T& x) { EIGEN_USING_STD(acosh); return static_cast(acosh(x)); } -#endif #if defined(SYCL_DEVICE_ONLY) SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(acos, acos) @@ -1674,28 +1562,28 @@ SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(acosh, acosh) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float acos(const float &x) { return ::acosf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float acos(const float& x) { + return ::acosf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double acos(const double &x) { return ::acos(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double acos(const double& x) { + return ::acos(x); +} #endif -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T asin(const T &x) { +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T asin(const T& x) { EIGEN_USING_STD(asin); return asin(x); } -#if EIGEN_HAS_CXX11_MATH -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T asinh(const T &x) { +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T asinh(const T& x) { EIGEN_USING_STD(asinh); return static_cast(asinh(x)); } -#endif #if defined(SYCL_DEVICE_ONLY) SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(asin, asin) @@ -1703,28 +1591,34 @@ SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(asinh, asinh) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float asin(const float &x) { return ::asinf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float asin(const float& x) { + return ::asinf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double asin(const double &x) { return ::asin(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double asin(const double& x) { + return ::asin(x); +} #endif -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T atan(const T &x) { +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T atan(const T& x) { EIGEN_USING_STD(atan); return static_cast(atan(x)); } -#if EIGEN_HAS_CXX11_MATH -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T atanh(const T &x) { +template ::IsComplex, int> = 0> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T atan2(const T& y, const T& x) { + EIGEN_USING_STD(atan2); + return static_cast(atan2(y, x)); +} + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T atanh(const T& x) { EIGEN_USING_STD(atanh); return static_cast(atanh(x)); } -#endif #if defined(SYCL_DEVICE_ONLY) SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(atan, atan) @@ -1732,17 +1626,19 @@ SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(atanh, atanh) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float atan(const float &x) { return ::atanf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float atan(const float& x) { + return ::atanf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double atan(const double &x) { return ::atan(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double atan(const double& x) { + return ::atan(x); +} #endif - -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T cosh(const T &x) { +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T cosh(const T& x) { EIGEN_USING_STD(cosh); return static_cast(cosh(x)); } @@ -1752,16 +1648,19 @@ SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(cosh, cosh) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float cosh(const float &x) { return ::coshf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float cosh(const float& x) { + return ::coshf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double cosh(const double &x) { return ::cosh(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double cosh(const double& x) { + return ::cosh(x); +} #endif -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T sinh(const T &x) { +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T sinh(const T& x) { EIGEN_USING_STD(sinh); return static_cast(sinh(x)); } @@ -1771,23 +1670,25 @@ SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(sinh, sinh) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float sinh(const float &x) { return ::sinhf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float sinh(const float& x) { + return ::sinhf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double sinh(const double &x) { return ::sinh(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double sinh(const double& x) { + return ::sinh(x); +} #endif -template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T tanh(const T &x) { +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T tanh(const T& x) { EIGEN_USING_STD(tanh); return tanh(x); } #if (!defined(EIGEN_GPUCC)) && EIGEN_FAST_MATH && !defined(SYCL_DEVICE_ONLY) -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float tanh(float x) { return internal::generic_fast_tanh_float(x); } +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float tanh(float x) { return internal::ptanh_float(x); } #endif #if defined(SYCL_DEVICE_ONLY) @@ -1795,16 +1696,19 @@ SYCL_SPECIALIZE_FLOATING_TYPES_UNARY(tanh, tanh) #endif #if defined(EIGEN_GPUCC) -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float tanh(const float &x) { return ::tanhf(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float tanh(const float& x) { + return ::tanhf(x); +} -template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double tanh(const double &x) { return ::tanh(x); } +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double tanh(const double& x) { + return ::tanh(x); +} #endif template -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -T fmod(const T& a, const T& b) { +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T fmod(const T& a, const T& b) { EIGEN_USING_STD(fmod); return fmod(a, b); } @@ -1815,14 +1719,12 @@ SYCL_SPECIALIZE_FLOATING_TYPES_BINARY(fmod, fmod) #if defined(EIGEN_GPUCC) template <> -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -float fmod(const float& a, const float& b) { +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float fmod(const float& a, const float& b) { return ::fmodf(a, b); } template <> -EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE -double fmod(const double& a, const double& b) { +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double fmod(const double& a, const double& b) { return ::fmod(a, b); } #endif @@ -1844,116 +1746,113 @@ double fmod(const double& a, const double& b) { #undef SYCL_SPECIALIZE_BINARY_FUNC #endif -} // end namespace numext +template ::value>> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar logical_shift_left(const Scalar& a, int n) { + return a << n; +} + +template ::value>> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar logical_shift_right(const Scalar& a, int n) { + using UnsignedScalar = typename numext::get_integer_by_size::unsigned_type; + return bit_cast(bit_cast(a) >> n); +} + +template ::value>> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar arithmetic_shift_right(const Scalar& a, int n) { + using SignedScalar = typename numext::get_integer_by_size::signed_type; + return bit_cast(bit_cast(a) >> n); +} + +} // end namespace numext namespace internal { -template -EIGEN_DEVICE_FUNC bool isfinite_impl(const std::complex& x) -{ +template +EIGEN_DEVICE_FUNC bool isfinite_impl(const std::complex& x) { return (numext::isfinite)(numext::real(x)) && (numext::isfinite)(numext::imag(x)); } -template -EIGEN_DEVICE_FUNC bool isnan_impl(const std::complex& x) -{ +template +EIGEN_DEVICE_FUNC bool isnan_impl(const std::complex& x) { return (numext::isnan)(numext::real(x)) || (numext::isnan)(numext::imag(x)); } -template -EIGEN_DEVICE_FUNC bool isinf_impl(const std::complex& x) -{ +template +EIGEN_DEVICE_FUNC bool isinf_impl(const std::complex& x) { return ((numext::isinf)(numext::real(x)) || (numext::isinf)(numext::imag(x))) && (!(numext::isnan)(x)); } /**************************************************************************** -* Implementation of fuzzy comparisons * -****************************************************************************/ + * Implementation of fuzzy comparisons * + ****************************************************************************/ -template +template struct scalar_fuzzy_default_impl {}; -template -struct scalar_fuzzy_default_impl -{ +template +struct scalar_fuzzy_default_impl { typedef typename NumTraits::Real RealScalar; - template EIGEN_DEVICE_FUNC - static inline bool isMuchSmallerThan(const Scalar& x, const OtherScalar& y, const RealScalar& prec) - { + template + EIGEN_DEVICE_FUNC static inline bool isMuchSmallerThan(const Scalar& x, const OtherScalar& y, + const RealScalar& prec) { return numext::abs(x) <= numext::abs(y) * prec; } - EIGEN_DEVICE_FUNC - static inline bool isApprox(const Scalar& x, const Scalar& y, const RealScalar& prec) - { + EIGEN_DEVICE_FUNC static inline bool isApprox(const Scalar& x, const Scalar& y, const RealScalar& prec) { return numext::abs(x - y) <= numext::mini(numext::abs(x), numext::abs(y)) * prec; } - EIGEN_DEVICE_FUNC - static inline bool isApproxOrLessThan(const Scalar& x, const Scalar& y, const RealScalar& prec) - { + EIGEN_DEVICE_FUNC static inline bool isApproxOrLessThan(const Scalar& x, const Scalar& y, const RealScalar& prec) { return x <= y || isApprox(x, y, prec); } }; -template -struct scalar_fuzzy_default_impl -{ +template +struct scalar_fuzzy_default_impl { typedef typename NumTraits::Real RealScalar; - template EIGEN_DEVICE_FUNC - static inline bool isMuchSmallerThan(const Scalar& x, const Scalar&, const RealScalar&) - { + template + EIGEN_DEVICE_FUNC static inline bool isMuchSmallerThan(const Scalar& x, const Scalar&, const RealScalar&) { return x == Scalar(0); } - EIGEN_DEVICE_FUNC - static inline bool isApprox(const Scalar& x, const Scalar& y, const RealScalar&) - { - return x == y; - } - EIGEN_DEVICE_FUNC - static inline bool isApproxOrLessThan(const Scalar& x, const Scalar& y, const RealScalar&) - { + EIGEN_DEVICE_FUNC static inline bool isApprox(const Scalar& x, const Scalar& y, const RealScalar&) { return x == y; } + EIGEN_DEVICE_FUNC static inline bool isApproxOrLessThan(const Scalar& x, const Scalar& y, const RealScalar&) { return x <= y; } }; -template -struct scalar_fuzzy_default_impl -{ +template +struct scalar_fuzzy_default_impl { typedef typename NumTraits::Real RealScalar; - template EIGEN_DEVICE_FUNC - static inline bool isMuchSmallerThan(const Scalar& x, const OtherScalar& y, const RealScalar& prec) - { + template + EIGEN_DEVICE_FUNC static inline bool isMuchSmallerThan(const Scalar& x, const OtherScalar& y, + const RealScalar& prec) { return numext::abs2(x) <= numext::abs2(y) * prec * prec; } - EIGEN_DEVICE_FUNC - static inline bool isApprox(const Scalar& x, const Scalar& y, const RealScalar& prec) - { + EIGEN_DEVICE_FUNC static inline bool isApprox(const Scalar& x, const Scalar& y, const RealScalar& prec) { return numext::abs2(x - y) <= numext::mini(numext::abs2(x), numext::abs2(y)) * prec * prec; } }; -template -struct scalar_fuzzy_impl : scalar_fuzzy_default_impl::IsComplex, NumTraits::IsInteger> {}; +template +struct scalar_fuzzy_impl + : scalar_fuzzy_default_impl::IsComplex, NumTraits::IsInteger> {}; -template EIGEN_DEVICE_FUNC -inline bool isMuchSmallerThan(const Scalar& x, const OtherScalar& y, - const typename NumTraits::Real &precision = NumTraits::dummy_precision()) -{ +template +EIGEN_DEVICE_FUNC inline bool isMuchSmallerThan( + const Scalar& x, const OtherScalar& y, + const typename NumTraits::Real& precision = NumTraits::dummy_precision()) { return scalar_fuzzy_impl::template isMuchSmallerThan(x, y, precision); } -template EIGEN_DEVICE_FUNC -inline bool isApprox(const Scalar& x, const Scalar& y, - const typename NumTraits::Real &precision = NumTraits::dummy_precision()) -{ +template +EIGEN_DEVICE_FUNC inline bool isApprox( + const Scalar& x, const Scalar& y, + const typename NumTraits::Real& precision = NumTraits::dummy_precision()) { return scalar_fuzzy_impl::isApprox(x, y, precision); } -template EIGEN_DEVICE_FUNC -inline bool isApproxOrLessThan(const Scalar& x, const Scalar& y, - const typename NumTraits::Real &precision = NumTraits::dummy_precision()) -{ +template +EIGEN_DEVICE_FUNC inline bool isApproxOrLessThan( + const Scalar& x, const Scalar& y, + const typename NumTraits::Real& precision = NumTraits::dummy_precision()) { return scalar_fuzzy_impl::isApproxOrLessThan(x, y, precision); } @@ -1961,54 +1860,33 @@ inline bool isApproxOrLessThan(const Scalar& x, const Scalar& y, *** The special case of the bool type *** ******************************************/ -template<> struct random_impl -{ - static inline bool run() - { - return random(0,1)==0 ? false : true; - } - - static inline bool run(const bool& a, const bool& b) - { - return random(a, b)==0 ? false : true; - } -}; - -template<> struct scalar_fuzzy_impl -{ +template <> +struct scalar_fuzzy_impl { typedef bool RealScalar; - template EIGEN_DEVICE_FUNC - static inline bool isMuchSmallerThan(const bool& x, const bool&, const bool&) - { + template + EIGEN_DEVICE_FUNC static inline bool isMuchSmallerThan(const bool& x, const bool&, const bool&) { return !x; } - EIGEN_DEVICE_FUNC - static inline bool isApprox(bool x, bool y, bool) - { - return x == y; - } + EIGEN_DEVICE_FUNC static inline bool isApprox(bool x, bool y, bool) { return x == y; } - EIGEN_DEVICE_FUNC - static inline bool isApproxOrLessThan(const bool& x, const bool& y, const bool&) - { + EIGEN_DEVICE_FUNC static inline bool isApproxOrLessThan(const bool& x, const bool& y, const bool&) { return (!x) || y; } - }; -} // end namespace internal +} // end namespace internal // Default implementations that rely on other numext implementations namespace internal { // Specialization for complex types that are not supported by std::expm1. template -struct expm1_impl > { - EIGEN_DEVICE_FUNC static inline std::complex run( - const std::complex& x) { - EIGEN_STATIC_ASSERT_NON_INTEGER(RealScalar) +struct expm1_impl> { + EIGEN_STATIC_ASSERT_NON_INTEGER(RealScalar) + + EIGEN_DEVICE_FUNC static inline std::complex run(const std::complex& x) { RealScalar xr = x.real(); RealScalar xi = x.imag(); // expm1(z) = exp(z) - 1 @@ -2030,28 +1908,22 @@ struct expm1_impl > { } }; -template +template struct rsqrt_impl { - EIGEN_DEVICE_FUNC - static EIGEN_ALWAYS_INLINE T run(const T& x) { - return T(1)/numext::sqrt(x); - } + EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE T run(const T& x) { return T(1) / numext::sqrt(x); } }; #if defined(EIGEN_GPU_COMPILE_PHASE) -template -struct conj_impl, true> -{ - EIGEN_DEVICE_FUNC - static inline std::complex run(const std::complex& x) - { +template +struct conj_impl, true> { + EIGEN_DEVICE_FUNC static inline std::complex run(const std::complex& x) { return std::complex(numext::real(x), -numext::imag(x)); } }; #endif -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_MATHFUNCTIONS_H +#endif // EIGEN_MATHFUNCTIONS_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MathFunctionsImpl.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MathFunctionsImpl.h index 4eaaaa78449..689c6d82764 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MathFunctionsImpl.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MathFunctionsImpl.h @@ -11,95 +11,159 @@ #ifndef EIGEN_MATHFUNCTIONSIMPL_H #define EIGEN_MATHFUNCTIONSIMPL_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -/** \internal \returns the hyperbolic tan of \a a (coeff-wise) - Doesn't do anything fancy, just a 13/6-degree rational interpolant which - is accurate up to a couple of ulps in the (approximate) range [-8, 8], - outside of which tanh(x) = +/-1 in single precision. The input is clamped - to the range [-c, c]. The value c is chosen as the smallest value where - the approximation evaluates to exactly 1. In the reange [-0.0004, 0.0004] - the approxmation tanh(x) ~= x is used for better accuracy as x tends to zero. +/** \internal Fast reciprocal using Newton-Raphson's method. + + Preconditions: + 1. The starting guess provided in approx_a_recip must have at least half + the leading mantissa bits in the correct result, such that a single + Newton-Raphson step is sufficient to get within 1-2 ulps of the currect + result. + 2. If a is zero, approx_a_recip must be infinite with the same sign as a. + 3. If a is infinite, approx_a_recip must be zero with the same sign as a. - This implementation works on both scalars and packets. + If the preconditions are satisfied, which they are for for the _*_rcp_ps + instructions on x86, the result has a maximum relative error of 2 ulps, + and correctly handles reciprocals of zero, infinity, and NaN. */ -template -T generic_fast_tanh_float(const T& a_x) -{ - // Clamp the inputs to the range [-c, c] -#ifdef EIGEN_VECTORIZE_FMA - const T plus_clamp = pset1(7.99881172180175781f); - const T minus_clamp = pset1(-7.99881172180175781f); -#else - const T plus_clamp = pset1(7.90531110763549805f); - const T minus_clamp = pset1(-7.90531110763549805f); -#endif - const T tiny = pset1(0.0004f); - const T x = pmax(pmin(a_x, plus_clamp), minus_clamp); - const T tiny_mask = pcmp_lt(pabs(a_x), tiny); - // The monomial coefficients of the numerator polynomial (odd). - const T alpha_1 = pset1(4.89352455891786e-03f); - const T alpha_3 = pset1(6.37261928875436e-04f); - const T alpha_5 = pset1(1.48572235717979e-05f); - const T alpha_7 = pset1(5.12229709037114e-08f); - const T alpha_9 = pset1(-8.60467152213735e-11f); - const T alpha_11 = pset1(2.00018790482477e-13f); - const T alpha_13 = pset1(-2.76076847742355e-16f); - - // The monomial coefficients of the denominator polynomial (even). - const T beta_0 = pset1(4.89352518554385e-03f); - const T beta_2 = pset1(2.26843463243900e-03f); - const T beta_4 = pset1(1.18534705686654e-04f); - const T beta_6 = pset1(1.19825839466702e-06f); - - // Since the polynomials are odd/even, we need x^2. - const T x2 = pmul(x, x); - - // Evaluate the numerator polynomial p. - T p = pmadd(x2, alpha_13, alpha_11); - p = pmadd(x2, p, alpha_9); - p = pmadd(x2, p, alpha_7); - p = pmadd(x2, p, alpha_5); - p = pmadd(x2, p, alpha_3); - p = pmadd(x2, p, alpha_1); - p = pmul(x, p); - - // Evaluate the denominator polynomial q. - T q = pmadd(x2, beta_6, beta_4); - q = pmadd(x2, q, beta_2); - q = pmadd(x2, q, beta_0); - - // Divide the numerator by the denominator. - return pselect(tiny_mask, x, pdiv(p, q)); -} +template +struct generic_reciprocal_newton_step { + static_assert(Steps > 0, "Steps must be at least 1."); + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Packet run(const Packet& a, const Packet& approx_a_recip) { + using Scalar = typename unpacket_traits::type; + const Packet two = pset1(Scalar(2)); + // Refine the approximation using one Newton-Raphson step: + // x_{i} = x_{i-1} * (2 - a * x_{i-1}) + const Packet x = generic_reciprocal_newton_step::run(a, approx_a_recip); + const Packet tmp = pnmadd(a, x, two); + // If tmp is NaN, it means that a is either +/-0 or +/-Inf. + // In this case return the approximation directly. + const Packet is_not_nan = pcmp_eq(tmp, tmp); + return pselect(is_not_nan, pmul(x, tmp), x); + } +}; + +template +struct generic_reciprocal_newton_step { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Packet run(const Packet& /*unused*/, const Packet& approx_rsqrt) { + return approx_rsqrt; + } +}; + +/** \internal Fast reciprocal sqrt using Newton-Raphson's method. + + Preconditions: + 1. The starting guess provided in approx_a_recip must have at least half + the leading mantissa bits in the correct result, such that a single + Newton-Raphson step is sufficient to get within 1-2 ulps of the currect + result. + 2. If a is zero, approx_a_recip must be infinite with the same sign as a. + 3. If a is infinite, approx_a_recip must be zero with the same sign as a. + + If the preconditions are satisfied, which they are for for the _*_rcp_ps + instructions on x86, the result has a maximum relative error of 2 ulps, + and correctly handles zero, infinity, and NaN. Positive denormals are + treated as zero. +*/ +template +struct generic_rsqrt_newton_step { + static_assert(Steps > 0, "Steps must be at least 1."); + using Scalar = typename unpacket_traits::type; + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Packet run(const Packet& a, const Packet& approx_rsqrt) { + constexpr Scalar kMinusHalf = Scalar(-1) / Scalar(2); + const Packet cst_minus_half = pset1(kMinusHalf); + const Packet cst_minus_one = pset1(Scalar(-1)); + + Packet inv_sqrt = approx_rsqrt; + for (int step = 0; step < Steps; ++step) { + // Refine the approximation using one Newton-Raphson step: + // h_n = (x * inv_sqrt) * inv_sqrt - 1 (so that h_n is nearly 0). + // inv_sqrt = inv_sqrt - 0.5 * inv_sqrt * h_n + Packet r2 = pmul(a, inv_sqrt); + Packet half_r = pmul(inv_sqrt, cst_minus_half); + Packet h_n = pmadd(r2, inv_sqrt, cst_minus_one); + inv_sqrt = pmadd(half_r, h_n, inv_sqrt); + } + + // If x is NaN, then either: + // 1) the input is NaN + // 2) zero and infinity were multiplied + // In either of these cases, return approx_rsqrt + return pselect(pisnan(inv_sqrt), approx_rsqrt, inv_sqrt); + } +}; + +template +struct generic_rsqrt_newton_step { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Packet run(const Packet& /*unused*/, const Packet& approx_rsqrt) { + return approx_rsqrt; + } +}; + +/** \internal Fast sqrt using Newton-Raphson's method. + + Preconditions: + 1. The starting guess for the reciprocal sqrt provided in approx_rsqrt must + have at least half the leading mantissa bits in the correct result, such + that a single Newton-Raphson step is sufficient to get within 1-2 ulps of + the currect result. + 2. If a is zero, approx_rsqrt must be infinite. + 3. If a is infinite, approx_rsqrt must be zero. -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -RealScalar positive_real_hypot(const RealScalar& x, const RealScalar& y) -{ + If the preconditions are satisfied, which they are for for the _*_rsqrt_ps + instructions on x86, the result has a maximum relative error of 2 ulps, + and correctly handles zero and infinity, and NaN. Positive denormal inputs + are treated as zero. +*/ +template +struct generic_sqrt_newton_step { + static_assert(Steps > 0, "Steps must be at least 1."); + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Packet run(const Packet& a, const Packet& approx_rsqrt) { + using Scalar = typename unpacket_traits::type; + const Packet one_point_five = pset1(Scalar(1.5)); + const Packet minus_half = pset1(Scalar(-0.5)); + // If a is inf or zero, return a directly. + const Packet inf_mask = pcmp_eq(a, pset1(NumTraits::infinity())); + const Packet return_a = por(pcmp_eq(a, pzero(a)), inf_mask); + // Do a single step of Newton's iteration for reciprocal square root: + // x_{n+1} = x_n * (1.5 + (-0.5 * x_n) * (a * x_n))). + // The Newton's step is computed this way to avoid over/under-flows. + Packet rsqrt = pmul(approx_rsqrt, pmadd(pmul(minus_half, approx_rsqrt), pmul(a, approx_rsqrt), one_point_five)); + for (int step = 1; step < Steps; ++step) { + rsqrt = pmul(rsqrt, pmadd(pmul(minus_half, rsqrt), pmul(a, rsqrt), one_point_five)); + } + + // Return sqrt(x) = x * rsqrt(x) for non-zero finite positive arguments. + // Return a itself for 0 or +inf, NaN for negative arguments. + return pselect(return_a, a, pmul(a, rsqrt)); + } +}; + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE RealScalar positive_real_hypot(const RealScalar& x, const RealScalar& y) { // IEEE IEC 6059 special cases. - if ((numext::isinf)(x) || (numext::isinf)(y)) - return NumTraits::infinity(); - if ((numext::isnan)(x) || (numext::isnan)(y)) - return NumTraits::quiet_NaN(); - + if ((numext::isinf)(x) || (numext::isinf)(y)) return NumTraits::infinity(); + if ((numext::isnan)(x) || (numext::isnan)(y)) return NumTraits::quiet_NaN(); + EIGEN_USING_STD(sqrt); RealScalar p, qp; - p = numext::maxi(x,y); - if(p==RealScalar(0)) return RealScalar(0); - qp = numext::mini(y,x) / p; - return p * sqrt(RealScalar(1) + qp*qp); + p = numext::maxi(x, y); + if (numext::is_exactly_zero(p)) return RealScalar(0); + qp = numext::mini(y, x) / p; + return p * sqrt(RealScalar(1) + qp * qp); } -template -struct hypot_impl -{ +template +struct hypot_impl { typedef typename NumTraits::Real RealScalar; - static EIGEN_DEVICE_FUNC - inline RealScalar run(const Scalar& x, const Scalar& y) - { + static EIGEN_DEVICE_FUNC inline RealScalar run(const Scalar& x, const Scalar& y) { EIGEN_USING_STD(abs); return positive_real_hypot(abs(x), abs(y)); } @@ -107,7 +171,7 @@ struct hypot_impl // Generic complex sqrt implementation that correctly handles corner cases // according to https://en.cppreference.com/w/cpp/numeric/complex/sqrt -template +template EIGEN_DEVICE_FUNC std::complex complex_sqrt(const std::complex& z) { // Computes the principal sqrt of the input. // @@ -136,15 +200,14 @@ EIGEN_DEVICE_FUNC std::complex complex_sqrt(const std::complex& z) { const T zero = T(0); const T w = numext::sqrt(T(0.5) * (numext::abs(x) + numext::hypot(x, y))); - return - (numext::isinf)(y) ? std::complex(NumTraits::infinity(), y) - : x == zero ? std::complex(w, y < zero ? -w : w) - : x > zero ? std::complex(w, y / (2 * w)) - : std::complex(numext::abs(y) / (2 * w), y < zero ? -w : w ); + return (numext::isinf)(y) ? std::complex(NumTraits::infinity(), y) + : numext::is_exactly_zero(x) ? std::complex(w, y < zero ? -w : w) + : x > zero ? std::complex(w, y / (2 * w)) + : std::complex(numext::abs(y) / (2 * w), y < zero ? -w : w); } // Generic complex rsqrt implementation. -template +template EIGEN_DEVICE_FUNC std::complex complex_rsqrt(const std::complex& z) { // Computes the principal reciprocal sqrt of the input. // @@ -176,15 +239,14 @@ EIGEN_DEVICE_FUNC std::complex complex_rsqrt(const std::complex& z) { const T w = numext::sqrt(T(0.5) * (numext::abs(x) + abs_z)); const T woz = w / abs_z; // Corner cases consistent with 1/sqrt(z) on gcc/clang. - return - abs_z == zero ? std::complex(NumTraits::infinity(), NumTraits::quiet_NaN()) - : ((numext::isinf)(x) || (numext::isinf)(y)) ? std::complex(zero, zero) - : x == zero ? std::complex(woz, y < zero ? woz : -woz) - : x > zero ? std::complex(woz, -y / (2 * w * abs_z)) - : std::complex(numext::abs(y) / (2 * w * abs_z), y < zero ? woz : -woz ); + return numext::is_exactly_zero(abs_z) ? std::complex(NumTraits::infinity(), NumTraits::quiet_NaN()) + : ((numext::isinf)(x) || (numext::isinf)(y)) ? std::complex(zero, zero) + : numext::is_exactly_zero(x) ? std::complex(woz, y < zero ? woz : -woz) + : x > zero ? std::complex(woz, -y / (2 * w * abs_z)) + : std::complex(numext::abs(y) / (2 * w * abs_z), y < zero ? woz : -woz); } -template +template EIGEN_DEVICE_FUNC std::complex complex_log(const std::complex& z) { // Computes complex log. T a = numext::abs(z); @@ -193,8 +255,8 @@ EIGEN_DEVICE_FUNC std::complex complex_log(const std::complex& z) { return std::complex(numext::log(a), b); } -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_MATHFUNCTIONSIMPL_H +#endif // EIGEN_MATHFUNCTIONSIMPL_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Matrix.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Matrix.h index f0e59a911d2..af6afafc0ce 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Matrix.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Matrix.h @@ -11,531 +11,496 @@ #ifndef EIGEN_MATRIX_H #define EIGEN_MATRIX_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > -{ -private: - enum { size = internal::size_at_compile_time<_Rows,_Cols>::ret }; - typedef typename find_best_packet<_Scalar,size>::type PacketScalar; +template +struct traits> { + private: + constexpr static int size = internal::size_at_compile_time(Rows_, Cols_); + typedef typename find_best_packet::type PacketScalar; enum { - row_major_bit = _Options&RowMajor ? RowMajorBit : 0, - is_dynamic_size_storage = _MaxRows==Dynamic || _MaxCols==Dynamic, - max_size = is_dynamic_size_storage ? Dynamic : _MaxRows*_MaxCols, - default_alignment = compute_default_alignment<_Scalar,max_size>::value, - actual_alignment = ((_Options&DontAlign)==0) ? default_alignment : 0, - required_alignment = unpacket_traits::alignment, - packet_access_bit = (packet_traits<_Scalar>::Vectorizable && (EIGEN_UNALIGNED_VECTORIZE || (actual_alignment>=required_alignment))) ? PacketAccessBit : 0 - }; - -public: - typedef _Scalar Scalar; + row_major_bit = Options_ & RowMajor ? RowMajorBit : 0, + is_dynamic_size_storage = MaxRows_ == Dynamic || MaxCols_ == Dynamic, + max_size = is_dynamic_size_storage ? Dynamic : MaxRows_ * MaxCols_, + default_alignment = compute_default_alignment::value, + actual_alignment = ((Options_ & DontAlign) == 0) ? default_alignment : 0, + required_alignment = unpacket_traits::alignment, + packet_access_bit = (packet_traits::Vectorizable && + (EIGEN_UNALIGNED_VECTORIZE || (int(actual_alignment) >= int(required_alignment)))) + ? PacketAccessBit + : 0 + }; + + public: + typedef Scalar_ Scalar; typedef Dense StorageKind; typedef Eigen::Index StorageIndex; typedef MatrixXpr XprKind; enum { - RowsAtCompileTime = _Rows, - ColsAtCompileTime = _Cols, - MaxRowsAtCompileTime = _MaxRows, - MaxColsAtCompileTime = _MaxCols, - Flags = compute_matrix_flags<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::ret, - Options = _Options, + RowsAtCompileTime = Rows_, + ColsAtCompileTime = Cols_, + MaxRowsAtCompileTime = MaxRows_, + MaxColsAtCompileTime = MaxCols_, + Flags = compute_matrix_flags(Options_), + Options = Options_, InnerStrideAtCompileTime = 1, - OuterStrideAtCompileTime = (Options&RowMajor) ? ColsAtCompileTime : RowsAtCompileTime, + OuterStrideAtCompileTime = (int(Options) & int(RowMajor)) ? ColsAtCompileTime : RowsAtCompileTime, // FIXME, the following flag in only used to define NeedsToAlign in PlainObjectBase EvaluatorFlags = LinearAccessBit | DirectAccessBit | packet_access_bit | row_major_bit, Alignment = actual_alignment }; }; -} +} // namespace internal /** \class Matrix - * \ingroup Core_Module - * - * \brief The matrix class, also used for vectors and row-vectors - * - * The %Matrix class is the work-horse for all \em dense (\ref dense "note") matrices and vectors within Eigen. - * Vectors are matrices with one column, and row-vectors are matrices with one row. - * - * The %Matrix class encompasses \em both fixed-size and dynamic-size objects (\ref fixedsize "note"). - * - * The first three template parameters are required: - * \tparam _Scalar Numeric type, e.g. float, double, int or std::complex. - * User defined scalar types are supported as well (see \ref user_defined_scalars "here"). - * \tparam _Rows Number of rows, or \b Dynamic - * \tparam _Cols Number of columns, or \b Dynamic - * - * The remaining template parameters are optional -- in most cases you don't have to worry about them. - * \tparam _Options A combination of either \b #RowMajor or \b #ColMajor, and of either - * \b #AutoAlign or \b #DontAlign. - * The former controls \ref TopicStorageOrders "storage order", and defaults to column-major. The latter controls alignment, which is required - * for vectorization. It defaults to aligning matrices except for fixed sizes that aren't a multiple of the packet size. - * \tparam _MaxRows Maximum number of rows. Defaults to \a _Rows (\ref maxrows "note"). - * \tparam _MaxCols Maximum number of columns. Defaults to \a _Cols (\ref maxrows "note"). - * - * Eigen provides a number of typedefs covering the usual cases. Here are some examples: - * - * \li \c Matrix2d is a 2x2 square matrix of doubles (\c Matrix) - * \li \c Vector4f is a vector of 4 floats (\c Matrix) - * \li \c RowVector3i is a row-vector of 3 ints (\c Matrix) - * - * \li \c MatrixXf is a dynamic-size matrix of floats (\c Matrix) - * \li \c VectorXf is a dynamic-size vector of floats (\c Matrix) - * - * \li \c Matrix2Xf is a partially fixed-size (dynamic-size) matrix of floats (\c Matrix) - * \li \c MatrixX3d is a partially dynamic-size (fixed-size) matrix of double (\c Matrix) - * - * See \link matrixtypedefs this page \endlink for a complete list of predefined \em %Matrix and \em Vector typedefs. - * - * You can access elements of vectors and matrices using normal subscripting: - * - * \code - * Eigen::VectorXd v(10); - * v[0] = 0.1; - * v[1] = 0.2; - * v(0) = 0.3; - * v(1) = 0.4; - * - * Eigen::MatrixXi m(10, 10); - * m(0, 1) = 1; - * m(0, 2) = 2; - * m(0, 3) = 3; - * \endcode - * - * This class can be extended with the help of the plugin mechanism described on the page - * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_MATRIX_PLUGIN. - * - * Some notes: - * - *

    - *
    \anchor dense Dense versus sparse:
    - *
    This %Matrix class handles dense, not sparse matrices and vectors. For sparse matrices and vectors, see the Sparse module. - * - * Dense matrices and vectors are plain usual arrays of coefficients. All the coefficients are stored, in an ordinary contiguous array. - * This is unlike Sparse matrices and vectors where the coefficients are stored as a list of nonzero coefficients.
    - * - *
    \anchor fixedsize Fixed-size versus dynamic-size:
    - *
    Fixed-size means that the numbers of rows and columns are known are compile-time. In this case, Eigen allocates the array - * of coefficients as a fixed-size array, as a class member. This makes sense for very small matrices, typically up to 4x4, sometimes up - * to 16x16. Larger matrices should be declared as dynamic-size even if one happens to know their size at compile-time. - * - * Dynamic-size means that the numbers of rows or columns are not necessarily known at compile-time. In this case they are runtime - * variables, and the array of coefficients is allocated dynamically on the heap. - * - * Note that \em dense matrices, be they Fixed-size or Dynamic-size, do not expand dynamically in the sense of a std::map. - * If you want this behavior, see the Sparse module.
    - * - *
    \anchor maxrows _MaxRows and _MaxCols:
    - *
    In most cases, one just leaves these parameters to the default values. - * These parameters mean the maximum size of rows and columns that the matrix may have. They are useful in cases - * when the exact numbers of rows and columns are not known are compile-time, but it is known at compile-time that they cannot - * exceed a certain value. This happens when taking dynamic-size blocks inside fixed-size matrices: in this case _MaxRows and _MaxCols - * are the dimensions of the original matrix, while _Rows and _Cols are Dynamic.
    - *
    - * - * ABI and storage layout - * - * The table below summarizes the ABI of some possible Matrix instances which is fixed thorough the lifetime of Eigen 3. - * - * - * - * - * - * - *
    Matrix typeEquivalent C structure
    \code Matrix \endcode\code - * struct { - * T *data; // with (size_t(data)%EIGEN_MAX_ALIGN_BYTES)==0 - * Eigen::Index rows, cols; - * }; - * \endcode
    \code - * Matrix - * Matrix \endcode\code - * struct { - * T *data; // with (size_t(data)%EIGEN_MAX_ALIGN_BYTES)==0 - * Eigen::Index size; - * }; - * \endcode
    \code Matrix \endcode\code - * struct { - * T data[Rows*Cols]; // with (size_t(data)%A(Rows*Cols*sizeof(T)))==0 - * }; - * \endcode
    \code Matrix \endcode\code - * struct { - * T data[MaxRows*MaxCols]; // with (size_t(data)%A(MaxRows*MaxCols*sizeof(T)))==0 - * Eigen::Index rows, cols; - * }; - * \endcode
    - * Note that in this table Rows, Cols, MaxRows and MaxCols are all positive integers. A(S) is defined to the largest possible power-of-two - * smaller to EIGEN_MAX_STATIC_ALIGN_BYTES. - * - * \see MatrixBase for the majority of the API methods for matrices, \ref TopicClassHierarchy, - * \ref TopicStorageOrders - */ - -template -class Matrix - : public PlainObjectBase > -{ - public: - - /** \brief Base class typedef. - * \sa PlainObjectBase - */ - typedef PlainObjectBase Base; - - enum { Options = _Options }; - - EIGEN_DENSE_PUBLIC_INTERFACE(Matrix) - - typedef typename Base::PlainObject PlainObject; - - using Base::base; - using Base::coeffRef; - - /** - * \brief Assigns matrices to each other. - * - * \note This is a special case of the templated operator=. Its purpose is - * to prevent a default operator= from hiding the templated operator=. - * - * \callgraph - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Matrix& operator=(const Matrix& other) - { - return Base::_set(other); - } - - /** \internal - * \brief Copies the value of the expression \a other into \c *this with automatic resizing. - * - * *this might be resized to match the dimensions of \a other. If *this was a null matrix (not already initialized), - * it will be initialized. - * - * Note that copying a row-vector into a vector (and conversely) is allowed. - * The resizing, if any, is then done in the appropriate way so that row-vectors - * remain row-vectors and vectors remain vectors. - */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Matrix& operator=(const DenseBase& other) - { - return Base::_set(other); - } - - /* Here, doxygen failed to copy the brief information when using \copydoc */ - - /** - * \brief Copies the generic expression \a other into *this. - * \copydetails DenseBase::operator=(const EigenBase &other) - */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Matrix& operator=(const EigenBase &other) - { - return Base::operator=(other); - } - - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Matrix& operator=(const ReturnByValue& func) - { - return Base::operator=(func); - } - - /** \brief Default constructor. - * - * For fixed-size matrices, does nothing. - * - * For dynamic-size matrices, creates an empty matrix of size 0. Does not allocate any array. Such a matrix - * is called a null matrix. This constructor is the unique way to create null matrices: resizing - * a matrix to 0 is not supported. - * - * \sa resize(Index,Index) - */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Matrix() : Base() - { - Base::_check_template_params(); - EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED - } - - // FIXME is it still needed - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit Matrix(internal::constructor_without_unaligned_array_assert) - : Base(internal::constructor_without_unaligned_array_assert()) - { Base::_check_template_params(); EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED } - -#if EIGEN_HAS_RVALUE_REFERENCES - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Matrix(Matrix&& other) EIGEN_NOEXCEPT_IF(std::is_nothrow_move_constructible::value) - : Base(std::move(other)) - { - Base::_check_template_params(); - } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Matrix& operator=(Matrix&& other) EIGEN_NOEXCEPT_IF(std::is_nothrow_move_assignable::value) - { - Base::operator=(std::move(other)); - return *this; - } -#endif - -#if EIGEN_HAS_CXX11 - /** \copydoc PlainObjectBase(const Scalar&, const Scalar&, const Scalar&, const Scalar&, const ArgTypes&... args) - * - * Example: \include Matrix_variadic_ctor_cxx11.cpp - * Output: \verbinclude Matrix_variadic_ctor_cxx11.out - * - * \sa Matrix(const std::initializer_list>&) - */ - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Matrix(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) + * \ingroup Core_Module + * + * \brief The matrix class, also used for vectors and row-vectors + * + * The %Matrix class is the work-horse for all \em dense (\ref dense "note") matrices and vectors within Eigen. + * Vectors are matrices with one column, and row-vectors are matrices with one row. + * + * The %Matrix class encompasses \em both fixed-size and dynamic-size objects (\ref fixedsize "note"). + * + * The first three template parameters are required: + * \tparam Scalar_ Numeric type, e.g. float, double, int or std::complex. + * User defined scalar types are supported as well (see \ref user_defined_scalars "here"). + * \tparam Rows_ Number of rows, or \b Dynamic + * \tparam Cols_ Number of columns, or \b Dynamic + * + * The remaining template parameters are optional -- in most cases you don't have to worry about them. + * \tparam Options_ A combination of either \b #RowMajor or \b #ColMajor, and of either + * \b #AutoAlign or \b #DontAlign. + * The former controls \ref TopicStorageOrders "storage order", and defaults to column-major. The latter + * controls alignment, which is required for vectorization. It defaults to aligning matrices except for fixed sizes that + * aren't a multiple of the packet size. \tparam MaxRows_ Maximum number of rows. Defaults to \a Rows_ (\ref maxrows + * "note"). \tparam MaxCols_ Maximum number of columns. Defaults to \a Cols_ (\ref maxrows "note"). + * + * Eigen provides a number of typedefs covering the usual cases. Here are some examples: + * + * \li \c Matrix2d is a 2x2 square matrix of doubles (\c Matrix) + * \li \c Vector4f is a vector of 4 floats (\c Matrix) + * \li \c RowVector3i is a row-vector of 3 ints (\c Matrix) + * + * \li \c MatrixXf is a dynamic-size matrix of floats (\c Matrix) + * \li \c VectorXf is a dynamic-size vector of floats (\c Matrix) + * + * \li \c Matrix2Xf is a partially fixed-size (dynamic-size) matrix of floats (\c Matrix) + * \li \c MatrixX3d is a partially dynamic-size (fixed-size) matrix of double (\c Matrix) + * + * See \link matrixtypedefs this page \endlink for a complete list of predefined \em %Matrix and \em Vector typedefs. + * + * You can access elements of vectors and matrices using normal subscripting: + * + * \code + * Eigen::VectorXd v(10); + * v[0] = 0.1; + * v[1] = 0.2; + * v(0) = 0.3; + * v(1) = 0.4; + * + * Eigen::MatrixXi m(10, 10); + * m(0, 1) = 1; + * m(0, 2) = 2; + * m(0, 3) = 3; + * \endcode + * + * This class can be extended with the help of the plugin mechanism described on the page + * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_MATRIX_PLUGIN. + * + * Some notes: + * + *
    + *
    \anchor dense Dense versus sparse:
    + *
    This %Matrix class handles dense, not sparse matrices and vectors. For sparse matrices and vectors, see the + * Sparse module. + * + * Dense matrices and vectors are plain usual arrays of coefficients. All the coefficients are stored, in an ordinary + * contiguous array. This is unlike Sparse matrices and vectors where the coefficients are stored as a list of nonzero + * coefficients.
    + * + *
    \anchor fixedsize Fixed-size versus dynamic-size:
    + *
    Fixed-size means that the numbers of rows and columns are known are compile-time. In this case, Eigen allocates + * the array of coefficients as a fixed-size array, as a class member. This makes sense for very small matrices, + * typically up to 4x4, sometimes up to 16x16. Larger matrices should be declared as dynamic-size even if one happens to + * know their size at compile-time. + * + * Dynamic-size means that the numbers of rows or columns are not necessarily known at compile-time. In this case they + * are runtime variables, and the array of coefficients is allocated dynamically on the heap. + * + * Note that \em dense matrices, be they Fixed-size or Dynamic-size, do not expand dynamically in the sense of + * a std::map. If you want this behavior, see the Sparse module.
    + * + *
    \anchor maxrows MaxRows_ and MaxCols_:
    + *
    In most cases, one just leaves these parameters to the default values. + * These parameters mean the maximum size of rows and columns that the matrix may have. They are useful in cases + * when the exact numbers of rows and columns are not known are compile-time, but it is known at compile-time that they + * cannot exceed a certain value. This happens when taking dynamic-size blocks inside fixed-size matrices: in this case + * MaxRows_ and MaxCols_ are the dimensions of the original matrix, while Rows_ and Cols_ are Dynamic.
    + *
    + * + * ABI and storage layout + * + * The table below summarizes the ABI of some possible Matrix instances which is fixed thorough the lifetime of Eigen 3. + * + * + * + * + * + * + *
    Matrix typeEquivalent C structure
    \code Matrix \endcode\code + * struct { + * T *data; // with (size_t(data)%EIGEN_MAX_ALIGN_BYTES)==0 + * Eigen::Index rows, cols; + * }; + * \endcode
    \code + * Matrix + * Matrix \endcode\code + * struct { + * T *data; // with (size_t(data)%EIGEN_MAX_ALIGN_BYTES)==0 + * Eigen::Index size; + * }; + * \endcode
    \code Matrix \endcode\code + * struct { + * T data[Rows*Cols]; // with (size_t(data)%A(Rows*Cols*sizeof(T)))==0 + * }; + * \endcode
    \code Matrix \endcode\code + * struct { + * T data[MaxRows*MaxCols]; // with (size_t(data)%A(MaxRows*MaxCols*sizeof(T)))==0 + * Eigen::Index rows, cols; + * }; + * \endcode
    + * Note that in this table Rows, Cols, MaxRows and MaxCols are all positive integers. A(S) is defined to the largest + * possible power-of-two smaller to EIGEN_MAX_STATIC_ALIGN_BYTES. + * + * \see MatrixBase for the majority of the API methods for matrices, \ref TopicClassHierarchy, + * \ref TopicStorageOrders + */ + +template +class Matrix : public PlainObjectBase> { + public: + /** \brief Base class typedef. + * \sa PlainObjectBase + */ + typedef PlainObjectBase Base; + + enum { Options = Options_ }; + + EIGEN_DENSE_PUBLIC_INTERFACE(Matrix) + + typedef typename Base::PlainObject PlainObject; + + using Base::base; + using Base::coeffRef; + + /** + * \brief Assigns matrices to each other. + * + * \note This is a special case of the templated operator=. Its purpose is + * to prevent a default operator= from hiding the templated operator=. + * + * \callgraph + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr Matrix& operator=(const Matrix& other) { return Base::_set(other); } + + /** \internal + * \brief Copies the value of the expression \a other into \c *this with automatic resizing. + * + * *this might be resized to match the dimensions of \a other. If *this was a null matrix (not already initialized), + * it will be initialized. + * + * Note that copying a row-vector into a vector (and conversely) is allowed. + * The resizing, if any, is then done in the appropriate way so that row-vectors + * remain row-vectors and vectors remain vectors. + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Matrix& operator=(const DenseBase& other) { + return Base::_set(other); + } + + /* Here, doxygen failed to copy the brief information when using \copydoc */ + + /** + * \brief Copies the generic expression \a other into *this. + * \copydetails DenseBase::operator=(const EigenBase &other) + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Matrix& operator=(const EigenBase& other) { + return Base::operator=(other); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Matrix& operator=(const ReturnByValue& func) { + return Base::operator=(func); + } + + /** \brief Default constructor. + * + * For fixed-size matrices, does nothing. + * + * For dynamic-size matrices, creates an empty matrix of size 0. Does not allocate any array. Such a matrix + * is called a null matrix. This constructor is the unique way to create null matrices: resizing + * a matrix to 0 is not supported. + * + * \sa resize(Index,Index) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr Matrix() + : Base(){EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED} + + // FIXME is it still needed + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr explicit Matrix( + internal::constructor_without_unaligned_array_assert) + : Base(internal::constructor_without_unaligned_array_assert()){EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr Matrix(Matrix && other) + EIGEN_NOEXCEPT_IF(std::is_nothrow_move_constructible::value) + : Base(std::move(other)) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr Matrix& operator=(Matrix&& other) + EIGEN_NOEXCEPT_IF(std::is_nothrow_move_assignable::value) { + Base::operator=(std::move(other)); + return *this; + } + + /** \copydoc PlainObjectBase(const Scalar&, const Scalar&, const Scalar&, const Scalar&, const ArgTypes&... args) + * + * Example: \include Matrix_variadic_ctor_cxx11.cpp + * Output: \verbinclude Matrix_variadic_ctor_cxx11.out + * + * \sa Matrix(const std::initializer_list>&) + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Matrix(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, + const ArgTypes&... args) : Base(a0, a1, a2, a3, args...) {} - /** \brief Constructs a Matrix and initializes it from the coefficients given as initializer-lists grouped by row. \cpp11 - * - * In the general case, the constructor takes a list of rows, each row being represented as a list of coefficients: - * - * Example: \include Matrix_initializer_list_23_cxx11.cpp - * Output: \verbinclude Matrix_initializer_list_23_cxx11.out - * - * Each of the inner initializer lists must contain the exact same number of elements, otherwise an assertion is triggered. - * - * In the case of a compile-time column vector, implicit transposition from a single row is allowed. - * Therefore VectorXd{{1,2,3,4,5}} is legal and the more verbose syntax - * RowVectorXd{{1},{2},{3},{4},{5}} can be avoided: - * - * Example: \include Matrix_initializer_list_vector_cxx11.cpp - * Output: \verbinclude Matrix_initializer_list_vector_cxx11.out - * - * In the case of fixed-sized matrices, the initializer list sizes must exactly match the matrix sizes, - * and implicit transposition is allowed for compile-time vectors only. - * - * \sa Matrix(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) - */ - EIGEN_DEVICE_FUNC - explicit EIGEN_STRONG_INLINE Matrix(const std::initializer_list>& list) : Base(list) {} -#endif // end EIGEN_HAS_CXX11 + /** \brief Constructs a Matrix and initializes it from the coefficients given as initializer-lists grouped by row. + * \cpp11 + * + * In the general case, the constructor takes a list of rows, each row being represented as a list of coefficients: + * + * Example: \include Matrix_initializer_list_23_cxx11.cpp + * Output: \verbinclude Matrix_initializer_list_23_cxx11.out + * + * Each of the inner initializer lists must contain the exact same number of elements, otherwise an assertion is + * triggered. + * + * In the case of a compile-time column vector, implicit transposition from a single row is allowed. + * Therefore VectorXd{{1,2,3,4,5}} is legal and the more verbose syntax + * RowVectorXd{{1},{2},{3},{4},{5}} can be avoided: + * + * Example: \include Matrix_initializer_list_vector_cxx11.cpp + * Output: \verbinclude Matrix_initializer_list_vector_cxx11.out + * + * In the case of fixed-sized matrices, the initializer list sizes must exactly match the matrix sizes, + * and implicit transposition is allowed for compile-time vectors only. + * + * \sa Matrix(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) + */ + EIGEN_DEVICE_FUNC explicit constexpr EIGEN_STRONG_INLINE Matrix( + const std::initializer_list>& list) + : Base(list) {} #ifndef EIGEN_PARSED_BY_DOXYGEN - // This constructor is for both 1x1 matrices and dynamic vectors - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit Matrix(const T& x) - { - Base::_check_template_params(); - Base::template _init1(x); - } - - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Matrix(const T0& x, const T1& y) - { - Base::_check_template_params(); - Base::template _init2(x, y); - } + // This constructor is for both 1x1 matrices and dynamic vectors + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit Matrix(const T& x) { + Base::template _init1(x); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Matrix(const T0& x, const T1& y) { + Base::template _init2(x, y); + } #else - /** \brief Constructs a fixed-sized matrix initialized with coefficients starting at \a data */ - EIGEN_DEVICE_FUNC - explicit Matrix(const Scalar *data); - - /** \brief Constructs a vector or row-vector with given dimension. \only_for_vectors - * - * This is useful for dynamic-size vectors. For fixed-size vectors, - * it is redundant to pass these parameters, so one should use the default constructor - * Matrix() instead. - * - * \warning This constructor is disabled for fixed-size \c 1x1 matrices. For instance, - * calling Matrix(1) will call the initialization constructor: Matrix(const Scalar&). - * For fixed-size \c 1x1 matrices it is therefore recommended to use the default - * constructor Matrix() instead, especially when using one of the non standard - * \c EIGEN_INITIALIZE_MATRICES_BY_{ZERO,\c NAN} macros (see \ref TopicPreprocessorDirectives). - */ - EIGEN_STRONG_INLINE explicit Matrix(Index dim); - /** \brief Constructs an initialized 1x1 matrix with the given coefficient - * \sa Matrix(const Scalar&, const Scalar&, const Scalar&, const Scalar&, const ArgTypes&...) */ - Matrix(const Scalar& x); - /** \brief Constructs an uninitialized matrix with \a rows rows and \a cols columns. - * - * This is useful for dynamic-size matrices. For fixed-size matrices, - * it is redundant to pass these parameters, so one should use the default constructor - * Matrix() instead. - * - * \warning This constructor is disabled for fixed-size \c 1x2 and \c 2x1 vectors. For instance, - * calling Matrix2f(2,1) will call the initialization constructor: Matrix(const Scalar& x, const Scalar& y). - * For fixed-size \c 1x2 or \c 2x1 vectors it is therefore recommended to use the default - * constructor Matrix() instead, especially when using one of the non standard - * \c EIGEN_INITIALIZE_MATRICES_BY_{ZERO,\c NAN} macros (see \ref TopicPreprocessorDirectives). - */ - EIGEN_DEVICE_FUNC - Matrix(Index rows, Index cols); - - /** \brief Constructs an initialized 2D vector with given coefficients - * \sa Matrix(const Scalar&, const Scalar&, const Scalar&, const Scalar&, const ArgTypes&...) */ - Matrix(const Scalar& x, const Scalar& y); - #endif // end EIGEN_PARSED_BY_DOXYGEN - - /** \brief Constructs an initialized 3D vector with given coefficients - * \sa Matrix(const Scalar&, const Scalar&, const Scalar&, const Scalar&, const ArgTypes&...) - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Matrix(const Scalar& x, const Scalar& y, const Scalar& z) - { - Base::_check_template_params(); - EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Matrix, 3) - m_storage.data()[0] = x; - m_storage.data()[1] = y; - m_storage.data()[2] = z; - } - /** \brief Constructs an initialized 4D vector with given coefficients - * \sa Matrix(const Scalar&, const Scalar&, const Scalar&, const Scalar&, const ArgTypes&...) - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Matrix(const Scalar& x, const Scalar& y, const Scalar& z, const Scalar& w) - { - Base::_check_template_params(); - EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Matrix, 4) - m_storage.data()[0] = x; - m_storage.data()[1] = y; - m_storage.data()[2] = z; - m_storage.data()[3] = w; - } - - - /** \brief Copy constructor */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Matrix(const Matrix& other) : Base(other) - { } - - /** \brief Copy constructor for generic expressions. - * \sa MatrixBase::operator=(const EigenBase&) - */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Matrix(const EigenBase &other) - : Base(other.derived()) - { } - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index innerStride() const EIGEN_NOEXCEPT { return 1; } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outerStride() const EIGEN_NOEXCEPT { return this->innerSize(); } - - /////////// Geometry module /////////// - - template - EIGEN_DEVICE_FUNC - explicit Matrix(const RotationBase& r); - template - EIGEN_DEVICE_FUNC - Matrix& operator=(const RotationBase& r); - - // allow to extend Matrix outside Eigen - #ifdef EIGEN_MATRIX_PLUGIN - #include EIGEN_MATRIX_PLUGIN - #endif - - protected: - template - friend struct internal::conservative_resize_like_impl; - - using Base::m_storage; + /** \brief Constructs a fixed-sized matrix initialized with coefficients starting at \a data */ + EIGEN_DEVICE_FUNC explicit Matrix(const Scalar* data); + + /** \brief Constructs a vector or row-vector with given dimension. \only_for_vectors + * + * This is useful for dynamic-size vectors. For fixed-size vectors, + * it is redundant to pass these parameters, so one should use the default constructor + * Matrix() instead. + * + * \warning This constructor is disabled for fixed-size \c 1x1 matrices. For instance, + * calling Matrix(1) will call the initialization constructor: Matrix(const Scalar&). + * For fixed-size \c 1x1 matrices it is therefore recommended to use the default + * constructor Matrix() instead, especially when using one of the non standard + * \c EIGEN_INITIALIZE_MATRICES_BY_{ZERO,\c NAN} macros (see \ref TopicPreprocessorDirectives). + */ + EIGEN_STRONG_INLINE explicit Matrix(Index dim); + /** \brief Constructs an initialized 1x1 matrix with the given coefficient + * \sa Matrix(const Scalar&, const Scalar&, const Scalar&, const Scalar&, const ArgTypes&...) */ + Matrix(const Scalar& x); + /** \brief Constructs an uninitialized matrix with \a rows rows and \a cols columns. + * + * This is useful for dynamic-size matrices. For fixed-size matrices, + * it is redundant to pass these parameters, so one should use the default constructor + * Matrix() instead. + * + * \warning This constructor is disabled for fixed-size \c 1x2 and \c 2x1 vectors. For instance, + * calling Matrix2f(2,1) will call the initialization constructor: Matrix(const Scalar& x, const Scalar& y). + * For fixed-size \c 1x2 or \c 2x1 vectors it is therefore recommended to use the default + * constructor Matrix() instead, especially when using one of the non standard + * \c EIGEN_INITIALIZE_MATRICES_BY_{ZERO,\c NAN} macros (see \ref TopicPreprocessorDirectives). + */ + EIGEN_DEVICE_FUNC Matrix(Index rows, Index cols); + + /** \brief Constructs an initialized 2D vector with given coefficients + * \sa Matrix(const Scalar&, const Scalar&, const Scalar&, const Scalar&, const ArgTypes&...) */ + Matrix(const Scalar& x, const Scalar& y); +#endif // end EIGEN_PARSED_BY_DOXYGEN + + /** \brief Constructs an initialized 3D vector with given coefficients + * \sa Matrix(const Scalar&, const Scalar&, const Scalar&, const Scalar&, const ArgTypes&...) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Matrix(const Scalar& x, const Scalar& y, const Scalar& z) { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Matrix, 3) + m_storage.data()[0] = x; + m_storage.data()[1] = y; + m_storage.data()[2] = z; + } + /** \brief Constructs an initialized 4D vector with given coefficients + * \sa Matrix(const Scalar&, const Scalar&, const Scalar&, const Scalar&, const ArgTypes&...) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Matrix(const Scalar& x, const Scalar& y, const Scalar& z, const Scalar& w) { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Matrix, 4) + m_storage.data()[0] = x; + m_storage.data()[1] = y; + m_storage.data()[2] = z; + m_storage.data()[3] = w; + } + + /** \brief Copy constructor */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Matrix(const Matrix& other) : Base(other) {} + + /** \brief Copy constructor for generic expressions. + * \sa MatrixBase::operator=(const EigenBase&) + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Matrix(const EigenBase& other) : Base(other.derived()) {} + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const EIGEN_NOEXCEPT { return 1; } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const EIGEN_NOEXCEPT { return this->innerSize(); } + + /////////// Geometry module /////////// + + template + EIGEN_DEVICE_FUNC explicit Matrix(const RotationBase& r); + template + EIGEN_DEVICE_FUNC Matrix& operator=(const RotationBase& r); + +// allow to extend Matrix outside Eigen +#ifdef EIGEN_MATRIX_PLUGIN +#include EIGEN_MATRIX_PLUGIN +#endif + + protected: + template + friend struct internal::conservative_resize_like_impl; + + using Base::m_storage; }; /** \defgroup matrixtypedefs Global matrix typedefs - * - * \ingroup Core_Module - * - * %Eigen defines several typedef shortcuts for most common matrix and vector types. - * - * The general patterns are the following: - * - * \c MatrixSizeType where \c Size can be \c 2,\c 3,\c 4 for fixed size square matrices or \c X for dynamic size, - * and where \c Type can be \c i for integer, \c f for float, \c d for double, \c cf for complex float, \c cd - * for complex double. - * - * For example, \c Matrix3d is a fixed-size 3x3 matrix type of doubles, and \c MatrixXf is a dynamic-size matrix of floats. - * - * There are also \c VectorSizeType and \c RowVectorSizeType which are self-explanatory. For example, \c Vector4cf is - * a fixed-size vector of 4 complex floats. - * - * With \cpp11, template alias are also defined for common sizes. - * They follow the same pattern as above except that the scalar type suffix is replaced by a - * template parameter, i.e.: - * - `MatrixSize` where `Size` can be \c 2,\c 3,\c 4 for fixed size square matrices or \c X for dynamic size. - * - `MatrixXSize` and `MatrixSizeX` where `Size` can be \c 2,\c 3,\c 4 for hybrid dynamic/fixed matrices. - * - `VectorSize` and `RowVectorSize` for column and row vectors. - * - * With \cpp11, you can also use fully generic column and row vector types: `Vector` and `RowVector`. - * - * \sa class Matrix - */ - -#define EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, Size, SizeSuffix) \ -/** \ingroup matrixtypedefs */ \ -typedef Matrix Matrix##SizeSuffix##TypeSuffix; \ -/** \ingroup matrixtypedefs */ \ -typedef Matrix Vector##SizeSuffix##TypeSuffix; \ -/** \ingroup matrixtypedefs */ \ -typedef Matrix RowVector##SizeSuffix##TypeSuffix; - -#define EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, Size) \ -/** \ingroup matrixtypedefs */ \ -typedef Matrix Matrix##Size##X##TypeSuffix; \ -/** \ingroup matrixtypedefs */ \ -typedef Matrix Matrix##X##Size##TypeSuffix; + * + * \ingroup Core_Module + * + * %Eigen defines several typedef shortcuts for most common matrix and vector types. + * + * The general patterns are the following: + * + * \c MatrixSizeType where \c Size can be \c 2,\c 3,\c 4 for fixed size square matrices or \c X for dynamic size, + * and where \c Type can be \c i for integer, \c f for float, \c d for double, \c cf for complex float, \c cd + * for complex double. + * + * For example, \c Matrix3d is a fixed-size 3x3 matrix type of doubles, and \c MatrixXf is a dynamic-size matrix of + * floats. + * + * There are also \c VectorSizeType and \c RowVectorSizeType which are self-explanatory. For example, \c Vector4cf is + * a fixed-size vector of 4 complex floats. + * + * With \cpp11, template alias are also defined for common sizes. + * They follow the same pattern as above except that the scalar type suffix is replaced by a + * template parameter, i.e.: + * - `MatrixSize` where `Size` can be \c 2,\c 3,\c 4 for fixed size square matrices or \c X for dynamic size. + * - `MatrixXSize` and `MatrixSizeX` where `Size` can be \c 2,\c 3,\c 4 for hybrid dynamic/fixed matrices. + * - `VectorSize` and `RowVectorSize` for column and row vectors. + * + * With \cpp11, you can also use fully generic column and row vector types: `Vector` and + * `RowVector`. + * + * \sa class Matrix + */ + +#define EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, Size, SizeSuffix) \ + /** \ingroup matrixtypedefs */ \ + /** \brief `Size`×`Size` matrix of type `Type`. */ \ + typedef Matrix Matrix##SizeSuffix##TypeSuffix; \ + /** \ingroup matrixtypedefs */ \ + /** \brief `Size`×`1` vector of type `Type`. */ \ + typedef Matrix Vector##SizeSuffix##TypeSuffix; \ + /** \ingroup matrixtypedefs */ \ + /** \brief `1`×`Size` vector of type `Type`. */ \ + typedef Matrix RowVector##SizeSuffix##TypeSuffix; + +#define EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, Size) \ + /** \ingroup matrixtypedefs */ \ + /** \brief `Size`×`Dynamic` matrix of type `Type`. */ \ + typedef Matrix Matrix##Size##X##TypeSuffix; \ + /** \ingroup matrixtypedefs */ \ + /** \brief `Dynamic`×`Size` matrix of type `Type`. */ \ + typedef Matrix Matrix##X##Size##TypeSuffix; #define EIGEN_MAKE_TYPEDEFS_ALL_SIZES(Type, TypeSuffix) \ -EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 2, 2) \ -EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 3, 3) \ -EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 4, 4) \ -EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, Dynamic, X) \ -EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 2) \ -EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 3) \ -EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 4) - -EIGEN_MAKE_TYPEDEFS_ALL_SIZES(int, i) -EIGEN_MAKE_TYPEDEFS_ALL_SIZES(float, f) -EIGEN_MAKE_TYPEDEFS_ALL_SIZES(double, d) -EIGEN_MAKE_TYPEDEFS_ALL_SIZES(std::complex, cf) + EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 2, 2) \ + EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 3, 3) \ + EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 4, 4) \ + EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, Dynamic, X) \ + EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 2) \ + EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 3) \ + EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 4) + +EIGEN_MAKE_TYPEDEFS_ALL_SIZES(int, i) +EIGEN_MAKE_TYPEDEFS_ALL_SIZES(float, f) +EIGEN_MAKE_TYPEDEFS_ALL_SIZES(double, d) +EIGEN_MAKE_TYPEDEFS_ALL_SIZES(std::complex, cf) EIGEN_MAKE_TYPEDEFS_ALL_SIZES(std::complex, cd) #undef EIGEN_MAKE_TYPEDEFS_ALL_SIZES #undef EIGEN_MAKE_TYPEDEFS #undef EIGEN_MAKE_FIXED_TYPEDEFS -#if EIGEN_HAS_CXX11 - -#define EIGEN_MAKE_TYPEDEFS(Size, SizeSuffix) \ -/** \ingroup matrixtypedefs */ \ -/** \brief \cpp11 */ \ -template \ -using Matrix##SizeSuffix = Matrix; \ -/** \ingroup matrixtypedefs */ \ -/** \brief \cpp11 */ \ -template \ -using Vector##SizeSuffix = Matrix; \ -/** \ingroup matrixtypedefs */ \ -/** \brief \cpp11 */ \ -template \ -using RowVector##SizeSuffix = Matrix; - -#define EIGEN_MAKE_FIXED_TYPEDEFS(Size) \ -/** \ingroup matrixtypedefs */ \ -/** \brief \cpp11 */ \ -template \ -using Matrix##Size##X = Matrix; \ -/** \ingroup matrixtypedefs */ \ -/** \brief \cpp11 */ \ -template \ -using Matrix##X##Size = Matrix; +#define EIGEN_MAKE_TYPEDEFS(Size, SizeSuffix) \ + /** \ingroup matrixtypedefs */ \ + /** \brief \cpp11 `Size`×`Size` matrix of type `Type`.*/ \ + template \ + using Matrix##SizeSuffix = Matrix; \ + /** \ingroup matrixtypedefs */ \ + /** \brief \cpp11 `Size`×`1` vector of type `Type`.*/ \ + template \ + using Vector##SizeSuffix = Matrix; \ + /** \ingroup matrixtypedefs */ \ + /** \brief \cpp11 `1`×`Size` vector of type `Type`.*/ \ + template \ + using RowVector##SizeSuffix = Matrix; + +#define EIGEN_MAKE_FIXED_TYPEDEFS(Size) \ + /** \ingroup matrixtypedefs */ \ + /** \brief \cpp11 `Size`×`Dynamic` matrix of type `Type` */ \ + template \ + using Matrix##Size##X = Matrix; \ + /** \ingroup matrixtypedefs */ \ + /** \brief \cpp11 `Dynamic`×`Size` matrix of type `Type`. */ \ + template \ + using Matrix##X##Size = Matrix; EIGEN_MAKE_TYPEDEFS(2, 2) EIGEN_MAKE_TYPEDEFS(3, 3) @@ -546,20 +511,18 @@ EIGEN_MAKE_FIXED_TYPEDEFS(3) EIGEN_MAKE_FIXED_TYPEDEFS(4) /** \ingroup matrixtypedefs - * \brief \cpp11 */ + * \brief \cpp11 `Size`×`1` vector of type `Type`. */ template using Vector = Matrix; /** \ingroup matrixtypedefs - * \brief \cpp11 */ + * \brief \cpp11 `1`×`Size` vector of type `Type`. */ template using RowVector = Matrix; #undef EIGEN_MAKE_TYPEDEFS #undef EIGEN_MAKE_FIXED_TYPEDEFS -#endif // EIGEN_HAS_CXX11 - -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_MATRIX_H +#endif // EIGEN_MATRIX_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MatrixBase.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MatrixBase.h index 45c3a596ecb..81d5a97ea2f 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MatrixBase.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/MatrixBase.h @@ -11,6 +11,9 @@ #ifndef EIGEN_MATRIXBASE_H #define EIGEN_MATRIXBASE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { /** \class MatrixBase @@ -45,503 +48,495 @@ namespace Eigen { * * \sa \blank \ref TopicClassHierarchy */ -template class MatrixBase - : public DenseBase -{ - public: +template +class MatrixBase : public DenseBase { + public: #ifndef EIGEN_PARSED_BY_DOXYGEN - typedef MatrixBase StorageBaseType; - typedef typename internal::traits::StorageKind StorageKind; - typedef typename internal::traits::StorageIndex StorageIndex; - typedef typename internal::traits::Scalar Scalar; - typedef typename internal::packet_traits::type PacketScalar; - typedef typename NumTraits::Real RealScalar; - - typedef DenseBase Base; - using Base::RowsAtCompileTime; - using Base::ColsAtCompileTime; - using Base::SizeAtCompileTime; - using Base::MaxRowsAtCompileTime; - using Base::MaxColsAtCompileTime; - using Base::MaxSizeAtCompileTime; - using Base::IsVectorAtCompileTime; - using Base::Flags; - - using Base::derived; - using Base::const_cast_derived; - using Base::rows; - using Base::cols; - using Base::size; - using Base::coeff; - using Base::coeffRef; - using Base::lazyAssign; - using Base::eval; - using Base::operator-; - using Base::operator+=; - using Base::operator-=; - using Base::operator*=; - using Base::operator/=; - - typedef typename Base::CoeffReturnType CoeffReturnType; - typedef typename Base::ConstTransposeReturnType ConstTransposeReturnType; - typedef typename Base::RowXpr RowXpr; - typedef typename Base::ColXpr ColXpr; -#endif // not EIGEN_PARSED_BY_DOXYGEN - - + typedef MatrixBase StorageBaseType; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::StorageIndex StorageIndex; + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::packet_traits::type PacketScalar; + typedef typename NumTraits::Real RealScalar; + + typedef DenseBase Base; + using Base::ColsAtCompileTime; + using Base::Flags; + using Base::IsVectorAtCompileTime; + using Base::MaxColsAtCompileTime; + using Base::MaxRowsAtCompileTime; + using Base::MaxSizeAtCompileTime; + using Base::RowsAtCompileTime; + using Base::SizeAtCompileTime; + + using Base::coeff; + using Base::coeffRef; + using Base::cols; + using Base::const_cast_derived; + using Base::derived; + using Base::eval; + using Base::lazyAssign; + using Base::rows; + using Base::size; + using Base::operator-; + using Base::operator+=; + using Base::operator-=; + using Base::operator*=; + using Base::operator/=; + + typedef typename Base::CoeffReturnType CoeffReturnType; + typedef typename Base::ConstTransposeReturnType ConstTransposeReturnType; + typedef typename Base::RowXpr RowXpr; + typedef typename Base::ColXpr ColXpr; +#endif // not EIGEN_PARSED_BY_DOXYGEN #ifndef EIGEN_PARSED_BY_DOXYGEN - /** type of the equivalent square matrix */ - typedef Matrix SquareMatrixType; -#endif // not EIGEN_PARSED_BY_DOXYGEN + /** type of the equivalent square matrix */ + typedef Matrix + SquareMatrixType; +#endif // not EIGEN_PARSED_BY_DOXYGEN - /** \returns the size of the main diagonal, which is min(rows(),cols()). - * \sa rows(), cols(), SizeAtCompileTime. */ - EIGEN_DEVICE_FUNC - inline Index diagonalSize() const { return (numext::mini)(rows(),cols()); } + /** \returns the size of the main diagonal, which is min(rows(),cols()). + * \sa rows(), cols(), SizeAtCompileTime. */ + EIGEN_DEVICE_FUNC inline Index diagonalSize() const { return (numext::mini)(rows(), cols()); } - typedef typename Base::PlainObject PlainObject; + typedef typename Base::PlainObject PlainObject; #ifndef EIGEN_PARSED_BY_DOXYGEN - /** \internal Represents a matrix with all coefficients equal to one another*/ - typedef CwiseNullaryOp,PlainObject> ConstantReturnType; - /** \internal the return type of MatrixBase::adjoint() */ - typedef typename internal::conditional::IsComplex, - CwiseUnaryOp, ConstTransposeReturnType>, - ConstTransposeReturnType - >::type AdjointReturnType; - /** \internal Return type of eigenvalues() */ - typedef Matrix, internal::traits::ColsAtCompileTime, 1, ColMajor> EigenvaluesReturnType; - /** \internal the return type of identity */ - typedef CwiseNullaryOp,PlainObject> IdentityReturnType; - /** \internal the return type of unit vectors */ - typedef Block, SquareMatrixType>, - internal::traits::RowsAtCompileTime, - internal::traits::ColsAtCompileTime> BasisReturnType; -#endif // not EIGEN_PARSED_BY_DOXYGEN + /** \internal Represents a matrix with all coefficients equal to one another*/ + typedef CwiseNullaryOp, PlainObject> ConstantReturnType; + /** \internal the return type of MatrixBase::adjoint() */ + typedef std::conditional_t::IsComplex, + CwiseUnaryOp, ConstTransposeReturnType>, + ConstTransposeReturnType> + AdjointReturnType; + /** \internal Return type of eigenvalues() */ + typedef Matrix, internal::traits::ColsAtCompileTime, 1, ColMajor> + EigenvaluesReturnType; + /** \internal the return type of identity */ + typedef CwiseNullaryOp, PlainObject> IdentityReturnType; + /** \internal the return type of unit vectors */ + typedef Block, SquareMatrixType>, + internal::traits::RowsAtCompileTime, internal::traits::ColsAtCompileTime> + BasisReturnType; +#endif // not EIGEN_PARSED_BY_DOXYGEN #define EIGEN_CURRENT_STORAGE_BASE_CLASS Eigen::MatrixBase -#define EIGEN_DOC_UNARY_ADDONS(X,Y) -# include "../plugins/CommonCwiseBinaryOps.h" -# include "../plugins/MatrixCwiseUnaryOps.h" -# include "../plugins/MatrixCwiseBinaryOps.h" -# ifdef EIGEN_MATRIXBASE_PLUGIN -# include EIGEN_MATRIXBASE_PLUGIN -# endif +#define EIGEN_DOC_UNARY_ADDONS(X, Y) +#include "../plugins/CommonCwiseBinaryOps.inc" +#include "../plugins/MatrixCwiseUnaryOps.inc" +#include "../plugins/MatrixCwiseBinaryOps.inc" +#ifdef EIGEN_MATRIXBASE_PLUGIN +#include EIGEN_MATRIXBASE_PLUGIN +#endif #undef EIGEN_CURRENT_STORAGE_BASE_CLASS #undef EIGEN_DOC_UNARY_ADDONS - /** Special case of the template operator=, in order to prevent the compiler - * from generating a default operator= (issue hit with g++ 4.1) - */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator=(const MatrixBase& other); - - // We cannot inherit here via Base::operator= since it is causing - // trouble with MSVC. - - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator=(const DenseBase& other); - - template - EIGEN_DEVICE_FUNC - Derived& operator=(const EigenBase& other); - - template - EIGEN_DEVICE_FUNC - Derived& operator=(const ReturnByValue& other); - - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator+=(const MatrixBase& other); - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Derived& operator-=(const MatrixBase& other); - - template - EIGEN_DEVICE_FUNC - const Product - operator*(const MatrixBase &other) const; - - template - EIGEN_DEVICE_FUNC - const Product - lazyProduct(const MatrixBase &other) const; - - template - Derived& operator*=(const EigenBase& other); - - template - void applyOnTheLeft(const EigenBase& other); - - template - void applyOnTheRight(const EigenBase& other); - - template - EIGEN_DEVICE_FUNC - const Product - operator*(const DiagonalBase &diagonal) const; - - template - EIGEN_DEVICE_FUNC - typename ScalarBinaryOpTraits::Scalar,typename internal::traits::Scalar>::ReturnType - dot(const MatrixBase& other) const; - - EIGEN_DEVICE_FUNC RealScalar squaredNorm() const; - EIGEN_DEVICE_FUNC RealScalar norm() const; - RealScalar stableNorm() const; - RealScalar blueNorm() const; - RealScalar hypotNorm() const; - EIGEN_DEVICE_FUNC const PlainObject normalized() const; - EIGEN_DEVICE_FUNC const PlainObject stableNormalized() const; - EIGEN_DEVICE_FUNC void normalize(); - EIGEN_DEVICE_FUNC void stableNormalize(); - - EIGEN_DEVICE_FUNC const AdjointReturnType adjoint() const; - EIGEN_DEVICE_FUNC void adjointInPlace(); - - typedef Diagonal DiagonalReturnType; - EIGEN_DEVICE_FUNC - DiagonalReturnType diagonal(); - - typedef typename internal::add_const >::type ConstDiagonalReturnType; - EIGEN_DEVICE_FUNC - ConstDiagonalReturnType diagonal() const; - - template struct DiagonalIndexReturnType { typedef Diagonal Type; }; - template struct ConstDiagonalIndexReturnType { typedef const Diagonal Type; }; - - template - EIGEN_DEVICE_FUNC - typename DiagonalIndexReturnType::Type diagonal(); - - template - EIGEN_DEVICE_FUNC - typename ConstDiagonalIndexReturnType::Type diagonal() const; - - typedef Diagonal DiagonalDynamicIndexReturnType; - typedef typename internal::add_const >::type ConstDiagonalDynamicIndexReturnType; - - EIGEN_DEVICE_FUNC - DiagonalDynamicIndexReturnType diagonal(Index index); - EIGEN_DEVICE_FUNC - ConstDiagonalDynamicIndexReturnType diagonal(Index index) const; - - template struct TriangularViewReturnType { typedef TriangularView Type; }; - template struct ConstTriangularViewReturnType { typedef const TriangularView Type; }; - - template - EIGEN_DEVICE_FUNC - typename TriangularViewReturnType::Type triangularView(); - template - EIGEN_DEVICE_FUNC - typename ConstTriangularViewReturnType::Type triangularView() const; - - template struct SelfAdjointViewReturnType { typedef SelfAdjointView Type; }; - template struct ConstSelfAdjointViewReturnType { typedef const SelfAdjointView Type; }; - - template - EIGEN_DEVICE_FUNC - typename SelfAdjointViewReturnType::Type selfadjointView(); - template - EIGEN_DEVICE_FUNC - typename ConstSelfAdjointViewReturnType::Type selfadjointView() const; - - const SparseView sparseView(const Scalar& m_reference = Scalar(0), - const typename NumTraits::Real& m_epsilon = NumTraits::dummy_precision()) const; - EIGEN_DEVICE_FUNC static const IdentityReturnType Identity(); - EIGEN_DEVICE_FUNC static const IdentityReturnType Identity(Index rows, Index cols); - EIGEN_DEVICE_FUNC static const BasisReturnType Unit(Index size, Index i); - EIGEN_DEVICE_FUNC static const BasisReturnType Unit(Index i); - EIGEN_DEVICE_FUNC static const BasisReturnType UnitX(); - EIGEN_DEVICE_FUNC static const BasisReturnType UnitY(); - EIGEN_DEVICE_FUNC static const BasisReturnType UnitZ(); - EIGEN_DEVICE_FUNC static const BasisReturnType UnitW(); - - EIGEN_DEVICE_FUNC - const DiagonalWrapper asDiagonal() const; - const PermutationWrapper asPermutation() const; - - EIGEN_DEVICE_FUNC - Derived& setIdentity(); - EIGEN_DEVICE_FUNC - Derived& setIdentity(Index rows, Index cols); - EIGEN_DEVICE_FUNC Derived& setUnit(Index i); - EIGEN_DEVICE_FUNC Derived& setUnit(Index newSize, Index i); - - bool isIdentity(const RealScalar& prec = NumTraits::dummy_precision()) const; - bool isDiagonal(const RealScalar& prec = NumTraits::dummy_precision()) const; - - bool isUpperTriangular(const RealScalar& prec = NumTraits::dummy_precision()) const; - bool isLowerTriangular(const RealScalar& prec = NumTraits::dummy_precision()) const; - - template - bool isOrthogonal(const MatrixBase& other, - const RealScalar& prec = NumTraits::dummy_precision()) const; - bool isUnitary(const RealScalar& prec = NumTraits::dummy_precision()) const; - - /** \returns true if each coefficients of \c *this and \a other are all exactly equal. - * \warning When using floating point scalar values you probably should rather use a - * fuzzy comparison such as isApprox() - * \sa isApprox(), operator!= */ - template - EIGEN_DEVICE_FUNC inline bool operator==(const MatrixBase& other) const - { return cwiseEqual(other).all(); } - - /** \returns true if at least one pair of coefficients of \c *this and \a other are not exactly equal to each other. - * \warning When using floating point scalar values you probably should rather use a - * fuzzy comparison such as isApprox() - * \sa isApprox(), operator== */ - template - EIGEN_DEVICE_FUNC inline bool operator!=(const MatrixBase& other) const - { return cwiseNotEqual(other).any(); } - - NoAlias EIGEN_DEVICE_FUNC noalias(); - - // TODO forceAlignedAccess is temporarily disabled - // Need to find a nicer workaround. - inline const Derived& forceAlignedAccess() const { return derived(); } - inline Derived& forceAlignedAccess() { return derived(); } - template inline const Derived& forceAlignedAccessIf() const { return derived(); } - template inline Derived& forceAlignedAccessIf() { return derived(); } - - EIGEN_DEVICE_FUNC Scalar trace() const; - - template EIGEN_DEVICE_FUNC RealScalar lpNorm() const; - - EIGEN_DEVICE_FUNC MatrixBase& matrix() { return *this; } - EIGEN_DEVICE_FUNC const MatrixBase& matrix() const { return *this; } - - /** \returns an \link Eigen::ArrayBase Array \endlink expression of this matrix - * \sa ArrayBase::matrix() */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ArrayWrapper array() { return ArrayWrapper(derived()); } - /** \returns a const \link Eigen::ArrayBase Array \endlink expression of this matrix - * \sa ArrayBase::matrix() */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const ArrayWrapper array() const { return ArrayWrapper(derived()); } - -/////////// LU module /////////// - - inline const FullPivLU fullPivLu() const; - inline const PartialPivLU partialPivLu() const; - - inline const PartialPivLU lu() const; - - EIGEN_DEVICE_FUNC - inline const Inverse inverse() const; - - template - inline void computeInverseAndDetWithCheck( - ResultType& inverse, - typename ResultType::Scalar& determinant, - bool& invertible, - const RealScalar& absDeterminantThreshold = NumTraits::dummy_precision() - ) const; - - template - inline void computeInverseWithCheck( - ResultType& inverse, - bool& invertible, - const RealScalar& absDeterminantThreshold = NumTraits::dummy_precision() - ) const; - - EIGEN_DEVICE_FUNC - Scalar determinant() const; - -/////////// Cholesky module /////////// - - inline const LLT llt() const; - inline const LDLT ldlt() const; - -/////////// QR module /////////// - - inline const HouseholderQR householderQr() const; - inline const ColPivHouseholderQR colPivHouseholderQr() const; - inline const FullPivHouseholderQR fullPivHouseholderQr() const; - inline const CompleteOrthogonalDecomposition completeOrthogonalDecomposition() const; - -/////////// Eigenvalues module /////////// - - inline EigenvaluesReturnType eigenvalues() const; - inline RealScalar operatorNorm() const; - -/////////// SVD module /////////// - - inline JacobiSVD jacobiSvd(unsigned int computationOptions = 0) const; - inline BDCSVD bdcSvd(unsigned int computationOptions = 0) const; - -/////////// Geometry module /////////// - - #ifndef EIGEN_PARSED_BY_DOXYGEN - /// \internal helper struct to form the return type of the cross product - template struct cross_product_return_type { - typedef typename ScalarBinaryOpTraits::Scalar,typename internal::traits::Scalar>::ReturnType Scalar; - typedef Matrix type; - }; - #endif // EIGEN_PARSED_BY_DOXYGEN - template - EIGEN_DEVICE_FUNC -#ifndef EIGEN_PARSED_BY_DOXYGEN - inline typename cross_product_return_type::type -#else - inline PlainObject -#endif - cross(const MatrixBase& other) const; - - template - EIGEN_DEVICE_FUNC - inline PlainObject cross3(const MatrixBase& other) const; - - EIGEN_DEVICE_FUNC - inline PlainObject unitOrthogonal(void) const; - - EIGEN_DEVICE_FUNC - inline Matrix eulerAngles(Index a0, Index a1, Index a2) const; - - // put this as separate enum value to work around possible GCC 4.3 bug (?) - enum { HomogeneousReturnTypeDirection = ColsAtCompileTime==1&&RowsAtCompileTime==1 ? ((internal::traits::Flags&RowMajorBit)==RowMajorBit ? Horizontal : Vertical) - : ColsAtCompileTime==1 ? Vertical : Horizontal }; - typedef Homogeneous HomogeneousReturnType; - EIGEN_DEVICE_FUNC - inline HomogeneousReturnType homogeneous() const; - - enum { - SizeMinusOne = SizeAtCompileTime==Dynamic ? Dynamic : SizeAtCompileTime-1 - }; - typedef Block::ColsAtCompileTime==1 ? SizeMinusOne : 1, - internal::traits::ColsAtCompileTime==1 ? 1 : SizeMinusOne> ConstStartMinusOne; - typedef EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(ConstStartMinusOne,Scalar,quotient) HNormalizedReturnType; - EIGEN_DEVICE_FUNC - inline const HNormalizedReturnType hnormalized() const; - -////////// Householder module /////////// - - EIGEN_DEVICE_FUNC - void makeHouseholderInPlace(Scalar& tau, RealScalar& beta); - template - EIGEN_DEVICE_FUNC - void makeHouseholder(EssentialPart& essential, - Scalar& tau, RealScalar& beta) const; - template - EIGEN_DEVICE_FUNC - void applyHouseholderOnTheLeft(const EssentialPart& essential, - const Scalar& tau, - Scalar* workspace); - template - EIGEN_DEVICE_FUNC - void applyHouseholderOnTheRight(const EssentialPart& essential, - const Scalar& tau, - Scalar* workspace); - -///////// Jacobi module ///////// - - template - EIGEN_DEVICE_FUNC - void applyOnTheLeft(Index p, Index q, const JacobiRotation& j); - template - EIGEN_DEVICE_FUNC - void applyOnTheRight(Index p, Index q, const JacobiRotation& j); - -///////// SparseCore module ///////// - - template - EIGEN_STRONG_INLINE const typename SparseMatrixBase::template CwiseProductDenseReturnType::Type - cwiseProduct(const SparseMatrixBase &other) const - { - return other.cwiseProduct(derived()); - } - -///////// MatrixFunctions module ///////// - - typedef typename internal::stem_function::type StemFunction; -#define EIGEN_MATRIX_FUNCTION(ReturnType, Name, Description) \ - /** \returns an expression of the matrix Description of \c *this. \brief This function requires the unsupported MatrixFunctions module. To compute the coefficient-wise Description use ArrayBase::##Name . */ \ - const ReturnType Name() const; -#define EIGEN_MATRIX_FUNCTION_1(ReturnType, Name, Description, Argument) \ - /** \returns an expression of the matrix Description of \c *this. \brief This function requires the unsupported MatrixFunctions module. To compute the coefficient-wise Description use ArrayBase::##Name . */ \ - const ReturnType Name(Argument) const; - - EIGEN_MATRIX_FUNCTION(MatrixExponentialReturnValue, exp, exponential) - /** \brief Helper function for the unsupported MatrixFunctions module.*/ - const MatrixFunctionReturnValue matrixFunction(StemFunction f) const; - EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, cosh, hyperbolic cosine) - EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, sinh, hyperbolic sine) -#if EIGEN_HAS_CXX11_MATH - EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, atanh, inverse hyperbolic cosine) - EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, acosh, inverse hyperbolic cosine) - EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, asinh, inverse hyperbolic sine) -#endif - EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, cos, cosine) - EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, sin, sine) - EIGEN_MATRIX_FUNCTION(MatrixSquareRootReturnValue, sqrt, square root) - EIGEN_MATRIX_FUNCTION(MatrixLogarithmReturnValue, log, logarithm) - EIGEN_MATRIX_FUNCTION_1(MatrixPowerReturnValue, pow, power to \c p, const RealScalar& p) - EIGEN_MATRIX_FUNCTION_1(MatrixComplexPowerReturnValue, pow, power to \c p, const std::complex& p) - - protected: - EIGEN_DEFAULT_COPY_CONSTRUCTOR(MatrixBase) - EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(MatrixBase) - - private: - EIGEN_DEVICE_FUNC explicit MatrixBase(int); - EIGEN_DEVICE_FUNC MatrixBase(int,int); - template EIGEN_DEVICE_FUNC explicit MatrixBase(const MatrixBase&); - protected: - // mixing arrays and matrices is not legal - template Derived& operator+=(const ArrayBase& ) - {EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;} - // mixing arrays and matrices is not legal - template Derived& operator-=(const ArrayBase& ) - {EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;} + /** Special case of the template operator=, in order to prevent the compiler + * from generating a default operator= (issue hit with g++ 4.1) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator=(const MatrixBase& other); + + // We cannot inherit here via Base::operator= since it is causing + // trouble with MSVC. + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator=(const DenseBase& other); + + template + EIGEN_DEVICE_FUNC Derived& operator=(const EigenBase& other); + + template + EIGEN_DEVICE_FUNC Derived& operator=(const ReturnByValue& other); + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator+=(const MatrixBase& other); + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator-=(const MatrixBase& other); + + template + EIGEN_DEVICE_FUNC const Product operator*(const MatrixBase& other) const; + + template + EIGEN_DEVICE_FUNC const Product lazyProduct( + const MatrixBase& other) const; + + template + Derived& operator*=(const EigenBase& other); + + template + void applyOnTheLeft(const EigenBase& other); + + template + void applyOnTheRight(const EigenBase& other); + + template + EIGEN_DEVICE_FUNC const Product operator*( + const DiagonalBase& diagonal) const; + + template + EIGEN_DEVICE_FUNC const Product operator*( + const SkewSymmetricBase& skew) const; + + template + EIGEN_DEVICE_FUNC typename ScalarBinaryOpTraits::Scalar, + typename internal::traits::Scalar>::ReturnType + dot(const MatrixBase& other) const; + + EIGEN_DEVICE_FUNC RealScalar squaredNorm() const; + EIGEN_DEVICE_FUNC RealScalar norm() const; + RealScalar stableNorm() const; + RealScalar blueNorm() const; + RealScalar hypotNorm() const; + EIGEN_DEVICE_FUNC const PlainObject normalized() const; + EIGEN_DEVICE_FUNC const PlainObject stableNormalized() const; + EIGEN_DEVICE_FUNC void normalize(); + EIGEN_DEVICE_FUNC void stableNormalize(); + + EIGEN_DEVICE_FUNC const AdjointReturnType adjoint() const; + EIGEN_DEVICE_FUNC void adjointInPlace(); + + typedef Diagonal DiagonalReturnType; + EIGEN_DEVICE_FUNC DiagonalReturnType diagonal(); + + typedef Diagonal ConstDiagonalReturnType; + EIGEN_DEVICE_FUNC const ConstDiagonalReturnType diagonal() const; + + template + EIGEN_DEVICE_FUNC Diagonal diagonal(); + + template + EIGEN_DEVICE_FUNC const Diagonal diagonal() const; + + EIGEN_DEVICE_FUNC Diagonal diagonal(Index index); + EIGEN_DEVICE_FUNC const Diagonal diagonal(Index index) const; + + template + struct TriangularViewReturnType { + typedef TriangularView Type; + }; + template + struct ConstTriangularViewReturnType { + typedef const TriangularView Type; + }; + + template + EIGEN_DEVICE_FUNC typename TriangularViewReturnType::Type triangularView(); + template + EIGEN_DEVICE_FUNC typename ConstTriangularViewReturnType::Type triangularView() const; + + template + struct SelfAdjointViewReturnType { + typedef SelfAdjointView Type; + }; + template + struct ConstSelfAdjointViewReturnType { + typedef const SelfAdjointView Type; + }; + + template + EIGEN_DEVICE_FUNC typename SelfAdjointViewReturnType::Type selfadjointView(); + template + EIGEN_DEVICE_FUNC typename ConstSelfAdjointViewReturnType::Type selfadjointView() const; + + const SparseView sparseView( + const Scalar& m_reference = Scalar(0), + const typename NumTraits::Real& m_epsilon = NumTraits::dummy_precision()) const; + EIGEN_DEVICE_FUNC static const IdentityReturnType Identity(); + EIGEN_DEVICE_FUNC static const IdentityReturnType Identity(Index rows, Index cols); + EIGEN_DEVICE_FUNC static const BasisReturnType Unit(Index size, Index i); + EIGEN_DEVICE_FUNC static const BasisReturnType Unit(Index i); + EIGEN_DEVICE_FUNC static const BasisReturnType UnitX(); + EIGEN_DEVICE_FUNC static const BasisReturnType UnitY(); + EIGEN_DEVICE_FUNC static const BasisReturnType UnitZ(); + EIGEN_DEVICE_FUNC static const BasisReturnType UnitW(); + + EIGEN_DEVICE_FUNC const DiagonalWrapper asDiagonal() const; + const PermutationWrapper asPermutation() const; + EIGEN_DEVICE_FUNC const SkewSymmetricWrapper asSkewSymmetric() const; + + EIGEN_DEVICE_FUNC Derived& setIdentity(); + EIGEN_DEVICE_FUNC Derived& setIdentity(Index rows, Index cols); + EIGEN_DEVICE_FUNC Derived& setUnit(Index i); + EIGEN_DEVICE_FUNC Derived& setUnit(Index newSize, Index i); + + bool isIdentity(const RealScalar& prec = NumTraits::dummy_precision()) const; + bool isDiagonal(const RealScalar& prec = NumTraits::dummy_precision()) const; + + bool isUpperTriangular(const RealScalar& prec = NumTraits::dummy_precision()) const; + bool isLowerTriangular(const RealScalar& prec = NumTraits::dummy_precision()) const; + + bool isSkewSymmetric(const RealScalar& prec = NumTraits::dummy_precision()) const; + + template + bool isOrthogonal(const MatrixBase& other, + const RealScalar& prec = NumTraits::dummy_precision()) const; + bool isUnitary(const RealScalar& prec = NumTraits::dummy_precision()) const; + + /** \returns true if each coefficients of \c *this and \a other are all exactly equal. + * \warning When using floating point scalar values you probably should rather use a + * fuzzy comparison such as isApprox() + * \sa isApprox(), operator!= */ + template + EIGEN_DEVICE_FUNC inline bool operator==(const MatrixBase& other) const { + return cwiseEqual(other).all(); + } + + /** \returns true if at least one pair of coefficients of \c *this and \a other are not exactly equal to each other. + * \warning When using floating point scalar values you probably should rather use a + * fuzzy comparison such as isApprox() + * \sa isApprox(), operator== */ + template + EIGEN_DEVICE_FUNC inline bool operator!=(const MatrixBase& other) const { + return cwiseNotEqual(other).any(); + } + + NoAlias EIGEN_DEVICE_FUNC noalias(); + + // TODO forceAlignedAccess is temporarily disabled + // Need to find a nicer workaround. + inline const Derived& forceAlignedAccess() const { return derived(); } + inline Derived& forceAlignedAccess() { return derived(); } + template + inline const Derived& forceAlignedAccessIf() const { + return derived(); + } + template + inline Derived& forceAlignedAccessIf() { + return derived(); + } + + EIGEN_DEVICE_FUNC Scalar trace() const; + + template + EIGEN_DEVICE_FUNC RealScalar lpNorm() const; + + EIGEN_DEVICE_FUNC MatrixBase& matrix() { return *this; } + EIGEN_DEVICE_FUNC const MatrixBase& matrix() const { return *this; } + + /** \returns an \link Eigen::ArrayBase Array \endlink expression of this matrix + * \sa ArrayBase::matrix() */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ArrayWrapper array() { return ArrayWrapper(derived()); } + /** \returns a const \link Eigen::ArrayBase Array \endlink expression of this matrix + * \sa ArrayBase::matrix() */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const ArrayWrapper array() const { + return ArrayWrapper(derived()); + } + + /////////// LU module /////////// + + template + inline const FullPivLU fullPivLu() const; + template + inline const PartialPivLU partialPivLu() const; + + template + inline const PartialPivLU lu() const; + + EIGEN_DEVICE_FUNC inline const Inverse inverse() const; + + template + inline void computeInverseAndDetWithCheck( + ResultType& inverse, typename ResultType::Scalar& determinant, bool& invertible, + const RealScalar& absDeterminantThreshold = NumTraits::dummy_precision()) const; + + template + inline void computeInverseWithCheck( + ResultType& inverse, bool& invertible, + const RealScalar& absDeterminantThreshold = NumTraits::dummy_precision()) const; + + EIGEN_DEVICE_FUNC Scalar determinant() const; + + /////////// Cholesky module /////////// + + inline const LLT llt() const; + inline const LDLT ldlt() const; + + /////////// QR module /////////// + + inline const HouseholderQR householderQr() const; + template + inline const ColPivHouseholderQR colPivHouseholderQr() const; + template + inline const FullPivHouseholderQR fullPivHouseholderQr() const; + template + inline const CompleteOrthogonalDecomposition completeOrthogonalDecomposition() const; + + /////////// Eigenvalues module /////////// + + inline EigenvaluesReturnType eigenvalues() const; + inline RealScalar operatorNorm() const; + + /////////// SVD module /////////// + + template + inline JacobiSVD jacobiSvd() const; + template + EIGEN_DEPRECATED inline JacobiSVD jacobiSvd(unsigned int computationOptions) const; + + template + inline BDCSVD bdcSvd() const; + template + EIGEN_DEPRECATED inline BDCSVD bdcSvd(unsigned int computationOptions) const; + + /////////// Geometry module /////////// + + template + EIGEN_DEVICE_FUNC inline typename internal::cross_impl::return_type cross( + const MatrixBase& other) const; + + template + EIGEN_DEVICE_FUNC inline PlainObject cross3(const MatrixBase& other) const; + + EIGEN_DEVICE_FUNC inline PlainObject unitOrthogonal(void) const; + + EIGEN_DEPRECATED EIGEN_DEVICE_FUNC inline Matrix eulerAngles(Index a0, Index a1, Index a2) const; + + EIGEN_DEVICE_FUNC inline Matrix canonicalEulerAngles(Index a0, Index a1, Index a2) const; + + // put this as separate enum value to work around possible GCC 4.3 bug (?) + enum { + HomogeneousReturnTypeDirection = + ColsAtCompileTime == 1 && RowsAtCompileTime == 1 + ? ((internal::traits::Flags & RowMajorBit) == RowMajorBit ? Horizontal : Vertical) + : ColsAtCompileTime == 1 ? Vertical + : Horizontal + }; + typedef Homogeneous HomogeneousReturnType; + EIGEN_DEVICE_FUNC inline HomogeneousReturnType homogeneous() const; + + enum { SizeMinusOne = SizeAtCompileTime == Dynamic ? Dynamic : SizeAtCompileTime - 1 }; + typedef Block::ColsAtCompileTime == 1 ? SizeMinusOne : 1, + internal::traits::ColsAtCompileTime == 1 ? 1 : SizeMinusOne> + ConstStartMinusOne; + typedef EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(ConstStartMinusOne, Scalar, quotient) HNormalizedReturnType; + EIGEN_DEVICE_FUNC inline const HNormalizedReturnType hnormalized() const; + + ////////// Householder module /////////// + + EIGEN_DEVICE_FUNC void makeHouseholderInPlace(Scalar& tau, RealScalar& beta); + template + EIGEN_DEVICE_FUNC void makeHouseholder(EssentialPart& essential, Scalar& tau, RealScalar& beta) const; + template + EIGEN_DEVICE_FUNC void applyHouseholderOnTheLeft(const EssentialPart& essential, const Scalar& tau, + Scalar* workspace); + template + EIGEN_DEVICE_FUNC void applyHouseholderOnTheRight(const EssentialPart& essential, const Scalar& tau, + Scalar* workspace); + + ///////// Jacobi module ///////// + + template + EIGEN_DEVICE_FUNC void applyOnTheLeft(Index p, Index q, const JacobiRotation& j); + template + EIGEN_DEVICE_FUNC void applyOnTheRight(Index p, Index q, const JacobiRotation& j); + + ///////// SparseCore module ///////// + + template + EIGEN_STRONG_INLINE const typename SparseMatrixBase::template CwiseProductDenseReturnType::Type + cwiseProduct(const SparseMatrixBase& other) const { + return other.cwiseProduct(derived()); + } + + ///////// MatrixFunctions module ///////// + + typedef typename internal::stem_function::type StemFunction; +#define EIGEN_MATRIX_FUNCTION(ReturnType, Name, Description) \ + /** \returns an expression of the matrix Description of \c *this. \brief This function requires the unsupported MatrixFunctions module. To compute the \ + * coefficient-wise Description use ArrayBase::##Name . */ \ + const ReturnType Name() const; +#define EIGEN_MATRIX_FUNCTION_1(ReturnType, Name, Description, Argument) \ + /** \returns an expression of the matrix Description of \c *this. \brief This function requires the unsupported MatrixFunctions module. To compute the \ + * coefficient-wise Description use ArrayBase::##Name . */ \ + const ReturnType Name(Argument) const; + + EIGEN_MATRIX_FUNCTION(MatrixExponentialReturnValue, exp, exponential) + /** \brief Helper function for the unsupported + * MatrixFunctions module.*/ + const MatrixFunctionReturnValue matrixFunction(StemFunction f) const; + EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, cosh, hyperbolic cosine) + EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, sinh, hyperbolic sine) + EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, atanh, inverse hyperbolic cosine) + EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, acosh, inverse hyperbolic cosine) + EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, asinh, inverse hyperbolic sine) + EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, cos, cosine) + EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, sin, sine) + EIGEN_MATRIX_FUNCTION(MatrixSquareRootReturnValue, sqrt, square root) + EIGEN_MATRIX_FUNCTION(MatrixLogarithmReturnValue, log, logarithm) + EIGEN_MATRIX_FUNCTION_1(MatrixPowerReturnValue, pow, power to \c p, const RealScalar& p) + EIGEN_MATRIX_FUNCTION_1(MatrixComplexPowerReturnValue, pow, power to \c p, const std::complex& p) + + protected: + EIGEN_DEFAULT_COPY_CONSTRUCTOR(MatrixBase) + EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(MatrixBase) + + private: + EIGEN_DEVICE_FUNC explicit MatrixBase(int); + EIGEN_DEVICE_FUNC MatrixBase(int, int); + template + EIGEN_DEVICE_FUNC explicit MatrixBase(const MatrixBase&); + + protected: + // mixing arrays and matrices is not legal + template + Derived& operator+=(const ArrayBase&) { + EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar)) == -1, + YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); + return *this; + } + // mixing arrays and matrices is not legal + template + Derived& operator-=(const ArrayBase&) { + EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar)) == -1, + YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); + return *this; + } }; - /*************************************************************************** -* Implementation of matrix base methods -***************************************************************************/ + * Implementation of matrix base methods + ***************************************************************************/ /** replaces \c *this by \c *this * \a other. - * - * \returns a reference to \c *this - * - * Example: \include MatrixBase_applyOnTheRight.cpp - * Output: \verbinclude MatrixBase_applyOnTheRight.out - */ -template -template -inline Derived& -MatrixBase::operator*=(const EigenBase &other) -{ + * + * \returns a reference to \c *this + * + * Example: \include MatrixBase_applyOnTheRight.cpp + * Output: \verbinclude MatrixBase_applyOnTheRight.out + */ +template +template +inline Derived& MatrixBase::operator*=(const EigenBase& other) { other.derived().applyThisOnTheRight(derived()); return derived(); } /** replaces \c *this by \c *this * \a other. It is equivalent to MatrixBase::operator*=(). - * - * Example: \include MatrixBase_applyOnTheRight.cpp - * Output: \verbinclude MatrixBase_applyOnTheRight.out - */ -template -template -inline void MatrixBase::applyOnTheRight(const EigenBase &other) -{ + * + * Example: \include MatrixBase_applyOnTheRight.cpp + * Output: \verbinclude MatrixBase_applyOnTheRight.out + */ +template +template +inline void MatrixBase::applyOnTheRight(const EigenBase& other) { other.derived().applyThisOnTheRight(derived()); } /** replaces \c *this by \a other * \c *this. - * - * Example: \include MatrixBase_applyOnTheLeft.cpp - * Output: \verbinclude MatrixBase_applyOnTheLeft.out - */ -template -template -inline void MatrixBase::applyOnTheLeft(const EigenBase &other) -{ + * + * Example: \include MatrixBase_applyOnTheLeft.cpp + * Output: \verbinclude MatrixBase_applyOnTheLeft.out + */ +template +template +inline void MatrixBase::applyOnTheLeft(const EigenBase& other) { other.derived().applyThisOnTheLeft(derived()); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_MATRIXBASE_H +#endif // EIGEN_MATRIXBASE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/NestByValue.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/NestByValue.h index b4275768a01..ec360ebdea9 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/NestByValue.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/NestByValue.h @@ -11,75 +11,81 @@ #ifndef EIGEN_NESTBYVALUE_H #define EIGEN_NESTBYVALUE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > : public traits -{ - enum { - Flags = traits::Flags & ~NestByRefBit - }; +template +struct traits > : public traits { + enum { Flags = traits::Flags & ~NestByRefBit }; }; -} +} // namespace internal /** \class NestByValue - * \ingroup Core_Module - * - * \brief Expression which must be nested by value - * - * \tparam ExpressionType the type of the object of which we are requiring nesting-by-value - * - * This class is the return type of MatrixBase::nestByValue() - * and most of the time this is the only way it is used. - * - * \sa MatrixBase::nestByValue() - */ -template class NestByValue - : public internal::dense_xpr_base< NestByValue >::type -{ - public: - - typedef typename internal::dense_xpr_base::type Base; - EIGEN_DENSE_PUBLIC_INTERFACE(NestByValue) - - EIGEN_DEVICE_FUNC explicit inline NestByValue(const ExpressionType& matrix) : m_expression(matrix) {} - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { return m_expression.rows(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return m_expression.cols(); } - - EIGEN_DEVICE_FUNC operator const ExpressionType&() const { return m_expression; } - - EIGEN_DEVICE_FUNC const ExpressionType& nestedExpression() const { return m_expression; } - - protected: - const ExpressionType m_expression; + * \ingroup Core_Module + * + * \brief Expression which must be nested by value + * + * \tparam ExpressionType the type of the object of which we are requiring nesting-by-value + * + * This class is the return type of MatrixBase::nestByValue() + * and most of the time this is the only way it is used. + * + * \sa MatrixBase::nestByValue() + */ +template +class NestByValue : public internal::dense_xpr_base >::type { + public: + typedef typename internal::dense_xpr_base::type Base; + static constexpr bool HasDirectAccess = internal::has_direct_access::ret; + + EIGEN_DENSE_PUBLIC_INTERFACE(NestByValue) + + EIGEN_DEVICE_FUNC explicit inline NestByValue(const ExpressionType& matrix) : m_expression(matrix) {} + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { return m_expression.rows(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return m_expression.cols(); } + + EIGEN_DEVICE_FUNC operator const ExpressionType&() const { return m_expression; } + + EIGEN_DEVICE_FUNC const ExpressionType& nestedExpression() const { return m_expression; } + + EIGEN_DEVICE_FUNC typename std::enable_if::type data() const { + return m_expression.data(); + } + + EIGEN_DEVICE_FUNC typename std::enable_if::type innerStride() const { + return m_expression.innerStride(); + } + + EIGEN_DEVICE_FUNC typename std::enable_if::type outerStride() const { + return m_expression.outerStride(); + } + + protected: + const ExpressionType m_expression; }; /** \returns an expression of the temporary version of *this. - */ -template -EIGEN_DEVICE_FUNC inline const NestByValue -DenseBase::nestByValue() const -{ + */ +template +EIGEN_DEVICE_FUNC inline const NestByValue DenseBase::nestByValue() const { return NestByValue(derived()); } namespace internal { // Evaluator of Solve -> eval into a temporary -template -struct evaluator > - : public evaluator -{ +template +struct evaluator > : public evaluator { typedef evaluator Base; - EIGEN_DEVICE_FUNC explicit evaluator(const NestByValue& xpr) - : Base(xpr.nestedExpression()) - {} + EIGEN_DEVICE_FUNC explicit evaluator(const NestByValue& xpr) : Base(xpr.nestedExpression()) {} }; -} +} // namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_NESTBYVALUE_H +#endif // EIGEN_NESTBYVALUE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/NoAlias.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/NoAlias.h index 570283d90f1..b6c7209104e 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/NoAlias.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/NoAlias.h @@ -10,100 +10,93 @@ #ifndef EIGEN_NOALIAS_H #define EIGEN_NOALIAS_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { /** \class NoAlias - * \ingroup Core_Module - * - * \brief Pseudo expression providing an operator = assuming no aliasing - * - * \tparam ExpressionType the type of the object on which to do the lazy assignment - * - * This class represents an expression with special assignment operators - * assuming no aliasing between the target expression and the source expression. - * More precisely it alloas to bypass the EvalBeforeAssignBit flag of the source expression. - * It is the return type of MatrixBase::noalias() - * and most of the time this is the only way it is used. - * - * \sa MatrixBase::noalias() - */ -template class StorageBase> -class NoAlias -{ - public: - typedef typename ExpressionType::Scalar Scalar; - - EIGEN_DEVICE_FUNC - explicit NoAlias(ExpressionType& expression) : m_expression(expression) {} - - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE ExpressionType& operator=(const StorageBase& other) - { - call_assignment_no_alias(m_expression, other.derived(), internal::assign_op()); - return m_expression; - } - - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE ExpressionType& operator+=(const StorageBase& other) - { - call_assignment_no_alias(m_expression, other.derived(), internal::add_assign_op()); - return m_expression; - } - - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE ExpressionType& operator-=(const StorageBase& other) - { - call_assignment_no_alias(m_expression, other.derived(), internal::sub_assign_op()); - return m_expression; - } + * \ingroup Core_Module + * + * \brief Pseudo expression providing an operator = assuming no aliasing + * + * \tparam ExpressionType the type of the object on which to do the lazy assignment + * + * This class represents an expression with special assignment operators + * assuming no aliasing between the target expression and the source expression. + * More precisely it alloas to bypass the EvalBeforeAssignBit flag of the source expression. + * It is the return type of MatrixBase::noalias() + * and most of the time this is the only way it is used. + * + * \sa MatrixBase::noalias() + */ +template class StorageBase> +class NoAlias { + public: + typedef typename ExpressionType::Scalar Scalar; + + EIGEN_DEVICE_FUNC explicit NoAlias(ExpressionType& expression) : m_expression(expression) {} + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ExpressionType& operator=(const StorageBase& other) { + call_assignment_no_alias(m_expression, other.derived(), + internal::assign_op()); + return m_expression; + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ExpressionType& operator+=(const StorageBase& other) { + call_assignment_no_alias(m_expression, other.derived(), + internal::add_assign_op()); + return m_expression; + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ExpressionType& operator-=(const StorageBase& other) { + call_assignment_no_alias(m_expression, other.derived(), + internal::sub_assign_op()); + return m_expression; + } - EIGEN_DEVICE_FUNC - ExpressionType& expression() const - { - return m_expression; - } + EIGEN_DEVICE_FUNC ExpressionType& expression() const { return m_expression; } - protected: - ExpressionType& m_expression; + protected: + ExpressionType& m_expression; }; /** \returns a pseudo expression of \c *this with an operator= assuming - * no aliasing between \c *this and the source expression. - * - * More precisely, noalias() allows to bypass the EvalBeforeAssignBit flag. - * Currently, even though several expressions may alias, only product - * expressions have this flag. Therefore, noalias() is only useful when - * the source expression contains a matrix product. - * - * Here are some examples where noalias is useful: - * \code - * D.noalias() = A * B; - * D.noalias() += A.transpose() * B; - * D.noalias() -= 2 * A * B.adjoint(); - * \endcode - * - * On the other hand the following example will lead to a \b wrong result: - * \code - * A.noalias() = A * B; - * \endcode - * because the result matrix A is also an operand of the matrix product. Therefore, - * there is no alternative than evaluating A * B in a temporary, that is the default - * behavior when you write: - * \code - * A = A * B; - * \endcode - * - * \sa class NoAlias - */ -template -NoAlias EIGEN_DEVICE_FUNC MatrixBase::noalias() -{ - return NoAlias(derived()); + * no aliasing between \c *this and the source expression. + * + * More precisely, noalias() allows to bypass the EvalBeforeAssignBit flag. + * Currently, even though several expressions may alias, only product + * expressions have this flag. Therefore, noalias() is only useful when + * the source expression contains a matrix product. + * + * Here are some examples where noalias is useful: + * \code + * D.noalias() = A * B; + * D.noalias() += A.transpose() * B; + * D.noalias() -= 2 * A * B.adjoint(); + * \endcode + * + * On the other hand the following example will lead to a \b wrong result: + * \code + * A.noalias() = A * B; + * \endcode + * because the result matrix A is also an operand of the matrix product. Therefore, + * there is no alternative than evaluating A * B in a temporary, that is the default + * behavior when you write: + * \code + * A = A * B; + * \endcode + * + * \sa class NoAlias + */ +template +NoAlias EIGEN_DEVICE_FUNC MatrixBase::noalias() { + return NoAlias(derived()); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_NOALIAS_H +#endif // EIGEN_NOALIAS_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/NumTraits.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/NumTraits.h index 72eac5a93c0..a6e2de47746 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/NumTraits.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/NumTraits.h @@ -10,72 +10,89 @@ #ifndef EIGEN_NUMTRAITS_H #define EIGEN_NUMTRAITS_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -// default implementation of digits10(), based on numeric_limits if specialized, -// 0 for integer types, and log10(epsilon()) otherwise. -template< typename T, - bool use_numeric_limits = std::numeric_limits::is_specialized, +// default implementation of digits(), based on numeric_limits if specialized, +// 0 for integer types, and log2(epsilon()) otherwise. +template ::is_specialized, bool is_integer = NumTraits::IsInteger> -struct default_digits10_impl -{ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static int run() { return std::numeric_limits::digits10; } +struct default_digits_impl { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static int run() { return std::numeric_limits::digits; } }; -template -struct default_digits10_impl // Floating point +template +struct default_digits_impl // Floating point { - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static int run() { - using std::log10; + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static int run() { using std::ceil; + using std::log2; typedef typename NumTraits::Real Real; - return int(ceil(-log10(NumTraits::epsilon()))); + return int(ceil(-log2(NumTraits::epsilon()))); } }; -template -struct default_digits10_impl // Integer +template +struct default_digits_impl // Integer { - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static int run() { return 0; } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static int run() { return 0; } }; - -// default implementation of digits(), based on numeric_limits if specialized, -// 0 for integer types, and log2(epsilon()) otherwise. -template< typename T, - bool use_numeric_limits = std::numeric_limits::is_specialized, +// default implementation of digits10(), based on numeric_limits if specialized, +// 0 for integer types, and floor((digits()-1)*log10(2)) otherwise. +template ::is_specialized, bool is_integer = NumTraits::IsInteger> -struct default_digits_impl +struct default_digits10_impl { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static int run() { return std::numeric_limits::digits10; } +}; + +template +struct default_digits10_impl // Floating point +{ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static int run() { + using std::floor; + using std::log10; + typedef typename NumTraits::Real Real; + return int(floor((internal::default_digits_impl::run() - 1) * log10(2))); + } +}; + +template +struct default_digits10_impl // Integer { - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static int run() { return std::numeric_limits::digits; } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static int run() { return 0; } }; -template -struct default_digits_impl // Floating point +// default implementation of max_digits10(), based on numeric_limits if specialized, +// 0 for integer types, and log10(2) * digits() + 1 otherwise. +template ::is_specialized, + bool is_integer = NumTraits::IsInteger> +struct default_max_digits10_impl { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static int run() { return std::numeric_limits::max_digits10; } +}; + +template +struct default_max_digits10_impl // Floating point { - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static int run() { - using std::log; + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static int run() { using std::ceil; + using std::log10; typedef typename NumTraits::Real Real; - return int(ceil(-log(NumTraits::epsilon())/log(static_cast(2)))); + return int(ceil(internal::default_digits_impl::run() * log10(2) + 1)); } }; -template -struct default_digits_impl // Integer +template +struct default_max_digits10_impl // Integer { - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static int run() { return 0; } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static int run() { return 0; } }; -} // end namespace internal +} // end namespace internal namespace numext { /** \internal bit-wise cast without changing the underlying bit representation. */ @@ -83,74 +100,76 @@ namespace numext { // TODO: Replace by std::bit_cast (available in C++20) template EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Tgt bit_cast(const Src& src) { -#if EIGEN_HAS_TYPE_TRAITS // The behaviour of memcpy is not specified for non-trivially copyable types - EIGEN_STATIC_ASSERT(std::is_trivially_copyable::value, THIS_TYPE_IS_NOT_SUPPORTED); + EIGEN_STATIC_ASSERT(std::is_trivially_copyable::value, THIS_TYPE_IS_NOT_SUPPORTED) EIGEN_STATIC_ASSERT(std::is_trivially_copyable::value && std::is_default_constructible::value, - THIS_TYPE_IS_NOT_SUPPORTED); -#endif + THIS_TYPE_IS_NOT_SUPPORTED) + EIGEN_STATIC_ASSERT(sizeof(Src) == sizeof(Tgt), THIS_TYPE_IS_NOT_SUPPORTED) - EIGEN_STATIC_ASSERT(sizeof(Src) == sizeof(Tgt), THIS_TYPE_IS_NOT_SUPPORTED); Tgt tgt; + // Load src into registers first. This allows the memcpy to be elided by CUDA. + const Src staged = src; EIGEN_USING_STD(memcpy) - memcpy(&tgt, &src, sizeof(Tgt)); + memcpy(static_cast(&tgt), static_cast(&staged), sizeof(Tgt)); return tgt; } } // namespace numext /** \class NumTraits - * \ingroup Core_Module - * - * \brief Holds information about the various numeric (i.e. scalar) types allowed by Eigen. - * - * \tparam T the numeric type at hand - * - * This class stores enums, typedefs and static methods giving information about a numeric type. - * - * The provided data consists of: - * \li A typedef \c Real, giving the "real part" type of \a T. If \a T is already real, - * then \c Real is just a typedef to \a T. If \a T is \c std::complex then \c Real - * is a typedef to \a U. - * \li A typedef \c NonInteger, giving the type that should be used for operations producing non-integral values, - * such as quotients, square roots, etc. If \a T is a floating-point type, then this typedef just gives - * \a T again. Note however that many Eigen functions such as internal::sqrt simply refuse to - * take integers. Outside of a few cases, Eigen doesn't do automatic type promotion. Thus, this typedef is - * only intended as a helper for code that needs to explicitly promote types. - * \li A typedef \c Literal giving the type to use for numeric literals such as "2" or "0.5". For instance, for \c std::complex, Literal is defined as \c U. - * Of course, this type must be fully compatible with \a T. In doubt, just use \a T here. - * \li A typedef \a Nested giving the type to use to nest a value inside of the expression tree. If you don't know what - * this means, just use \a T here. - * \li An enum value \a IsComplex. It is equal to 1 if \a T is a \c std::complex - * type, and to 0 otherwise. - * \li An enum value \a IsInteger. It is equal to \c 1 if \a T is an integer type such as \c int, - * and to \c 0 otherwise. - * \li Enum values ReadCost, AddCost and MulCost representing a rough estimate of the number of CPU cycles needed - * to by move / add / mul instructions respectively, assuming the data is already stored in CPU registers. - * Stay vague here. No need to do architecture-specific stuff. If you don't know what this means, just use \c Eigen::HugeCost. - * \li An enum value \a IsSigned. It is equal to \c 1 if \a T is a signed type and to 0 if \a T is unsigned. - * \li An enum value \a RequireInitialization. It is equal to \c 1 if the constructor of the numeric type \a T must - * be called, and to 0 if it is safe not to call it. Default is 0 if \a T is an arithmetic type, and 1 otherwise. - * \li An epsilon() function which, unlike std::numeric_limits::epsilon(), - * it returns a \a Real instead of a \a T. - * \li A dummy_precision() function returning a weak epsilon value. It is mainly used as a default - * value by the fuzzy comparison operators. - * \li highest() and lowest() functions returning the highest and lowest possible values respectively. - * \li digits() function returning the number of radix digits (non-sign digits for integers, mantissa for floating-point). This is - * the analogue of std::numeric_limits::digits - * which is used as the default implementation if specialized. - * \li digits10() function returning the number of decimal digits that can be represented without change. This is - * the analogue of std::numeric_limits::digits10 - * which is used as the default implementation if specialized. - * \li min_exponent() and max_exponent() functions returning the highest and lowest possible values, respectively, - * such that the radix raised to the power exponent-1 is a normalized floating-point number. These are equivalent to - * std::numeric_limits::min_exponent/ - * std::numeric_limits::max_exponent. - * \li infinity() function returning a representation of positive infinity, if available. - * \li quiet_NaN function returning a non-signaling "not-a-number", if available. - */ - -template struct GenericNumTraits -{ + * \ingroup Core_Module + * + * \brief Holds information about the various numeric (i.e. scalar) types allowed by Eigen. + * + * \tparam T the numeric type at hand + * + * This class stores enums, typedefs and static methods giving information about a numeric type. + * + * The provided data consists of: + * \li A typedef \c Real, giving the "real part" type of \a T. If \a T is already real, + * then \c Real is just a typedef to \a T. If \a T is \c std::complex then \c Real + * is a typedef to \a U. + * \li A typedef \c NonInteger, giving the type that should be used for operations producing non-integral values, + * such as quotients, square roots, etc. If \a T is a floating-point type, then this typedef just gives + * \a T again. Note however that many Eigen functions such as internal::sqrt simply refuse to + * take integers. Outside of a few cases, Eigen doesn't do automatic type promotion. Thus, this typedef is + * only intended as a helper for code that needs to explicitly promote types. + * \li A typedef \c Literal giving the type to use for numeric literals such as "2" or "0.5". For instance, for \c + * std::complex, Literal is defined as \c U. Of course, this type must be fully compatible with \a T. In doubt, just + * use \a T here. \li A typedef \a Nested giving the type to use to nest a value inside of the expression tree. If you + * don't know what this means, just use \a T here. \li An enum value \a IsComplex. It is equal to 1 if \a T is a \c + * std::complex type, and to 0 otherwise. \li An enum value \a IsInteger. It is equal to \c 1 if \a T is an integer type + * such as \c int, and to \c 0 otherwise. \li Enum values ReadCost, AddCost and MulCost representing a rough estimate of + * the number of CPU cycles needed to by move / add / mul instructions respectively, assuming the data is already stored + * in CPU registers. Stay vague here. No need to do architecture-specific stuff. If you don't know what this means, just + * use \c Eigen::HugeCost. \li An enum value \a IsSigned. It is equal to \c 1 if \a T is a signed type and to 0 if \a T + * is unsigned. \li An enum value \a RequireInitialization. It is equal to \c 1 if the constructor of the numeric type + * \a T must be called, and to 0 if it is safe not to call it. Default is 0 if \a T is an arithmetic type, and 1 + * otherwise. \li An epsilon() function which, unlike std::numeric_limits::epsilon(), it returns a + * \a Real instead of a \a T. \li A dummy_precision() function returning a weak epsilon value. It is mainly used as a + * default value by the fuzzy comparison operators. \li highest() and lowest() functions returning the highest and + * lowest possible values respectively. \li digits() function returning the number of radix digits (non-sign digits for + * integers, mantissa for floating-point). This is the analogue of std::numeric_limits::digits which is used + * as the default implementation if specialized. \li digits10() function returning the number of decimal digits that can + * be represented without change. This is the analogue of std::numeric_limits::digits10 which is + * used as the default implementation if specialized. \li max_digits10() function returning the number of decimal digits + * required to uniquely represent all distinct values of the type. This is the analogue of std::numeric_limits::max_digits10 + * which is used as the default implementation if specialized. + * \li min_exponent() and max_exponent() functions returning the highest and lowest possible values, respectively, + * such that the radix raised to the power exponent-1 is a normalized floating-point number. These are equivalent + * to std::numeric_limits::min_exponent/ + * std::numeric_limits::max_exponent. + * \li infinity() function returning a representation of positive infinity, if available. + * \li quiet_NaN function returning a non-signaling "not-a-number", if available. + */ + +template +struct GenericNumTraits { enum { IsInteger = std::numeric_limits::is_integer, IsSigned = std::numeric_limits::is_signed, @@ -162,161 +181,132 @@ template struct GenericNumTraits }; typedef T Real; - typedef typename internal::conditional< - IsInteger, - typename internal::conditional::type, - T - >::type NonInteger; + typedef std::conditional_t, T> NonInteger; typedef T Nested; typedef T Literal; - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline Real epsilon() - { - return numext::numeric_limits::epsilon(); - } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline Real epsilon() { return numext::numeric_limits::epsilon(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline int digits10() - { - return internal::default_digits10_impl::run(); - } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline int digits10() { return internal::default_digits10_impl::run(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline int digits() - { - return internal::default_digits_impl::run(); + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline int max_digits10() { + return internal::default_max_digits10_impl::run(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline int min_exponent() - { - return numext::numeric_limits::min_exponent; - } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline int digits() { return internal::default_digits_impl::run(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline int max_exponent() - { - return numext::numeric_limits::max_exponent; - } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline int min_exponent() { return numext::numeric_limits::min_exponent; } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline Real dummy_precision() - { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline int max_exponent() { return numext::numeric_limits::max_exponent; } + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline Real dummy_precision() { // make sure to override this for floating-point types return Real(0); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline T highest() { - return (numext::numeric_limits::max)(); - } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline T highest() { return (numext::numeric_limits::max)(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline T lowest() { - return IsInteger ? (numext::numeric_limits::min)() - : static_cast(-(numext::numeric_limits::max)()); - } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline T lowest() { return (numext::numeric_limits::lowest)(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline T infinity() { - return numext::numeric_limits::infinity(); - } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline T infinity() { return numext::numeric_limits::infinity(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline T quiet_NaN() { - return numext::numeric_limits::quiet_NaN(); - } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline T quiet_NaN() { return numext::numeric_limits::quiet_NaN(); } }; -template struct NumTraits : GenericNumTraits -{}; +template +struct NumTraits : GenericNumTraits {}; -template<> struct NumTraits - : GenericNumTraits -{ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline float dummy_precision() { return 1e-5f; } +template <> +struct NumTraits : GenericNumTraits { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline float dummy_precision() { return 1e-5f; } }; -template<> struct NumTraits : GenericNumTraits -{ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline double dummy_precision() { return 1e-12; } +template <> +struct NumTraits : GenericNumTraits { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline double dummy_precision() { return 1e-12; } }; -template<> struct NumTraits - : GenericNumTraits -{ - EIGEN_CONSTEXPR - static inline long double dummy_precision() { return 1e-15l; } +// GPU devices treat `long double` as `double`. +#ifndef EIGEN_GPU_COMPILE_PHASE +template <> +struct NumTraits : GenericNumTraits { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline long double dummy_precision() { + return static_cast(1e-15l); + } + +#if defined(EIGEN_ARCH_PPC) && (__LDBL_MANT_DIG__ == 106) + // PowerPC double double causes issues with some values + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline long double epsilon() { + // 2^(-(__LDBL_MANT_DIG__)+1) + return static_cast(2.4651903288156618919116517665087e-32l); + } +#endif }; +#endif -template struct NumTraits > - : GenericNumTraits > -{ - typedef _Real Real; - typedef typename NumTraits<_Real>::Literal Literal; +template +struct NumTraits > : GenericNumTraits > { + typedef Real_ Real; + typedef typename NumTraits::Literal Literal; enum { IsComplex = 1, - RequireInitialization = NumTraits<_Real>::RequireInitialization, - ReadCost = 2 * NumTraits<_Real>::ReadCost, + RequireInitialization = NumTraits::RequireInitialization, + ReadCost = 2 * NumTraits::ReadCost, AddCost = 2 * NumTraits::AddCost, MulCost = 4 * NumTraits::MulCost + 2 * NumTraits::AddCost }; - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline Real epsilon() { return NumTraits::epsilon(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline Real dummy_precision() { return NumTraits::dummy_precision(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline int digits10() { return NumTraits::digits10(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline Real epsilon() { return NumTraits::epsilon(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline Real dummy_precision() { return NumTraits::dummy_precision(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline int digits10() { return NumTraits::digits10(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline int max_digits10() { return NumTraits::max_digits10(); } }; -template -struct NumTraits > -{ +template +struct NumTraits > { typedef Array ArrayType; typedef typename NumTraits::Real RealScalar; typedef Array Real; typedef typename NumTraits::NonInteger NonIntegerScalar; typedef Array NonInteger; - typedef ArrayType & Nested; + typedef ArrayType& Nested; typedef typename NumTraits::Literal Literal; enum { IsComplex = NumTraits::IsComplex, IsInteger = NumTraits::IsInteger, - IsSigned = NumTraits::IsSigned, + IsSigned = NumTraits::IsSigned, RequireInitialization = 1, - ReadCost = ArrayType::SizeAtCompileTime==Dynamic ? HugeCost : ArrayType::SizeAtCompileTime * int(NumTraits::ReadCost), - AddCost = ArrayType::SizeAtCompileTime==Dynamic ? HugeCost : ArrayType::SizeAtCompileTime * int(NumTraits::AddCost), - MulCost = ArrayType::SizeAtCompileTime==Dynamic ? HugeCost : ArrayType::SizeAtCompileTime * int(NumTraits::MulCost) + ReadCost = ArrayType::SizeAtCompileTime == Dynamic + ? HugeCost + : ArrayType::SizeAtCompileTime * int(NumTraits::ReadCost), + AddCost = ArrayType::SizeAtCompileTime == Dynamic ? HugeCost + : ArrayType::SizeAtCompileTime * int(NumTraits::AddCost), + MulCost = ArrayType::SizeAtCompileTime == Dynamic ? HugeCost + : ArrayType::SizeAtCompileTime * int(NumTraits::MulCost) }; - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline RealScalar epsilon() { return NumTraits::epsilon(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - static inline RealScalar dummy_precision() { return NumTraits::dummy_precision(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline RealScalar epsilon() { return NumTraits::epsilon(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR static inline RealScalar dummy_precision() { + return NumTraits::dummy_precision(); + } EIGEN_CONSTEXPR static inline int digits10() { return NumTraits::digits10(); } + EIGEN_CONSTEXPR + static inline int max_digits10() { return NumTraits::max_digits10(); } }; -template<> struct NumTraits - : GenericNumTraits -{ - enum { - RequireInitialization = 1, - ReadCost = HugeCost, - AddCost = HugeCost, - MulCost = HugeCost - }; +template <> +struct NumTraits : GenericNumTraits { + enum { RequireInitialization = 1, ReadCost = HugeCost, AddCost = HugeCost, MulCost = HugeCost }; EIGEN_CONSTEXPR static inline int digits10() { return 0; } + EIGEN_CONSTEXPR + static inline int max_digits10() { return 0; } -private: + private: static inline std::string epsilon(); static inline std::string dummy_precision(); static inline std::string lowest(); @@ -326,10 +316,12 @@ template<> struct NumTraits }; // Empty specialization for void to allow template specialization based on NumTraits::Real with T==void and SFINAE. -template<> struct NumTraits {}; +template <> +struct NumTraits {}; -template<> struct NumTraits : GenericNumTraits {}; +template <> +struct NumTraits : GenericNumTraits {}; -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_NUMTRAITS_H +#endif // EIGEN_NUMTRAITS_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/PartialReduxEvaluator.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/PartialReduxEvaluator.h index 29abf35b99b..7b2c8dca38f 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/PartialReduxEvaluator.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/PartialReduxEvaluator.h @@ -10,75 +10,74 @@ #ifndef EIGEN_PARTIALREDUX_H #define EIGEN_PARTIALREDUX_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" -namespace internal { +namespace Eigen { +namespace internal { /*************************************************************************** -* -* This file provides evaluators for partial reductions. -* There are two modes: -* -* - scalar path: simply calls the respective function on the column or row. -* -> nothing special here, all the tricky part is handled by the return -* types of VectorwiseOp's members. They embed the functor calling the -* respective DenseBase's member function. -* -* - vectorized path: implements a packet-wise reductions followed by -* some (optional) processing of the outcome, e.g., division by n for mean. -* -* For the vectorized path let's observe that the packet-size and outer-unrolling -* are both decided by the assignement logic. So all we have to do is to decide -* on the inner unrolling. -* -* For the unrolling, we can reuse "internal::redux_vec_unroller" from Redux.h, -* but be need to be careful to specify correct increment. -* -***************************************************************************/ - + * + * This file provides evaluators for partial reductions. + * There are two modes: + * + * - scalar path: simply calls the respective function on the column or row. + * -> nothing special here, all the tricky part is handled by the return + * types of VectorwiseOp's members. They embed the functor calling the + * respective DenseBase's member function. + * + * - vectorized path: implements a packet-wise reductions followed by + * some (optional) processing of the outcome, e.g., division by n for mean. + * + * For the vectorized path let's observe that the packet-size and outer-unrolling + * are both decided by the assignment logic. So all we have to do is to decide + * on the inner unrolling. + * + * For the unrolling, we can reuse "internal::redux_vec_unroller" from Redux.h, + * but be need to be careful to specify correct increment. + * + ***************************************************************************/ /* logic deciding a strategy for unrolling of vectorized paths */ -template -struct packetwise_redux_traits -{ +template +struct packetwise_redux_traits { enum { OuterSize = int(Evaluator::IsRowMajor) ? Evaluator::RowsAtCompileTime : Evaluator::ColsAtCompileTime, Cost = OuterSize == Dynamic ? HugeCost - : OuterSize * Evaluator::CoeffReadCost + (OuterSize-1) * functor_traits::Cost, + : OuterSize * Evaluator::CoeffReadCost + (OuterSize - 1) * functor_traits::Cost, Unrolling = Cost <= EIGEN_UNROLLING_LIMIT ? CompleteUnrolling : NoUnrolling }; - }; /* Value to be returned when size==0 , by default let's return 0 */ -template -EIGEN_DEVICE_FUNC -PacketType packetwise_redux_empty_value(const Func& ) { return pset1(0); } +template +EIGEN_DEVICE_FUNC PacketType packetwise_redux_empty_value(const Func&) { + const typename unpacket_traits::type zero(0); + return pset1(zero); +} /* For products the default is 1 */ -template -EIGEN_DEVICE_FUNC -PacketType packetwise_redux_empty_value(const scalar_product_op& ) { return pset1(1); } +template +EIGEN_DEVICE_FUNC PacketType packetwise_redux_empty_value(const scalar_product_op&) { + return pset1(Scalar(1)); +} /* Perform the actual reduction */ -template::Unrolling -> +template ::Unrolling> struct packetwise_redux_impl; /* Perform the actual reduction with unrolling */ -template -struct packetwise_redux_impl -{ - typedef redux_novec_unroller Base; +template +struct packetwise_redux_impl { + typedef redux_novec_unroller Base; typedef typename Evaluator::Scalar Scalar; - template - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE - PacketType run(const Evaluator &eval, const Func& func, Index /*size*/) - { - return redux_vec_unroller::OuterSize>::template run(eval,func); + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE PacketType run(const Evaluator& eval, const Func& func, Index /*size*/) { + return redux_vec_unroller::OuterSize>::template run(eval, + func); } }; @@ -86,147 +85,125 @@ struct packetwise_redux_impl * This specialization is not required for general reductions, which is * why it is defined here. */ -template -struct redux_vec_unroller -{ - template - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE PacketType run(const Evaluator &, const Func& f) - { +template +struct redux_vec_unroller { + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE PacketType run(const Evaluator&, const Func& f) { return packetwise_redux_empty_value(f); } }; /* Perform the actual reduction for dynamic sizes */ -template -struct packetwise_redux_impl -{ +template +struct packetwise_redux_impl { typedef typename Evaluator::Scalar Scalar; typedef typename redux_traits::PacketType PacketScalar; - template - EIGEN_DEVICE_FUNC - static PacketType run(const Evaluator &eval, const Func& func, Index size) - { - if(size==0) - return packetwise_redux_empty_value(func); - - const Index size4 = (size-1)&(~3); - PacketType p = eval.template packetByOuterInner(0,0); + template + EIGEN_DEVICE_FUNC static PacketType run(const Evaluator& eval, const Func& func, Index size) { + if (size == 0) return packetwise_redux_empty_value(func); + + const Index size4 = (size - 1) & (~3); + PacketType p = eval.template packetByOuterInner(0, 0); Index i = 1; // This loop is optimized for instruction pipelining: // - each iteration generates two independent instructions // - thanks to branch prediction and out-of-order execution we have independent instructions across loops - for(; i(i+0,0),eval.template packetByOuterInner(i+1,0)), - func.packetOp(eval.template packetByOuterInner(i+2,0),eval.template packetByOuterInner(i+3,0)))); - for(; i(i,0)); + for (; i < size4; i += 4) + p = func.packetOp( + p, func.packetOp(func.packetOp(eval.template packetByOuterInner(i + 0, 0), + eval.template packetByOuterInner(i + 1, 0)), + func.packetOp(eval.template packetByOuterInner(i + 2, 0), + eval.template packetByOuterInner(i + 3, 0)))); + for (; i < size; ++i) p = func.packetOp(p, eval.template packetByOuterInner(i, 0)); return p; } }; -template< typename ArgType, typename MemberOp, int Direction> +template struct evaluator > - : evaluator_base > -{ + : evaluator_base > { typedef PartialReduxExpr XprType; - typedef typename internal::nested_eval::type ArgTypeNested; - typedef typename internal::add_const_on_value_type::type ConstArgTypeNested; - typedef typename internal::remove_all::type ArgTypeNestedCleaned; + typedef typename internal::nested_eval::type ArgTypeNested; + typedef add_const_on_value_type_t ConstArgTypeNested; + typedef internal::remove_all_t ArgTypeNestedCleaned; typedef typename ArgType::Scalar InputScalar; typedef typename XprType::Scalar Scalar; enum { - TraversalSize = Direction==int(Vertical) ? int(ArgType::RowsAtCompileTime) : int(ArgType::ColsAtCompileTime) + TraversalSize = Direction == int(Vertical) ? int(ArgType::RowsAtCompileTime) : int(ArgType::ColsAtCompileTime) }; typedef typename MemberOp::template Cost CostOpType; enum { - CoeffReadCost = TraversalSize==Dynamic ? HugeCost - : TraversalSize==0 ? 1 - : int(TraversalSize) * int(evaluator::CoeffReadCost) + int(CostOpType::value), - - _ArgFlags = evaluator::Flags, - - _Vectorizable = bool(int(_ArgFlags)&PacketAccessBit) - && bool(MemberOp::Vectorizable) - && (Direction==int(Vertical) ? bool(_ArgFlags&RowMajorBit) : (_ArgFlags&RowMajorBit)==0) - && (TraversalSize!=0), - - Flags = (traits::Flags&RowMajorBit) - | (evaluator::Flags&(HereditaryBits&(~RowMajorBit))) - | (_Vectorizable ? PacketAccessBit : 0) - | LinearAccessBit, - - Alignment = 0 // FIXME this will need to be improved once PartialReduxExpr is vectorized + CoeffReadCost = TraversalSize == Dynamic ? HugeCost + : TraversalSize == 0 + ? 1 + : int(TraversalSize) * int(evaluator::CoeffReadCost) + int(CostOpType::value), + + ArgFlags_ = evaluator::Flags, + + Vectorizable_ = bool(int(ArgFlags_) & PacketAccessBit) && bool(MemberOp::Vectorizable) && + (Direction == int(Vertical) ? bool(ArgFlags_ & RowMajorBit) : (ArgFlags_ & RowMajorBit) == 0) && + (TraversalSize != 0), + + Flags = (traits::Flags & RowMajorBit) | (evaluator::Flags & (HereditaryBits & (~RowMajorBit))) | + (Vectorizable_ ? PacketAccessBit : 0) | LinearAccessBit, + + Alignment = 0 // FIXME this will need to be improved once PartialReduxExpr is vectorized }; - EIGEN_DEVICE_FUNC explicit evaluator(const XprType xpr) - : m_arg(xpr.nestedExpression()), m_functor(xpr.functor()) - { - EIGEN_INTERNAL_CHECK_COST_VALUE(TraversalSize==Dynamic ? HugeCost : (TraversalSize==0 ? 1 : int(CostOpType::value))); + EIGEN_DEVICE_FUNC explicit evaluator(const XprType xpr) : m_arg(xpr.nestedExpression()), m_functor(xpr.functor()) { + EIGEN_INTERNAL_CHECK_COST_VALUE(TraversalSize == Dynamic ? HugeCost + : (TraversalSize == 0 ? 1 : int(CostOpType::value))); EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } typedef typename XprType::CoeffReturnType CoeffReturnType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const Scalar coeff(Index i, Index j) const - { - return coeff(Direction==Vertical ? j : i); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index i, Index j) const { + return coeff(Direction == Vertical ? j : i); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const Scalar coeff(Index index) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index index) const { return m_functor(m_arg.template subVector(index)); } - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - PacketType packet(Index i, Index j) const - { - return packet(Direction==Vertical ? j : i); + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketType packet(Index i, Index j) const { + return packet(Direction == Vertical ? j : i); } - - template - EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC - PacketType packet(Index idx) const - { + + template + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC PacketType packet(Index idx) const { enum { PacketSize = internal::unpacket_traits::size }; - typedef Block PanelType; - - PanelType panel(m_arg, - Direction==Vertical ? 0 : idx, - Direction==Vertical ? idx : 0, - Direction==Vertical ? m_arg.rows() : Index(PacketSize), - Direction==Vertical ? Index(PacketSize) : m_arg.cols()); + typedef Block + PanelType; + + PanelType panel(m_arg, Direction == Vertical ? 0 : idx, Direction == Vertical ? idx : 0, + Direction == Vertical ? m_arg.rows() : Index(PacketSize), + Direction == Vertical ? Index(PacketSize) : m_arg.cols()); // FIXME - // See bug 1612, currently if PacketSize==1 (i.e. complex with 128bits registers) then the storage-order of panel get reversed - // and methods like packetByOuterInner do not make sense anymore in this context. - // So let's just by pass "vectorization" in this case: - if(PacketSize==1) - return internal::pset1(coeff(idx)); - + // See bug 1612, currently if PacketSize==1 (i.e. complex with 128bits registers) then the storage-order of + // panel get reversed and methods like packetByOuterInner do not make sense anymore in this context. So let's just + // by pass "vectorization" in this case: + if (PacketSize == 1) return internal::pset1(coeff(idx)); + typedef typename internal::redux_evaluator PanelEvaluator; PanelEvaluator panel_eval(panel); typedef typename MemberOp::BinaryOp BinaryOp; - PacketType p = internal::packetwise_redux_impl::template run(panel_eval,m_functor.binaryFunc(),m_arg.outerSize()); + PacketType p = internal::packetwise_redux_impl::template run( + panel_eval, m_functor.binaryFunc(), m_arg.outerSize()); return p; } -protected: + protected: ConstArgTypeNested m_arg; const MemberOp m_functor; }; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_PARTIALREDUX_H +#endif // EIGEN_PARTIALREDUX_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/PermutationMatrix.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/PermutationMatrix.h index 69401bf41e5..6945964adfe 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/PermutationMatrix.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/PermutationMatrix.h @@ -11,595 +11,542 @@ #ifndef EIGEN_PERMUTATIONMATRIX_H #define EIGEN_PERMUTATIONMATRIX_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { namespace internal { -enum PermPermProduct_t {PermPermProduct}; +enum PermPermProduct_t { PermPermProduct }; -} // end namespace internal +} // end namespace internal /** \class PermutationBase - * \ingroup Core_Module - * - * \brief Base class for permutations - * - * \tparam Derived the derived class - * - * This class is the base class for all expressions representing a permutation matrix, - * internally stored as a vector of integers. - * The convention followed here is that if \f$ \sigma \f$ is a permutation, the corresponding permutation matrix - * \f$ P_\sigma \f$ is such that if \f$ (e_1,\ldots,e_p) \f$ is the canonical basis, we have: - * \f[ P_\sigma(e_i) = e_{\sigma(i)}. \f] - * This convention ensures that for any two permutations \f$ \sigma, \tau \f$, we have: - * \f[ P_{\sigma\circ\tau} = P_\sigma P_\tau. \f] - * - * Permutation matrices are square and invertible. - * - * Notice that in addition to the member functions and operators listed here, there also are non-member - * operator* to multiply any kind of permutation object with any kind of matrix expression (MatrixBase) - * on either side. - * - * \sa class PermutationMatrix, class PermutationWrapper - */ -template -class PermutationBase : public EigenBase -{ - typedef internal::traits Traits; - typedef EigenBase Base; - public: - - #ifndef EIGEN_PARSED_BY_DOXYGEN - typedef typename Traits::IndicesType IndicesType; - enum { - Flags = Traits::Flags, - RowsAtCompileTime = Traits::RowsAtCompileTime, - ColsAtCompileTime = Traits::ColsAtCompileTime, - MaxRowsAtCompileTime = Traits::MaxRowsAtCompileTime, - MaxColsAtCompileTime = Traits::MaxColsAtCompileTime - }; - typedef typename Traits::StorageIndex StorageIndex; - typedef Matrix - DenseMatrixType; - typedef PermutationMatrix - PlainPermutationType; - typedef PlainPermutationType PlainObject; - using Base::derived; - typedef Inverse InverseReturnType; - typedef void Scalar; - #endif - - /** Copies the other permutation into *this */ - template - Derived& operator=(const PermutationBase& other) - { - indices() = other.indices(); - return derived(); - } - - /** Assignment from the Transpositions \a tr */ - template - Derived& operator=(const TranspositionsBase& tr) - { - setIdentity(tr.size()); - for(Index k=size()-1; k>=0; --k) - applyTranspositionOnTheRight(k,tr.coeff(k)); - return derived(); - } - - /** \returns the number of rows */ - inline EIGEN_DEVICE_FUNC Index rows() const { return Index(indices().size()); } - - /** \returns the number of columns */ - inline EIGEN_DEVICE_FUNC Index cols() const { return Index(indices().size()); } - - /** \returns the size of a side of the respective square matrix, i.e., the number of indices */ - inline EIGEN_DEVICE_FUNC Index size() const { return Index(indices().size()); } + * \ingroup Core_Module + * + * \brief Base class for permutations + * + * \tparam Derived the derived class + * + * This class is the base class for all expressions representing a permutation matrix, + * internally stored as a vector of integers. + * The convention followed here is that if \f$ \sigma \f$ is a permutation, the corresponding permutation matrix + * \f$ P_\sigma \f$ is such that if \f$ (e_1,\ldots,e_p) \f$ is the canonical basis, we have: + * \f[ P_\sigma(e_i) = e_{\sigma(i)}. \f] + * This convention ensures that for any two permutations \f$ \sigma, \tau \f$, we have: + * \f[ P_{\sigma\circ\tau} = P_\sigma P_\tau. \f] + * + * Permutation matrices are square and invertible. + * + * Notice that in addition to the member functions and operators listed here, there also are non-member + * operator* to multiply any kind of permutation object with any kind of matrix expression (MatrixBase) + * on either side. + * + * \sa class PermutationMatrix, class PermutationWrapper + */ +template +class PermutationBase : public EigenBase { + typedef internal::traits Traits; + typedef EigenBase Base; + + public: +#ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename Traits::IndicesType IndicesType; + enum { + Flags = Traits::Flags, + RowsAtCompileTime = Traits::RowsAtCompileTime, + ColsAtCompileTime = Traits::ColsAtCompileTime, + MaxRowsAtCompileTime = Traits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = Traits::MaxColsAtCompileTime + }; + typedef typename Traits::StorageIndex StorageIndex; + typedef Matrix + DenseMatrixType; + typedef PermutationMatrix + PlainPermutationType; + typedef PlainPermutationType PlainObject; + using Base::derived; + typedef Inverse InverseReturnType; + typedef void Scalar; +#endif - #ifndef EIGEN_PARSED_BY_DOXYGEN - template - void evalTo(MatrixBase& other) const - { - other.setZero(); - for (Index i=0; i + Derived& operator=(const PermutationBase& other) { + indices() = other.indices(); + return derived(); + } - /** const version of indices(). */ - const IndicesType& indices() const { return derived().indices(); } - /** \returns a reference to the stored array representing the permutation. */ - IndicesType& indices() { return derived().indices(); } + /** Assignment from the Transpositions \a tr */ + template + Derived& operator=(const TranspositionsBase& tr) { + setIdentity(tr.size()); + for (Index k = size() - 1; k >= 0; --k) applyTranspositionOnTheRight(k, tr.coeff(k)); + return derived(); + } - /** Resizes to given size. - */ - inline void resize(Index newSize) - { - indices().resize(newSize); - } + /** \returns the number of rows */ + inline EIGEN_DEVICE_FUNC Index rows() const { return Index(indices().size()); } - /** Sets *this to be the identity permutation matrix */ - void setIdentity() - { - StorageIndex n = StorageIndex(size()); - for(StorageIndex i = 0; i < n; ++i) - indices().coeffRef(i) = i; - } + /** \returns the number of columns */ + inline EIGEN_DEVICE_FUNC Index cols() const { return Index(indices().size()); } - /** Sets *this to be the identity permutation matrix of given size. - */ - void setIdentity(Index newSize) - { - resize(newSize); - setIdentity(); - } + /** \returns the size of a side of the respective square matrix, i.e., the number of indices */ + inline EIGEN_DEVICE_FUNC Index size() const { return Index(indices().size()); } - /** Multiplies *this by the transposition \f$(ij)\f$ on the left. - * - * \returns a reference to *this. - * - * \warning This is much slower than applyTranspositionOnTheRight(Index,Index): - * this has linear complexity and requires a lot of branching. - * - * \sa applyTranspositionOnTheRight(Index,Index) - */ - Derived& applyTranspositionOnTheLeft(Index i, Index j) - { - eigen_assert(i>=0 && j>=0 && i + void evalTo(MatrixBase& other) const { + other.setZero(); + for (Index i = 0; i < rows(); ++i) other.coeffRef(indices().coeff(i), i) = typename DenseDerived::Scalar(1); + } +#endif - /** Multiplies *this by the transposition \f$(ij)\f$ on the right. - * - * \returns a reference to *this. - * - * This is a fast operation, it only consists in swapping two indices. - * - * \sa applyTranspositionOnTheLeft(Index,Index) - */ - Derived& applyTranspositionOnTheRight(Index i, Index j) - { - eigen_assert(i>=0 && j>=0 && i= 0 && j >= 0 && i < size() && j < size()); + for (Index k = 0; k < size(); ++k) { + if (indices().coeff(k) == i) + indices().coeffRef(k) = StorageIndex(j); + else if (indices().coeff(k) == j) + indices().coeffRef(k) = StorageIndex(i); } + return derived(); + } + + /** Multiplies *this by the transposition \f$(ij)\f$ on the right. + * + * \returns a reference to *this. + * + * This is a fast operation, it only consists in swapping two indices. + * + * \sa applyTranspositionOnTheLeft(Index,Index) + */ + Derived& applyTranspositionOnTheRight(Index i, Index j) { + eigen_assert(i >= 0 && j >= 0 && i < size() && j < size()); + std::swap(indices().coeffRef(i), indices().coeffRef(j)); + return derived(); + } + + /** \returns the inverse permutation matrix. + * + * \note \blank \note_try_to_help_rvo + */ + inline InverseReturnType inverse() const { return InverseReturnType(derived()); } + /** \returns the tranpose permutation matrix. + * + * \note \blank \note_try_to_help_rvo + */ + inline InverseReturnType transpose() const { return InverseReturnType(derived()); } + + /**** multiplication helpers to hopefully get RVO ****/ - /** \returns the inverse permutation matrix. - * - * \note \blank \note_try_to_help_rvo - */ - inline InverseReturnType inverse() const - { return InverseReturnType(derived()); } - /** \returns the tranpose permutation matrix. - * - * \note \blank \note_try_to_help_rvo - */ - inline InverseReturnType transpose() const - { return InverseReturnType(derived()); } - - /**** multiplication helpers to hopefully get RVO ****/ - - #ifndef EIGEN_PARSED_BY_DOXYGEN - protected: - template - void assignTranspose(const PermutationBase& other) - { - for (Index i=0; i - void assignProduct(const Lhs& lhs, const Rhs& rhs) - { - eigen_assert(lhs.cols() == rhs.rows()); - for (Index i=0; i + void assignTranspose(const PermutationBase& other) { + for (Index i = 0; i < rows(); ++i) indices().coeffRef(other.indices().coeff(i)) = i; + } + template + void assignProduct(const Lhs& lhs, const Rhs& rhs) { + eigen_assert(lhs.cols() == rhs.rows()); + for (Index i = 0; i < rows(); ++i) indices().coeffRef(i) = lhs.indices().coeff(rhs.indices().coeff(i)); + } #endif - public: - - /** \returns the product permutation matrix. - * - * \note \blank \note_try_to_help_rvo - */ - template - inline PlainPermutationType operator*(const PermutationBase& other) const - { return PlainPermutationType(internal::PermPermProduct, derived(), other.derived()); } - - /** \returns the product of a permutation with another inverse permutation. - * - * \note \blank \note_try_to_help_rvo - */ - template - inline PlainPermutationType operator*(const InverseImpl& other) const - { return PlainPermutationType(internal::PermPermProduct, *this, other.eval()); } - - /** \returns the product of an inverse permutation with another permutation. - * - * \note \blank \note_try_to_help_rvo - */ - template friend - inline PlainPermutationType operator*(const InverseImpl& other, const PermutationBase& perm) - { return PlainPermutationType(internal::PermPermProduct, other.eval(), perm); } - - /** \returns the determinant of the permutation matrix, which is either 1 or -1 depending on the parity of the permutation. - * - * This function is O(\c n) procedure allocating a buffer of \c n booleans. - */ - Index determinant() const - { - Index res = 1; - Index n = size(); - Matrix mask(n); - mask.fill(false); - Index r = 0; - while(r < n) - { - // search for the next seed - while(r=n) - break; - // we got one, let's follow it until we are back to the seed - Index k0 = r++; - mask.coeffRef(k0) = true; - for(Index k=indices().coeff(k0); k!=k0; k=indices().coeff(k)) - { - mask.coeffRef(k) = true; - res = -res; - } + public: + /** \returns the product permutation matrix. + * + * \note \blank \note_try_to_help_rvo + */ + template + inline PlainPermutationType operator*(const PermutationBase& other) const { + return PlainPermutationType(internal::PermPermProduct, derived(), other.derived()); + } + + /** \returns the product of a permutation with another inverse permutation. + * + * \note \blank \note_try_to_help_rvo + */ + template + inline PlainPermutationType operator*(const InverseImpl& other) const { + return PlainPermutationType(internal::PermPermProduct, *this, other.eval()); + } + + /** \returns the product of an inverse permutation with another permutation. + * + * \note \blank \note_try_to_help_rvo + */ + template + friend inline PlainPermutationType operator*(const InverseImpl& other, + const PermutationBase& perm) { + return PlainPermutationType(internal::PermPermProduct, other.eval(), perm); + } + + /** \returns the determinant of the permutation matrix, which is either 1 or -1 depending on the parity of the + * permutation. + * + * This function is O(\c n) procedure allocating a buffer of \c n booleans. + */ + Index determinant() const { + Index res = 1; + Index n = size(); + Matrix mask(n); + mask.fill(false); + Index r = 0; + while (r < n) { + // search for the next seed + while (r < n && mask[r]) r++; + if (r >= n) break; + // we got one, let's follow it until we are back to the seed + Index k0 = r++; + mask.coeffRef(k0) = true; + for (Index k = indices().coeff(k0); k != k0; k = indices().coeff(k)) { + mask.coeffRef(k) = true; + res = -res; } - return res; } + return res; + } - protected: - + protected: }; namespace internal { -template -struct traits > - : traits > -{ +template +struct traits > + : traits< + Matrix > { typedef PermutationStorage StorageKind; - typedef Matrix<_StorageIndex, SizeAtCompileTime, 1, 0, MaxSizeAtCompileTime, 1> IndicesType; - typedef _StorageIndex StorageIndex; + typedef Matrix IndicesType; + typedef StorageIndex_ StorageIndex; typedef void Scalar; }; -} +} // namespace internal /** \class PermutationMatrix - * \ingroup Core_Module - * - * \brief Permutation matrix - * - * \tparam SizeAtCompileTime the number of rows/cols, or Dynamic - * \tparam MaxSizeAtCompileTime the maximum number of rows/cols, or Dynamic. This optional parameter defaults to SizeAtCompileTime. Most of the time, you should not have to specify it. - * \tparam _StorageIndex the integer type of the indices - * - * This class represents a permutation matrix, internally stored as a vector of integers. - * - * \sa class PermutationBase, class PermutationWrapper, class DiagonalMatrix - */ -template -class PermutationMatrix : public PermutationBase > -{ - typedef PermutationBase Base; - typedef internal::traits Traits; - public: - - typedef const PermutationMatrix& Nested; - - #ifndef EIGEN_PARSED_BY_DOXYGEN - typedef typename Traits::IndicesType IndicesType; - typedef typename Traits::StorageIndex StorageIndex; - #endif - - inline PermutationMatrix() - {} - - /** Constructs an uninitialized permutation matrix of given size. - */ - explicit inline PermutationMatrix(Index size) : m_indices(size) - { - eigen_internal_assert(size <= NumTraits::highest()); - } - - /** Copy constructor. */ - template - inline PermutationMatrix(const PermutationBase& other) - : m_indices(other.indices()) {} - - /** Generic constructor from expression of the indices. The indices - * array has the meaning that the permutations sends each integer i to indices[i]. - * - * \warning It is your responsibility to check that the indices array that you passes actually - * describes a permutation, i.e., each value between 0 and n-1 occurs exactly once, where n is the - * array's size. - */ - template - explicit inline PermutationMatrix(const MatrixBase& indices) : m_indices(indices) - {} - - /** Convert the Transpositions \a tr to a permutation matrix */ - template - explicit PermutationMatrix(const TranspositionsBase& tr) - : m_indices(tr.size()) - { - *this = tr; - } - - /** Copies the other permutation into *this */ - template - PermutationMatrix& operator=(const PermutationBase& other) - { - m_indices = other.indices(); - return *this; - } - - /** Assignment from the Transpositions \a tr */ - template - PermutationMatrix& operator=(const TranspositionsBase& tr) - { - return Base::operator=(tr.derived()); - } - - /** const version of indices(). */ - const IndicesType& indices() const { return m_indices; } - /** \returns a reference to the stored array representing the permutation. */ - IndicesType& indices() { return m_indices; } + * \ingroup Core_Module + * + * \brief Permutation matrix + * + * \tparam SizeAtCompileTime the number of rows/cols, or Dynamic + * \tparam MaxSizeAtCompileTime the maximum number of rows/cols, or Dynamic. This optional parameter defaults to + * SizeAtCompileTime. Most of the time, you should not have to specify it. \tparam StorageIndex_ the integer type of the + * indices + * + * This class represents a permutation matrix, internally stored as a vector of integers. + * + * \sa class PermutationBase, class PermutationWrapper, class DiagonalMatrix + */ +template +class PermutationMatrix + : public PermutationBase > { + typedef PermutationBase Base; + typedef internal::traits Traits; + + public: + typedef const PermutationMatrix& Nested; +#ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename Traits::IndicesType IndicesType; + typedef typename Traits::StorageIndex StorageIndex; +#endif - /**** multiplication helpers to hopefully get RVO ****/ + inline PermutationMatrix() {} + + /** Constructs an uninitialized permutation matrix of given size. + */ + explicit inline PermutationMatrix(Index size) : m_indices(size) { + eigen_internal_assert(size <= NumTraits::highest()); + } + + /** Copy constructor. */ + template + inline PermutationMatrix(const PermutationBase& other) : m_indices(other.indices()) {} + + /** Generic constructor from expression of the indices. The indices + * array has the meaning that the permutations sends each integer i to indices[i]. + * + * \warning It is your responsibility to check that the indices array that you passes actually + * describes a permutation, i.e., each value between 0 and n-1 occurs exactly once, where n is the + * array's size. + */ + template + explicit inline PermutationMatrix(const MatrixBase& indices) : m_indices(indices) {} + + /** Convert the Transpositions \a tr to a permutation matrix */ + template + explicit PermutationMatrix(const TranspositionsBase& tr) : m_indices(tr.size()) { + *this = tr; + } + + /** Copies the other permutation into *this */ + template + PermutationMatrix& operator=(const PermutationBase& other) { + m_indices = other.indices(); + return *this; + } + + /** Assignment from the Transpositions \a tr */ + template + PermutationMatrix& operator=(const TranspositionsBase& tr) { + return Base::operator=(tr.derived()); + } + + /** const version of indices(). */ + const IndicesType& indices() const { return m_indices; } + /** \returns a reference to the stored array representing the permutation. */ + IndicesType& indices() { return m_indices; } + + /**** multiplication helpers to hopefully get RVO ****/ #ifndef EIGEN_PARSED_BY_DOXYGEN - template - PermutationMatrix(const InverseImpl& other) - : m_indices(other.derived().nestedExpression().size()) - { - eigen_internal_assert(m_indices.size() <= NumTraits::highest()); - StorageIndex end = StorageIndex(m_indices.size()); - for (StorageIndex i=0; i - PermutationMatrix(internal::PermPermProduct_t, const Lhs& lhs, const Rhs& rhs) - : m_indices(lhs.indices().size()) - { - Base::assignProduct(lhs,rhs); - } + template + PermutationMatrix(const InverseImpl& other) + : m_indices(other.derived().nestedExpression().size()) { + eigen_internal_assert(m_indices.size() <= NumTraits::highest()); + StorageIndex end = StorageIndex(m_indices.size()); + for (StorageIndex i = 0; i < end; ++i) + m_indices.coeffRef(other.derived().nestedExpression().indices().coeff(i)) = i; + } + template + PermutationMatrix(internal::PermPermProduct_t, const Lhs& lhs, const Rhs& rhs) : m_indices(lhs.indices().size()) { + Base::assignProduct(lhs, rhs); + } #endif - protected: - - IndicesType m_indices; + protected: + IndicesType m_indices; }; - namespace internal { -template -struct traits,_PacketAccess> > - : traits > -{ +template +struct traits, PacketAccess_> > + : traits< + Matrix > { typedef PermutationStorage StorageKind; - typedef Map, _PacketAccess> IndicesType; - typedef _StorageIndex StorageIndex; + typedef Map, PacketAccess_> IndicesType; + typedef StorageIndex_ StorageIndex; typedef void Scalar; }; -} +} // namespace internal -template -class Map,_PacketAccess> - : public PermutationBase,_PacketAccess> > -{ - typedef PermutationBase Base; - typedef internal::traits Traits; - public: - - #ifndef EIGEN_PARSED_BY_DOXYGEN - typedef typename Traits::IndicesType IndicesType; - typedef typename IndicesType::Scalar StorageIndex; - #endif - - inline Map(const StorageIndex* indicesPtr) - : m_indices(indicesPtr) - {} - - inline Map(const StorageIndex* indicesPtr, Index size) - : m_indices(indicesPtr,size) - {} - - /** Copies the other permutation into *this */ - template - Map& operator=(const PermutationBase& other) - { return Base::operator=(other.derived()); } - - /** Assignment from the Transpositions \a tr */ - template - Map& operator=(const TranspositionsBase& tr) - { return Base::operator=(tr.derived()); } - - #ifndef EIGEN_PARSED_BY_DOXYGEN - /** This is a special case of the templated operator=. Its purpose is to - * prevent a default operator= from hiding the templated operator=. - */ - Map& operator=(const Map& other) - { - m_indices = other.m_indices; - return *this; - } - #endif +template +class Map, PacketAccess_> + : public PermutationBase< + Map, PacketAccess_> > { + typedef PermutationBase Base; + typedef internal::traits Traits; - /** const version of indices(). */ - const IndicesType& indices() const { return m_indices; } - /** \returns a reference to the stored array representing the permutation. */ - IndicesType& indices() { return m_indices; } + public: +#ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename Traits::IndicesType IndicesType; + typedef typename IndicesType::Scalar StorageIndex; +#endif - protected: + inline Map(const StorageIndex* indicesPtr) : m_indices(indicesPtr) {} - IndicesType m_indices; + inline Map(const StorageIndex* indicesPtr, Index size) : m_indices(indicesPtr, size) {} + + /** Copies the other permutation into *this */ + template + Map& operator=(const PermutationBase& other) { + return Base::operator=(other.derived()); + } + + /** Assignment from the Transpositions \a tr */ + template + Map& operator=(const TranspositionsBase& tr) { + return Base::operator=(tr.derived()); + } + +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** This is a special case of the templated operator=. Its purpose is to + * prevent a default operator= from hiding the templated operator=. + */ + Map& operator=(const Map& other) { + m_indices = other.m_indices; + return *this; + } +#endif + + /** const version of indices(). */ + const IndicesType& indices() const { return m_indices; } + /** \returns a reference to the stored array representing the permutation. */ + IndicesType& indices() { return m_indices; } + + protected: + IndicesType m_indices; }; -template class TranspositionsWrapper; +template +class TranspositionsWrapper; namespace internal { -template -struct traits > -{ +template +struct traits > { typedef PermutationStorage StorageKind; typedef void Scalar; - typedef typename _IndicesType::Scalar StorageIndex; - typedef _IndicesType IndicesType; + typedef typename IndicesType_::Scalar StorageIndex; + typedef IndicesType_ IndicesType; enum { - RowsAtCompileTime = _IndicesType::SizeAtCompileTime, - ColsAtCompileTime = _IndicesType::SizeAtCompileTime, + RowsAtCompileTime = IndicesType_::SizeAtCompileTime, + ColsAtCompileTime = IndicesType_::SizeAtCompileTime, MaxRowsAtCompileTime = IndicesType::MaxSizeAtCompileTime, MaxColsAtCompileTime = IndicesType::MaxSizeAtCompileTime, Flags = 0 }; }; -} +} // namespace internal /** \class PermutationWrapper - * \ingroup Core_Module - * - * \brief Class to view a vector of integers as a permutation matrix - * - * \tparam _IndicesType the type of the vector of integer (can be any compatible expression) - * - * This class allows to view any vector expression of integers as a permutation matrix. - * - * \sa class PermutationBase, class PermutationMatrix - */ -template -class PermutationWrapper : public PermutationBase > -{ - typedef PermutationBase Base; - typedef internal::traits Traits; - public: - - #ifndef EIGEN_PARSED_BY_DOXYGEN - typedef typename Traits::IndicesType IndicesType; - #endif - - inline PermutationWrapper(const IndicesType& indices) - : m_indices(indices) - {} - - /** const version of indices(). */ - const typename internal::remove_all::type& - indices() const { return m_indices; } - - protected: - - typename IndicesType::Nested m_indices; -}; + * \ingroup Core_Module + * + * \brief Class to view a vector of integers as a permutation matrix + * + * \tparam IndicesType_ the type of the vector of integer (can be any compatible expression) + * + * This class allows to view any vector expression of integers as a permutation matrix. + * + * \sa class PermutationBase, class PermutationMatrix + */ +template +class PermutationWrapper : public PermutationBase > { + typedef PermutationBase Base; + typedef internal::traits Traits; + + public: +#ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename Traits::IndicesType IndicesType; +#endif + + inline PermutationWrapper(const IndicesType& indices) : m_indices(indices) {} + /** const version of indices(). */ + const internal::remove_all_t& indices() const { return m_indices; } + + protected: + typename IndicesType::Nested m_indices; +}; /** \returns the matrix with the permutation applied to the columns. - */ -template -EIGEN_DEVICE_FUNC -const Product -operator*(const MatrixBase &matrix, - const PermutationBase& permutation) -{ - return Product - (matrix.derived(), permutation.derived()); + */ +template +EIGEN_DEVICE_FUNC const Product operator*( + const MatrixBase& matrix, const PermutationBase& permutation) { + return Product(matrix.derived(), permutation.derived()); } /** \returns the matrix with the permutation applied to the rows. - */ -template -EIGEN_DEVICE_FUNC -const Product -operator*(const PermutationBase &permutation, - const MatrixBase& matrix) -{ - return Product - (permutation.derived(), matrix.derived()); + */ +template +EIGEN_DEVICE_FUNC const Product operator*( + const PermutationBase& permutation, const MatrixBase& matrix) { + return Product(permutation.derived(), matrix.derived()); } +template +class InverseImpl : public EigenBase > { + typedef typename PermutationType::PlainPermutationType PlainPermutationType; + typedef internal::traits PermTraits; -template -class InverseImpl - : public EigenBase > -{ - typedef typename PermutationType::PlainPermutationType PlainPermutationType; - typedef internal::traits PermTraits; - protected: - InverseImpl() {} - public: - typedef Inverse InverseType; - using EigenBase >::derived; - - #ifndef EIGEN_PARSED_BY_DOXYGEN - typedef typename PermutationType::DenseMatrixType DenseMatrixType; - enum { - RowsAtCompileTime = PermTraits::RowsAtCompileTime, - ColsAtCompileTime = PermTraits::ColsAtCompileTime, - MaxRowsAtCompileTime = PermTraits::MaxRowsAtCompileTime, - MaxColsAtCompileTime = PermTraits::MaxColsAtCompileTime - }; - #endif - - #ifndef EIGEN_PARSED_BY_DOXYGEN - template - void evalTo(MatrixBase& other) const - { - other.setZero(); - for (Index i=0; i InverseType; + using EigenBase >::derived; - DenseMatrixType toDenseMatrix() const { return derived(); } +#ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename PermutationType::DenseMatrixType DenseMatrixType; + enum { + RowsAtCompileTime = PermTraits::RowsAtCompileTime, + ColsAtCompileTime = PermTraits::ColsAtCompileTime, + MaxRowsAtCompileTime = PermTraits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = PermTraits::MaxColsAtCompileTime + }; +#endif - /** \returns the matrix with the inverse permutation applied to the columns. - */ - template friend - const Product - operator*(const MatrixBase& matrix, const InverseType& trPerm) - { - return Product(matrix.derived(), trPerm.derived()); - } +#ifndef EIGEN_PARSED_BY_DOXYGEN + template + void evalTo(MatrixBase& other) const { + other.setZero(); + for (Index i = 0; i < derived().rows(); ++i) + other.coeffRef(i, derived().nestedExpression().indices().coeff(i)) = typename DenseDerived::Scalar(1); + } +#endif - /** \returns the matrix with the inverse permutation applied to the rows. - */ - template - const Product - operator*(const MatrixBase& matrix) const - { - return Product(derived(), matrix.derived()); - } + /** \return the equivalent permutation matrix */ + PlainPermutationType eval() const { return derived(); } + + DenseMatrixType toDenseMatrix() const { return derived(); } + + /** \returns the matrix with the inverse permutation applied to the columns. + */ + template + friend const Product operator*(const MatrixBase& matrix, + const InverseType& trPerm) { + return Product(matrix.derived(), trPerm.derived()); + } + + /** \returns the matrix with the inverse permutation applied to the rows. + */ + template + const Product operator*(const MatrixBase& matrix) const { + return Product(derived(), matrix.derived()); + } }; -template -const PermutationWrapper MatrixBase::asPermutation() const -{ +template +const PermutationWrapper MatrixBase::asPermutation() const { return derived(); } namespace internal { -template<> struct AssignmentKind { typedef EigenBase2EigenBase Kind; }; +template <> +struct AssignmentKind { + typedef EigenBase2EigenBase Kind; +}; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_PERMUTATIONMATRIX_H +#endif // EIGEN_PERMUTATIONMATRIX_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/PlainObjectBase.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/PlainObjectBase.h index e2ddbd1d522..5f846a0f104 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/PlainObjectBase.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/PlainObjectBase.h @@ -12,51 +12,73 @@ #define EIGEN_DENSESTORAGEBASE_H #if defined(EIGEN_INITIALIZE_MATRICES_BY_ZERO) -# define EIGEN_INITIALIZE_COEFFS -# define EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED for(Index i=0;i::quiet_NaN(); +#define EIGEN_INITIALIZE_COEFFS +#define EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED \ + for (Index i = 0; i < base().size(); ++i) coeffRef(i) = std::numeric_limits::quiet_NaN(); #else -# undef EIGEN_INITIALIZE_COEFFS -# define EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED +#undef EIGEN_INITIALIZE_COEFFS +#define EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED #endif +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template struct check_rows_cols_for_overflow { - template - EIGEN_DEVICE_FUNC - static EIGEN_ALWAYS_INLINE void run(Index, Index) - { +#ifndef EIGEN_NO_DEBUG +template +struct check_rows_cols_for_overflow { + EIGEN_STATIC_ASSERT(MaxRowsAtCompileTime* MaxColsAtCompileTime == MaxSizeAtCompileTime, + YOU MADE A PROGRAMMING MISTAKE) + template + EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE constexpr void run(Index, Index) {} +}; + +template +struct check_rows_cols_for_overflow { + template + EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE constexpr void run(Index, Index cols) { + constexpr Index MaxIndex = NumTraits::highest(); + bool error = cols > (MaxIndex / MaxRowsAtCompileTime); + if (error) throw_std_bad_alloc(); } }; -template<> struct check_rows_cols_for_overflow { - template - EIGEN_DEVICE_FUNC - static EIGEN_ALWAYS_INLINE void run(Index rows, Index cols) - { - // http://hg.mozilla.org/mozilla-central/file/6c8a909977d3/xpcom/ds/CheckedInt.h#l242 - // we assume Index is signed - Index max_index = (std::size_t(1) << (8 * sizeof(Index) - 1)) - 1; // assume Index is signed - bool error = (rows == 0 || cols == 0) ? false - : (rows > max_index / cols); - if (error) - throw_std_bad_alloc(); +template +struct check_rows_cols_for_overflow { + template + EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE constexpr void run(Index rows, Index) { + constexpr Index MaxIndex = NumTraits::highest(); + bool error = rows > (MaxIndex / MaxColsAtCompileTime); + if (error) throw_std_bad_alloc(); } }; -template +struct check_rows_cols_for_overflow { + template + EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE constexpr void run(Index rows, Index cols) { + constexpr Index MaxIndex = NumTraits::highest(); + bool error = cols == 0 ? false : (rows > (MaxIndex / cols)); + if (error) throw_std_bad_alloc(); + } +}; +#endif + +template struct conservative_resize_like_impl; -template struct matrix_swap_impl; +template +struct matrix_swap_impl; -} // end namespace internal +} // end namespace internal #ifdef EIGEN_PARSED_BY_DOXYGEN namespace doxygen { @@ -64,971 +86,886 @@ namespace doxygen { // This is a workaround to doxygen not being able to understand the inheritance logic // when it is hidden by the dense_xpr_base helper struct. // Moreover, doxygen fails to include members that are not documented in the declaration body of -// MatrixBase if we inherits MatrixBase >, +// MatrixBase if we inherits MatrixBase >, // this is why we simply inherits MatrixBase, though this does not make sense. /** This class is just a workaround for Doxygen and it does not not actually exist. */ -template struct dense_xpr_base_dispatcher; +template +struct dense_xpr_base_dispatcher; /** This class is just a workaround for Doxygen and it does not not actually exist. */ -template -struct dense_xpr_base_dispatcher > - : public MatrixBase {}; +template +struct dense_xpr_base_dispatcher> : public MatrixBase {}; /** This class is just a workaround for Doxygen and it does not not actually exist. */ -template -struct dense_xpr_base_dispatcher > - : public ArrayBase {}; +template +struct dense_xpr_base_dispatcher> : public ArrayBase {}; -} // namespace doxygen +} // namespace doxygen /** \class PlainObjectBase - * \ingroup Core_Module - * \brief %Dense storage base class for matrices and arrays. - * - * This class can be extended with the help of the plugin mechanism described on the page - * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_PLAINOBJECTBASE_PLUGIN. - * - * \tparam Derived is the derived type, e.g., a Matrix or Array - * - * \sa \ref TopicClassHierarchy - */ -template + * \ingroup Core_Module + * \brief %Dense storage base class for matrices and arrays. + * + * This class can be extended with the help of the plugin mechanism described on the page + * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_PLAINOBJECTBASE_PLUGIN. + * + * \tparam Derived is the derived type, e.g., a Matrix or Array + * + * \sa \ref TopicClassHierarchy + */ +template class PlainObjectBase : public doxygen::dense_xpr_base_dispatcher #else -template +template class PlainObjectBase : public internal::dense_xpr_base::type #endif { - public: - enum { Options = internal::traits::Options }; - typedef typename internal::dense_xpr_base::type Base; - - typedef typename internal::traits::StorageKind StorageKind; - typedef typename internal::traits::Scalar Scalar; - - typedef typename internal::packet_traits::type PacketScalar; - typedef typename NumTraits::Real RealScalar; - typedef Derived DenseType; - - using Base::RowsAtCompileTime; - using Base::ColsAtCompileTime; - using Base::SizeAtCompileTime; - using Base::MaxRowsAtCompileTime; - using Base::MaxColsAtCompileTime; - using Base::MaxSizeAtCompileTime; - using Base::IsVectorAtCompileTime; - using Base::Flags; - - typedef Eigen::Map MapType; - typedef const Eigen::Map ConstMapType; - typedef Eigen::Map AlignedMapType; - typedef const Eigen::Map ConstAlignedMapType; - template struct StridedMapType { typedef Eigen::Map type; }; - template struct StridedConstMapType { typedef Eigen::Map type; }; - template struct StridedAlignedMapType { typedef Eigen::Map type; }; - template struct StridedConstAlignedMapType { typedef Eigen::Map type; }; - - protected: - DenseStorage m_storage; - - public: - enum { NeedsToAlign = (SizeAtCompileTime != Dynamic) && (internal::traits::Alignment>0) }; - EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(NeedsToAlign) - - EIGEN_DEVICE_FUNC - Base& base() { return *static_cast(this); } - EIGEN_DEVICE_FUNC - const Base& base() const { return *static_cast(this); } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index rows() const EIGEN_NOEXCEPT { return m_storage.rows(); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index cols() const EIGEN_NOEXCEPT { return m_storage.cols(); } - - /** This is an overloaded version of DenseCoeffsBase::coeff(Index,Index) const - * provided to by-pass the creation of an evaluator of the expression, thus saving compilation efforts. - * - * See DenseCoeffsBase::coeff(Index) const for details. */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE const Scalar& coeff(Index rowId, Index colId) const - { - if(Flags & RowMajorBit) - return m_storage.data()[colId + rowId * m_storage.cols()]; - else // column-major - return m_storage.data()[rowId + colId * m_storage.rows()]; - } - - /** This is an overloaded version of DenseCoeffsBase::coeff(Index) const - * provided to by-pass the creation of an evaluator of the expression, thus saving compilation efforts. - * - * See DenseCoeffsBase::coeff(Index) const for details. */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE const Scalar& coeff(Index index) const - { - return m_storage.data()[index]; - } - - /** This is an overloaded version of DenseCoeffsBase::coeffRef(Index,Index) const - * provided to by-pass the creation of an evaluator of the expression, thus saving compilation efforts. - * - * See DenseCoeffsBase::coeffRef(Index,Index) const for details. */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Scalar& coeffRef(Index rowId, Index colId) - { - if(Flags & RowMajorBit) - return m_storage.data()[colId + rowId * m_storage.cols()]; - else // column-major - return m_storage.data()[rowId + colId * m_storage.rows()]; - } - - /** This is an overloaded version of DenseCoeffsBase::coeffRef(Index) const - * provided to by-pass the creation of an evaluator of the expression, thus saving compilation efforts. - * - * See DenseCoeffsBase::coeffRef(Index) const for details. */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) - { - return m_storage.data()[index]; - } - - /** This is the const version of coeffRef(Index,Index) which is thus synonym of coeff(Index,Index). - * It is provided for convenience. */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE const Scalar& coeffRef(Index rowId, Index colId) const - { - if(Flags & RowMajorBit) - return m_storage.data()[colId + rowId * m_storage.cols()]; - else // column-major - return m_storage.data()[rowId + colId * m_storage.rows()]; - } + public: + enum { Options = internal::traits::Options }; + typedef typename internal::dense_xpr_base::type Base; + + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Scalar Scalar; + + typedef typename internal::packet_traits::type PacketScalar; + typedef typename NumTraits::Real RealScalar; + typedef Derived DenseType; + + using Base::ColsAtCompileTime; + using Base::Flags; + using Base::IsVectorAtCompileTime; + using Base::MaxColsAtCompileTime; + using Base::MaxRowsAtCompileTime; + using Base::MaxSizeAtCompileTime; + using Base::RowsAtCompileTime; + using Base::SizeAtCompileTime; + + typedef Eigen::Map MapType; + typedef const Eigen::Map ConstMapType; + typedef Eigen::Map AlignedMapType; + typedef const Eigen::Map ConstAlignedMapType; + template + struct StridedMapType { + typedef Eigen::Map type; + }; + template + struct StridedConstMapType { + typedef Eigen::Map type; + }; + template + struct StridedAlignedMapType { + typedef Eigen::Map type; + }; + template + struct StridedConstAlignedMapType { + typedef Eigen::Map type; + }; + + protected: + DenseStorage m_storage; + + public: + enum { NeedsToAlign = (SizeAtCompileTime != Dynamic) && (internal::traits::Alignment > 0) }; + EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(NeedsToAlign) + + EIGEN_STATIC_ASSERT(internal::check_implication(MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1, + (int(Options) & RowMajor) == RowMajor), + INVALID_MATRIX_TEMPLATE_PARAMETERS) + EIGEN_STATIC_ASSERT(internal::check_implication(MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1, + (int(Options) & RowMajor) == 0), + INVALID_MATRIX_TEMPLATE_PARAMETERS) + EIGEN_STATIC_ASSERT((RowsAtCompileTime == Dynamic) || (RowsAtCompileTime >= 0), INVALID_MATRIX_TEMPLATE_PARAMETERS) + EIGEN_STATIC_ASSERT((ColsAtCompileTime == Dynamic) || (ColsAtCompileTime >= 0), INVALID_MATRIX_TEMPLATE_PARAMETERS) + EIGEN_STATIC_ASSERT((MaxRowsAtCompileTime == Dynamic) || (MaxRowsAtCompileTime >= 0), + INVALID_MATRIX_TEMPLATE_PARAMETERS) + EIGEN_STATIC_ASSERT((MaxColsAtCompileTime == Dynamic) || (MaxColsAtCompileTime >= 0), + INVALID_MATRIX_TEMPLATE_PARAMETERS) + EIGEN_STATIC_ASSERT((MaxRowsAtCompileTime == RowsAtCompileTime || RowsAtCompileTime == Dynamic), + INVALID_MATRIX_TEMPLATE_PARAMETERS) + EIGEN_STATIC_ASSERT((MaxColsAtCompileTime == ColsAtCompileTime || ColsAtCompileTime == Dynamic), + INVALID_MATRIX_TEMPLATE_PARAMETERS) + EIGEN_STATIC_ASSERT(((Options & (DontAlign | RowMajor)) == Options), INVALID_MATRIX_TEMPLATE_PARAMETERS) + + EIGEN_DEVICE_FUNC Base& base() { return *static_cast(this); } + EIGEN_DEVICE_FUNC const Base& base() const { return *static_cast(this); } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_storage.rows(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_storage.cols(); } + + /** This is an overloaded version of DenseCoeffsBase::coeff(Index,Index) const + * provided to by-pass the creation of an evaluator of the expression, thus saving compilation efforts. + * + * See DenseCoeffsBase::coeff(Index) const for details. */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr const Scalar& coeff(Index rowId, Index colId) const { + if (Flags & RowMajorBit) + return m_storage.data()[colId + rowId * m_storage.cols()]; + else // column-major + return m_storage.data()[rowId + colId * m_storage.rows()]; + } - /** This is the const version of coeffRef(Index) which is thus synonym of coeff(Index). - * It is provided for convenience. */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE const Scalar& coeffRef(Index index) const - { - return m_storage.data()[index]; - } + /** This is an overloaded version of DenseCoeffsBase::coeff(Index) const + * provided to by-pass the creation of an evaluator of the expression, thus saving compilation efforts. + * + * See DenseCoeffsBase::coeff(Index) const for details. */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr const Scalar& coeff(Index index) const { + return m_storage.data()[index]; + } - /** \internal */ - template - EIGEN_STRONG_INLINE PacketScalar packet(Index rowId, Index colId) const - { - return internal::ploadt - (m_storage.data() + (Flags & RowMajorBit - ? colId + rowId * m_storage.cols() - : rowId + colId * m_storage.rows())); - } + /** This is an overloaded version of DenseCoeffsBase::coeffRef(Index,Index) const + * provided to by-pass the creation of an evaluator of the expression, thus saving compilation efforts. + * + * See DenseCoeffsBase::coeffRef(Index,Index) const for details. */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr Scalar& coeffRef(Index rowId, Index colId) { + if (Flags & RowMajorBit) + return m_storage.data()[colId + rowId * m_storage.cols()]; + else // column-major + return m_storage.data()[rowId + colId * m_storage.rows()]; + } - /** \internal */ - template - EIGEN_STRONG_INLINE PacketScalar packet(Index index) const - { - return internal::ploadt(m_storage.data() + index); - } + /** This is an overloaded version of DenseCoeffsBase::coeffRef(Index) const + * provided to by-pass the creation of an evaluator of the expression, thus saving compilation efforts. + * + * See DenseCoeffsBase::coeffRef(Index) const for details. */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr Scalar& coeffRef(Index index) { return m_storage.data()[index]; } + + /** This is the const version of coeffRef(Index,Index) which is thus synonym of coeff(Index,Index). + * It is provided for convenience. */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr const Scalar& coeffRef(Index rowId, Index colId) const { + if (Flags & RowMajorBit) + return m_storage.data()[colId + rowId * m_storage.cols()]; + else // column-major + return m_storage.data()[rowId + colId * m_storage.rows()]; + } - /** \internal */ - template - EIGEN_STRONG_INLINE void writePacket(Index rowId, Index colId, const PacketScalar& val) - { - internal::pstoret - (m_storage.data() + (Flags & RowMajorBit - ? colId + rowId * m_storage.cols() - : rowId + colId * m_storage.rows()), val); - } + /** This is the const version of coeffRef(Index) which is thus synonym of coeff(Index). + * It is provided for convenience. */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr const Scalar& coeffRef(Index index) const { + return m_storage.data()[index]; + } - /** \internal */ - template - EIGEN_STRONG_INLINE void writePacket(Index index, const PacketScalar& val) - { - internal::pstoret(m_storage.data() + index, val); - } + /** \internal */ + template + EIGEN_STRONG_INLINE PacketScalar packet(Index rowId, Index colId) const { + return internal::ploadt( + m_storage.data() + (Flags & RowMajorBit ? colId + rowId * m_storage.cols() : rowId + colId * m_storage.rows())); + } - /** \returns a const pointer to the data array of this matrix */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar *data() const - { return m_storage.data(); } - - /** \returns a pointer to the data array of this matrix */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar *data() - { return m_storage.data(); } - - /** Resizes \c *this to a \a rows x \a cols matrix. - * - * This method is intended for dynamic-size matrices, although it is legal to call it on any - * matrix as long as fixed dimensions are left unchanged. If you only want to change the number - * of rows and/or of columns, you can use resize(NoChange_t, Index), resize(Index, NoChange_t). - * - * If the current number of coefficients of \c *this exactly matches the - * product \a rows * \a cols, then no memory allocation is performed and - * the current values are left unchanged. In all other cases, including - * shrinking, the data is reallocated and all previous values are lost. - * - * Example: \include Matrix_resize_int_int.cpp - * Output: \verbinclude Matrix_resize_int_int.out - * - * \sa resize(Index) for vectors, resize(NoChange_t, Index), resize(Index, NoChange_t) - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void resize(Index rows, Index cols) - { - eigen_assert( EIGEN_IMPLIES(RowsAtCompileTime!=Dynamic,rows==RowsAtCompileTime) - && EIGEN_IMPLIES(ColsAtCompileTime!=Dynamic,cols==ColsAtCompileTime) - && EIGEN_IMPLIES(RowsAtCompileTime==Dynamic && MaxRowsAtCompileTime!=Dynamic,rows<=MaxRowsAtCompileTime) - && EIGEN_IMPLIES(ColsAtCompileTime==Dynamic && MaxColsAtCompileTime!=Dynamic,cols<=MaxColsAtCompileTime) - && rows>=0 && cols>=0 && "Invalid sizes when resizing a matrix or array."); - internal::check_rows_cols_for_overflow::run(rows, cols); - #ifdef EIGEN_INITIALIZE_COEFFS - Index size = rows*cols; - bool size_changed = size != this->size(); - m_storage.resize(size, rows, cols); - if(size_changed) EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED - #else - m_storage.resize(rows*cols, rows, cols); - #endif - } + /** \internal */ + template + EIGEN_STRONG_INLINE PacketScalar packet(Index index) const { + return internal::ploadt(m_storage.data() + index); + } - /** Resizes \c *this to a vector of length \a size - * - * \only_for_vectors. This method does not work for - * partially dynamic matrices when the static dimension is anything other - * than 1. For example it will not work with Matrix. - * - * Example: \include Matrix_resize_int.cpp - * Output: \verbinclude Matrix_resize_int.out - * - * \sa resize(Index,Index), resize(NoChange_t, Index), resize(Index, NoChange_t) - */ - EIGEN_DEVICE_FUNC - inline void resize(Index size) - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(PlainObjectBase) - eigen_assert(((SizeAtCompileTime == Dynamic && (MaxSizeAtCompileTime==Dynamic || size<=MaxSizeAtCompileTime)) || SizeAtCompileTime == size) && size>=0); - #ifdef EIGEN_INITIALIZE_COEFFS - bool size_changed = size != this->size(); - #endif - if(RowsAtCompileTime == 1) - m_storage.resize(size, 1, size); - else - m_storage.resize(size, size, 1); - #ifdef EIGEN_INITIALIZE_COEFFS - if(size_changed) EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED - #endif - } + /** \internal */ + template + EIGEN_STRONG_INLINE void writePacket(Index rowId, Index colId, const PacketScalar& val) { + internal::pstoret( + m_storage.data() + (Flags & RowMajorBit ? colId + rowId * m_storage.cols() : rowId + colId * m_storage.rows()), + val); + } - /** Resizes the matrix, changing only the number of columns. For the parameter of type NoChange_t, just pass the special value \c NoChange - * as in the example below. - * - * Example: \include Matrix_resize_NoChange_int.cpp - * Output: \verbinclude Matrix_resize_NoChange_int.out - * - * \sa resize(Index,Index) - */ - EIGEN_DEVICE_FUNC - inline void resize(NoChange_t, Index cols) - { - resize(rows(), cols); - } + /** \internal */ + template + EIGEN_STRONG_INLINE void writePacket(Index index, const PacketScalar& val) { + internal::pstoret(m_storage.data() + index, val); + } - /** Resizes the matrix, changing only the number of rows. For the parameter of type NoChange_t, just pass the special value \c NoChange - * as in the example below. - * - * Example: \include Matrix_resize_int_NoChange.cpp - * Output: \verbinclude Matrix_resize_int_NoChange.out - * - * \sa resize(Index,Index) - */ - EIGEN_DEVICE_FUNC - inline void resize(Index rows, NoChange_t) - { - resize(rows, cols()); - } + /** \returns a const pointer to the data array of this matrix */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar* data() const { return m_storage.data(); } + + /** \returns a pointer to the data array of this matrix */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar* data() { return m_storage.data(); } + + /** Resizes \c *this to a \a rows x \a cols matrix. + * + * This method is intended for dynamic-size matrices, although it is legal to call it on any + * matrix as long as fixed dimensions are left unchanged. If you only want to change the number + * of rows and/or of columns, you can use resize(NoChange_t, Index), resize(Index, NoChange_t). + * + * If the current number of coefficients of \c *this exactly matches the + * product \a rows * \a cols, then no memory allocation is performed and + * the current values are left unchanged. In all other cases, including + * shrinking, the data is reallocated and all previous values are lost. + * + * Example: \include Matrix_resize_int_int.cpp + * Output: \verbinclude Matrix_resize_int_int.out + * + * \sa resize(Index) for vectors, resize(NoChange_t, Index), resize(Index, NoChange_t) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr void resize(Index rows, Index cols) { + eigen_assert(internal::check_implication(RowsAtCompileTime != Dynamic, rows == RowsAtCompileTime) && + internal::check_implication(ColsAtCompileTime != Dynamic, cols == ColsAtCompileTime) && + internal::check_implication(RowsAtCompileTime == Dynamic && MaxRowsAtCompileTime != Dynamic, + rows <= MaxRowsAtCompileTime) && + internal::check_implication(ColsAtCompileTime == Dynamic && MaxColsAtCompileTime != Dynamic, + cols <= MaxColsAtCompileTime) && + rows >= 0 && cols >= 0 && "Invalid sizes when resizing a matrix or array."); +#ifndef EIGEN_NO_DEBUG + internal::check_rows_cols_for_overflow::run(rows, + cols); +#endif +#ifdef EIGEN_INITIALIZE_COEFFS + Index size = rows * cols; + bool size_changed = size != this->size(); + m_storage.resize(size, rows, cols); + if (size_changed) EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED +#else + m_storage.resize(rows * cols, rows, cols); +#endif + } - /** Resizes \c *this to have the same dimensions as \a other. - * Takes care of doing all the checking that's needed. - * - * Note that copying a row-vector into a vector (and conversely) is allowed. - * The resizing, if any, is then done in the appropriate way so that row-vectors - * remain row-vectors and vectors remain vectors. - */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void resizeLike(const EigenBase& _other) - { - const OtherDerived& other = _other.derived(); - internal::check_rows_cols_for_overflow::run(other.rows(), other.cols()); - const Index othersize = other.rows()*other.cols(); - if(RowsAtCompileTime == 1) - { - eigen_assert(other.rows() == 1 || other.cols() == 1); - resize(1, othersize); - } - else if(ColsAtCompileTime == 1) - { - eigen_assert(other.rows() == 1 || other.cols() == 1); - resize(othersize, 1); - } - else resize(other.rows(), other.cols()); - } + /** Resizes \c *this to a vector of length \a size + * + * \only_for_vectors. This method does not work for + * partially dynamic matrices when the static dimension is anything other + * than 1. For example it will not work with Matrix. + * + * Example: \include Matrix_resize_int.cpp + * Output: \verbinclude Matrix_resize_int.out + * + * \sa resize(Index,Index), resize(NoChange_t, Index), resize(Index, NoChange_t) + */ + EIGEN_DEVICE_FUNC inline constexpr void resize(Index size) { + EIGEN_STATIC_ASSERT_VECTOR_ONLY(PlainObjectBase) + eigen_assert(((SizeAtCompileTime == Dynamic && (MaxSizeAtCompileTime == Dynamic || size <= MaxSizeAtCompileTime)) || + SizeAtCompileTime == size) && + size >= 0); +#ifdef EIGEN_INITIALIZE_COEFFS + bool size_changed = size != this->size(); +#endif + if (RowsAtCompileTime == 1) + m_storage.resize(size, 1, size); + else + m_storage.resize(size, size, 1); +#ifdef EIGEN_INITIALIZE_COEFFS + if (size_changed) EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED +#endif + } - /** Resizes the matrix to \a rows x \a cols while leaving old values untouched. - * - * The method is intended for matrices of dynamic size. If you only want to change the number - * of rows and/or of columns, you can use conservativeResize(NoChange_t, Index) or - * conservativeResize(Index, NoChange_t). - * - * Matrices are resized relative to the top-left element. In case values need to be - * appended to the matrix they will be uninitialized. - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void conservativeResize(Index rows, Index cols) - { - internal::conservative_resize_like_impl::run(*this, rows, cols); - } + /** Resizes the matrix, changing only the number of columns. For the parameter of type NoChange_t, just pass the + * special value \c NoChange as in the example below. + * + * Example: \include Matrix_resize_NoChange_int.cpp + * Output: \verbinclude Matrix_resize_NoChange_int.out + * + * \sa resize(Index,Index) + */ + EIGEN_DEVICE_FUNC inline constexpr void resize(NoChange_t, Index cols) { resize(rows(), cols); } + + /** Resizes the matrix, changing only the number of rows. For the parameter of type NoChange_t, just pass the special + * value \c NoChange as in the example below. + * + * Example: \include Matrix_resize_int_NoChange.cpp + * Output: \verbinclude Matrix_resize_int_NoChange.out + * + * \sa resize(Index,Index) + */ + EIGEN_DEVICE_FUNC inline constexpr void resize(Index rows, NoChange_t) { resize(rows, cols()); } + + /** Resizes \c *this to have the same dimensions as \a other. + * Takes care of doing all the checking that's needed. + * + * Note that copying a row-vector into a vector (and conversely) is allowed. + * The resizing, if any, is then done in the appropriate way so that row-vectors + * remain row-vectors and vectors remain vectors. + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeLike(const EigenBase& _other) { + const OtherDerived& other = _other.derived(); +#ifndef EIGEN_NO_DEBUG + internal::check_rows_cols_for_overflow::run( + other.rows(), other.cols()); +#endif + const Index othersize = other.rows() * other.cols(); + if (RowsAtCompileTime == 1) { + eigen_assert(other.rows() == 1 || other.cols() == 1); + resize(1, othersize); + } else if (ColsAtCompileTime == 1) { + eigen_assert(other.rows() == 1 || other.cols() == 1); + resize(othersize, 1); + } else + resize(other.rows(), other.cols()); + } - /** Resizes the matrix to \a rows x \a cols while leaving old values untouched. - * - * As opposed to conservativeResize(Index rows, Index cols), this version leaves - * the number of columns unchanged. - * - * In case the matrix is growing, new rows will be uninitialized. - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void conservativeResize(Index rows, NoChange_t) - { - // Note: see the comment in conservativeResize(Index,Index) - conservativeResize(rows, cols()); - } + /** Resizes the matrix to \a rows x \a cols while leaving old values untouched. + * + * The method is intended for matrices of dynamic size. If you only want to change the number + * of rows and/or of columns, you can use conservativeResize(NoChange_t, Index) or + * conservativeResize(Index, NoChange_t). + * + * Matrices are resized relative to the top-left element. In case values need to be + * appended to the matrix they will be uninitialized. + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void conservativeResize(Index rows, Index cols) { + internal::conservative_resize_like_impl::run(*this, rows, cols); + } - /** Resizes the matrix to \a rows x \a cols while leaving old values untouched. - * - * As opposed to conservativeResize(Index rows, Index cols), this version leaves - * the number of rows unchanged. - * - * In case the matrix is growing, new columns will be uninitialized. - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void conservativeResize(NoChange_t, Index cols) - { - // Note: see the comment in conservativeResize(Index,Index) - conservativeResize(rows(), cols); - } + /** Resizes the matrix to \a rows x \a cols while leaving old values untouched. + * + * As opposed to conservativeResize(Index rows, Index cols), this version leaves + * the number of columns unchanged. + * + * In case the matrix is growing, new rows will be uninitialized. + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void conservativeResize(Index rows, NoChange_t) { + // Note: see the comment in conservativeResize(Index,Index) + conservativeResize(rows, cols()); + } - /** Resizes the vector to \a size while retaining old values. - * - * \only_for_vectors. This method does not work for - * partially dynamic matrices when the static dimension is anything other - * than 1. For example it will not work with Matrix. - * - * When values are appended, they will be uninitialized. - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void conservativeResize(Index size) - { - internal::conservative_resize_like_impl::run(*this, size); - } + /** Resizes the matrix to \a rows x \a cols while leaving old values untouched. + * + * As opposed to conservativeResize(Index rows, Index cols), this version leaves + * the number of rows unchanged. + * + * In case the matrix is growing, new columns will be uninitialized. + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void conservativeResize(NoChange_t, Index cols) { + // Note: see the comment in conservativeResize(Index,Index) + conservativeResize(rows(), cols); + } - /** Resizes the matrix to \a rows x \a cols of \c other, while leaving old values untouched. - * - * The method is intended for matrices of dynamic size. If you only want to change the number - * of rows and/or of columns, you can use conservativeResize(NoChange_t, Index) or - * conservativeResize(Index, NoChange_t). - * - * Matrices are resized relative to the top-left element. In case values need to be - * appended to the matrix they will copied from \c other. - */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void conservativeResizeLike(const DenseBase& other) - { - internal::conservative_resize_like_impl::run(*this, other); - } + /** Resizes the vector to \a size while retaining old values. + * + * \only_for_vectors. This method does not work for + * partially dynamic matrices when the static dimension is anything other + * than 1. For example it will not work with Matrix. + * + * When values are appended, they will be uninitialized. + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void conservativeResize(Index size) { + internal::conservative_resize_like_impl::run(*this, size); + } - /** This is a special case of the templated operator=. Its purpose is to - * prevent a default operator= from hiding the templated operator=. - */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Derived& operator=(const PlainObjectBase& other) - { - return _set(other); - } + /** Resizes the matrix to \a rows x \a cols of \c other, while leaving old values untouched. + * + * The method is intended for matrices of dynamic size. If you only want to change the number + * of rows and/or of columns, you can use conservativeResize(NoChange_t, Index) or + * conservativeResize(Index, NoChange_t). + * + * Matrices are resized relative to the top-left element. In case values need to be + * appended to the matrix they will copied from \c other. + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void conservativeResizeLike(const DenseBase& other) { + internal::conservative_resize_like_impl::run(*this, other); + } - /** \sa MatrixBase::lazyAssign() */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Derived& lazyAssign(const DenseBase& other) - { - _resize_to_match(other); - return Base::lazyAssign(other.derived()); - } + /** This is a special case of the templated operator=. Its purpose is to + * prevent a default operator= from hiding the templated operator=. + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr Derived& operator=(const PlainObjectBase& other) { + return _set(other); + } - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Derived& operator=(const ReturnByValue& func) - { - resize(func.rows(), func.cols()); - return Base::operator=(func); - } + /** \sa MatrixBase::lazyAssign() */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& lazyAssign(const DenseBase& other) { + _resize_to_match(other); + return Base::lazyAssign(other.derived()); + } - // Prevent user from trying to instantiate PlainObjectBase objects - // by making all its constructor protected. See bug 1074. - protected: + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator=(const ReturnByValue& func) { + resize(func.rows(), func.cols()); + return Base::operator=(func); + } - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE PlainObjectBase() : m_storage() - { -// _check_template_params(); -// EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED - } + // Prevent user from trying to instantiate PlainObjectBase objects + // by making all its constructor protected. See bug 1074. + protected: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr PlainObjectBase() : m_storage() { + // EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + } #ifndef EIGEN_PARSED_BY_DOXYGEN - // FIXME is it still needed ? - /** \internal */ - EIGEN_DEVICE_FUNC - explicit PlainObjectBase(internal::constructor_without_unaligned_array_assert) - : m_storage(internal::constructor_without_unaligned_array_assert()) - { -// _check_template_params(); EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED - } + // FIXME is it still needed ? + /** \internal */ + EIGEN_DEVICE_FUNC constexpr explicit PlainObjectBase(internal::constructor_without_unaligned_array_assert) + : m_storage(internal::constructor_without_unaligned_array_assert()) { + // EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + } #endif -#if EIGEN_HAS_RVALUE_REFERENCES - EIGEN_DEVICE_FUNC - PlainObjectBase(PlainObjectBase&& other) EIGEN_NOEXCEPT - : m_storage( std::move(other.m_storage) ) - { - } + EIGEN_DEVICE_FUNC constexpr PlainObjectBase(PlainObjectBase&& other) EIGEN_NOEXCEPT + : m_storage(std::move(other.m_storage)) {} - EIGEN_DEVICE_FUNC - PlainObjectBase& operator=(PlainObjectBase&& other) EIGEN_NOEXCEPT - { - _check_template_params(); - m_storage = std::move(other.m_storage); - return *this; - } -#endif - - /** Copy constructor */ - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE PlainObjectBase(const PlainObjectBase& other) - : Base(), m_storage(other.m_storage) { } - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE PlainObjectBase(Index size, Index rows, Index cols) - : m_storage(size, rows, cols) - { -// _check_template_params(); -// EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED - } + EIGEN_DEVICE_FUNC constexpr PlainObjectBase& operator=(PlainObjectBase&& other) EIGEN_NOEXCEPT { + m_storage = std::move(other.m_storage); + return *this; + } - #if EIGEN_HAS_CXX11 - /** \brief Construct a row of column vector with fixed size from an arbitrary number of coefficients. \cpp11 - * - * \only_for_vectors - * - * This constructor is for 1D array or vectors with more than 4 coefficients. - * There exists C++98 analogue constructors for fixed-size array/vector having 1, 2, 3, or 4 coefficients. - * - * \warning To construct a column (resp. row) vector of fixed length, the number of values passed to this - * constructor must match the the fixed number of rows (resp. columns) of \c *this. - */ - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - PlainObjectBase(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) - : m_storage() - { - _check_template_params(); - EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, sizeof...(args) + 4); - m_storage.data()[0] = a0; - m_storage.data()[1] = a1; - m_storage.data()[2] = a2; - m_storage.data()[3] = a3; - Index i = 4; - auto x = {(m_storage.data()[i++] = args, 0)...}; - static_cast(x); - } + /** Copy constructor */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr PlainObjectBase(const PlainObjectBase& other) + : Base(), m_storage(other.m_storage) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PlainObjectBase(Index size, Index rows, Index cols) + : m_storage(size, rows, cols) { + // EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + } - /** \brief Constructs a Matrix or Array and initializes it by elements given by an initializer list of initializer - * lists \cpp11 - */ - EIGEN_DEVICE_FUNC - explicit EIGEN_STRONG_INLINE PlainObjectBase(const std::initializer_list>& list) - : m_storage() - { - _check_template_params(); + /** \brief Construct a row of column vector with fixed size from an arbitrary number of coefficients. + * + * \only_for_vectors + * + * This constructor is for 1D array or vectors with more than 4 coefficients. + * + * \warning To construct a column (resp. row) vector of fixed length, the number of values passed to this + * constructor must match the the fixed number of rows (resp. columns) of \c *this. + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PlainObjectBase(const Scalar& a0, const Scalar& a1, const Scalar& a2, + const Scalar& a3, const ArgTypes&... args) + : m_storage() { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, sizeof...(args) + 4); + m_storage.data()[0] = a0; + m_storage.data()[1] = a1; + m_storage.data()[2] = a2; + m_storage.data()[3] = a3; + Index i = 4; + auto x = {(m_storage.data()[i++] = args, 0)...}; + static_cast(x); + } - size_t list_size = 0; - if (list.begin() != list.end()) { - list_size = list.begin()->size(); - } + /** \brief Constructs a Matrix or Array and initializes it by elements given by an initializer list of initializer + * lists + */ + EIGEN_DEVICE_FUNC explicit constexpr EIGEN_STRONG_INLINE PlainObjectBase( + const std::initializer_list>& list) + : m_storage() { + size_t list_size = 0; + if (list.begin() != list.end()) { + list_size = list.begin()->size(); + } - // This is to allow syntax like VectorXi {{1, 2, 3, 4}} - if (ColsAtCompileTime == 1 && list.size() == 1) { - eigen_assert(list_size == static_cast(RowsAtCompileTime) || RowsAtCompileTime == Dynamic); - resize(list_size, ColsAtCompileTime); + // This is to allow syntax like VectorXi {{1, 2, 3, 4}} + if (ColsAtCompileTime == 1 && list.size() == 1) { + eigen_assert(list_size == static_cast(RowsAtCompileTime) || RowsAtCompileTime == Dynamic); + resize(list_size, ColsAtCompileTime); + if (list.begin()->begin() != nullptr) { std::copy(list.begin()->begin(), list.begin()->end(), m_storage.data()); - } else { - eigen_assert(list.size() == static_cast(RowsAtCompileTime) || RowsAtCompileTime == Dynamic); - eigen_assert(list_size == static_cast(ColsAtCompileTime) || ColsAtCompileTime == Dynamic); - resize(list.size(), list_size); - - Index row_index = 0; - for (const std::initializer_list& row : list) { - eigen_assert(list_size == row.size()); - Index col_index = 0; - for (const Scalar& e : row) { - coeffRef(row_index, col_index) = e; - ++col_index; - } - ++row_index; + } + } else { + eigen_assert(list.size() == static_cast(RowsAtCompileTime) || RowsAtCompileTime == Dynamic); + eigen_assert(list_size == static_cast(ColsAtCompileTime) || ColsAtCompileTime == Dynamic); + resize(list.size(), list_size); + + Index row_index = 0; + for (const std::initializer_list& row : list) { + eigen_assert(list_size == row.size()); + Index col_index = 0; + for (const Scalar& e : row) { + coeffRef(row_index, col_index) = e; + ++col_index; } + ++row_index; } } - #endif // end EIGEN_HAS_CXX11 + } - /** \sa PlainObjectBase::operator=(const EigenBase&) */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE PlainObjectBase(const DenseBase &other) - : m_storage() - { - _check_template_params(); - resizeLike(other); - _set_noalias(other); - } + /** \sa PlainObjectBase::operator=(const EigenBase&) */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PlainObjectBase(const DenseBase& other) : m_storage() { + resizeLike(other); + _set_noalias(other); + } - /** \sa PlainObjectBase::operator=(const EigenBase&) */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE PlainObjectBase(const EigenBase &other) - : m_storage() - { - _check_template_params(); - resizeLike(other); - *this = other.derived(); - } - /** \brief Copy constructor with in-place evaluation */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE PlainObjectBase(const ReturnByValue& other) - { - _check_template_params(); - // FIXME this does not automatically transpose vectors if necessary - resize(other.rows(), other.cols()); - other.evalTo(this->derived()); - } + /** \sa PlainObjectBase::operator=(const EigenBase&) */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PlainObjectBase(const EigenBase& other) : m_storage() { + resizeLike(other); + *this = other.derived(); + } + /** \brief Copy constructor with in-place evaluation */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PlainObjectBase(const ReturnByValue& other) { + // FIXME this does not automatically transpose vectors if necessary + resize(other.rows(), other.cols()); + other.evalTo(this->derived()); + } - public: + public: + /** \brief Copies the generic expression \a other into *this. + * \copydetails DenseBase::operator=(const EigenBase &other) + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator=(const EigenBase& other) { + _resize_to_match(other); + Base::operator=(other.derived()); + return this->derived(); + } - /** \brief Copies the generic expression \a other into *this. - * \copydetails DenseBase::operator=(const EigenBase &other) - */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Derived& operator=(const EigenBase &other) - { - _resize_to_match(other); - Base::operator=(other.derived()); - return this->derived(); - } + /** \name Map + * These are convenience functions returning Map objects. The Map() static functions return unaligned Map objects, + * while the AlignedMap() functions return aligned Map objects and thus should be called only with 16-byte-aligned + * \a data pointers. + * + * Here is an example using strides: + * \include Matrix_Map_stride.cpp + * Output: \verbinclude Matrix_Map_stride.out + * + * \see class Map + */ + ///@{ + static inline ConstMapType Map(const Scalar* data) { return ConstMapType(data); } + static inline MapType Map(Scalar* data) { return MapType(data); } + static inline ConstMapType Map(const Scalar* data, Index size) { return ConstMapType(data, size); } + static inline MapType Map(Scalar* data, Index size) { return MapType(data, size); } + static inline ConstMapType Map(const Scalar* data, Index rows, Index cols) { return ConstMapType(data, rows, cols); } + static inline MapType Map(Scalar* data, Index rows, Index cols) { return MapType(data, rows, cols); } + + static inline ConstAlignedMapType MapAligned(const Scalar* data) { return ConstAlignedMapType(data); } + static inline AlignedMapType MapAligned(Scalar* data) { return AlignedMapType(data); } + static inline ConstAlignedMapType MapAligned(const Scalar* data, Index size) { + return ConstAlignedMapType(data, size); + } + static inline AlignedMapType MapAligned(Scalar* data, Index size) { return AlignedMapType(data, size); } + static inline ConstAlignedMapType MapAligned(const Scalar* data, Index rows, Index cols) { + return ConstAlignedMapType(data, rows, cols); + } + static inline AlignedMapType MapAligned(Scalar* data, Index rows, Index cols) { + return AlignedMapType(data, rows, cols); + } - /** \name Map - * These are convenience functions returning Map objects. The Map() static functions return unaligned Map objects, - * while the AlignedMap() functions return aligned Map objects and thus should be called only with 16-byte-aligned - * \a data pointers. - * - * Here is an example using strides: - * \include Matrix_Map_stride.cpp - * Output: \verbinclude Matrix_Map_stride.out - * - * \see class Map - */ - //@{ - static inline ConstMapType Map(const Scalar* data) - { return ConstMapType(data); } - static inline MapType Map(Scalar* data) - { return MapType(data); } - static inline ConstMapType Map(const Scalar* data, Index size) - { return ConstMapType(data, size); } - static inline MapType Map(Scalar* data, Index size) - { return MapType(data, size); } - static inline ConstMapType Map(const Scalar* data, Index rows, Index cols) - { return ConstMapType(data, rows, cols); } - static inline MapType Map(Scalar* data, Index rows, Index cols) - { return MapType(data, rows, cols); } - - static inline ConstAlignedMapType MapAligned(const Scalar* data) - { return ConstAlignedMapType(data); } - static inline AlignedMapType MapAligned(Scalar* data) - { return AlignedMapType(data); } - static inline ConstAlignedMapType MapAligned(const Scalar* data, Index size) - { return ConstAlignedMapType(data, size); } - static inline AlignedMapType MapAligned(Scalar* data, Index size) - { return AlignedMapType(data, size); } - static inline ConstAlignedMapType MapAligned(const Scalar* data, Index rows, Index cols) - { return ConstAlignedMapType(data, rows, cols); } - static inline AlignedMapType MapAligned(Scalar* data, Index rows, Index cols) - { return AlignedMapType(data, rows, cols); } - - template - static inline typename StridedConstMapType >::type Map(const Scalar* data, const Stride& stride) - { return typename StridedConstMapType >::type(data, stride); } - template - static inline typename StridedMapType >::type Map(Scalar* data, const Stride& stride) - { return typename StridedMapType >::type(data, stride); } - template - static inline typename StridedConstMapType >::type Map(const Scalar* data, Index size, const Stride& stride) - { return typename StridedConstMapType >::type(data, size, stride); } - template - static inline typename StridedMapType >::type Map(Scalar* data, Index size, const Stride& stride) - { return typename StridedMapType >::type(data, size, stride); } - template - static inline typename StridedConstMapType >::type Map(const Scalar* data, Index rows, Index cols, const Stride& stride) - { return typename StridedConstMapType >::type(data, rows, cols, stride); } - template - static inline typename StridedMapType >::type Map(Scalar* data, Index rows, Index cols, const Stride& stride) - { return typename StridedMapType >::type(data, rows, cols, stride); } - - template - static inline typename StridedConstAlignedMapType >::type MapAligned(const Scalar* data, const Stride& stride) - { return typename StridedConstAlignedMapType >::type(data, stride); } - template - static inline typename StridedAlignedMapType >::type MapAligned(Scalar* data, const Stride& stride) - { return typename StridedAlignedMapType >::type(data, stride); } - template - static inline typename StridedConstAlignedMapType >::type MapAligned(const Scalar* data, Index size, const Stride& stride) - { return typename StridedConstAlignedMapType >::type(data, size, stride); } - template - static inline typename StridedAlignedMapType >::type MapAligned(Scalar* data, Index size, const Stride& stride) - { return typename StridedAlignedMapType >::type(data, size, stride); } - template - static inline typename StridedConstAlignedMapType >::type MapAligned(const Scalar* data, Index rows, Index cols, const Stride& stride) - { return typename StridedConstAlignedMapType >::type(data, rows, cols, stride); } - template - static inline typename StridedAlignedMapType >::type MapAligned(Scalar* data, Index rows, Index cols, const Stride& stride) - { return typename StridedAlignedMapType >::type(data, rows, cols, stride); } - //@} - - using Base::setConstant; - EIGEN_DEVICE_FUNC Derived& setConstant(Index size, const Scalar& val); - EIGEN_DEVICE_FUNC Derived& setConstant(Index rows, Index cols, const Scalar& val); - EIGEN_DEVICE_FUNC Derived& setConstant(NoChange_t, Index cols, const Scalar& val); - EIGEN_DEVICE_FUNC Derived& setConstant(Index rows, NoChange_t, const Scalar& val); - - using Base::setZero; - EIGEN_DEVICE_FUNC Derived& setZero(Index size); - EIGEN_DEVICE_FUNC Derived& setZero(Index rows, Index cols); - EIGEN_DEVICE_FUNC Derived& setZero(NoChange_t, Index cols); - EIGEN_DEVICE_FUNC Derived& setZero(Index rows, NoChange_t); - - using Base::setOnes; - EIGEN_DEVICE_FUNC Derived& setOnes(Index size); - EIGEN_DEVICE_FUNC Derived& setOnes(Index rows, Index cols); - EIGEN_DEVICE_FUNC Derived& setOnes(NoChange_t, Index cols); - EIGEN_DEVICE_FUNC Derived& setOnes(Index rows, NoChange_t); - - using Base::setRandom; - Derived& setRandom(Index size); - Derived& setRandom(Index rows, Index cols); - Derived& setRandom(NoChange_t, Index cols); - Derived& setRandom(Index rows, NoChange_t); - - #ifdef EIGEN_PLAINOBJECTBASE_PLUGIN - #include EIGEN_PLAINOBJECTBASE_PLUGIN - #endif - - protected: - /** \internal Resizes *this in preparation for assigning \a other to it. - * Takes care of doing all the checking that's needed. - * - * Note that copying a row-vector into a vector (and conversely) is allowed. - * The resizing, if any, is then done in the appropriate way so that row-vectors - * remain row-vectors and vectors remain vectors. - */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _resize_to_match(const EigenBase& other) - { - #ifdef EIGEN_NO_AUTOMATIC_RESIZING - eigen_assert((this->size()==0 || (IsVectorAtCompileTime ? (this->size() == other.size()) - : (rows() == other.rows() && cols() == other.cols()))) - && "Size mismatch. Automatic resizing is disabled because EIGEN_NO_AUTOMATIC_RESIZING is defined"); - EIGEN_ONLY_USED_FOR_DEBUG(other); - #else - resizeLike(other); - #endif - } + template + static inline typename StridedConstMapType>::type Map(const Scalar* data, + const Stride& stride) { + return typename StridedConstMapType>::type(data, stride); + } + template + static inline typename StridedMapType>::type Map(Scalar* data, + const Stride& stride) { + return typename StridedMapType>::type(data, stride); + } + template + static inline typename StridedConstMapType>::type Map(const Scalar* data, Index size, + const Stride& stride) { + return typename StridedConstMapType>::type(data, size, stride); + } + template + static inline typename StridedMapType>::type Map(Scalar* data, Index size, + const Stride& stride) { + return typename StridedMapType>::type(data, size, stride); + } + template + static inline typename StridedConstMapType>::type Map(const Scalar* data, Index rows, Index cols, + const Stride& stride) { + return typename StridedConstMapType>::type(data, rows, cols, stride); + } + template + static inline typename StridedMapType>::type Map(Scalar* data, Index rows, Index cols, + const Stride& stride) { + return typename StridedMapType>::type(data, rows, cols, stride); + } - /** - * \brief Copies the value of the expression \a other into \c *this with automatic resizing. - * - * *this might be resized to match the dimensions of \a other. If *this was a null matrix (not already initialized), - * it will be initialized. - * - * Note that copying a row-vector into a vector (and conversely) is allowed. - * The resizing, if any, is then done in the appropriate way so that row-vectors - * remain row-vectors and vectors remain vectors. - * - * \sa operator=(const MatrixBase&), _set_noalias() - * - * \internal - */ - // aliasing is dealt once in internal::call_assignment - // so at this stage we have to assume aliasing... and resising has to be done later. - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Derived& _set(const DenseBase& other) - { - internal::call_assignment(this->derived(), other.derived()); - return this->derived(); - } + template + static inline typename StridedConstAlignedMapType>::type MapAligned( + const Scalar* data, const Stride& stride) { + return typename StridedConstAlignedMapType>::type(data, stride); + } + template + static inline typename StridedAlignedMapType>::type MapAligned( + Scalar* data, const Stride& stride) { + return typename StridedAlignedMapType>::type(data, stride); + } + template + static inline typename StridedConstAlignedMapType>::type MapAligned( + const Scalar* data, Index size, const Stride& stride) { + return typename StridedConstAlignedMapType>::type(data, size, stride); + } + template + static inline typename StridedAlignedMapType>::type MapAligned( + Scalar* data, Index size, const Stride& stride) { + return typename StridedAlignedMapType>::type(data, size, stride); + } + template + static inline typename StridedConstAlignedMapType>::type MapAligned( + const Scalar* data, Index rows, Index cols, const Stride& stride) { + return typename StridedConstAlignedMapType>::type(data, rows, cols, stride); + } + template + static inline typename StridedAlignedMapType>::type MapAligned( + Scalar* data, Index rows, Index cols, const Stride& stride) { + return typename StridedAlignedMapType>::type(data, rows, cols, stride); + } + ///@} + + using Base::setConstant; + EIGEN_DEVICE_FUNC Derived& setConstant(Index size, const Scalar& val); + EIGEN_DEVICE_FUNC Derived& setConstant(Index rows, Index cols, const Scalar& val); + EIGEN_DEVICE_FUNC Derived& setConstant(NoChange_t, Index cols, const Scalar& val); + EIGEN_DEVICE_FUNC Derived& setConstant(Index rows, NoChange_t, const Scalar& val); + + using Base::setZero; + EIGEN_DEVICE_FUNC Derived& setZero(Index size); + EIGEN_DEVICE_FUNC Derived& setZero(Index rows, Index cols); + EIGEN_DEVICE_FUNC Derived& setZero(NoChange_t, Index cols); + EIGEN_DEVICE_FUNC Derived& setZero(Index rows, NoChange_t); + + using Base::setOnes; + EIGEN_DEVICE_FUNC Derived& setOnes(Index size); + EIGEN_DEVICE_FUNC Derived& setOnes(Index rows, Index cols); + EIGEN_DEVICE_FUNC Derived& setOnes(NoChange_t, Index cols); + EIGEN_DEVICE_FUNC Derived& setOnes(Index rows, NoChange_t); + + using Base::setRandom; + Derived& setRandom(Index size); + Derived& setRandom(Index rows, Index cols); + Derived& setRandom(NoChange_t, Index cols); + Derived& setRandom(Index rows, NoChange_t); + +#ifdef EIGEN_PLAINOBJECTBASE_PLUGIN +#include EIGEN_PLAINOBJECTBASE_PLUGIN +#endif - /** \internal Like _set() but additionally makes the assumption that no aliasing effect can happen (which - * is the case when creating a new matrix) so one can enforce lazy evaluation. - * - * \sa operator=(const MatrixBase&), _set() - */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE Derived& _set_noalias(const DenseBase& other) - { - // I don't think we need this resize call since the lazyAssign will anyways resize - // and lazyAssign will be called by the assign selector. - //_resize_to_match(other); - // the 'false' below means to enforce lazy evaluation. We don't use lazyAssign() because - // it wouldn't allow to copy a row-vector into a column-vector. - internal::call_assignment_no_alias(this->derived(), other.derived(), internal::assign_op()); - return this->derived(); - } + protected: + /** \internal Resizes *this in preparation for assigning \a other to it. + * Takes care of doing all the checking that's needed. + * + * Note that copying a row-vector into a vector (and conversely) is allowed. + * The resizing, if any, is then done in the appropriate way so that row-vectors + * remain row-vectors and vectors remain vectors. + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _resize_to_match(const EigenBase& other) { +#ifdef EIGEN_NO_AUTOMATIC_RESIZING + eigen_assert((this->size() == 0 || (IsVectorAtCompileTime ? (this->size() == other.size()) + : (rows() == other.rows() && cols() == other.cols()))) && + "Size mismatch. Automatic resizing is disabled because EIGEN_NO_AUTOMATIC_RESIZING is defined"); + EIGEN_ONLY_USED_FOR_DEBUG(other); +#else + resizeLike(other); +#endif + } - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init2(Index rows, Index cols, typename internal::enable_if::type* = 0) - { - const bool t0_is_integer_alike = internal::is_valid_index_type::value; - const bool t1_is_integer_alike = internal::is_valid_index_type::value; - EIGEN_STATIC_ASSERT(t0_is_integer_alike && - t1_is_integer_alike, - FLOATING_POINT_ARGUMENT_PASSED__INTEGER_WAS_EXPECTED) - resize(rows,cols); - } + /** + * \brief Copies the value of the expression \a other into \c *this with automatic resizing. + * + * *this might be resized to match the dimensions of \a other. If *this was a null matrix (not already initialized), + * it will be initialized. + * + * Note that copying a row-vector into a vector (and conversely) is allowed. + * The resizing, if any, is then done in the appropriate way so that row-vectors + * remain row-vectors and vectors remain vectors. + * + * \sa operator=(const MatrixBase&), _set_noalias() + * + * \internal + */ + // aliasing is dealt once in internal::call_assignment + // so at this stage we have to assume aliasing... and resising has to be done later. + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr Derived& _set(const DenseBase& other) { + internal::call_assignment(this->derived(), other.derived()); + return this->derived(); + } - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init2(const T0& val0, const T1& val1, typename internal::enable_if::type* = 0) - { - EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, 2) - m_storage.data()[0] = Scalar(val0); - m_storage.data()[1] = Scalar(val1); - } + /** \internal Like _set() but additionally makes the assumption that no aliasing effect can happen (which + * is the case when creating a new matrix) so one can enforce lazy evaluation. + * + * \sa operator=(const MatrixBase&), _set() + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE constexpr Derived& _set_noalias(const DenseBase& other) { + // I don't think we need this resize call since the lazyAssign will anyways resize + // and lazyAssign will be called by the assign selector. + //_resize_to_match(other); + // the 'false' below means to enforce lazy evaluation. We don't use lazyAssign() because + // it wouldn't allow to copy a row-vector into a column-vector. + internal::call_assignment_no_alias(this->derived(), other.derived(), + internal::assign_op()); + return this->derived(); + } - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init2(const Index& val0, const Index& val1, - typename internal::enable_if< (!internal::is_same::value) - && (internal::is_same::value) - && (internal::is_same::value) - && Base::SizeAtCompileTime==2,T1>::type* = 0) - { - EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, 2) - m_storage.data()[0] = Scalar(val0); - m_storage.data()[1] = Scalar(val1); - } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init2(Index rows, Index cols, + std::enable_if_t* = 0) { + EIGEN_STATIC_ASSERT(internal::is_valid_index_type::value && internal::is_valid_index_type::value, + T0 AND T1 MUST BE INTEGER TYPES) + resize(rows, cols); + } - // The argument is convertible to the Index type and we either have a non 1x1 Matrix, or a dynamic-sized Array, - // then the argument is meant to be the size of the object. - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init1(Index size, typename internal::enable_if< (Base::SizeAtCompileTime!=1 || !internal::is_convertible::value) - && ((!internal::is_same::XprKind,ArrayXpr>::value || Base::SizeAtCompileTime==Dynamic)),T>::type* = 0) - { - // NOTE MSVC 2008 complains if we directly put bool(NumTraits::IsInteger) as the EIGEN_STATIC_ASSERT argument. - const bool is_integer_alike = internal::is_valid_index_type::value; - EIGEN_UNUSED_VARIABLE(is_integer_alike); - EIGEN_STATIC_ASSERT(is_integer_alike, - FLOATING_POINT_ARGUMENT_PASSED__INTEGER_WAS_EXPECTED) - resize(size); - } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init2(const T0& val0, const T1& val1, + std::enable_if_t* = 0) { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, 2) + m_storage.data()[0] = Scalar(val0); + m_storage.data()[1] = Scalar(val1); + } - // We have a 1x1 matrix/array => the argument is interpreted as the value of the unique coefficient (case where scalar type can be implicitly converted) - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init1(const Scalar& val0, typename internal::enable_if::value,T>::type* = 0) - { - EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, 1) - m_storage.data()[0] = val0; - } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init2( + const Index& val0, const Index& val1, + std::enable_if_t<(!internal::is_same::value) && (internal::is_same::value) && + (internal::is_same::value) && Base::SizeAtCompileTime == 2, + T1>* = 0) { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, 2) + m_storage.data()[0] = Scalar(val0); + m_storage.data()[1] = Scalar(val1); + } - // We have a 1x1 matrix/array => the argument is interpreted as the value of the unique coefficient (case where scalar type match the index type) - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init1(const Index& val0, - typename internal::enable_if< (!internal::is_same::value) - && (internal::is_same::value) - && Base::SizeAtCompileTime==1 - && internal::is_convertible::value,T*>::type* = 0) - { - EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, 1) - m_storage.data()[0] = Scalar(val0); - } + // The argument is convertible to the Index type and we either have a non 1x1 Matrix, or a dynamic-sized Array, + // then the argument is meant to be the size of the object. + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init1( + Index size, + std::enable_if_t<(Base::SizeAtCompileTime != 1 || !internal::is_convertible::value) && + ((!internal::is_same::XprKind, ArrayXpr>::value || + Base::SizeAtCompileTime == Dynamic)), + T>* = 0) { + // NOTE MSVC 2008 complains if we directly put bool(NumTraits::IsInteger) as the EIGEN_STATIC_ASSERT argument. + const bool is_integer_alike = internal::is_valid_index_type::value; + EIGEN_UNUSED_VARIABLE(is_integer_alike); + EIGEN_STATIC_ASSERT(is_integer_alike, FLOATING_POINT_ARGUMENT_PASSED__INTEGER_WAS_EXPECTED) + resize(size); + } - // Initialize a fixed size matrix from a pointer to raw data - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init1(const Scalar* data){ - this->_set_noalias(ConstMapType(data)); - } + // We have a 1x1 matrix/array => the argument is interpreted as the value of the unique coefficient (case where scalar + // type can be implicitly converted) + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init1( + const Scalar& val0, + std::enable_if_t::value, T>* = 0) { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, 1) + m_storage.data()[0] = val0; + } - // Initialize an arbitrary matrix from a dense expression - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init1(const DenseBase& other){ - this->_set_noalias(other); - } + // We have a 1x1 matrix/array => the argument is interpreted as the value of the unique coefficient (case where scalar + // type match the index type) + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init1( + const Index& val0, + std::enable_if_t<(!internal::is_same::value) && (internal::is_same::value) && + Base::SizeAtCompileTime == 1 && internal::is_convertible::value, + T*>* = 0) { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, 1) + m_storage.data()[0] = Scalar(val0); + } - // Initialize an arbitrary matrix from an object convertible to the Derived type. - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init1(const Derived& other){ - this->_set_noalias(other); - } + // Initialize a fixed size matrix from a pointer to raw data + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init1(const Scalar* data) { + this->_set_noalias(ConstMapType(data)); + } - // Initialize an arbitrary matrix from a generic Eigen expression - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init1(const EigenBase& other){ - this->derived() = other; - } + // Initialize an arbitrary matrix from a dense expression + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init1(const DenseBase& other) { + this->_set_noalias(other); + } - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init1(const ReturnByValue& other) - { - resize(other.rows(), other.cols()); - other.evalTo(this->derived()); - } + // Initialize an arbitrary matrix from an object convertible to the Derived type. + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init1(const Derived& other) { + this->_set_noalias(other); + } - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init1(const RotationBase& r) - { - this->derived() = r; - } + // Initialize an arbitrary matrix from a generic Eigen expression + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init1(const EigenBase& other) { + this->derived() = other; + } - // For fixed-size Array - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init1(const Scalar& val0, - typename internal::enable_if< Base::SizeAtCompileTime!=Dynamic - && Base::SizeAtCompileTime!=1 - && internal::is_convertible::value - && internal::is_same::XprKind,ArrayXpr>::value,T>::type* = 0) - { - Base::setConstant(val0); - } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init1(const ReturnByValue& other) { + resize(other.rows(), other.cols()); + other.evalTo(this->derived()); + } - // For fixed-size Array - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _init1(const Index& val0, - typename internal::enable_if< (!internal::is_same::value) - && (internal::is_same::value) - && Base::SizeAtCompileTime!=Dynamic - && Base::SizeAtCompileTime!=1 - && internal::is_convertible::value - && internal::is_same::XprKind,ArrayXpr>::value,T*>::type* = 0) - { - Base::setConstant(val0); - } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init1(const RotationBase& r) { + this->derived() = r; + } - template - friend struct internal::matrix_swap_impl; + // For fixed-size Array + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init1( + const Scalar& val0, + std::enable_if_t::value && + internal::is_same::XprKind, ArrayXpr>::value, + T>* = 0) { + Base::setConstant(val0); + } - public: + // For fixed-size Array + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _init1( + const Index& val0, + std::enable_if_t<(!internal::is_same::value) && (internal::is_same::value) && + Base::SizeAtCompileTime != Dynamic && Base::SizeAtCompileTime != 1 && + internal::is_convertible::value && + internal::is_same::XprKind, ArrayXpr>::value, + T*>* = 0) { + Base::setConstant(val0); + } -#ifndef EIGEN_PARSED_BY_DOXYGEN - /** \internal - * \brief Override DenseBase::swap() since for dynamic-sized matrices - * of same type it is enough to swap the data pointers. - */ - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void swap(DenseBase & other) - { - enum { SwapPointers = internal::is_same::value && Base::SizeAtCompileTime==Dynamic }; - internal::matrix_swap_impl::run(this->derived(), other.derived()); - } + template + friend struct internal::matrix_swap_impl; - /** \internal - * \brief const version forwarded to DenseBase::swap - */ - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void swap(DenseBase const & other) - { Base::swap(other.derived()); } + public: +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** \internal + * \brief Override DenseBase::swap() since for dynamic-sized matrices + * of same type it is enough to swap the data pointers. + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void swap(DenseBase& other) { + enum {SwapPointers = internal::is_same::value && Base::SizeAtCompileTime == Dynamic}; + internal::matrix_swap_impl::run(this->derived(), other.derived()); + } - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE void _check_template_params() - { - EIGEN_STATIC_ASSERT((EIGEN_IMPLIES(MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1, (int(Options)&RowMajor)==RowMajor) - && EIGEN_IMPLIES(MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1, (int(Options)&RowMajor)==0) - && ((RowsAtCompileTime == Dynamic) || (RowsAtCompileTime >= 0)) - && ((ColsAtCompileTime == Dynamic) || (ColsAtCompileTime >= 0)) - && ((MaxRowsAtCompileTime == Dynamic) || (MaxRowsAtCompileTime >= 0)) - && ((MaxColsAtCompileTime == Dynamic) || (MaxColsAtCompileTime >= 0)) - && (MaxRowsAtCompileTime == RowsAtCompileTime || RowsAtCompileTime==Dynamic) - && (MaxColsAtCompileTime == ColsAtCompileTime || ColsAtCompileTime==Dynamic) - && (Options & (DontAlign|RowMajor)) == Options), - INVALID_MATRIX_TEMPLATE_PARAMETERS) - } + /** \internal + * \brief const version forwarded to DenseBase::swap + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void swap(DenseBase const& other) { + Base::swap(other.derived()); + } - enum { IsPlainObjectBase = 1 }; + enum {IsPlainObjectBase = 1}; #endif - public: - // These apparently need to be down here for nvcc+icc to prevent duplicate - // Map symbol. - template friend class Eigen::Map; - friend class Eigen::Map; - friend class Eigen::Map; -#if EIGEN_MAX_ALIGN_BYTES>0 - // for EIGEN_MAX_ALIGN_BYTES==0, AlignedMax==Unaligned, and many compilers generate warnings for friend-ing a class twice. - friend class Eigen::Map; - friend class Eigen::Map; + public: + // These apparently need to be down here for nvcc+icc to prevent duplicate + // Map symbol. + template + friend class Eigen::Map; + friend class Eigen::Map; + friend class Eigen::Map; +#if EIGEN_MAX_ALIGN_BYTES > 0 + // for EIGEN_MAX_ALIGN_BYTES==0, AlignedMax==Unaligned, and many compilers generate warnings for friend-ing a class + // twice. + friend class Eigen::Map; + friend class Eigen::Map; #endif }; namespace internal { template -struct conservative_resize_like_impl -{ - #if EIGEN_HAS_TYPE_TRAITS - static const bool IsRelocatable = std::is_trivially_copyable::value; - #else - static const bool IsRelocatable = !NumTraits::RequireInitialization; - #endif - static void run(DenseBase& _this, Index rows, Index cols) - { +struct conservative_resize_like_impl { + static constexpr bool IsRelocatable = std::is_trivially_copyable::value; + static void run(DenseBase& _this, Index rows, Index cols) { if (_this.rows() == rows && _this.cols() == cols) return; EIGEN_STATIC_ASSERT_DYNAMIC_SIZE(Derived) - if ( IsRelocatable - && (( Derived::IsRowMajor && _this.cols() == cols) || // row-major and we change only the number of rows - (!Derived::IsRowMajor && _this.rows() == rows) )) // column-major and we change only the number of columns - { - internal::check_rows_cols_for_overflow::run(rows, cols); - _this.derived().m_storage.conservativeResize(rows*cols,rows,cols); - } - else + if (IsRelocatable && + ((Derived::IsRowMajor && _this.cols() == cols) || // row-major and we change only the number of rows + (!Derived::IsRowMajor && _this.rows() == rows))) // column-major and we change only the number of columns { +#ifndef EIGEN_NO_DEBUG + internal::check_rows_cols_for_overflow::run(rows, cols); +#endif + _this.derived().m_storage.conservativeResize(rows * cols, rows, cols); + } else { // The storage order does not allow us to use reallocation. - Derived tmp(rows,cols); + Derived tmp(rows, cols); const Index common_rows = numext::mini(rows, _this.rows()); const Index common_cols = numext::mini(cols, _this.cols()); - tmp.block(0,0,common_rows,common_cols) = _this.block(0,0,common_rows,common_cols); + tmp.block(0, 0, common_rows, common_cols) = _this.block(0, 0, common_rows, common_cols); _this.derived().swap(tmp); } } - static void run(DenseBase& _this, const DenseBase& other) - { + static void run(DenseBase& _this, const DenseBase& other) { if (_this.rows() == other.rows() && _this.cols() == other.cols()) return; // Note: Here is space for improvement. Basically, for conservativeResize(Index,Index), @@ -1039,25 +976,24 @@ struct conservative_resize_like_impl EIGEN_STATIC_ASSERT_DYNAMIC_SIZE(Derived) EIGEN_STATIC_ASSERT_DYNAMIC_SIZE(OtherDerived) - if ( IsRelocatable && - (( Derived::IsRowMajor && _this.cols() == other.cols()) || // row-major and we change only the number of rows - (!Derived::IsRowMajor && _this.rows() == other.rows()) )) // column-major and we change only the number of columns + if (IsRelocatable && + ((Derived::IsRowMajor && _this.cols() == other.cols()) || // row-major and we change only the number of rows + (!Derived::IsRowMajor && + _this.rows() == other.rows()))) // column-major and we change only the number of columns { const Index new_rows = other.rows() - _this.rows(); const Index new_cols = other.cols() - _this.cols(); - _this.derived().m_storage.conservativeResize(other.size(),other.rows(),other.cols()); - if (new_rows>0) + _this.derived().m_storage.conservativeResize(other.size(), other.rows(), other.cols()); + if (new_rows > 0) _this.bottomRightCorner(new_rows, other.cols()) = other.bottomRows(new_rows); - else if (new_cols>0) + else if (new_cols > 0) _this.bottomRightCorner(other.rows(), new_cols) = other.rightCols(new_cols); - } - else - { + } else { // The storage order does not allow us to use reallocation. Derived tmp(other); const Index common_rows = numext::mini(tmp.rows(), _this.rows()); const Index common_cols = numext::mini(tmp.cols(), _this.cols()); - tmp.block(0,0,common_rows,common_cols) = _this.block(0,0,common_rows,common_cols); + tmp.block(0, 0, common_rows, common_cols) = _this.block(0, 0, common_rows, common_cols); _this.derived().swap(tmp); } } @@ -1066,63 +1002,51 @@ struct conservative_resize_like_impl // Here, the specialization for vectors inherits from the general matrix case // to allow calling .conservativeResize(rows,cols) on vectors. template -struct conservative_resize_like_impl - : conservative_resize_like_impl -{ - typedef conservative_resize_like_impl Base; - using Base::run; +struct conservative_resize_like_impl + : conservative_resize_like_impl { + typedef conservative_resize_like_impl Base; using Base::IsRelocatable; + using Base::run; - static void run(DenseBase& _this, Index size) - { - const Index new_rows = Derived::RowsAtCompileTime==1 ? 1 : size; - const Index new_cols = Derived::RowsAtCompileTime==1 ? size : 1; - if(IsRelocatable) - _this.derived().m_storage.conservativeResize(size,new_rows,new_cols); + static void run(DenseBase& _this, Index size) { + const Index new_rows = Derived::RowsAtCompileTime == 1 ? 1 : size; + const Index new_cols = Derived::RowsAtCompileTime == 1 ? size : 1; + if (IsRelocatable) + _this.derived().m_storage.conservativeResize(size, new_rows, new_cols); else Base::run(_this.derived(), new_rows, new_cols); } - static void run(DenseBase& _this, const DenseBase& other) - { + static void run(DenseBase& _this, const DenseBase& other) { if (_this.rows() == other.rows() && _this.cols() == other.cols()) return; const Index num_new_elements = other.size() - _this.size(); - const Index new_rows = Derived::RowsAtCompileTime==1 ? 1 : other.rows(); - const Index new_cols = Derived::RowsAtCompileTime==1 ? other.cols() : 1; - if(IsRelocatable) - _this.derived().m_storage.conservativeResize(other.size(),new_rows,new_cols); + const Index new_rows = Derived::RowsAtCompileTime == 1 ? 1 : other.rows(); + const Index new_cols = Derived::RowsAtCompileTime == 1 ? other.cols() : 1; + if (IsRelocatable) + _this.derived().m_storage.conservativeResize(other.size(), new_rows, new_cols); else Base::run(_this.derived(), new_rows, new_cols); - if (num_new_elements > 0) - _this.tail(num_new_elements) = other.tail(num_new_elements); + if (num_new_elements > 0) _this.tail(num_new_elements) = other.tail(num_new_elements); } }; -template -struct matrix_swap_impl -{ - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE void run(MatrixTypeA& a, MatrixTypeB& b) - { - a.base().swap(b); - } +template +struct matrix_swap_impl { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(MatrixTypeA& a, MatrixTypeB& b) { a.base().swap(b); } }; -template -struct matrix_swap_impl -{ - EIGEN_DEVICE_FUNC - static inline void run(MatrixTypeA& a, MatrixTypeB& b) - { +template +struct matrix_swap_impl { + EIGEN_DEVICE_FUNC static inline void run(MatrixTypeA& a, MatrixTypeB& b) { static_cast(a).m_storage.swap(static_cast(b).m_storage); } }; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_DENSESTORAGEBASE_H +#endif // EIGEN_DENSESTORAGEBASE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Product.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Product.h index 70a6c106396..37683e3c272 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Product.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Product.h @@ -10,182 +10,298 @@ #ifndef EIGEN_PRODUCT_H #define EIGEN_PRODUCT_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { -template class ProductImpl; +template +class ProductImpl; namespace internal { -template -struct traits > -{ - typedef typename remove_all::type LhsCleaned; - typedef typename remove_all::type RhsCleaned; +template +struct traits> { + typedef remove_all_t LhsCleaned; + typedef remove_all_t RhsCleaned; typedef traits LhsTraits; typedef traits RhsTraits; typedef MatrixXpr XprKind; - typedef typename ScalarBinaryOpTraits::Scalar, typename traits::Scalar>::ReturnType Scalar; - typedef typename product_promote_storage_type::ret>::ret StorageKind; - typedef typename promote_index_type::type StorageIndex; + typedef typename ScalarBinaryOpTraits::Scalar, + typename traits::Scalar>::ReturnType Scalar; + typedef typename product_promote_storage_type::ret>::ret StorageKind; + typedef typename promote_index_type::type + StorageIndex; enum { - RowsAtCompileTime = LhsTraits::RowsAtCompileTime, - ColsAtCompileTime = RhsTraits::ColsAtCompileTime, + RowsAtCompileTime = LhsTraits::RowsAtCompileTime, + ColsAtCompileTime = RhsTraits::ColsAtCompileTime, MaxRowsAtCompileTime = LhsTraits::MaxRowsAtCompileTime, MaxColsAtCompileTime = RhsTraits::MaxColsAtCompileTime, // FIXME: only needed by GeneralMatrixMatrixTriangular - InnerSize = EIGEN_SIZE_MIN_PREFER_FIXED(LhsTraits::ColsAtCompileTime, RhsTraits::RowsAtCompileTime), + InnerSize = min_size_prefer_fixed(LhsTraits::ColsAtCompileTime, RhsTraits::RowsAtCompileTime), // The storage order is somewhat arbitrary here. The correct one will be determined through the evaluator. - Flags = (MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1) ? RowMajorBit - : (MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1) ? 0 - : ( ((LhsTraits::Flags&NoPreferredStorageOrderBit) && (RhsTraits::Flags&RowMajorBit)) - || ((RhsTraits::Flags&NoPreferredStorageOrderBit) && (LhsTraits::Flags&RowMajorBit)) ) ? RowMajorBit - : NoPreferredStorageOrderBit + Flags = (MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1) ? RowMajorBit + : (MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1) ? 0 + : (((LhsTraits::Flags & NoPreferredStorageOrderBit) && (RhsTraits::Flags & RowMajorBit)) || + ((RhsTraits::Flags & NoPreferredStorageOrderBit) && (LhsTraits::Flags & RowMajorBit))) + ? RowMajorBit + : NoPreferredStorageOrderBit + }; +}; + +struct TransposeProductEnum { + // convenience enumerations to specialize transposed products + enum : int { + Default = 0x00, + Matrix = 0x01, + Permutation = 0x02, + MatrixMatrix = (Matrix << 8) | Matrix, + MatrixPermutation = (Matrix << 8) | Permutation, + PermutationMatrix = (Permutation << 8) | Matrix }; }; +template +struct TransposeKind { + static constexpr int Kind = is_matrix_base_xpr::value ? TransposeProductEnum::Matrix + : is_permutation_base_xpr::value ? TransposeProductEnum::Permutation + : TransposeProductEnum::Default; +}; + +template +struct TransposeProductKind { + static constexpr int Kind = (TransposeKind::Kind << 8) | TransposeKind::Kind; +}; + +template ::Kind> +struct product_transpose_helper { + // by default, don't optimize the transposed product + using Derived = Product; + using Scalar = typename Derived::Scalar; + using TransposeType = Transpose; + using ConjugateTransposeType = CwiseUnaryOp, TransposeType>; + using AdjointType = std::conditional_t::IsComplex, ConjugateTransposeType, TransposeType>; + + // return (lhs * rhs)^T + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TransposeType run_transpose(const Derived& derived) { + return TransposeType(derived); + } + // return (lhs * rhs)^H + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE AdjointType run_adjoint(const Derived& derived) { + return AdjointType(TransposeType(derived)); + } +}; + +template +struct product_transpose_helper { + // expand the transposed matrix-matrix product + using Derived = Product; + + using LhsScalar = typename traits::Scalar; + using LhsTransposeType = typename DenseBase::ConstTransposeReturnType; + using LhsConjugateTransposeType = CwiseUnaryOp, LhsTransposeType>; + using LhsAdjointType = + std::conditional_t::IsComplex, LhsConjugateTransposeType, LhsTransposeType>; + + using RhsScalar = typename traits::Scalar; + using RhsTransposeType = typename DenseBase::ConstTransposeReturnType; + using RhsConjugateTransposeType = CwiseUnaryOp, RhsTransposeType>; + using RhsAdjointType = + std::conditional_t::IsComplex, RhsConjugateTransposeType, RhsTransposeType>; + + using TransposeType = Product; + using AdjointType = Product; + + // return rhs^T * lhs^T + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TransposeType run_transpose(const Derived& derived) { + return TransposeType(RhsTransposeType(derived.rhs()), LhsTransposeType(derived.lhs())); + } + // return rhs^H * lhs^H + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE AdjointType run_adjoint(const Derived& derived) { + return AdjointType(RhsAdjointType(RhsTransposeType(derived.rhs())), + LhsAdjointType(LhsTransposeType(derived.lhs()))); + } +}; +template +struct product_transpose_helper { + // expand the transposed permutation-matrix product + using Derived = Product; + + using LhsInverseType = typename PermutationBase::InverseReturnType; + + using RhsScalar = typename traits::Scalar; + using RhsTransposeType = typename DenseBase::ConstTransposeReturnType; + using RhsConjugateTransposeType = CwiseUnaryOp, RhsTransposeType>; + using RhsAdjointType = + std::conditional_t::IsComplex, RhsConjugateTransposeType, RhsTransposeType>; + + using TransposeType = Product; + using AdjointType = Product; + + // return rhs^T * lhs^-1 + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TransposeType run_transpose(const Derived& derived) { + return TransposeType(RhsTransposeType(derived.rhs()), LhsInverseType(derived.lhs())); + } + // return rhs^H * lhs^-1 + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE AdjointType run_adjoint(const Derived& derived) { + return AdjointType(RhsAdjointType(RhsTransposeType(derived.rhs())), LhsInverseType(derived.lhs())); + } +}; +template +struct product_transpose_helper { + // expand the transposed matrix-permutation product + using Derived = Product; + + using LhsScalar = typename traits::Scalar; + using LhsTransposeType = typename DenseBase::ConstTransposeReturnType; + using LhsConjugateTransposeType = CwiseUnaryOp, LhsTransposeType>; + using LhsAdjointType = + std::conditional_t::IsComplex, LhsConjugateTransposeType, LhsTransposeType>; -} // end namespace internal + using RhsInverseType = typename PermutationBase::InverseReturnType; + + using TransposeType = Product; + using AdjointType = Product; + + // return rhs^-1 * lhs^T + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TransposeType run_transpose(const Derived& derived) { + return TransposeType(RhsInverseType(derived.rhs()), LhsTransposeType(derived.lhs())); + } + // return rhs^-1 * lhs^H + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE AdjointType run_adjoint(const Derived& derived) { + return AdjointType(RhsInverseType(derived.rhs()), LhsAdjointType(LhsTransposeType(derived.lhs()))); + } +}; + +} // end namespace internal /** \class Product - * \ingroup Core_Module - * - * \brief Expression of the product of two arbitrary matrices or vectors - * - * \tparam _Lhs the type of the left-hand side expression - * \tparam _Rhs the type of the right-hand side expression - * - * This class represents an expression of the product of two arbitrary matrices. - * - * The other template parameters are: - * \tparam Option can be DefaultProduct, AliasFreeProduct, or LazyProduct - * - */ -template -class Product : public ProductImpl<_Lhs,_Rhs,Option, - typename internal::product_promote_storage_type::StorageKind, - typename internal::traits<_Rhs>::StorageKind, - internal::product_type<_Lhs,_Rhs>::ret>::ret> -{ - public: - - typedef _Lhs Lhs; - typedef _Rhs Rhs; - - typedef typename ProductImpl< - Lhs, Rhs, Option, - typename internal::product_promote_storage_type::StorageKind, - typename internal::traits::StorageKind, - internal::product_type::ret>::ret>::Base Base; - EIGEN_GENERIC_PUBLIC_INTERFACE(Product) - - typedef typename internal::ref_selector::type LhsNested; - typedef typename internal::ref_selector::type RhsNested; - typedef typename internal::remove_all::type LhsNestedCleaned; - typedef typename internal::remove_all::type RhsNestedCleaned; - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Product(const Lhs& lhs, const Rhs& rhs) : m_lhs(lhs), m_rhs(rhs) - { - eigen_assert(lhs.cols() == rhs.rows() - && "invalid matrix product" - && "if you wanted a coeff-wise or a dot product use the respective explicit functions"); - } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index rows() const EIGEN_NOEXCEPT { return m_lhs.rows(); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index cols() const EIGEN_NOEXCEPT { return m_rhs.cols(); } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const LhsNestedCleaned& lhs() const { return m_lhs; } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const RhsNestedCleaned& rhs() const { return m_rhs; } - - protected: - - LhsNested m_lhs; - RhsNested m_rhs; + * \ingroup Core_Module + * + * \brief Expression of the product of two arbitrary matrices or vectors + * + * \tparam Lhs_ the type of the left-hand side expression + * \tparam Rhs_ the type of the right-hand side expression + * + * This class represents an expression of the product of two arbitrary matrices. + * + * The other template parameters are: + * \tparam Option can be DefaultProduct, AliasFreeProduct, or LazyProduct + * + */ +template +class Product + : public ProductImpl::StorageKind, typename internal::traits::StorageKind, + internal::product_type::ret>::ret> { + public: + typedef Lhs_ Lhs; + typedef Rhs_ Rhs; + + typedef + typename ProductImpl::StorageKind, typename internal::traits::StorageKind, + internal::product_type::ret>::ret>::Base Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(Product) + + typedef typename internal::ref_selector::type LhsNested; + typedef typename internal::ref_selector::type RhsNested; + typedef internal::remove_all_t LhsNestedCleaned; + typedef internal::remove_all_t RhsNestedCleaned; + + using TransposeReturnType = typename internal::product_transpose_helper::TransposeType; + using AdjointReturnType = typename internal::product_transpose_helper::AdjointType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Product(const Lhs& lhs, const Rhs& rhs) : m_lhs(lhs), m_rhs(rhs) { + eigen_assert(lhs.cols() == rhs.rows() && "invalid matrix product" && + "if you wanted a coeff-wise or a dot product use the respective explicit functions"); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_lhs.rows(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_rhs.cols(); } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const LhsNestedCleaned& lhs() const { return m_lhs; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const RhsNestedCleaned& rhs() const { return m_rhs; } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TransposeReturnType transpose() const { + return internal::product_transpose_helper::run_transpose(*this); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE AdjointReturnType adjoint() const { + return internal::product_transpose_helper::run_adjoint(*this); + } + + protected: + LhsNested m_lhs; + RhsNested m_rhs; }; namespace internal { -template::ret> -class dense_product_base - : public internal::dense_xpr_base >::type -{}; +template ::ret> +class dense_product_base : public internal::dense_xpr_base>::type {}; /** Conversion to scalar for inner-products */ -template +template class dense_product_base - : public internal::dense_xpr_base >::type -{ - typedef Product ProductXpr; + : public internal::dense_xpr_base>::type { + typedef Product ProductXpr; typedef typename internal::dense_xpr_base::type Base; -public: + + public: using Base::derived; typedef typename Base::Scalar Scalar; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE operator const Scalar() const - { - return internal::evaluator(derived()).coeff(0,0); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE operator const Scalar() const { + return internal::evaluator(derived()).coeff(0, 0); } }; -} // namespace internal +} // namespace internal // Generic API dispatcher -template -class ProductImpl : public internal::generic_xpr_base, MatrixXpr, StorageKind>::type -{ - public: - typedef typename internal::generic_xpr_base, MatrixXpr, StorageKind>::type Base; +template +class ProductImpl : public internal::generic_xpr_base, MatrixXpr, StorageKind>::type { + public: + typedef typename internal::generic_xpr_base, MatrixXpr, StorageKind>::type Base; }; -template -class ProductImpl - : public internal::dense_product_base -{ - typedef Product Derived; - - public: - - typedef typename internal::dense_product_base Base; - EIGEN_DENSE_PUBLIC_INTERFACE(Derived) - protected: - enum { - IsOneByOne = (RowsAtCompileTime == 1 || RowsAtCompileTime == Dynamic) && - (ColsAtCompileTime == 1 || ColsAtCompileTime == Dynamic), - EnableCoeff = IsOneByOne || Option==LazyProduct - }; - - public: +template +class ProductImpl : public internal::dense_product_base { + typedef Product Derived; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar coeff(Index row, Index col) const - { - EIGEN_STATIC_ASSERT(EnableCoeff, THIS_METHOD_IS_ONLY_FOR_INNER_OR_LAZY_PRODUCTS); - eigen_assert( (Option==LazyProduct) || (this->rows() == 1 && this->cols() == 1) ); - - return internal::evaluator(derived()).coeff(row,col); - } + public: + typedef typename internal::dense_product_base Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Derived) + protected: + enum { + IsOneByOne = (RowsAtCompileTime == 1 || RowsAtCompileTime == Dynamic) && + (ColsAtCompileTime == 1 || ColsAtCompileTime == Dynamic), + EnableCoeff = IsOneByOne || Option == LazyProduct + }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar coeff(Index i) const - { - EIGEN_STATIC_ASSERT(EnableCoeff, THIS_METHOD_IS_ONLY_FOR_INNER_OR_LAZY_PRODUCTS); - eigen_assert( (Option==LazyProduct) || (this->rows() == 1 && this->cols() == 1) ); + public: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar coeff(Index row, Index col) const { + EIGEN_STATIC_ASSERT(EnableCoeff, THIS_METHOD_IS_ONLY_FOR_INNER_OR_LAZY_PRODUCTS); + eigen_assert((Option == LazyProduct) || (this->rows() == 1 && this->cols() == 1)); - return internal::evaluator(derived()).coeff(i); - } + return internal::evaluator(derived()).coeff(row, col); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar coeff(Index i) const { + EIGEN_STATIC_ASSERT(EnableCoeff, THIS_METHOD_IS_ONLY_FOR_INNER_OR_LAZY_PRODUCTS); + eigen_assert((Option == LazyProduct) || (this->rows() == 1 && this->cols() == 1)); + return internal::evaluator(derived()).coeff(i); + } }; -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_PRODUCT_H +#endif // EIGEN_PRODUCT_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ProductEvaluators.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ProductEvaluators.h index 8cf294b287b..19c25604d56 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ProductEvaluators.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ProductEvaluators.h @@ -9,26 +9,26 @@ // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. - #ifndef EIGEN_PRODUCTEVALUATORS_H #define EIGEN_PRODUCTEVALUATORS_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { /** \internal - * Evaluator of a product expression. - * Since products require special treatments to handle all possible cases, - * we simply defer the evaluation logic to a product_evaluator class - * which offers more partial specialization possibilities. - * - * \sa class product_evaluator - */ -template -struct evaluator > - : public product_evaluator > -{ + * Evaluator of a product expression. + * Since products require special treatments to handle all possible cases, + * we simply defer the evaluation logic to a product_evaluator class + * which offers more partial specialization possibilities. + * + * \sa class product_evaluator + */ +template +struct evaluator> : public product_evaluator> { typedef Product XprType; typedef product_evaluator Base; @@ -37,94 +37,82 @@ struct evaluator > // Catch "scalar * ( A * B )" and transform it to "(A*scalar) * B" // TODO we should apply that rule only if that's really helpful -template -struct evaluator_assume_aliasing, +template +struct evaluator_assume_aliasing, const CwiseNullaryOp, Plain1>, - const Product > > -{ + const Product>> { static const bool value = true; }; -template -struct evaluator, - const CwiseNullaryOp, Plain1>, - const Product > > - : public evaluator > -{ - typedef CwiseBinaryOp, +template +struct evaluator, const CwiseNullaryOp, Plain1>, - const Product > XprType; - typedef evaluator > Base; + const Product>> + : public evaluator> { + typedef CwiseBinaryOp, + const CwiseNullaryOp, Plain1>, + const Product> + XprType; + typedef evaluator> Base; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const XprType& xpr) - : Base(xpr.lhs().functor().m_other * xpr.rhs().lhs() * xpr.rhs().rhs()) - {} + : Base(xpr.lhs().functor().m_other * xpr.rhs().lhs() * xpr.rhs().rhs()) {} }; - -template -struct evaluator, DiagIndex> > - : public evaluator, DiagIndex> > -{ +template +struct evaluator, DiagIndex>> + : public evaluator, DiagIndex>> { typedef Diagonal, DiagIndex> XprType; - typedef evaluator, DiagIndex> > Base; + typedef evaluator, DiagIndex>> Base; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const XprType& xpr) - : Base(Diagonal, DiagIndex>( - Product(xpr.nestedExpression().lhs(), xpr.nestedExpression().rhs()), - xpr.index() )) - {} + : Base(Diagonal, DiagIndex>( + Product(xpr.nestedExpression().lhs(), xpr.nestedExpression().rhs()), xpr.index())) {} }; - // Helper class to perform a matrix product with the destination at hand. // Depending on the sizes of the factors, there are different evaluation strategies // as controlled by internal::product_type. -template< typename Lhs, typename Rhs, - typename LhsShape = typename evaluator_traits::Shape, +template ::Shape, typename RhsShape = typename evaluator_traits::Shape, - int ProductType = internal::product_type::value> + int ProductType = internal::product_type::value> struct generic_product_impl; -template -struct evaluator_assume_aliasing > { +template +struct evaluator_assume_aliasing> { static const bool value = true; }; // This is the default evaluator implementation for products: // It creates a temporary and call generic_product_impl -template +template struct product_evaluator, ProductTag, LhsShape, RhsShape> - : public evaluator::PlainObject> -{ + : public evaluator::PlainObject> { typedef Product XprType; typedef typename XprType::PlainObject PlainObject; typedef evaluator Base; - enum { - Flags = Base::Flags | EvalBeforeNestingBit - }; - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit product_evaluator(const XprType& xpr) - : m_result(xpr.rows(), xpr.cols()) - { - ::new (static_cast(this)) Base(m_result); - -// FIXME shall we handle nested_eval here?, -// if so, then we must take care at removing the call to nested_eval in the specializations (e.g., in permutation_matrix_product, transposition_matrix_product, etc.) -// typedef typename internal::nested_eval::type LhsNested; -// typedef typename internal::nested_eval::type RhsNested; -// typedef typename internal::remove_all::type LhsNestedCleaned; -// typedef typename internal::remove_all::type RhsNestedCleaned; -// -// const LhsNested lhs(xpr.lhs()); -// const RhsNested rhs(xpr.rhs()); -// -// generic_product_impl::evalTo(m_result, lhs, rhs); + enum { Flags = Base::Flags | EvalBeforeNestingBit }; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit product_evaluator(const XprType& xpr) + : m_result(xpr.rows(), xpr.cols()) { + internal::construct_at(this, m_result); + + // FIXME shall we handle nested_eval here?, + // if so, then we must take care at removing the call to nested_eval in the specializations (e.g., in + // permutation_matrix_product, transposition_matrix_product, etc.) + // typedef typename internal::nested_eval::type LhsNested; + // typedef typename internal::nested_eval::type RhsNested; + // typedef internal::remove_all_t LhsNestedCleaned; + // typedef internal::remove_all_t RhsNestedCleaned; + // + // const LhsNested lhs(xpr.lhs()); + // const RhsNested rhs(xpr.rhs()); + // + // generic_product_impl::evalTo(m_result, lhs, rhs); generic_product_impl::evalTo(m_result, xpr.lhs(), xpr.rhs()); } -protected: + protected: PlainObject m_result; }; @@ -132,32 +120,27 @@ struct product_evaluator, ProductTag, LhsShape, RhsSh // TODO: we could enable them for different scalar types when the product is not vectorized. // Dense = Product -template< typename DstXprType, typename Lhs, typename Rhs, int Options, typename Scalar> -struct Assignment, internal::assign_op, Dense2Dense, - typename enable_if<(Options==DefaultProduct || Options==AliasFreeProduct)>::type> -{ - typedef Product SrcXprType; - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &) - { +template +struct Assignment, internal::assign_op, Dense2Dense, + std::enable_if_t<(Options == DefaultProduct || Options == AliasFreeProduct)>> { + typedef Product SrcXprType; + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(DstXprType& dst, const SrcXprType& src, + const internal::assign_op&) { Index dstRows = src.rows(); Index dstCols = src.cols(); - if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) - dst.resize(dstRows, dstCols); + if ((dst.rows() != dstRows) || (dst.cols() != dstCols)) dst.resize(dstRows, dstCols); // FIXME shall we handle nested_eval here? generic_product_impl::evalTo(dst, src.lhs(), src.rhs()); } }; // Dense += Product -template< typename DstXprType, typename Lhs, typename Rhs, int Options, typename Scalar> -struct Assignment, internal::add_assign_op, Dense2Dense, - typename enable_if<(Options==DefaultProduct || Options==AliasFreeProduct)>::type> -{ - typedef Product SrcXprType; - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void run(DstXprType &dst, const SrcXprType &src, const internal::add_assign_op &) - { +template +struct Assignment, internal::add_assign_op, Dense2Dense, + std::enable_if_t<(Options == DefaultProduct || Options == AliasFreeProduct)>> { + typedef Product SrcXprType; + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(DstXprType& dst, const SrcXprType& src, + const internal::add_assign_op&) { eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); // FIXME shall we handle nested_eval here? generic_product_impl::addTo(dst, src.lhs(), src.rhs()); @@ -165,35 +148,35 @@ struct Assignment, internal::add_assign_op< }; // Dense -= Product -template< typename DstXprType, typename Lhs, typename Rhs, int Options, typename Scalar> -struct Assignment, internal::sub_assign_op, Dense2Dense, - typename enable_if<(Options==DefaultProduct || Options==AliasFreeProduct)>::type> -{ - typedef Product SrcXprType; - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void run(DstXprType &dst, const SrcXprType &src, const internal::sub_assign_op &) - { +template +struct Assignment, internal::sub_assign_op, Dense2Dense, + std::enable_if_t<(Options == DefaultProduct || Options == AliasFreeProduct)>> { + typedef Product SrcXprType; + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(DstXprType& dst, const SrcXprType& src, + const internal::sub_assign_op&) { eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); // FIXME shall we handle nested_eval here? generic_product_impl::subTo(dst, src.lhs(), src.rhs()); } }; - // Dense ?= scalar * Product // TODO we should apply that rule if that's really helpful // for instance, this is not good for inner products -template< typename DstXprType, typename Lhs, typename Rhs, typename AssignFunc, typename Scalar, typename ScalarBis, typename Plain> -struct Assignment, const CwiseNullaryOp,Plain>, - const Product >, AssignFunc, Dense2Dense> -{ - typedef CwiseBinaryOp, - const CwiseNullaryOp,Plain>, - const Product > SrcXprType; - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void run(DstXprType &dst, const SrcXprType &src, const AssignFunc& func) - { - call_assignment_no_alias(dst, (src.lhs().functor().m_other * src.rhs().lhs())*src.rhs().rhs(), func); +template +struct Assignment, + const CwiseNullaryOp, Plain>, + const Product>, + AssignFunc, Dense2Dense> { + typedef CwiseBinaryOp, + const CwiseNullaryOp, Plain>, + const Product> + SrcXprType; + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(DstXprType& dst, const SrcXprType& src, + const AssignFunc& func) { + call_assignment_no_alias(dst, (src.lhs().functor().m_other * src.rhs().lhs()) * src.rhs().rhs(), func); } }; @@ -201,219 +184,232 @@ struct Assignment" expression to save one temporary // FIXME we could probably enable these rules for any product, i.e., not only Dense and DefaultProduct -template -struct evaluator_assume_aliasing::Scalar>, const OtherXpr, - const Product >, DenseShape > { +template +struct evaluator_assume_aliasing< + CwiseBinaryOp< + internal::scalar_sum_op::Scalar>, + const OtherXpr, const Product>, + DenseShape> { static const bool value = true; }; -template -struct evaluator_assume_aliasing::Scalar>, const OtherXpr, - const Product >, DenseShape > { +template +struct evaluator_assume_aliasing< + CwiseBinaryOp< + internal::scalar_difference_op::Scalar>, + const OtherXpr, const Product>, + DenseShape> { static const bool value = true; }; -template -struct assignment_from_xpr_op_product -{ - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void run(DstXprType &dst, const SrcXprType &src, const InitialFunc& /*func*/) - { +template +struct assignment_from_xpr_op_product { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(DstXprType& dst, const SrcXprType& src, + const InitialFunc& /*func*/) { call_assignment_no_alias(dst, src.lhs(), Func1()); call_assignment_no_alias(dst, src.rhs(), Func2()); } }; -#define EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(ASSIGN_OP,BINOP,ASSIGN_OP2) \ - template< typename DstXprType, typename OtherXpr, typename Lhs, typename Rhs, typename DstScalar, typename SrcScalar, typename OtherScalar,typename ProdScalar> \ - struct Assignment, const OtherXpr, \ - const Product >, internal::ASSIGN_OP, Dense2Dense> \ - : assignment_from_xpr_op_product, internal::ASSIGN_OP, internal::ASSIGN_OP2 > \ - {} - -EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(assign_op, scalar_sum_op,add_assign_op); -EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(add_assign_op,scalar_sum_op,add_assign_op); -EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(sub_assign_op,scalar_sum_op,sub_assign_op); - -EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(assign_op, scalar_difference_op,sub_assign_op); -EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(add_assign_op,scalar_difference_op,sub_assign_op); -EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(sub_assign_op,scalar_difference_op,add_assign_op); +#define EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(ASSIGN_OP, BINOP, ASSIGN_OP2) \ + template \ + struct Assignment, const OtherXpr, \ + const Product>, \ + internal::ASSIGN_OP, Dense2Dense> \ + : assignment_from_xpr_op_product, \ + internal::ASSIGN_OP, \ + internal::ASSIGN_OP2> {} + +EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(assign_op, scalar_sum_op, add_assign_op); +EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(add_assign_op, scalar_sum_op, add_assign_op); +EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(sub_assign_op, scalar_sum_op, sub_assign_op); + +EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(assign_op, scalar_difference_op, sub_assign_op); +EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(add_assign_op, scalar_difference_op, sub_assign_op); +EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(sub_assign_op, scalar_difference_op, add_assign_op); //---------------------------------------- -template -struct generic_product_impl -{ - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) - { - dst.coeffRef(0,0) = (lhs.transpose().cwiseProduct(rhs)).sum(); +template +struct generic_product_impl { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { + dst.coeffRef(0, 0) = (lhs.transpose().cwiseProduct(rhs)).sum(); } - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) - { - dst.coeffRef(0,0) += (lhs.transpose().cwiseProduct(rhs)).sum(); + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { + dst.coeffRef(0, 0) += (lhs.transpose().cwiseProduct(rhs)).sum(); } - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) - { dst.coeffRef(0,0) -= (lhs.transpose().cwiseProduct(rhs)).sum(); } + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { + dst.coeffRef(0, 0) -= (lhs.transpose().cwiseProduct(rhs)).sum(); + } }; - /*********************************************************************** -* Implementation of outer dense * dense vector product -***********************************************************************/ + * Implementation of outer dense * dense vector product + ***********************************************************************/ // Column major result -template -void EIGEN_DEVICE_FUNC outer_product_selector_run(Dst& dst, const Lhs &lhs, const Rhs &rhs, const Func& func, const false_type&) -{ +template +void EIGEN_DEVICE_FUNC outer_product_selector_run(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Func& func, + const false_type&) { evaluator rhsEval(rhs); - ei_declare_local_nested_eval(Lhs,lhs,Rhs::SizeAtCompileTime,actual_lhs); + ei_declare_local_nested_eval(Lhs, lhs, Rhs::SizeAtCompileTime, actual_lhs); // FIXME if cols is large enough, then it might be useful to make sure that lhs is sequentially stored // FIXME not very good if rhs is real and lhs complex while alpha is real too const Index cols = dst.cols(); - for (Index j=0; j -void EIGEN_DEVICE_FUNC outer_product_selector_run(Dst& dst, const Lhs &lhs, const Rhs &rhs, const Func& func, const true_type&) -{ +template +void EIGEN_DEVICE_FUNC outer_product_selector_run(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Func& func, + const true_type&) { evaluator lhsEval(lhs); - ei_declare_local_nested_eval(Rhs,rhs,Lhs::SizeAtCompileTime,actual_rhs); + ei_declare_local_nested_eval(Rhs, rhs, Lhs::SizeAtCompileTime, actual_rhs); // FIXME if rows is large enough, then it might be useful to make sure that rhs is sequentially stored // FIXME not very good if lhs is real and rhs complex while alpha is real too const Index rows = dst.rows(); - for (Index i=0; i -struct generic_product_impl -{ - template struct is_row_major : internal::conditional<(int(T::Flags)&RowMajorBit), internal::true_type, internal::false_type>::type {}; - typedef typename Product::Scalar Scalar; +template +struct generic_product_impl { + template + struct is_row_major : std::conditional_t<(int(T::Flags) & RowMajorBit), internal::true_type, internal::false_type> {}; + typedef typename Product::Scalar Scalar; // TODO it would be nice to be able to exploit our *_assign_op functors for that purpose - struct set { template EIGEN_DEVICE_FUNC void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() = src; } }; - struct add { template EIGEN_DEVICE_FUNC void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() += src; } }; - struct sub { template EIGEN_DEVICE_FUNC void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() -= src; } }; + struct set { + template + EIGEN_DEVICE_FUNC void operator()(const Dst& dst, const Src& src) const { + dst.const_cast_derived() = src; + } + }; + struct add { + template + EIGEN_DEVICE_FUNC void operator()(const Dst& dst, const Src& src) const { + dst.const_cast_derived() += src; + } + }; + struct sub { + template + EIGEN_DEVICE_FUNC void operator()(const Dst& dst, const Src& src) const { + dst.const_cast_derived() -= src; + } + }; struct adds { Scalar m_scale; explicit adds(const Scalar& s) : m_scale(s) {} - template void EIGEN_DEVICE_FUNC operator()(const Dst& dst, const Src& src) const { + template + void EIGEN_DEVICE_FUNC operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() += m_scale * src; } }; - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) - { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { internal::outer_product_selector_run(dst, lhs, rhs, set(), is_row_major()); } - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) - { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { internal::outer_product_selector_run(dst, lhs, rhs, add(), is_row_major()); } - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) - { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { internal::outer_product_selector_run(dst, lhs, rhs, sub(), is_row_major()); } - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) - { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, + const Scalar& alpha) { internal::outer_product_selector_run(dst, lhs, rhs, adds(alpha), is_row_major()); } - }; - // This base class provides default implementations for evalTo, addTo, subTo, in terms of scaleAndAddTo -template -struct generic_product_impl_base -{ - typedef typename Product::Scalar Scalar; - - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) - { dst.setZero(); scaleAndAddTo(dst, lhs, rhs, Scalar(1)); } - - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) - { scaleAndAddTo(dst,lhs, rhs, Scalar(1)); } +template +struct generic_product_impl_base { + typedef typename Product::Scalar Scalar; + + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { + dst.setZero(); + scaleAndAddTo(dst, lhs, rhs, Scalar(1)); + } - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) - { scaleAndAddTo(dst, lhs, rhs, Scalar(-1)); } + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { + scaleAndAddTo(dst, lhs, rhs, Scalar(1)); + } - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) - { Derived::scaleAndAddTo(dst,lhs,rhs,alpha); } + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { + scaleAndAddTo(dst, lhs, rhs, Scalar(-1)); + } + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, + const Scalar& alpha) { + Derived::scaleAndAddTo(dst, lhs, rhs, alpha); + } }; -template -struct generic_product_impl - : generic_product_impl_base > -{ - typedef typename nested_eval::type LhsNested; - typedef typename nested_eval::type RhsNested; - typedef typename Product::Scalar Scalar; +template +struct generic_product_impl + : generic_product_impl_base> { + typedef typename nested_eval::type LhsNested; + typedef typename nested_eval::type RhsNested; + typedef typename Product::Scalar Scalar; enum { Side = Lhs::IsVectorAtCompileTime ? OnTheLeft : OnTheRight }; - typedef typename internal::remove_all::type>::type MatrixType; + typedef internal::remove_all_t> MatrixType; - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) - { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, + const Scalar& alpha) { // Fallback to inner product if both the lhs and rhs is a runtime vector. if (lhs.rows() == 1 && rhs.cols() == 1) { - dst.coeffRef(0,0) += alpha * lhs.row(0).conjugate().dot(rhs.col(0)); + dst.coeffRef(0, 0) += alpha * lhs.row(0).conjugate().dot(rhs.col(0)); return; } LhsNested actual_lhs(lhs); RhsNested actual_rhs(rhs); - internal::gemv_dense_selector::HasUsableDirectAccess) - >::run(actual_lhs, actual_rhs, dst, alpha); + internal::gemv_dense_selector::HasUsableDirectAccess)>::run(actual_lhs, + actual_rhs, dst, + alpha); } }; -template -struct generic_product_impl -{ - typedef typename Product::Scalar Scalar; +template +struct generic_product_impl { + typedef typename Product::Scalar Scalar; - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) - { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { // Same as: dst.noalias() = lhs.lazyProduct(rhs); // but easier on the compiler side - call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::assign_op()); + call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::assign_op()); } - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) - { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { // dst.noalias() += lhs.lazyProduct(rhs); - call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::add_assign_op()); + call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::add_assign_op()); } - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) - { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { // dst.noalias() -= lhs.lazyProduct(rhs); - call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::sub_assign_op()); + call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::sub_assign_op()); } // This is a special evaluation path called from generic_product_impl<...,GemmProduct> in file GeneralMatrixMatrix.h @@ -427,13 +423,12 @@ struct generic_product_impl // 3 - it makes this fallback consistent with the heavy GEMM routine. // 4 - it fully by-passes huge stack allocation attempts when multiplying huge fixed-size matrices. // (see https://stackoverflow.com/questions/54738495) - // For small fixed sizes matrices, howver, the gains are less obvious, it is sometimes x2 faster, but sometimes x3 slower, - // and the behavior depends also a lot on the compiler... This is why this re-writting strategy is currently + // For small fixed sizes matrices, however, the gains are less obvious, it is sometimes x2 faster, but sometimes x3 + // slower, and the behavior depends also a lot on the compiler... This is why this re-writing strategy is currently // enabled only when falling back from the main GEMM. - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void eval_dynamic(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Func &func) - { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void eval_dynamic(Dst& dst, const Lhs& lhs, const Rhs& rhs, + const Func& func) { enum { HasScalarFactor = blas_traits::HasScalarFactor || blas_traits::HasScalarFactor, ConjLhs = blas_traits::NeedToConjugate, @@ -443,37 +438,32 @@ struct generic_product_impl // this is important for real*complex_mat Scalar actualAlpha = combine_scalar_factors(lhs, rhs); - eval_dynamic_impl(dst, - blas_traits::extract(lhs).template conjugateIf(), - blas_traits::extract(rhs).template conjugateIf(), - func, - actualAlpha, - typename conditional::type()); + eval_dynamic_impl(dst, blas_traits::extract(lhs).template conjugateIf(), + blas_traits::extract(rhs).template conjugateIf(), func, actualAlpha, + std::conditional_t()); } -protected: - - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void eval_dynamic_impl(Dst& dst, const LhsT& lhs, const RhsT& rhs, const Func &func, const Scalar& s /* == 1 */, false_type) - { + protected: + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void eval_dynamic_impl(Dst& dst, const LhsT& lhs, const RhsT& rhs, + const Func& func, const Scalar& s /* == 1 */, + false_type) { EIGEN_UNUSED_VARIABLE(s); - eigen_internal_assert(s==Scalar(1)); + eigen_internal_assert(numext::is_exactly_one(s)); call_restricted_packet_assignment_no_alias(dst, lhs.lazyProduct(rhs), func); } - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void eval_dynamic_impl(Dst& dst, const LhsT& lhs, const RhsT& rhs, const Func &func, const Scalar& s, true_type) - { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void eval_dynamic_impl(Dst& dst, const LhsT& lhs, const RhsT& rhs, + const Func& func, const Scalar& s, true_type) { call_restricted_packet_assignment_no_alias(dst, s * lhs.lazyProduct(rhs), func); } }; // This specialization enforces the use of a coefficient-based evaluation strategy -template -struct generic_product_impl - : generic_product_impl {}; +template +struct generic_product_impl + : generic_product_impl {}; // Case 2: Evaluate coeff by coeff // @@ -481,29 +471,27 @@ struct generic_product_impl +template struct etor_product_coeff_impl; -template +template struct etor_product_packet_impl; -template +template struct product_evaluator, ProductTag, DenseShape, DenseShape> - : evaluator_base > -{ + : evaluator_base> { typedef Product XprType; typedef typename XprType::Scalar Scalar; typedef typename XprType::CoeffReturnType CoeffReturnType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit product_evaluator(const XprType& xpr) - : m_lhs(xpr.lhs()), - m_rhs(xpr.rhs()), - m_lhsImpl(m_lhs), // FIXME the creation of the evaluator objects should result in a no-op, but check that! - m_rhsImpl(m_rhs), // Moreover, they are only useful for the packet path, so we could completely disable them when not needed, - // or perhaps declare them on the fly on the packet method... We have experiment to check what's best. - m_innerDim(xpr.lhs().cols()) - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit product_evaluator(const XprType& xpr) + : m_lhs(xpr.lhs()), + m_rhs(xpr.rhs()), + m_lhsImpl(m_lhs), // FIXME the creation of the evaluator objects should result in a no-op, but check that! + m_rhsImpl(m_rhs), // Moreover, they are only useful for the packet path, so we could completely disable + // them when not needed, or perhaps declare them on the fly on the packet method... We + // have experiment to check what's best. + m_innerDim(xpr.lhs().cols()) { EIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits::MulCost); EIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits::AddCost); EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); @@ -523,11 +511,11 @@ struct product_evaluator, ProductTag, DenseShape, // Everything below here is taken from CoeffBasedProduct.h - typedef typename internal::nested_eval::type LhsNested; - typedef typename internal::nested_eval::type RhsNested; + typedef typename internal::nested_eval::type LhsNested; + typedef typename internal::nested_eval::type RhsNested; - typedef typename internal::remove_all::type LhsNestedCleaned; - typedef typename internal::remove_all::type RhsNestedCleaned; + typedef internal::remove_all_t LhsNestedCleaned; + typedef internal::remove_all_t RhsNestedCleaned; typedef evaluator LhsEtorType; typedef evaluator RhsEtorType; @@ -535,22 +523,23 @@ struct product_evaluator, ProductTag, DenseShape, enum { RowsAtCompileTime = LhsNestedCleaned::RowsAtCompileTime, ColsAtCompileTime = RhsNestedCleaned::ColsAtCompileTime, - InnerSize = EIGEN_SIZE_MIN_PREFER_FIXED(LhsNestedCleaned::ColsAtCompileTime, RhsNestedCleaned::RowsAtCompileTime), + InnerSize = min_size_prefer_fixed(LhsNestedCleaned::ColsAtCompileTime, RhsNestedCleaned::RowsAtCompileTime), MaxRowsAtCompileTime = LhsNestedCleaned::MaxRowsAtCompileTime, MaxColsAtCompileTime = RhsNestedCleaned::MaxColsAtCompileTime }; - typedef typename find_best_packet::type LhsVecPacketType; - typedef typename find_best_packet::type RhsVecPacketType; + typedef typename find_best_packet::type LhsVecPacketType; + typedef typename find_best_packet::type RhsVecPacketType; enum { LhsCoeffReadCost = LhsEtorType::CoeffReadCost, RhsCoeffReadCost = RhsEtorType::CoeffReadCost, - CoeffReadCost = InnerSize==0 ? NumTraits::ReadCost - : InnerSize == Dynamic ? HugeCost - : InnerSize * (NumTraits::MulCost + int(LhsCoeffReadCost) + int(RhsCoeffReadCost)) - + (InnerSize - 1) * NumTraits::AddCost, + CoeffReadCost = InnerSize == 0 ? NumTraits::ReadCost + : InnerSize == Dynamic + ? HugeCost + : InnerSize * (NumTraits::MulCost + int(LhsCoeffReadCost) + int(RhsCoeffReadCost)) + + (InnerSize - 1) * NumTraits::AddCost, Unroll = CoeffReadCost <= EIGEN_UNROLLING_LIMIT, @@ -564,84 +553,86 @@ struct product_evaluator, ProductTag, DenseShape, RhsVecPacketSize = unpacket_traits::size, // Here, we don't care about alignment larger than the usable packet size. - LhsAlignment = EIGEN_PLAIN_ENUM_MIN(LhsEtorType::Alignment,LhsVecPacketSize*int(sizeof(typename LhsNestedCleaned::Scalar))), - RhsAlignment = EIGEN_PLAIN_ENUM_MIN(RhsEtorType::Alignment,RhsVecPacketSize*int(sizeof(typename RhsNestedCleaned::Scalar))), - - SameType = is_same::value, - - CanVectorizeRhs = bool(RhsRowMajor) && (RhsFlags & PacketAccessBit) && (ColsAtCompileTime!=1), - CanVectorizeLhs = (!LhsRowMajor) && (LhsFlags & PacketAccessBit) && (RowsAtCompileTime!=1), - - EvalToRowMajor = (MaxRowsAtCompileTime==1&&MaxColsAtCompileTime!=1) ? 1 - : (MaxColsAtCompileTime==1&&MaxRowsAtCompileTime!=1) ? 0 - : (bool(RhsRowMajor) && !CanVectorizeLhs), - - Flags = ((int(LhsFlags) | int(RhsFlags)) & HereditaryBits & ~RowMajorBit) - | (EvalToRowMajor ? RowMajorBit : 0) - // TODO enable vectorization for mixed types - | (SameType && (CanVectorizeLhs || CanVectorizeRhs) ? PacketAccessBit : 0) - | (XprType::IsVectorAtCompileTime ? LinearAccessBit : 0), - - LhsOuterStrideBytes = int(LhsNestedCleaned::OuterStrideAtCompileTime) * int(sizeof(typename LhsNestedCleaned::Scalar)), - RhsOuterStrideBytes = int(RhsNestedCleaned::OuterStrideAtCompileTime) * int(sizeof(typename RhsNestedCleaned::Scalar)), - - Alignment = bool(CanVectorizeLhs) ? (LhsOuterStrideBytes<=0 || (int(LhsOuterStrideBytes) % EIGEN_PLAIN_ENUM_MAX(1,LhsAlignment))!=0 ? 0 : LhsAlignment) - : bool(CanVectorizeRhs) ? (RhsOuterStrideBytes<=0 || (int(RhsOuterStrideBytes) % EIGEN_PLAIN_ENUM_MAX(1,RhsAlignment))!=0 ? 0 : RhsAlignment) - : 0, + LhsAlignment = + plain_enum_min(LhsEtorType::Alignment, LhsVecPacketSize* int(sizeof(typename LhsNestedCleaned::Scalar))), + RhsAlignment = + plain_enum_min(RhsEtorType::Alignment, RhsVecPacketSize* int(sizeof(typename RhsNestedCleaned::Scalar))), + + SameType = is_same::value, + + CanVectorizeRhs = bool(RhsRowMajor) && (RhsFlags & PacketAccessBit) && (ColsAtCompileTime != 1), + CanVectorizeLhs = (!LhsRowMajor) && (LhsFlags & PacketAccessBit) && (RowsAtCompileTime != 1), + + EvalToRowMajor = (MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1) ? 1 + : (MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1) + ? 0 + : (bool(RhsRowMajor) && !CanVectorizeLhs), + + Flags = ((int(LhsFlags) | int(RhsFlags)) & HereditaryBits & ~RowMajorBit) | + (EvalToRowMajor ? RowMajorBit : 0) + // TODO enable vectorization for mixed types + | (SameType && (CanVectorizeLhs || CanVectorizeRhs) ? PacketAccessBit : 0) | + (XprType::IsVectorAtCompileTime ? LinearAccessBit : 0), + + LhsOuterStrideBytes = + int(LhsNestedCleaned::OuterStrideAtCompileTime) * int(sizeof(typename LhsNestedCleaned::Scalar)), + RhsOuterStrideBytes = + int(RhsNestedCleaned::OuterStrideAtCompileTime) * int(sizeof(typename RhsNestedCleaned::Scalar)), + + Alignment = bool(CanVectorizeLhs) + ? (LhsOuterStrideBytes <= 0 || (int(LhsOuterStrideBytes) % plain_enum_max(1, LhsAlignment)) != 0 + ? 0 + : LhsAlignment) + : bool(CanVectorizeRhs) + ? (RhsOuterStrideBytes <= 0 || (int(RhsOuterStrideBytes) % plain_enum_max(1, RhsAlignment)) != 0 + ? 0 + : RhsAlignment) + : 0, /* CanVectorizeInner deserves special explanation. It does not affect the product flags. It is not used outside * of Product. If the Product itself is not a packet-access expression, there is still a chance that the inner * loop of the product might be vectorized. This is the meaning of CanVectorizeInner. Since it doesn't affect * the Flags, it is safe to make this value depend on ActualPacketAccessBit, that doesn't affect the ABI. */ - CanVectorizeInner = SameType - && LhsRowMajor - && (!RhsRowMajor) - && (int(LhsFlags) & int(RhsFlags) & ActualPacketAccessBit) - && (int(InnerSize) % packet_traits::size == 0) + CanVectorizeInner = SameType && LhsRowMajor && (!RhsRowMajor) && + (int(LhsFlags) & int(RhsFlags) & ActualPacketAccessBit) && + (int(InnerSize) % packet_traits::size == 0) }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index row, Index col) const - { - return (m_lhs.row(row).transpose().cwiseProduct( m_rhs.col(col) )).sum(); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index row, Index col) const { + return (m_lhs.row(row).transpose().cwiseProduct(m_rhs.col(col))).sum(); } /* Allow index-based non-packet access. It is impossible though to allow index-based packed access, * which is why we don't set the LinearAccessBit. * TODO: this seems possible when the result is a vector */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const CoeffReturnType coeff(Index index) const - { - const Index row = (RowsAtCompileTime == 1 || MaxRowsAtCompileTime==1) ? 0 : index; - const Index col = (RowsAtCompileTime == 1 || MaxRowsAtCompileTime==1) ? index : 0; - return (m_lhs.row(row).transpose().cwiseProduct( m_rhs.col(col) )).sum(); - } - - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const PacketType packet(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index index) const { + const Index row = (RowsAtCompileTime == 1 || MaxRowsAtCompileTime == 1) ? 0 : index; + const Index col = (RowsAtCompileTime == 1 || MaxRowsAtCompileTime == 1) ? index : 0; + return (m_lhs.row(row).transpose().cwiseProduct(m_rhs.col(col))).sum(); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const PacketType packet(Index row, Index col) const { PacketType res; - typedef etor_product_packet_impl PacketImpl; + typedef etor_product_packet_impl + PacketImpl; PacketImpl::run(row, col, m_lhsImpl, m_rhsImpl, m_innerDim, res); return res; } - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const PacketType packet(Index index) const - { - const Index row = (RowsAtCompileTime == 1 || MaxRowsAtCompileTime==1) ? 0 : index; - const Index col = (RowsAtCompileTime == 1 || MaxRowsAtCompileTime==1) ? index : 0; - return packet(row,col); + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const PacketType packet(Index index) const { + const Index row = (RowsAtCompileTime == 1 || MaxRowsAtCompileTime == 1) ? 0 : index; + const Index col = (RowsAtCompileTime == 1 || MaxRowsAtCompileTime == 1) ? index : 0; + return packet(row, col); } -protected: - typename internal::add_const_on_value_type::type m_lhs; - typename internal::add_const_on_value_type::type m_rhs; + protected: + add_const_on_value_type_t m_lhs; + add_const_on_value_type_t m_rhs; LhsEtorType m_lhsImpl; RhsEtorType m_rhsImpl; @@ -650,530 +641,515 @@ struct product_evaluator, ProductTag, DenseShape, Index m_innerDim; }; -template +template struct product_evaluator, LazyCoeffBasedProductMode, DenseShape, DenseShape> - : product_evaluator, CoeffBasedProductMode, DenseShape, DenseShape> -{ + : product_evaluator, CoeffBasedProductMode, DenseShape, DenseShape> { typedef Product XprType; typedef Product BaseProduct; typedef product_evaluator Base; - enum { - Flags = Base::Flags | EvalBeforeNestingBit - }; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit product_evaluator(const XprType& xpr) - : Base(BaseProduct(xpr.lhs(),xpr.rhs())) - {} + enum { Flags = Base::Flags | EvalBeforeNestingBit }; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit product_evaluator(const XprType& xpr) + : Base(BaseProduct(xpr.lhs(), xpr.rhs())) {} }; /**************************************** *** Coeff based product, Packet path *** ****************************************/ -template -struct etor_product_packet_impl -{ - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet &res) - { - etor_product_packet_impl::run(row, col, lhs, rhs, innerDim, res); - res = pmadd(pset1(lhs.coeff(row, Index(UnrollingIndex-1))), rhs.template packet(Index(UnrollingIndex-1), col), res); +template +struct etor_product_packet_impl { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, + Index innerDim, Packet& res) { + etor_product_packet_impl::run(row, col, lhs, rhs, + innerDim, res); + res = pmadd(pset1(lhs.coeff(row, Index(UnrollingIndex - 1))), + rhs.template packet(Index(UnrollingIndex - 1), col), res); } }; -template -struct etor_product_packet_impl -{ - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet &res) - { - etor_product_packet_impl::run(row, col, lhs, rhs, innerDim, res); - res = pmadd(lhs.template packet(row, Index(UnrollingIndex-1)), pset1(rhs.coeff(Index(UnrollingIndex-1), col)), res); +template +struct etor_product_packet_impl { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, + Index innerDim, Packet& res) { + etor_product_packet_impl::run(row, col, lhs, rhs, + innerDim, res); + res = pmadd(lhs.template packet(row, Index(UnrollingIndex - 1)), + pset1(rhs.coeff(Index(UnrollingIndex - 1), col)), res); } }; -template -struct etor_product_packet_impl -{ - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index /*innerDim*/, Packet &res) - { - res = pmul(pset1(lhs.coeff(row, Index(0))),rhs.template packet(Index(0), col)); +template +struct etor_product_packet_impl { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, + Index /*innerDim*/, Packet& res) { + res = pmul(pset1(lhs.coeff(row, Index(0))), rhs.template packet(Index(0), col)); } }; -template -struct etor_product_packet_impl -{ - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index /*innerDim*/, Packet &res) - { - res = pmul(lhs.template packet(row, Index(0)), pset1(rhs.coeff(Index(0), col))); +template +struct etor_product_packet_impl { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, + Index /*innerDim*/, Packet& res) { + res = pmul(lhs.template packet(row, Index(0)), pset1(rhs.coeff(Index(0), col))); } }; -template -struct etor_product_packet_impl -{ - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index /*row*/, Index /*col*/, const Lhs& /*lhs*/, const Rhs& /*rhs*/, Index /*innerDim*/, Packet &res) - { +template +struct etor_product_packet_impl { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index /*row*/, Index /*col*/, const Lhs& /*lhs*/, + const Rhs& /*rhs*/, Index /*innerDim*/, Packet& res) { res = pset1(typename unpacket_traits::type(0)); } }; -template -struct etor_product_packet_impl -{ - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index /*row*/, Index /*col*/, const Lhs& /*lhs*/, const Rhs& /*rhs*/, Index /*innerDim*/, Packet &res) - { +template +struct etor_product_packet_impl { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index /*row*/, Index /*col*/, const Lhs& /*lhs*/, + const Rhs& /*rhs*/, Index /*innerDim*/, Packet& res) { res = pset1(typename unpacket_traits::type(0)); } }; -template -struct etor_product_packet_impl -{ - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet& res) - { +template +struct etor_product_packet_impl { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, + Index innerDim, Packet& res) { res = pset1(typename unpacket_traits::type(0)); - for(Index i = 0; i < innerDim; ++i) - res = pmadd(pset1(lhs.coeff(row, i)), rhs.template packet(i, col), res); + for (Index i = 0; i < innerDim; ++i) + res = pmadd(pset1(lhs.coeff(row, i)), rhs.template packet(i, col), res); } }; -template -struct etor_product_packet_impl -{ - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet& res) - { +template +struct etor_product_packet_impl { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, + Index innerDim, Packet& res) { res = pset1(typename unpacket_traits::type(0)); - for(Index i = 0; i < innerDim; ++i) - res = pmadd(lhs.template packet(row, i), pset1(rhs.coeff(i, col)), res); + for (Index i = 0; i < innerDim; ++i) + res = pmadd(lhs.template packet(row, i), pset1(rhs.coeff(i, col)), res); } }; - /*************************************************************************** -* Triangular products -***************************************************************************/ -template + * Triangular products + ***************************************************************************/ +template struct triangular_product_impl; -template -struct generic_product_impl - : generic_product_impl_base > -{ - typedef typename Product::Scalar Scalar; +template +struct generic_product_impl + : generic_product_impl_base> { + typedef typename Product::Scalar Scalar; - template - static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) - { - triangular_product_impl - ::run(dst, lhs.nestedExpression(), rhs, alpha); + template + static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) { + triangular_product_impl::run( + dst, lhs.nestedExpression(), rhs, alpha); } }; -template -struct generic_product_impl -: generic_product_impl_base > -{ - typedef typename Product::Scalar Scalar; +template +struct generic_product_impl + : generic_product_impl_base> { + typedef typename Product::Scalar Scalar; - template - static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) - { - triangular_product_impl::run(dst, lhs, rhs.nestedExpression(), alpha); + template + static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) { + triangular_product_impl::run( + dst, lhs, rhs.nestedExpression(), alpha); } }; - /*************************************************************************** -* SelfAdjoint products -***************************************************************************/ -template + * SelfAdjoint products + ***************************************************************************/ +template struct selfadjoint_product_impl; -template -struct generic_product_impl - : generic_product_impl_base > -{ - typedef typename Product::Scalar Scalar; +template +struct generic_product_impl + : generic_product_impl_base> { + typedef typename Product::Scalar Scalar; - template - static EIGEN_DEVICE_FUNC - void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) - { - selfadjoint_product_impl::run(dst, lhs.nestedExpression(), rhs, alpha); + template + static EIGEN_DEVICE_FUNC void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) { + selfadjoint_product_impl::run( + dst, lhs.nestedExpression(), rhs, alpha); } }; -template -struct generic_product_impl -: generic_product_impl_base > -{ - typedef typename Product::Scalar Scalar; +template +struct generic_product_impl + : generic_product_impl_base> { + typedef typename Product::Scalar Scalar; - template - static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) - { - selfadjoint_product_impl::run(dst, lhs, rhs.nestedExpression(), alpha); + template + static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) { + selfadjoint_product_impl::run( + dst, lhs, rhs.nestedExpression(), alpha); } }; - /*************************************************************************** -* Diagonal products -***************************************************************************/ - -template -struct diagonal_product_evaluator_base - : evaluator_base -{ - typedef typename ScalarBinaryOpTraits::ReturnType Scalar; -public: + * Diagonal products + ***************************************************************************/ + +template +struct diagonal_product_evaluator_base : evaluator_base { + typedef typename ScalarBinaryOpTraits::ReturnType Scalar; + + public: enum { - CoeffReadCost = int(NumTraits::MulCost) + int(evaluator::CoeffReadCost) + int(evaluator::CoeffReadCost), + CoeffReadCost = int(NumTraits::MulCost) + int(evaluator::CoeffReadCost) + + int(evaluator::CoeffReadCost), MatrixFlags = evaluator::Flags, DiagFlags = evaluator::Flags, - _StorageOrder = (Derived::MaxRowsAtCompileTime==1 && Derived::MaxColsAtCompileTime!=1) ? RowMajor - : (Derived::MaxColsAtCompileTime==1 && Derived::MaxRowsAtCompileTime!=1) ? ColMajor - : MatrixFlags & RowMajorBit ? RowMajor : ColMajor, - _SameStorageOrder = _StorageOrder == (MatrixFlags & RowMajorBit ? RowMajor : ColMajor), + StorageOrder_ = (Derived::MaxRowsAtCompileTime == 1 && Derived::MaxColsAtCompileTime != 1) ? RowMajor + : (Derived::MaxColsAtCompileTime == 1 && Derived::MaxRowsAtCompileTime != 1) ? ColMajor + : MatrixFlags & RowMajorBit ? RowMajor + : ColMajor, + SameStorageOrder_ = StorageOrder_ == (MatrixFlags & RowMajorBit ? RowMajor : ColMajor), - _ScalarAccessOnDiag = !((int(_StorageOrder) == ColMajor && int(ProductOrder) == OnTheLeft) - ||(int(_StorageOrder) == RowMajor && int(ProductOrder) == OnTheRight)), - _SameTypes = is_same::value, + ScalarAccessOnDiag_ = !((int(StorageOrder_) == ColMajor && int(ProductOrder) == OnTheLeft) || + (int(StorageOrder_) == RowMajor && int(ProductOrder) == OnTheRight)), + SameTypes_ = is_same::value, // FIXME currently we need same types, but in the future the next rule should be the one - //_Vectorizable = bool(int(MatrixFlags)&PacketAccessBit) && ((!_PacketOnDiag) || (_SameTypes && bool(int(DiagFlags)&PacketAccessBit))), - _Vectorizable = bool(int(MatrixFlags)&PacketAccessBit) - && _SameTypes - && (_SameStorageOrder || (MatrixFlags&LinearAccessBit)==LinearAccessBit) - && (_ScalarAccessOnDiag || (bool(int(DiagFlags)&PacketAccessBit))), - _LinearAccessMask = (MatrixType::RowsAtCompileTime==1 || MatrixType::ColsAtCompileTime==1) ? LinearAccessBit : 0, - Flags = ((HereditaryBits|_LinearAccessMask) & (unsigned int)(MatrixFlags)) | (_Vectorizable ? PacketAccessBit : 0), + // Vectorizable_ = bool(int(MatrixFlags)&PacketAccessBit) && ((!_PacketOnDiag) || (SameTypes_ && + // bool(int(DiagFlags)&PacketAccessBit))), + Vectorizable_ = bool(int(MatrixFlags) & PacketAccessBit) && SameTypes_ && + (SameStorageOrder_ || (MatrixFlags & LinearAccessBit) == LinearAccessBit) && + (ScalarAccessOnDiag_ || (bool(int(DiagFlags) & PacketAccessBit))), + LinearAccessMask_ = + (MatrixType::RowsAtCompileTime == 1 || MatrixType::ColsAtCompileTime == 1) ? LinearAccessBit : 0, + Flags = + ((HereditaryBits | LinearAccessMask_) & (unsigned int)(MatrixFlags)) | (Vectorizable_ ? PacketAccessBit : 0), Alignment = evaluator::Alignment, - AsScalarProduct = (DiagonalType::SizeAtCompileTime==1) - || (DiagonalType::SizeAtCompileTime==Dynamic && MatrixType::RowsAtCompileTime==1 && ProductOrder==OnTheLeft) - || (DiagonalType::SizeAtCompileTime==Dynamic && MatrixType::ColsAtCompileTime==1 && ProductOrder==OnTheRight) + AsScalarProduct = + (DiagonalType::SizeAtCompileTime == 1) || + (DiagonalType::SizeAtCompileTime == Dynamic && MatrixType::RowsAtCompileTime == 1 && + ProductOrder == OnTheLeft) || + (DiagonalType::SizeAtCompileTime == Dynamic && MatrixType::ColsAtCompileTime == 1 && ProductOrder == OnTheRight) }; - EIGEN_DEVICE_FUNC diagonal_product_evaluator_base(const MatrixType &mat, const DiagonalType &diag) - : m_diagImpl(diag), m_matImpl(mat) - { + EIGEN_DEVICE_FUNC diagonal_product_evaluator_base(const MatrixType& mat, const DiagonalType& diag) + : m_diagImpl(diag), m_matImpl(mat) { EIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits::MulCost); EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index idx) const - { - if(AsScalarProduct) + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index idx) const { + if (AsScalarProduct) return m_diagImpl.coeff(0) * m_matImpl.coeff(idx); else return m_diagImpl.coeff(idx) * m_matImpl.coeff(idx); } -protected: - template - EIGEN_STRONG_INLINE PacketType packet_impl(Index row, Index col, Index id, internal::true_type) const - { - return internal::pmul(m_matImpl.template packet(row, col), + protected: + template + EIGEN_STRONG_INLINE PacketType packet_impl(Index row, Index col, Index id, internal::true_type) const { + return internal::pmul(m_matImpl.template packet(row, col), internal::pset1(m_diagImpl.coeff(id))); } - template - EIGEN_STRONG_INLINE PacketType packet_impl(Index row, Index col, Index id, internal::false_type) const - { + template + EIGEN_STRONG_INLINE PacketType packet_impl(Index row, Index col, Index id, internal::false_type) const { enum { InnerSize = (MatrixType::Flags & RowMajorBit) ? MatrixType::ColsAtCompileTime : MatrixType::RowsAtCompileTime, - DiagonalPacketLoadMode = EIGEN_PLAIN_ENUM_MIN(LoadMode,((InnerSize%16) == 0) ? int(Aligned16) : int(evaluator::Alignment)) // FIXME hardcoded 16!! + DiagonalPacketLoadMode = plain_enum_min( + LoadMode, + ((InnerSize % 16) == 0) ? int(Aligned16) : int(evaluator::Alignment)) // FIXME hardcoded 16!! }; - return internal::pmul(m_matImpl.template packet(row, col), - m_diagImpl.template packet(id)); + return internal::pmul(m_matImpl.template packet(row, col), + m_diagImpl.template packet(id)); } evaluator m_diagImpl; - evaluator m_matImpl; + evaluator m_matImpl; }; // diagonal * dense -template +template struct product_evaluator, ProductTag, DiagonalShape, DenseShape> - : diagonal_product_evaluator_base, OnTheLeft> -{ - typedef diagonal_product_evaluator_base, OnTheLeft> Base; + : diagonal_product_evaluator_base, + OnTheLeft> { + typedef diagonal_product_evaluator_base, + OnTheLeft> + Base; + using Base::coeff; using Base::m_diagImpl; using Base::m_matImpl; - using Base::coeff; typedef typename Base::Scalar Scalar; typedef Product XprType; typedef typename XprType::PlainObject PlainObject; typedef typename Lhs::DiagonalVectorType DiagonalType; + enum { StorageOrder = Base::StorageOrder_ }; - enum { StorageOrder = Base::_StorageOrder }; + EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr) : Base(xpr.rhs(), xpr.lhs().diagonal()) {} - EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr) - : Base(xpr.rhs(), xpr.lhs().diagonal()) - { - } - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index row, Index col) const { return m_diagImpl.coeff(row) * m_matImpl.coeff(row, col); } #ifndef EIGEN_GPUCC - template - EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const - { + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { // FIXME: NVCC used to complain about the template keyword, but we have to check whether this is still the case. // See also similar calls below. - return this->template packet_impl(row,col, row, - typename internal::conditional::type()); + return this->template packet_impl( + row, col, row, std::conditional_t()); } - template - EIGEN_STRONG_INLINE PacketType packet(Index idx) const - { - return packet(int(StorageOrder)==ColMajor?idx:0,int(StorageOrder)==ColMajor?0:idx); + template + EIGEN_STRONG_INLINE PacketType packet(Index idx) const { + return packet(int(StorageOrder) == ColMajor ? idx : 0, + int(StorageOrder) == ColMajor ? 0 : idx); } #endif }; // dense * diagonal -template +template struct product_evaluator, ProductTag, DenseShape, DiagonalShape> - : diagonal_product_evaluator_base, OnTheRight> -{ - typedef diagonal_product_evaluator_base, OnTheRight> Base; + : diagonal_product_evaluator_base, + OnTheRight> { + typedef diagonal_product_evaluator_base, + OnTheRight> + Base; + using Base::coeff; using Base::m_diagImpl; using Base::m_matImpl; - using Base::coeff; typedef typename Base::Scalar Scalar; typedef Product XprType; typedef typename XprType::PlainObject PlainObject; - enum { StorageOrder = Base::_StorageOrder }; + enum { StorageOrder = Base::StorageOrder_ }; - EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr) - : Base(xpr.lhs(), xpr.rhs().diagonal()) - { - } + EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr) : Base(xpr.lhs(), xpr.rhs().diagonal()) {} - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index row, Index col) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index row, Index col) const { return m_matImpl.coeff(row, col) * m_diagImpl.coeff(col); } #ifndef EIGEN_GPUCC - template - EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const - { - return this->template packet_impl(row,col, col, - typename internal::conditional::type()); + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { + return this->template packet_impl( + row, col, col, std::conditional_t()); } - template - EIGEN_STRONG_INLINE PacketType packet(Index idx) const - { - return packet(int(StorageOrder)==ColMajor?idx:0,int(StorageOrder)==ColMajor?0:idx); + template + EIGEN_STRONG_INLINE PacketType packet(Index idx) const { + return packet(int(StorageOrder) == ColMajor ? idx : 0, + int(StorageOrder) == ColMajor ? 0 : idx); } #endif }; /*************************************************************************** -* Products with permutation matrices -***************************************************************************/ + * Products with permutation matrices + ***************************************************************************/ /** \internal - * \class permutation_matrix_product - * Internal helper class implementing the product between a permutation matrix and a matrix. - * This class is specialized for DenseShape below and for SparseShape in SparseCore/SparsePermutation.h - */ -template + * \class permutation_matrix_product + * Internal helper class implementing the product between a permutation matrix and a matrix. + * This class is specialized for DenseShape below and for SparseShape in SparseCore/SparsePermutation.h + */ +template struct permutation_matrix_product; -template -struct permutation_matrix_product -{ - typedef typename nested_eval::type MatrixType; - typedef typename remove_all::type MatrixTypeCleaned; - - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Dest& dst, const PermutationType& perm, const ExpressionType& xpr) - { - MatrixType mat(xpr); - const Index n = Side==OnTheLeft ? mat.rows() : mat.cols(); - // FIXME we need an is_same for expression that is not sensitive to constness. For instance - // is_same_xpr, Block >::value should be true. - //if(is_same::value && extract_data(dst) == extract_data(mat)) - if(is_same_dense(dst, mat)) - { - // apply the permutation inplace - Matrix mask(perm.size()); - mask.fill(false); - Index r = 0; - while(r < perm.size()) - { - // search for the next seed - while(r=perm.size()) - break; - // we got one, let's follow it until we are back to the seed - Index k0 = r++; - Index kPrev = k0; - mask.coeffRef(k0) = true; - for(Index k=perm.indices().coeff(k0); k!=k0; k=perm.indices().coeff(k)) - { - Block(dst, k) - .swap(Block - (dst,((Side==OnTheLeft) ^ Transposed) ? k0 : kPrev)); - - mask.coeffRef(k) = true; - kPrev = k; - } - } - } - else - { - for(Index i = 0; i < n; ++i) - { - Block - (dst, ((Side==OnTheLeft) ^ Transposed) ? perm.indices().coeff(i) : i) - - = +template +struct permutation_matrix_product { + typedef typename nested_eval::type MatrixType; + typedef remove_all_t MatrixTypeCleaned; - Block - (mat, ((Side==OnTheRight) ^ Transposed) ? perm.indices().coeff(i) : i); + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Dest& dst, const PermutationType& perm, + const ExpressionType& xpr) { + MatrixType mat(xpr); + const Index n = Side == OnTheLeft ? mat.rows() : mat.cols(); + // FIXME we need an is_same for expression that is not sensitive to constness. For instance + // is_same_xpr, Block >::value should be true. + // if(is_same::value && extract_data(dst) == extract_data(mat)) + if (is_same_dense(dst, mat)) { + // apply the permutation inplace + Matrix mask(perm.size()); + mask.fill(false); + Index r = 0; + while (r < perm.size()) { + // search for the next seed + while (r < perm.size() && mask[r]) r++; + if (r >= perm.size()) break; + // we got one, let's follow it until we are back to the seed + Index k0 = r++; + Index kPrev = k0; + mask.coeffRef(k0) = true; + for (Index k = perm.indices().coeff(k0); k != k0; k = perm.indices().coeff(k)) { + Block(dst, k) + .swap(Block < Dest, Side == OnTheLeft ? 1 : Dest::RowsAtCompileTime, + Side == OnTheRight + ? 1 + : Dest::ColsAtCompileTime > (dst, ((Side == OnTheLeft) ^ Transposed) ? k0 : kPrev)); + + mask.coeffRef(k) = true; + kPrev = k; } } + } else { + for (Index i = 0; i < n; ++i) { + Block( + dst, ((Side == OnTheLeft) ^ Transposed) ? perm.indices().coeff(i) : i) + + = + + Block < const MatrixTypeCleaned, + Side == OnTheLeft ? 1 : MatrixTypeCleaned::RowsAtCompileTime, + Side == OnTheRight ? 1 + : MatrixTypeCleaned::ColsAtCompileTime > + (mat, ((Side == OnTheRight) ^ Transposed) ? perm.indices().coeff(i) : i); + } } + } }; -template -struct generic_product_impl -{ - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) - { +template +struct generic_product_impl { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) { permutation_matrix_product::run(dst, lhs, rhs); } }; -template -struct generic_product_impl -{ - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) - { +template +struct generic_product_impl { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) { permutation_matrix_product::run(dst, rhs, lhs); } }; -template -struct generic_product_impl, Rhs, PermutationShape, MatrixShape, ProductTag> -{ - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Inverse& lhs, const Rhs& rhs) - { +template +struct generic_product_impl, Rhs, PermutationShape, MatrixShape, ProductTag> { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Inverse& lhs, const Rhs& rhs) { permutation_matrix_product::run(dst, lhs.nestedExpression(), rhs); } }; -template -struct generic_product_impl, MatrixShape, PermutationShape, ProductTag> -{ - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Inverse& rhs) - { +template +struct generic_product_impl, MatrixShape, PermutationShape, ProductTag> { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Inverse& rhs) { permutation_matrix_product::run(dst, rhs.nestedExpression(), lhs); } }; - /*************************************************************************** -* Products with transpositions matrices -***************************************************************************/ + * Products with transpositions matrices + ***************************************************************************/ // FIXME could we unify Transpositions and Permutation into a single "shape"?? /** \internal - * \class transposition_matrix_product - * Internal helper class implementing the product between a permutation matrix and a matrix. - */ -template -struct transposition_matrix_product -{ + * \class transposition_matrix_product + * Internal helper class implementing the product between a permutation matrix and a matrix. + */ +template +struct transposition_matrix_product { typedef typename nested_eval::type MatrixType; - typedef typename remove_all::type MatrixTypeCleaned; + typedef remove_all_t MatrixTypeCleaned; - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Dest& dst, const TranspositionType& tr, const ExpressionType& xpr) - { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(Dest& dst, const TranspositionType& tr, + const ExpressionType& xpr) { MatrixType mat(xpr); typedef typename TranspositionType::StorageIndex StorageIndex; const Index size = tr.size(); StorageIndex j = 0; - if(!is_same_dense(dst,mat)) - dst = mat; + if (!is_same_dense(dst, mat)) dst = mat; - for(Index k=(Transposed?size-1:0) ; Transposed?k>=0:k= 0 : k < size; Transposed ? --k : ++k) + if (Index(j = tr.coeff(k)) != k) { + if (Side == OnTheLeft) + dst.row(k).swap(dst.row(j)); + else if (Side == OnTheRight) + dst.col(k).swap(dst.col(j)); } } }; -template -struct generic_product_impl -{ - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) - { +template +struct generic_product_impl { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) { transposition_matrix_product::run(dst, lhs, rhs); } }; -template -struct generic_product_impl -{ - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) - { +template +struct generic_product_impl { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) { transposition_matrix_product::run(dst, rhs, lhs); } }; - -template -struct generic_product_impl, Rhs, TranspositionsShape, MatrixShape, ProductTag> -{ - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Transpose& lhs, const Rhs& rhs) - { +template +struct generic_product_impl, Rhs, TranspositionsShape, MatrixShape, ProductTag> { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Transpose& lhs, const Rhs& rhs) { transposition_matrix_product::run(dst, lhs.nestedExpression(), rhs); } }; -template -struct generic_product_impl, MatrixShape, TranspositionsShape, ProductTag> -{ - template - static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Transpose& rhs) - { +template +struct generic_product_impl, MatrixShape, TranspositionsShape, ProductTag> { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Transpose& rhs) { transposition_matrix_product::run(dst, rhs.nestedExpression(), lhs); } }; -} // end namespace internal +/*************************************************************************** + * skew symmetric products + * for now we just call the generic implementation + ***************************************************************************/ +template +struct generic_product_impl { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) { + generic_product_impl::evalTo(dst, lhs, + rhs); + } +}; + +template +struct generic_product_impl { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) { + generic_product_impl::evalTo(dst, lhs, + rhs); + } +}; + +template +struct generic_product_impl { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) { + generic_product_impl::evalTo(dst, lhs, rhs); + } +}; + +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_PRODUCT_EVALUATORS_H +#endif // EIGEN_PRODUCT_EVALUATORS_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Random.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Random.h index dab2ac8e9e8..f8a54356250 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Random.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Random.h @@ -10,209 +10,198 @@ #ifndef EIGEN_RANDOM_H #define EIGEN_RANDOM_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { namespace internal { -template struct scalar_random_op { - EIGEN_EMPTY_STRUCT_CTOR(scalar_random_op) - inline const Scalar operator() () const { return random(); } +template +struct scalar_random_op { + inline const Scalar operator()() const { return random(); } }; -template -struct functor_traits > -{ enum { Cost = 5 * NumTraits::MulCost, PacketAccess = false, IsRepeatable = false }; }; +template +struct functor_traits > { + enum { Cost = 5 * NumTraits::MulCost, PacketAccess = false, IsRepeatable = false }; +}; -} // end namespace internal +} // end namespace internal /** \returns a random matrix expression - * - * Numbers are uniformly spread through their whole definition range for integer types, - * and in the [-1:1] range for floating point scalar types. - * - * The parameters \a rows and \a cols are the number of rows and of columns of - * the returned matrix. Must be compatible with this MatrixBase type. - * - * \not_reentrant - * - * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, - * it is redundant to pass \a rows and \a cols as arguments, so Random() should be used - * instead. - * - * - * Example: \include MatrixBase_random_int_int.cpp - * Output: \verbinclude MatrixBase_random_int_int.out - * - * This expression has the "evaluate before nesting" flag so that it will be evaluated into - * a temporary matrix whenever it is nested in a larger expression. This prevents unexpected - * behavior with expressions involving random matrices. - * - * See DenseBase::NullaryExpr(Index, const CustomNullaryOp&) for an example using C++11 random generators. - * - * \sa DenseBase::setRandom(), DenseBase::Random(Index), DenseBase::Random() - */ -template -inline const typename DenseBase::RandomReturnType -DenseBase::Random(Index rows, Index cols) -{ + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * The parameters \a rows and \a cols are the number of rows and of columns of + * the returned matrix. Must be compatible with this MatrixBase type. + * + * \not_reentrant + * + * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, + * it is redundant to pass \a rows and \a cols as arguments, so Random() should be used + * instead. + * + * + * Example: \include MatrixBase_random_int_int.cpp + * Output: \verbinclude MatrixBase_random_int_int.out + * + * This expression has the "evaluate before nesting" flag so that it will be evaluated into + * a temporary matrix whenever it is nested in a larger expression. This prevents unexpected + * behavior with expressions involving random matrices. + * + * See DenseBase::NullaryExpr(Index, const CustomNullaryOp&) for an example using C++11 random generators. + * + * \sa DenseBase::setRandom(), DenseBase::Random(Index), DenseBase::Random() + */ +template +inline const typename DenseBase::RandomReturnType DenseBase::Random(Index rows, Index cols) { return NullaryExpr(rows, cols, internal::scalar_random_op()); } /** \returns a random vector expression - * - * Numbers are uniformly spread through their whole definition range for integer types, - * and in the [-1:1] range for floating point scalar types. - * - * The parameter \a size is the size of the returned vector. - * Must be compatible with this MatrixBase type. - * - * \only_for_vectors - * \not_reentrant - * - * This variant is meant to be used for dynamic-size vector types. For fixed-size types, - * it is redundant to pass \a size as argument, so Random() should be used - * instead. - * - * Example: \include MatrixBase_random_int.cpp - * Output: \verbinclude MatrixBase_random_int.out - * - * This expression has the "evaluate before nesting" flag so that it will be evaluated into - * a temporary vector whenever it is nested in a larger expression. This prevents unexpected - * behavior with expressions involving random matrices. - * - * \sa DenseBase::setRandom(), DenseBase::Random(Index,Index), DenseBase::Random() - */ -template -inline const typename DenseBase::RandomReturnType -DenseBase::Random(Index size) -{ + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * The parameter \a size is the size of the returned vector. + * Must be compatible with this MatrixBase type. + * + * \only_for_vectors + * \not_reentrant + * + * This variant is meant to be used for dynamic-size vector types. For fixed-size types, + * it is redundant to pass \a size as argument, so Random() should be used + * instead. + * + * Example: \include MatrixBase_random_int.cpp + * Output: \verbinclude MatrixBase_random_int.out + * + * This expression has the "evaluate before nesting" flag so that it will be evaluated into + * a temporary vector whenever it is nested in a larger expression. This prevents unexpected + * behavior with expressions involving random matrices. + * + * \sa DenseBase::setRandom(), DenseBase::Random(Index,Index), DenseBase::Random() + */ +template +inline const typename DenseBase::RandomReturnType DenseBase::Random(Index size) { return NullaryExpr(size, internal::scalar_random_op()); } /** \returns a fixed-size random matrix or vector expression - * - * Numbers are uniformly spread through their whole definition range for integer types, - * and in the [-1:1] range for floating point scalar types. - * - * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you - * need to use the variants taking size arguments. - * - * Example: \include MatrixBase_random.cpp - * Output: \verbinclude MatrixBase_random.out - * - * This expression has the "evaluate before nesting" flag so that it will be evaluated into - * a temporary matrix whenever it is nested in a larger expression. This prevents unexpected - * behavior with expressions involving random matrices. - * - * \not_reentrant - * - * \sa DenseBase::setRandom(), DenseBase::Random(Index,Index), DenseBase::Random(Index) - */ -template -inline const typename DenseBase::RandomReturnType -DenseBase::Random() -{ + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you + * need to use the variants taking size arguments. + * + * Example: \include MatrixBase_random.cpp + * Output: \verbinclude MatrixBase_random.out + * + * This expression has the "evaluate before nesting" flag so that it will be evaluated into + * a temporary matrix whenever it is nested in a larger expression. This prevents unexpected + * behavior with expressions involving random matrices. + * + * \not_reentrant + * + * \sa DenseBase::setRandom(), DenseBase::Random(Index,Index), DenseBase::Random(Index) + */ +template +inline const typename DenseBase::RandomReturnType DenseBase::Random() { return NullaryExpr(RowsAtCompileTime, ColsAtCompileTime, internal::scalar_random_op()); } /** Sets all coefficients in this expression to random values. - * - * Numbers are uniformly spread through their whole definition range for integer types, - * and in the [-1:1] range for floating point scalar types. - * - * \not_reentrant - * - * Example: \include MatrixBase_setRandom.cpp - * Output: \verbinclude MatrixBase_setRandom.out - * - * \sa class CwiseNullaryOp, setRandom(Index), setRandom(Index,Index) - */ -template -EIGEN_DEVICE_FUNC inline Derived& DenseBase::setRandom() -{ + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * \not_reentrant + * + * Example: \include MatrixBase_setRandom.cpp + * Output: \verbinclude MatrixBase_setRandom.out + * + * \sa class CwiseNullaryOp, setRandom(Index), setRandom(Index,Index) + */ +template +EIGEN_DEVICE_FUNC inline Derived& DenseBase::setRandom() { return *this = Random(rows(), cols()); } /** Resizes to the given \a newSize, and sets all coefficients in this expression to random values. - * - * Numbers are uniformly spread through their whole definition range for integer types, - * and in the [-1:1] range for floating point scalar types. - * - * \only_for_vectors - * \not_reentrant - * - * Example: \include Matrix_setRandom_int.cpp - * Output: \verbinclude Matrix_setRandom_int.out - * - * \sa DenseBase::setRandom(), setRandom(Index,Index), class CwiseNullaryOp, DenseBase::Random() - */ -template -EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setRandom(Index newSize) -{ + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * \only_for_vectors + * \not_reentrant + * + * Example: \include Matrix_setRandom_int.cpp + * Output: \verbinclude Matrix_setRandom_int.out + * + * \sa DenseBase::setRandom(), setRandom(Index,Index), class CwiseNullaryOp, DenseBase::Random() + */ +template +EIGEN_STRONG_INLINE Derived& PlainObjectBase::setRandom(Index newSize) { resize(newSize); return setRandom(); } /** Resizes to the given size, and sets all coefficients in this expression to random values. - * - * Numbers are uniformly spread through their whole definition range for integer types, - * and in the [-1:1] range for floating point scalar types. - * - * \not_reentrant - * - * \param rows the new number of rows - * \param cols the new number of columns - * - * Example: \include Matrix_setRandom_int_int.cpp - * Output: \verbinclude Matrix_setRandom_int_int.out - * - * \sa DenseBase::setRandom(), setRandom(Index), class CwiseNullaryOp, DenseBase::Random() - */ -template -EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setRandom(Index rows, Index cols) -{ + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * \not_reentrant + * + * \param rows the new number of rows + * \param cols the new number of columns + * + * Example: \include Matrix_setRandom_int_int.cpp + * Output: \verbinclude Matrix_setRandom_int_int.out + * + * \sa DenseBase::setRandom(), setRandom(Index), class CwiseNullaryOp, DenseBase::Random() + */ +template +EIGEN_STRONG_INLINE Derived& PlainObjectBase::setRandom(Index rows, Index cols) { resize(rows, cols); return setRandom(); } /** Resizes to the given size, changing only the number of columns, and sets all - * coefficients in this expression to random values. For the parameter of type - * NoChange_t, just pass the special value \c NoChange. - * - * Numbers are uniformly spread through their whole definition range for integer types, - * and in the [-1:1] range for floating point scalar types. - * - * \not_reentrant - * - * \sa DenseBase::setRandom(), setRandom(Index), setRandom(Index, NoChange_t), class CwiseNullaryOp, DenseBase::Random() - */ -template -EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setRandom(NoChange_t, Index cols) -{ + * coefficients in this expression to random values. For the parameter of type + * NoChange_t, just pass the special value \c NoChange. + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * \not_reentrant + * + * \sa DenseBase::setRandom(), setRandom(Index), setRandom(Index, NoChange_t), class CwiseNullaryOp, DenseBase::Random() + */ +template +EIGEN_STRONG_INLINE Derived& PlainObjectBase::setRandom(NoChange_t, Index cols) { return setRandom(rows(), cols); } /** Resizes to the given size, changing only the number of rows, and sets all - * coefficients in this expression to random values. For the parameter of type - * NoChange_t, just pass the special value \c NoChange. - * - * Numbers are uniformly spread through their whole definition range for integer types, - * and in the [-1:1] range for floating point scalar types. - * - * \not_reentrant - * - * \sa DenseBase::setRandom(), setRandom(Index), setRandom(NoChange_t, Index), class CwiseNullaryOp, DenseBase::Random() - */ -template -EIGEN_STRONG_INLINE Derived& -PlainObjectBase::setRandom(Index rows, NoChange_t) -{ + * coefficients in this expression to random values. For the parameter of type + * NoChange_t, just pass the special value \c NoChange. + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * \not_reentrant + * + * \sa DenseBase::setRandom(), setRandom(Index), setRandom(NoChange_t, Index), class CwiseNullaryOp, DenseBase::Random() + */ +template +EIGEN_STRONG_INLINE Derived& PlainObjectBase::setRandom(Index rows, NoChange_t) { return setRandom(rows, cols()); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_RANDOM_H +#endif // EIGEN_RANDOM_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/RandomImpl.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/RandomImpl.h new file mode 100644 index 00000000000..e82da96609d --- /dev/null +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/RandomImpl.h @@ -0,0 +1,253 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2024 Charles Schlosser +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_RANDOM_IMPL_H +#define EIGEN_RANDOM_IMPL_H + +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +/**************************************************************************** + * Implementation of random * + ****************************************************************************/ + +template +struct random_default_impl {}; + +template +struct random_impl : random_default_impl::IsComplex, NumTraits::IsInteger> {}; + +template +struct random_retval { + typedef Scalar type; +}; + +template +inline EIGEN_MATHFUNC_RETVAL(random, Scalar) random(const Scalar& x, const Scalar& y) { + return EIGEN_MATHFUNC_IMPL(random, Scalar)::run(x, y); +} + +template +inline EIGEN_MATHFUNC_RETVAL(random, Scalar) random() { + return EIGEN_MATHFUNC_IMPL(random, Scalar)::run(); +} + +// TODO: replace or provide alternatives to this, e.g. std::random_device +struct eigen_random_device { + using ReturnType = int; + static constexpr int Entropy = meta_floor_log2<(unsigned int)(RAND_MAX) + 1>::value; + static constexpr ReturnType Highest = RAND_MAX; + static EIGEN_DEVICE_FUNC inline ReturnType run() { return std::rand(); } +}; + +// Fill a built-in unsigned integer with numRandomBits beginning with the least significant bit +template +struct random_bits_impl { + EIGEN_STATIC_ASSERT(std::is_unsigned::value, SCALAR MUST BE A BUILT - IN UNSIGNED INTEGER) + using RandomDevice = eigen_random_device; + using RandomReturnType = typename RandomDevice::ReturnType; + static constexpr int kEntropy = RandomDevice::Entropy; + static constexpr int kTotalBits = sizeof(Scalar) * CHAR_BIT; + // return a Scalar filled with numRandomBits beginning from the least significant bit + static EIGEN_DEVICE_FUNC inline Scalar run(int numRandomBits) { + eigen_assert((numRandomBits >= 0) && (numRandomBits <= kTotalBits)); + const Scalar mask = Scalar(-1) >> ((kTotalBits - numRandomBits) & (kTotalBits - 1)); + Scalar randomBits = 0; + for (int shift = 0; shift < numRandomBits; shift += kEntropy) { + RandomReturnType r = RandomDevice::run(); + randomBits |= static_cast(r) << shift; + } + // clear the excess bits + randomBits &= mask; + return randomBits; + } +}; + +template +EIGEN_DEVICE_FUNC inline BitsType getRandomBits(int numRandomBits) { + return random_bits_impl::run(numRandomBits); +} + +// random implementation for a built-in floating point type +template ::value> +struct random_float_impl { + using BitsType = typename numext::get_integer_by_size::unsigned_type; + static constexpr EIGEN_DEVICE_FUNC inline int mantissaBits() { + const int digits = NumTraits::digits(); + return digits - 1; + } + static EIGEN_DEVICE_FUNC inline Scalar run(int numRandomBits) { + eigen_assert(numRandomBits >= 0 && numRandomBits <= mantissaBits()); + BitsType randomBits = getRandomBits(numRandomBits); + // if fewer than MantissaBits is requested, shift them to the left + randomBits <<= (mantissaBits() - numRandomBits); + // randomBits is in the half-open interval [2,4) + randomBits |= numext::bit_cast(Scalar(2)); + // result is in the half-open interval [-1,1) + Scalar result = numext::bit_cast(randomBits) - Scalar(3); + return result; + } +}; +// random implementation for a custom floating point type +// uses double as the implementation with a mantissa with a size equal to either the target scalar's mantissa or that of +// double, whichever is smaller +template +struct random_float_impl { + static EIGEN_DEVICE_FUNC inline int mantissaBits() { + const int digits = NumTraits::digits(); + constexpr int kDoubleDigits = NumTraits::digits(); + return numext::mini(digits, kDoubleDigits) - 1; + } + static EIGEN_DEVICE_FUNC inline Scalar run(int numRandomBits) { + eigen_assert(numRandomBits >= 0 && numRandomBits <= mantissaBits()); + Scalar result = static_cast(random_float_impl::run(numRandomBits)); + return result; + } +}; + +// random implementation for long double +// this specialization is not compatible with double-double scalars +template ::digits != (2 * std::numeric_limits::digits)))> +struct random_longdouble_impl { + static constexpr int Size = sizeof(long double); + static constexpr EIGEN_DEVICE_FUNC inline int mantissaBits() { return NumTraits::digits() - 1; } + static EIGEN_DEVICE_FUNC inline long double run(int numRandomBits) { + eigen_assert(numRandomBits >= 0 && numRandomBits <= mantissaBits()); + EIGEN_USING_STD(memcpy); + int numLowBits = numext::mini(numRandomBits, 64); + int numHighBits = numext::maxi(numRandomBits - 64, 0); + uint64_t randomBits[2]; + long double result = 2.0L; + memcpy(&randomBits, &result, Size); + randomBits[0] |= getRandomBits(numLowBits); + randomBits[1] |= getRandomBits(numHighBits); + memcpy(&result, &randomBits, Size); + result -= 3.0L; + return result; + } +}; +template <> +struct random_longdouble_impl { + static constexpr EIGEN_DEVICE_FUNC inline int mantissaBits() { return NumTraits::digits() - 1; } + static EIGEN_DEVICE_FUNC inline long double run(int numRandomBits) { + return static_cast(random_float_impl::run(numRandomBits)); + } +}; +template <> +struct random_float_impl : random_longdouble_impl<> {}; + +template +struct random_default_impl { + using Impl = random_float_impl; + static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& x, const Scalar& y, int numRandomBits) { + Scalar half_x = Scalar(0.5) * x; + Scalar half_y = Scalar(0.5) * y; + Scalar result = (half_x + half_y) + (half_y - half_x) * run(numRandomBits); + // result is in the half-open interval [x, y) -- provided that x < y + return result; + } + static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& x, const Scalar& y) { + return run(x, y, Impl::mantissaBits()); + } + static EIGEN_DEVICE_FUNC inline Scalar run(int numRandomBits) { return Impl::run(numRandomBits); } + static EIGEN_DEVICE_FUNC inline Scalar run() { return run(Impl::mantissaBits()); } +}; + +template ::IsSigned, bool BuiltIn = std::is_integral::value> +struct random_int_impl; + +// random implementation for a built-in unsigned integer type +template +struct random_int_impl { + static constexpr int kTotalBits = sizeof(Scalar) * CHAR_BIT; + static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& x, const Scalar& y) { + if (y <= x) return x; + Scalar range = y - x; + // handle edge case where [x,y] spans the entire range of Scalar + if (range == NumTraits::highest()) return run(); + Scalar count = range + 1; + // calculate the number of random bits needed to fill range + int numRandomBits = log2_ceil(count); + Scalar randomBits; + do { + randomBits = getRandomBits(numRandomBits); + // if the random draw is outside [0, range), try again (rejection sampling) + // in the worst-case scenario, the probability of rejection is: 1/2 - 1/2^numRandomBits < 50% + } while (randomBits >= count); + Scalar result = x + randomBits; + return result; + } + static EIGEN_DEVICE_FUNC inline Scalar run() { return getRandomBits(kTotalBits); } +}; + +// random implementation for a built-in signed integer type +template +struct random_int_impl { + static constexpr int kTotalBits = sizeof(Scalar) * CHAR_BIT; + using BitsType = typename make_unsigned::type; + static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& x, const Scalar& y) { + if (y <= x) return x; + // Avoid overflow by representing `range` as an unsigned type + BitsType range = static_cast(y) - static_cast(x); + BitsType randomBits = random_int_impl::run(0, range); + // Avoid overflow in the case where `x` is negative and there is a large range so + // `randomBits` would also be negative if cast to `Scalar` first. + Scalar result = static_cast(static_cast(x) + randomBits); + return result; + } + static EIGEN_DEVICE_FUNC inline Scalar run() { return static_cast(getRandomBits(kTotalBits)); } +}; + +// todo: custom integers +template +struct random_int_impl { + static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar&, const Scalar&) { return run(); } + static EIGEN_DEVICE_FUNC inline Scalar run() { + eigen_assert(std::false_type::value && "RANDOM FOR CUSTOM INTEGERS NOT YET SUPPORTED"); + return Scalar(0); + } +}; + +template +struct random_default_impl : random_int_impl {}; + +template <> +struct random_impl { + static EIGEN_DEVICE_FUNC inline bool run(const bool& x, const bool& y) { + if (y <= x) return x; + return run(); + } + static EIGEN_DEVICE_FUNC inline bool run() { return getRandomBits(1) ? true : false; } +}; + +template +struct random_default_impl { + typedef typename NumTraits::Real RealScalar; + using Impl = random_impl; + static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& x, const Scalar& y, int numRandomBits) { + return Scalar(Impl::run(x.real(), y.real(), numRandomBits), Impl::run(x.imag(), y.imag(), numRandomBits)); + } + static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& x, const Scalar& y) { + return Scalar(Impl::run(x.real(), y.real()), Impl::run(x.imag(), y.imag())); + } + static EIGEN_DEVICE_FUNC inline Scalar run(int numRandomBits) { + return Scalar(Impl::run(numRandomBits), Impl::run(numRandomBits)); + } + static EIGEN_DEVICE_FUNC inline Scalar run() { return Scalar(Impl::run(), Impl::run()); } +}; + +} // namespace internal +} // namespace Eigen + +#endif // EIGEN_RANDOM_IMPL_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Redux.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Redux.h index b6790d11050..0c5f2d9f6b6 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Redux.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Redux.h @@ -11,7 +11,10 @@ #ifndef EIGEN_REDUX_H #define EIGEN_REDUX_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { namespace internal { @@ -20,56 +23,51 @@ namespace internal { // * factorize code /*************************************************************************** -* Part 1 : the logic deciding a strategy for vectorization and unrolling -***************************************************************************/ - -template -struct redux_traits -{ -public: - typedef typename find_best_packet::type PacketType; + * Part 1 : the logic deciding a strategy for vectorization and unrolling + ***************************************************************************/ + +template +struct redux_traits { + public: + typedef typename find_best_packet::type PacketType; enum { PacketSize = unpacket_traits::size, - InnerMaxSize = int(Evaluator::IsRowMajor) - ? Evaluator::MaxColsAtCompileTime - : Evaluator::MaxRowsAtCompileTime, - OuterMaxSize = int(Evaluator::IsRowMajor) - ? Evaluator::MaxRowsAtCompileTime - : Evaluator::MaxColsAtCompileTime, - SliceVectorizedWork = int(InnerMaxSize)==Dynamic ? Dynamic - : int(OuterMaxSize)==Dynamic ? (int(InnerMaxSize)>=int(PacketSize) ? Dynamic : 0) - : (int(InnerMaxSize)/int(PacketSize)) * int(OuterMaxSize) + InnerMaxSize = int(Evaluator::IsRowMajor) ? Evaluator::MaxColsAtCompileTime : Evaluator::MaxRowsAtCompileTime, + OuterMaxSize = int(Evaluator::IsRowMajor) ? Evaluator::MaxRowsAtCompileTime : Evaluator::MaxColsAtCompileTime, + SliceVectorizedWork = int(InnerMaxSize) == Dynamic ? Dynamic + : int(OuterMaxSize) == Dynamic ? (int(InnerMaxSize) >= int(PacketSize) ? Dynamic : 0) + : (int(InnerMaxSize) / int(PacketSize)) * int(OuterMaxSize) }; enum { - MightVectorize = (int(Evaluator::Flags)&ActualPacketAccessBit) - && (functor_traits::PacketAccess), - MayLinearVectorize = bool(MightVectorize) && (int(Evaluator::Flags)&LinearAccessBit), - MaySliceVectorize = bool(MightVectorize) && (int(SliceVectorizedWork)==Dynamic || int(SliceVectorizedWork)>=3) + MayLinearize = (int(Evaluator::Flags) & LinearAccessBit), + MightVectorize = (int(Evaluator::Flags) & ActualPacketAccessBit) && (functor_traits::PacketAccess), + MayLinearVectorize = bool(MightVectorize) && bool(MayLinearize), + MaySliceVectorize = bool(MightVectorize) && (int(SliceVectorizedWork) == Dynamic || int(SliceVectorizedWork) >= 3) }; -public: + public: enum { - Traversal = int(MayLinearVectorize) ? int(LinearVectorizedTraversal) - : int(MaySliceVectorize) ? int(SliceVectorizedTraversal) - : int(DefaultTraversal) + Traversal = int(MayLinearVectorize) ? int(LinearVectorizedTraversal) + : int(MaySliceVectorize) ? int(SliceVectorizedTraversal) + : int(MayLinearize) ? int(LinearTraversal) + : int(DefaultTraversal) }; -public: + public: enum { - Cost = Evaluator::SizeAtCompileTime == Dynamic ? HugeCost - : int(Evaluator::SizeAtCompileTime) * int(Evaluator::CoeffReadCost) + (Evaluator::SizeAtCompileTime-1) * functor_traits::Cost, + Cost = Evaluator::SizeAtCompileTime == Dynamic + ? HugeCost + : int(Evaluator::SizeAtCompileTime) * int(Evaluator::CoeffReadCost) + + (Evaluator::SizeAtCompileTime - 1) * functor_traits::Cost, UnrollingLimit = EIGEN_UNROLLING_LIMIT * (int(Traversal) == int(DefaultTraversal) ? 1 : int(PacketSize)) }; -public: - enum { - Unrolling = Cost <= UnrollingLimit ? CompleteUnrolling : NoUnrolling - }; - + public: + enum { Unrolling = Cost <= UnrollingLimit ? CompleteUnrolling : NoUnrolling }; + #ifdef EIGEN_DEBUG_ASSIGN - static void debug() - { + static void debug() { std::cerr << "Xpr: " << typeid(typename Evaluator::XprType).name() << std::endl; std::cerr.setf(std::ios::hex, std::ios::basefield); EIGEN_DEBUG_VAR(Evaluator::Flags) @@ -81,50 +79,42 @@ struct redux_traits EIGEN_DEBUG_VAR(MightVectorize) EIGEN_DEBUG_VAR(MayLinearVectorize) EIGEN_DEBUG_VAR(MaySliceVectorize) - std::cerr << "Traversal" << " = " << Traversal << " (" << demangle_traversal(Traversal) << ")" << std::endl; + std::cerr << "Traversal" + << " = " << Traversal << " (" << demangle_traversal(Traversal) << ")" << std::endl; EIGEN_DEBUG_VAR(UnrollingLimit) - std::cerr << "Unrolling" << " = " << Unrolling << " (" << demangle_unrolling(Unrolling) << ")" << std::endl; + std::cerr << "Unrolling" + << " = " << Unrolling << " (" << demangle_unrolling(Unrolling) << ")" << std::endl; std::cerr << std::endl; } #endif }; /*************************************************************************** -* Part 2 : unrollers -***************************************************************************/ + * Part 2 : unrollers + ***************************************************************************/ /*** no vectorization ***/ -template -struct redux_novec_unroller -{ - enum { - HalfLength = Length/2 - }; +template +struct redux_novec_unroller { + static constexpr Index HalfLength = Length / 2; typedef typename Evaluator::Scalar Scalar; - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE Scalar run(const Evaluator &eval, const Func& func) - { - return func(redux_novec_unroller::run(eval,func), - redux_novec_unroller::run(eval,func)); + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Evaluator& eval, const Func& func) { + return func(redux_novec_unroller::run(eval, func), + redux_novec_unroller::run(eval, func)); } }; -template -struct redux_novec_unroller -{ - enum { - outer = Start / Evaluator::InnerSizeAtCompileTime, - inner = Start % Evaluator::InnerSizeAtCompileTime - }; +template +struct redux_novec_unroller { + static constexpr Index outer = Start / Evaluator::InnerSizeAtCompileTime; + static constexpr Index inner = Start % Evaluator::InnerSizeAtCompileTime; typedef typename Evaluator::Scalar Scalar; - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE Scalar run(const Evaluator &eval, const Func&) - { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Evaluator& eval, const Func&) { return eval.coeffByOuterInner(outer, inner); } }; @@ -132,150 +122,201 @@ struct redux_novec_unroller // This is actually dead code and will never be called. It is required // to prevent false warnings regarding failed inlining though // for 0 length run() will never be called at all. -template -struct redux_novec_unroller -{ +template +struct redux_novec_unroller { + typedef typename Evaluator::Scalar Scalar; + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Evaluator&, const Func&) { return Scalar(); } +}; + +template +struct redux_novec_linear_unroller { + static constexpr Index HalfLength = Length / 2; + typedef typename Evaluator::Scalar Scalar; - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE Scalar run(const Evaluator&, const Func&) { return Scalar(); } + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Evaluator& eval, const Func& func) { + return func(redux_novec_linear_unroller::run(eval, func), + redux_novec_linear_unroller::run(eval, func)); + } +}; + +template +struct redux_novec_linear_unroller { + typedef typename Evaluator::Scalar Scalar; + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Evaluator& eval, const Func&) { + return eval.coeff(Start); + } +}; + +// This is actually dead code and will never be called. It is required +// to prevent false warnings regarding failed inlining though +// for 0 length run() will never be called at all. +template +struct redux_novec_linear_unroller { + typedef typename Evaluator::Scalar Scalar; + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Evaluator&, const Func&) { return Scalar(); } }; /*** vectorization ***/ -template -struct redux_vec_unroller -{ - template - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE PacketType run(const Evaluator &eval, const Func& func) - { - enum { - PacketSize = unpacket_traits::size, - HalfLength = Length/2 - }; +template +struct redux_vec_unroller { + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE PacketType run(const Evaluator& eval, const Func& func) { + constexpr Index HalfLength = Length / 2; return func.packetOp( - redux_vec_unroller::template run(eval,func), - redux_vec_unroller::template run(eval,func) ); + redux_vec_unroller::template run(eval, func), + redux_vec_unroller::template run(eval, + func)); } }; -template -struct redux_vec_unroller -{ - template - EIGEN_DEVICE_FUNC - static EIGEN_STRONG_INLINE PacketType run(const Evaluator &eval, const Func&) - { - enum { - PacketSize = unpacket_traits::size, - index = Start * PacketSize, - outer = index / int(Evaluator::InnerSizeAtCompileTime), - inner = index % int(Evaluator::InnerSizeAtCompileTime), - alignment = Evaluator::Alignment - }; - return eval.template packetByOuterInner(outer, inner); +template +struct redux_vec_unroller { + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE PacketType run(const Evaluator& eval, const Func&) { + constexpr Index PacketSize = unpacket_traits::size; + constexpr Index index = Start * PacketSize; + constexpr Index outer = index / int(Evaluator::InnerSizeAtCompileTime); + constexpr Index inner = index % int(Evaluator::InnerSizeAtCompileTime); + constexpr int alignment = Evaluator::Alignment; + + return eval.template packetByOuterInner(outer, inner); + } +}; + +template +struct redux_vec_linear_unroller { + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE PacketType run(const Evaluator& eval, const Func& func) { + constexpr Index HalfLength = Length / 2; + + return func.packetOp( + redux_vec_linear_unroller::template run(eval, func), + redux_vec_linear_unroller::template run( + eval, func)); + } +}; + +template +struct redux_vec_linear_unroller { + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE PacketType run(const Evaluator& eval, const Func&) { + constexpr Index PacketSize = unpacket_traits::size; + constexpr Index index = (Start * PacketSize); + constexpr int alignment = Evaluator::Alignment; + return eval.template packet(index); } }; /*************************************************************************** -* Part 3 : implementation of all cases -***************************************************************************/ + * Part 3 : implementation of all cases + ***************************************************************************/ -template::Traversal, - int Unrolling = redux_traits::Unrolling -> +template ::Traversal, + int Unrolling = redux_traits::Unrolling> struct redux_impl; -template -struct redux_impl -{ +template +struct redux_impl { typedef typename Evaluator::Scalar Scalar; - template - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE - Scalar run(const Evaluator &eval, const Func& func, const XprType& xpr) - { - eigen_assert(xpr.rows()>0 && xpr.cols()>0 && "you are using an empty matrix"); - Scalar res; - res = eval.coeffByOuterInner(0, 0); - for(Index i = 1; i < xpr.innerSize(); ++i) - res = func(res, eval.coeffByOuterInner(0, i)); - for(Index i = 1; i < xpr.outerSize(); ++i) - for(Index j = 0; j < xpr.innerSize(); ++j) - res = func(res, eval.coeffByOuterInner(i, j)); + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Evaluator& eval, const Func& func, const XprType& xpr) { + eigen_assert(xpr.rows() > 0 && xpr.cols() > 0 && "you are using an empty matrix"); + Scalar res = eval.coeffByOuterInner(0, 0); + for (Index i = 1; i < xpr.innerSize(); ++i) res = func(res, eval.coeffByOuterInner(0, i)); + for (Index i = 1; i < xpr.outerSize(); ++i) + for (Index j = 0; j < xpr.innerSize(); ++j) res = func(res, eval.coeffByOuterInner(i, j)); return res; } }; -template -struct redux_impl - : redux_novec_unroller -{ - typedef redux_novec_unroller Base; +template +struct redux_impl { typedef typename Evaluator::Scalar Scalar; - template - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE - Scalar run(const Evaluator &eval, const Func& func, const XprType& /*xpr*/) - { - return Base::run(eval,func); + + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Evaluator& eval, const Func& func, const XprType& xpr) { + eigen_assert(xpr.size() > 0 && "you are using an empty matrix"); + Scalar res = eval.coeff(0); + for (Index k = 1; k < xpr.size(); ++k) res = func(res, eval.coeff(k)); + return res; } }; -template -struct redux_impl -{ +template +struct redux_impl + : redux_novec_unroller { + typedef redux_novec_unroller Base; + typedef typename Evaluator::Scalar Scalar; + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Evaluator& eval, const Func& func, + const XprType& /*xpr*/) { + return Base::run(eval, func); + } +}; + +template +struct redux_impl + : redux_novec_linear_unroller { + typedef redux_novec_linear_unroller Base; + typedef typename Evaluator::Scalar Scalar; + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Evaluator& eval, const Func& func, + const XprType& /*xpr*/) { + return Base::run(eval, func); + } +}; + +template +struct redux_impl { typedef typename Evaluator::Scalar Scalar; typedef typename redux_traits::PacketType PacketScalar; - template - static Scalar run(const Evaluator &eval, const Func& func, const XprType& xpr) - { + template + static Scalar run(const Evaluator& eval, const Func& func, const XprType& xpr) { const Index size = xpr.size(); - - const Index packetSize = redux_traits::PacketSize; - const int packetAlignment = unpacket_traits::alignment; - enum { - alignment0 = (bool(Evaluator::Flags & DirectAccessBit) && bool(packet_traits::AlignedOnScalar)) ? int(packetAlignment) : int(Unaligned), - alignment = EIGEN_PLAIN_ENUM_MAX(alignment0, Evaluator::Alignment) - }; + + constexpr Index packetSize = redux_traits::PacketSize; + constexpr int packetAlignment = unpacket_traits::alignment; + constexpr int alignment0 = + (bool(Evaluator::Flags & DirectAccessBit) && bool(packet_traits::AlignedOnScalar)) + ? int(packetAlignment) + : int(Unaligned); + constexpr int alignment = plain_enum_max(alignment0, Evaluator::Alignment); const Index alignedStart = internal::first_default_aligned(xpr); - const Index alignedSize2 = ((size-alignedStart)/(2*packetSize))*(2*packetSize); - const Index alignedSize = ((size-alignedStart)/(packetSize))*(packetSize); + const Index alignedSize2 = ((size - alignedStart) / (2 * packetSize)) * (2 * packetSize); + const Index alignedSize = ((size - alignedStart) / (packetSize)) * (packetSize); const Index alignedEnd2 = alignedStart + alignedSize2; - const Index alignedEnd = alignedStart + alignedSize; + const Index alignedEnd = alignedStart + alignedSize; Scalar res; - if(alignedSize) - { - PacketScalar packet_res0 = eval.template packet(alignedStart); - if(alignedSize>packetSize) // we have at least two packets to partly unroll the loop + if (alignedSize) { + PacketScalar packet_res0 = eval.template packet(alignedStart); + if (alignedSize > packetSize) // we have at least two packets to partly unroll the loop { - PacketScalar packet_res1 = eval.template packet(alignedStart+packetSize); - for(Index index = alignedStart + 2*packetSize; index < alignedEnd2; index += 2*packetSize) - { - packet_res0 = func.packetOp(packet_res0, eval.template packet(index)); - packet_res1 = func.packetOp(packet_res1, eval.template packet(index+packetSize)); + PacketScalar packet_res1 = eval.template packet(alignedStart + packetSize); + for (Index index = alignedStart + 2 * packetSize; index < alignedEnd2; index += 2 * packetSize) { + packet_res0 = func.packetOp(packet_res0, eval.template packet(index)); + packet_res1 = func.packetOp(packet_res1, eval.template packet(index + packetSize)); } - packet_res0 = func.packetOp(packet_res0,packet_res1); - if(alignedEnd>alignedEnd2) - packet_res0 = func.packetOp(packet_res0, eval.template packet(alignedEnd2)); + packet_res0 = func.packetOp(packet_res0, packet_res1); + if (alignedEnd > alignedEnd2) + packet_res0 = func.packetOp(packet_res0, eval.template packet(alignedEnd2)); } res = func.predux(packet_res0); - for(Index index = 0; index < alignedStart; ++index) - res = func(res,eval.coeff(index)); + for (Index index = 0; index < alignedStart; ++index) res = func(res, eval.coeff(index)); - for(Index index = alignedEnd; index < size; ++index) - res = func(res,eval.coeff(index)); - } - else // too small to vectorize anything. - // since this is dynamic-size hence inefficient anyway for such small sizes, don't try to optimize. + for (Index index = alignedEnd; index < size; ++index) res = func(res, eval.coeff(index)); + } else // too small to vectorize anything. + // since this is dynamic-size hence inefficient anyway for such small sizes, don't try to optimize. { res = eval.coeff(0); - for(Index index = 1; index < size; ++index) - res = func(res,eval.coeff(index)); + for (Index index = 1; index < size; ++index) res = func(res, eval.coeff(index)); } return res; @@ -283,37 +324,30 @@ struct redux_impl }; // NOTE: for SliceVectorizedTraversal we simply bypass unrolling -template -struct redux_impl -{ +template +struct redux_impl { typedef typename Evaluator::Scalar Scalar; typedef typename redux_traits::PacketType PacketType; - template - EIGEN_DEVICE_FUNC static Scalar run(const Evaluator &eval, const Func& func, const XprType& xpr) - { - eigen_assert(xpr.rows()>0 && xpr.cols()>0 && "you are using an empty matrix"); + template + EIGEN_DEVICE_FUNC static Scalar run(const Evaluator& eval, const Func& func, const XprType& xpr) { + eigen_assert(xpr.rows() > 0 && xpr.cols() > 0 && "you are using an empty matrix"); + constexpr Index packetSize = redux_traits::PacketSize; const Index innerSize = xpr.innerSize(); const Index outerSize = xpr.outerSize(); - enum { - packetSize = redux_traits::PacketSize - }; - const Index packetedInnerSize = ((innerSize)/packetSize)*packetSize; + const Index packetedInnerSize = ((innerSize) / packetSize) * packetSize; Scalar res; - if(packetedInnerSize) - { - PacketType packet_res = eval.template packet(0,0); - for(Index j=0; j(j,i)); + if (packetedInnerSize) { + PacketType packet_res = eval.template packet(0, 0); + for (Index j = 0; j < outerSize; ++j) + for (Index i = (j == 0 ? packetSize : 0); i < packetedInnerSize; i += Index(packetSize)) + packet_res = func.packetOp(packet_res, eval.template packetByOuterInner(j, i)); res = func.predux(packet_res); - for(Index j=0; j::run(eval, func, xpr); } @@ -322,194 +356,173 @@ struct redux_impl } }; -template -struct redux_impl -{ +template +struct redux_impl { typedef typename Evaluator::Scalar Scalar; typedef typename redux_traits::PacketType PacketType; - enum { - PacketSize = redux_traits::PacketSize, - Size = Evaluator::SizeAtCompileTime, - VectorizedSize = (int(Size) / int(PacketSize)) * int(PacketSize) - }; + static constexpr Index PacketSize = redux_traits::PacketSize; + static constexpr Index Size = Evaluator::SizeAtCompileTime; + static constexpr Index VectorizedSize = (int(Size) / int(PacketSize)) * int(PacketSize); - template - EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE - Scalar run(const Evaluator &eval, const Func& func, const XprType &xpr) - { + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Evaluator& eval, const Func& func, const XprType& xpr) { EIGEN_ONLY_USED_FOR_DEBUG(xpr) - eigen_assert(xpr.rows()>0 && xpr.cols()>0 && "you are using an empty matrix"); + eigen_assert(xpr.rows() > 0 && xpr.cols() > 0 && "you are using an empty matrix"); if (VectorizedSize > 0) { - Scalar res = func.predux(redux_vec_unroller::template run(eval,func)); + Scalar res = func.predux( + redux_vec_linear_unroller::template run(eval, func)); if (VectorizedSize != Size) - res = func(res,redux_novec_unroller::run(eval,func)); + res = func( + res, redux_novec_linear_unroller::run(eval, func)); return res; - } - else { - return redux_novec_unroller::run(eval,func); + } else { + return redux_novec_linear_unroller::run(eval, func); } } }; // evaluator adaptor -template -class redux_evaluator : public internal::evaluator<_XprType> -{ - typedef internal::evaluator<_XprType> Base; -public: - typedef _XprType XprType; - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - explicit redux_evaluator(const XprType &xpr) : Base(xpr) {} - +template +class redux_evaluator : public internal::evaluator { + typedef internal::evaluator Base; + + public: + typedef XprType_ XprType; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit redux_evaluator(const XprType& xpr) : Base(xpr) {} + typedef typename XprType::Scalar Scalar; typedef typename XprType::CoeffReturnType CoeffReturnType; typedef typename XprType::PacketScalar PacketScalar; - + enum { MaxRowsAtCompileTime = XprType::MaxRowsAtCompileTime, MaxColsAtCompileTime = XprType::MaxColsAtCompileTime, - // TODO we should not remove DirectAccessBit and rather find an elegant way to query the alignment offset at runtime from the evaluator + // TODO we should not remove DirectAccessBit and rather find an elegant way to query the alignment offset at runtime + // from the evaluator Flags = Base::Flags & ~DirectAccessBit, IsRowMajor = XprType::IsRowMajor, SizeAtCompileTime = XprType::SizeAtCompileTime, InnerSizeAtCompileTime = XprType::InnerSizeAtCompileTime }; - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - CoeffReturnType coeffByOuterInner(Index outer, Index inner) const - { return Base::coeff(IsRowMajor ? outer : inner, IsRowMajor ? inner : outer); } - - template - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - PacketType packetByOuterInner(Index outer, Index inner) const - { return Base::template packet(IsRowMajor ? outer : inner, IsRowMajor ? inner : outer); } - + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeffByOuterInner(Index outer, Index inner) const { + return Base::coeff(IsRowMajor ? outer : inner, IsRowMajor ? inner : outer); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketType packetByOuterInner(Index outer, Index inner) const { + return Base::template packet(IsRowMajor ? outer : inner, IsRowMajor ? inner : outer); + } }; -} // end namespace internal +} // end namespace internal /*************************************************************************** -* Part 4 : public API -***************************************************************************/ - + * Part 4 : public API + ***************************************************************************/ /** \returns the result of a full redux operation on the whole matrix or vector using \a func - * - * The template parameter \a BinaryOp is the type of the functor \a func which must be - * an associative operator. Both current C++98 and C++11 functor styles are handled. - * - * \warning the matrix must be not empty, otherwise an assertion is triggered. - * - * \sa DenseBase::sum(), DenseBase::minCoeff(), DenseBase::maxCoeff(), MatrixBase::colwise(), MatrixBase::rowwise() - */ -template -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar -DenseBase::redux(const Func& func) const -{ - eigen_assert(this->rows()>0 && this->cols()>0 && "you are using an empty matrix"); + * + * The template parameter \a BinaryOp is the type of the functor \a func which must be + * an associative operator. Both current C++98 and C++11 functor styles are handled. + * + * \warning the matrix must be not empty, otherwise an assertion is triggered. + * + * \sa DenseBase::sum(), DenseBase::minCoeff(), DenseBase::maxCoeff(), MatrixBase::colwise(), MatrixBase::rowwise() + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar DenseBase::redux( + const Func& func) const { + eigen_assert(this->rows() > 0 && this->cols() > 0 && "you are using an empty matrix"); typedef typename internal::redux_evaluator ThisEvaluator; ThisEvaluator thisEval(derived()); // The initial expression is passed to the reducer as an additional argument instead of - // passing it as a member of redux_evaluator to help + // passing it as a member of redux_evaluator to help return internal::redux_impl::run(thisEval, func, derived()); } /** \returns the minimum of all coefficients of \c *this. - * In case \c *this contains NaN, NaNPropagation determines the behavior: - * NaNPropagation == PropagateFast : undefined - * NaNPropagation == PropagateNaN : result is NaN - * NaNPropagation == PropagateNumbers : result is minimum of elements that are not NaN - * \warning the matrix must be not empty, otherwise an assertion is triggered. - */ -template -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar -DenseBase::minCoeff() const -{ - return derived().redux(Eigen::internal::scalar_min_op()); + * In case \c *this contains NaN, NaNPropagation determines the behavior: + * NaNPropagation == PropagateFast : undefined + * NaNPropagation == PropagateNaN : result is NaN + * NaNPropagation == PropagateNumbers : result is minimum of elements that are not NaN + * \warning the matrix must be not empty, otherwise an assertion is triggered. + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar DenseBase::minCoeff() const { + return derived().redux(Eigen::internal::scalar_min_op()); } -/** \returns the maximum of all coefficients of \c *this. - * In case \c *this contains NaN, NaNPropagation determines the behavior: - * NaNPropagation == PropagateFast : undefined - * NaNPropagation == PropagateNaN : result is NaN - * NaNPropagation == PropagateNumbers : result is maximum of elements that are not NaN - * \warning the matrix must be not empty, otherwise an assertion is triggered. - */ -template -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar -DenseBase::maxCoeff() const -{ - return derived().redux(Eigen::internal::scalar_max_op()); +/** \returns the maximum of all coefficients of \c *this. + * In case \c *this contains NaN, NaNPropagation determines the behavior: + * NaNPropagation == PropagateFast : undefined + * NaNPropagation == PropagateNaN : result is NaN + * NaNPropagation == PropagateNumbers : result is maximum of elements that are not NaN + * \warning the matrix must be not empty, otherwise an assertion is triggered. + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar DenseBase::maxCoeff() const { + return derived().redux(Eigen::internal::scalar_max_op()); } /** \returns the sum of all coefficients of \c *this - * - * If \c *this is empty, then the value 0 is returned. - * - * \sa trace(), prod(), mean() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar -DenseBase::sum() const -{ - if(SizeAtCompileTime==0 || (SizeAtCompileTime==Dynamic && size()==0)) - return Scalar(0); - return derived().redux(Eigen::internal::scalar_sum_op()); + * + * If \c *this is empty, then the value 0 is returned. + * + * \sa trace(), prod(), mean() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar DenseBase::sum() const { + if (SizeAtCompileTime == 0 || (SizeAtCompileTime == Dynamic && size() == 0)) return Scalar(0); + return derived().redux(Eigen::internal::scalar_sum_op()); } /** \returns the mean of all coefficients of *this -* -* \sa trace(), prod(), sum() -*/ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar -DenseBase::mean() const -{ + * + * \sa trace(), prod(), sum() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar DenseBase::mean() const { #ifdef __INTEL_COMPILER - #pragma warning push - #pragma warning ( disable : 2259 ) +#pragma warning push +#pragma warning(disable : 2259) #endif - return Scalar(derived().redux(Eigen::internal::scalar_sum_op())) / Scalar(this->size()); + return Scalar(derived().redux(Eigen::internal::scalar_sum_op())) / Scalar(this->size()); #ifdef __INTEL_COMPILER - #pragma warning pop +#pragma warning pop #endif } /** \returns the product of all coefficients of *this - * - * Example: \include MatrixBase_prod.cpp - * Output: \verbinclude MatrixBase_prod.out - * - * \sa sum(), mean(), trace() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar -DenseBase::prod() const -{ - if(SizeAtCompileTime==0 || (SizeAtCompileTime==Dynamic && size()==0)) - return Scalar(1); + * + * Example: \include MatrixBase_prod.cpp + * Output: \verbinclude MatrixBase_prod.out + * + * \sa sum(), mean(), trace() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar DenseBase::prod() const { + if (SizeAtCompileTime == 0 || (SizeAtCompileTime == Dynamic && size() == 0)) return Scalar(1); return derived().redux(Eigen::internal::scalar_product_op()); } /** \returns the trace of \c *this, i.e. the sum of the coefficients on the main diagonal. - * - * \c *this can be any matrix, not necessarily square. - * - * \sa diagonal(), sum() - */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar -MatrixBase::trace() const -{ + * + * \c *this can be any matrix, not necessarily square. + * + * \sa diagonal(), sum() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename internal::traits::Scalar MatrixBase::trace() const { return derived().diagonal().sum(); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_REDUX_H +#endif // EIGEN_REDUX_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Ref.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Ref.h index c2a37eadbb6..129bc85f46f 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Ref.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Ref.h @@ -10,197 +10,185 @@ #ifndef EIGEN_REF_H #define EIGEN_REF_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > - : public traits > -{ - typedef _PlainObjectType PlainObjectType; - typedef _StrideType StrideType; +template +struct traits > + : public traits > { + typedef PlainObjectType_ PlainObjectType; + typedef StrideType_ StrideType; enum { - Options = _Options, - Flags = traits >::Flags | NestByRefBit, - Alignment = traits >::Alignment + Options = Options_, + Flags = traits >::Flags | NestByRefBit, + Alignment = traits >::Alignment, + InnerStrideAtCompileTime = traits >::InnerStrideAtCompileTime, + OuterStrideAtCompileTime = traits >::OuterStrideAtCompileTime }; - template struct match { + template + struct match { enum { IsVectorAtCompileTime = PlainObjectType::IsVectorAtCompileTime || Derived::IsVectorAtCompileTime, HasDirectAccess = internal::has_direct_access::ret, - StorageOrderMatch = IsVectorAtCompileTime || ((PlainObjectType::Flags&RowMajorBit)==(Derived::Flags&RowMajorBit)), - InnerStrideMatch = int(StrideType::InnerStrideAtCompileTime)==int(Dynamic) - || int(StrideType::InnerStrideAtCompileTime)==int(Derived::InnerStrideAtCompileTime) - || (int(StrideType::InnerStrideAtCompileTime)==0 && int(Derived::InnerStrideAtCompileTime)==1), - OuterStrideMatch = IsVectorAtCompileTime - || int(StrideType::OuterStrideAtCompileTime)==int(Dynamic) || int(StrideType::OuterStrideAtCompileTime)==int(Derived::OuterStrideAtCompileTime), + StorageOrderMatch = + IsVectorAtCompileTime || ((PlainObjectType::Flags & RowMajorBit) == (Derived::Flags & RowMajorBit)), + InnerStrideMatch = int(InnerStrideAtCompileTime) == int(Dynamic) || + int(InnerStrideAtCompileTime) == int(Derived::InnerStrideAtCompileTime) || + (int(InnerStrideAtCompileTime) == 0 && int(Derived::InnerStrideAtCompileTime) == 1), + OuterStrideMatch = IsVectorAtCompileTime || int(OuterStrideAtCompileTime) == int(Dynamic) || + int(OuterStrideAtCompileTime) == int(Derived::OuterStrideAtCompileTime), // NOTE, this indirection of evaluator::Alignment is needed // to workaround a very strange bug in MSVC related to the instantiation // of has_*ary_operator in evaluator. // This line is surprisingly very sensitive. For instance, simply adding parenthesis // as "DerivedAlignment = (int(evaluator::Alignment))," will make MSVC fail... DerivedAlignment = int(evaluator::Alignment), - AlignmentMatch = (int(traits::Alignment)==int(Unaligned)) || (DerivedAlignment >= int(Alignment)), // FIXME the first condition is not very clear, it should be replaced by the required alignment + AlignmentMatch = (int(traits::Alignment) == int(Unaligned)) || + (DerivedAlignment >= int(Alignment)), // FIXME the first condition is not very clear, it should + // be replaced by the required alignment ScalarTypeMatch = internal::is_same::value, - MatchAtCompileTime = HasDirectAccess && StorageOrderMatch && InnerStrideMatch && OuterStrideMatch && AlignmentMatch && ScalarTypeMatch + MatchAtCompileTime = HasDirectAccess && StorageOrderMatch && InnerStrideMatch && OuterStrideMatch && + AlignmentMatch && ScalarTypeMatch }; - typedef typename internal::conditional::type type; + typedef std::conditional_t type; }; - }; -template +template struct traits > : public traits {}; -} +} // namespace internal -template class RefBase - : public MapBase -{ +template +class RefBase : public MapBase { typedef typename internal::traits::PlainObjectType PlainObjectType; typedef typename internal::traits::StrideType StrideType; -public: - + public: typedef MapBase Base; EIGEN_DENSE_PUBLIC_INTERFACE(RefBase) - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const - { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const { return StrideType::InnerStrideAtCompileTime != 0 ? m_stride.inner() : 1; } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const - { + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const { return StrideType::OuterStrideAtCompileTime != 0 ? m_stride.outer() - : IsVectorAtCompileTime ? this->size() - : int(Flags)&RowMajorBit ? this->cols() - : this->rows(); + : IsVectorAtCompileTime ? this->size() + : int(Flags) & RowMajorBit ? this->cols() + : this->rows(); } EIGEN_DEVICE_FUNC RefBase() - : Base(0,RowsAtCompileTime==Dynamic?0:RowsAtCompileTime,ColsAtCompileTime==Dynamic?0:ColsAtCompileTime), - // Stride<> does not allow default ctor for Dynamic strides, so let' initialize it with dummy values: - m_stride(StrideType::OuterStrideAtCompileTime==Dynamic?0:StrideType::OuterStrideAtCompileTime, - StrideType::InnerStrideAtCompileTime==Dynamic?0:StrideType::InnerStrideAtCompileTime) - {} + : Base(0, RowsAtCompileTime == Dynamic ? 0 : RowsAtCompileTime, + ColsAtCompileTime == Dynamic ? 0 : ColsAtCompileTime), + // Stride<> does not allow default ctor for Dynamic strides, so let' initialize it with dummy values: + m_stride(StrideType::OuterStrideAtCompileTime == Dynamic ? 0 : StrideType::OuterStrideAtCompileTime, + StrideType::InnerStrideAtCompileTime == Dynamic ? 0 : StrideType::InnerStrideAtCompileTime) {} EIGEN_INHERIT_ASSIGNMENT_OPERATORS(RefBase) -protected: - - typedef Stride StrideBase; + protected: + typedef Stride StrideBase; // Resolves inner stride if default 0. - static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index resolveInnerStride(Index inner) { - return inner == 0 ? 1 : inner; - } + static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index resolveInnerStride(Index inner) { return inner == 0 ? 1 : inner; } // Resolves outer stride if default 0. - static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index resolveOuterStride(Index inner, Index outer, Index rows, Index cols, bool isVectorAtCompileTime, bool isRowMajor) { + static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index resolveOuterStride(Index inner, Index outer, Index rows, Index cols, + bool isVectorAtCompileTime, bool isRowMajor) { return outer == 0 ? isVectorAtCompileTime ? inner * rows * cols : isRowMajor ? inner * cols : inner * rows : outer; } // Returns true if construction is valid, false if there is a stride mismatch, // and fails if there is a size mismatch. - template - EIGEN_DEVICE_FUNC bool construct(Expression& expr) - { + template + EIGEN_DEVICE_FUNC bool construct(Expression& expr) { // Check matrix sizes. If this is a compile-time vector, we do allow // implicitly transposing. - EIGEN_STATIC_ASSERT( - EIGEN_PREDICATE_SAME_MATRIX_SIZE(PlainObjectType, Expression) - // If it is a vector, the transpose sizes might match. - || ( PlainObjectType::IsVectorAtCompileTime - && ((int(PlainObjectType::RowsAtCompileTime)==Eigen::Dynamic - || int(Expression::ColsAtCompileTime)==Eigen::Dynamic - || int(PlainObjectType::RowsAtCompileTime)==int(Expression::ColsAtCompileTime)) - && (int(PlainObjectType::ColsAtCompileTime)==Eigen::Dynamic - || int(Expression::RowsAtCompileTime)==Eigen::Dynamic - || int(PlainObjectType::ColsAtCompileTime)==int(Expression::RowsAtCompileTime)))), - YOU_MIXED_MATRICES_OF_DIFFERENT_SIZES - ) + EIGEN_STATIC_ASSERT(EIGEN_PREDICATE_SAME_MATRIX_SIZE(PlainObjectType, Expression) + // If it is a vector, the transpose sizes might match. + || (PlainObjectType::IsVectorAtCompileTime && + ((int(PlainObjectType::RowsAtCompileTime) == Eigen::Dynamic || + int(Expression::ColsAtCompileTime) == Eigen::Dynamic || + int(PlainObjectType::RowsAtCompileTime) == int(Expression::ColsAtCompileTime)) && + (int(PlainObjectType::ColsAtCompileTime) == Eigen::Dynamic || + int(Expression::RowsAtCompileTime) == Eigen::Dynamic || + int(PlainObjectType::ColsAtCompileTime) == int(Expression::RowsAtCompileTime)))), + YOU_MIXED_MATRICES_OF_DIFFERENT_SIZES) // Determine runtime rows and columns. Index rows = expr.rows(); Index cols = expr.cols(); - if(PlainObjectType::RowsAtCompileTime==1) - { - eigen_assert(expr.rows()==1 || expr.cols()==1); + if (PlainObjectType::RowsAtCompileTime == 1) { + eigen_assert(expr.rows() == 1 || expr.cols() == 1); rows = 1; cols = expr.size(); - } - else if(PlainObjectType::ColsAtCompileTime==1) - { - eigen_assert(expr.rows()==1 || expr.cols()==1); + } else if (PlainObjectType::ColsAtCompileTime == 1) { + eigen_assert(expr.rows() == 1 || expr.cols() == 1); rows = expr.size(); cols = 1; } // Verify that the sizes are valid. - eigen_assert( - (PlainObjectType::RowsAtCompileTime == Dynamic) || (PlainObjectType::RowsAtCompileTime == rows)); - eigen_assert( - (PlainObjectType::ColsAtCompileTime == Dynamic) || (PlainObjectType::ColsAtCompileTime == cols)); - + eigen_assert((PlainObjectType::RowsAtCompileTime == Dynamic) || (PlainObjectType::RowsAtCompileTime == rows)); + eigen_assert((PlainObjectType::ColsAtCompileTime == Dynamic) || (PlainObjectType::ColsAtCompileTime == cols)); // If this is a vector, we might be transposing, which means that stride should swap. const bool transpose = PlainObjectType::IsVectorAtCompileTime && (rows != expr.rows()); // If the storage format differs, we also need to swap the stride. const bool row_major = ((PlainObjectType::Flags)&RowMajorBit) != 0; - const bool expr_row_major = (Expression::Flags&RowMajorBit) != 0; - const bool storage_differs = (row_major != expr_row_major); + const bool expr_row_major = (Expression::Flags & RowMajorBit) != 0; + const bool storage_differs = (row_major != expr_row_major); const bool swap_stride = (transpose != storage_differs); // Determine expr's actual strides, resolving any defaults if zero. const Index expr_inner_actual = resolveInnerStride(expr.innerStride()); - const Index expr_outer_actual = resolveOuterStride(expr_inner_actual, - expr.outerStride(), - expr.rows(), - expr.cols(), - Expression::IsVectorAtCompileTime != 0, - expr_row_major); + const Index expr_outer_actual = resolveOuterStride(expr_inner_actual, expr.outerStride(), expr.rows(), expr.cols(), + Expression::IsVectorAtCompileTime != 0, expr_row_major); // If this is a column-major row vector or row-major column vector, the inner-stride // is arbitrary, so set it to either the compile-time inner stride or 1. const bool row_vector = (rows == 1); const bool col_vector = (cols == 1); const Index inner_stride = - ( (!row_major && row_vector) || (row_major && col_vector) ) ? - ( StrideType::InnerStrideAtCompileTime > 0 ? Index(StrideType::InnerStrideAtCompileTime) : 1) - : swap_stride ? expr_outer_actual : expr_inner_actual; + ((!row_major && row_vector) || (row_major && col_vector)) + ? (StrideType::InnerStrideAtCompileTime > 0 ? Index(StrideType::InnerStrideAtCompileTime) : 1) + : swap_stride ? expr_outer_actual + : expr_inner_actual; // If this is a column-major column vector or row-major row vector, the outer-stride // is arbitrary, so set it to either the compile-time outer stride or vector size. const Index outer_stride = - ( (!row_major && col_vector) || (row_major && row_vector) ) ? - ( StrideType::OuterStrideAtCompileTime > 0 ? Index(StrideType::OuterStrideAtCompileTime) : rows * cols * inner_stride) - : swap_stride ? expr_inner_actual : expr_outer_actual; + ((!row_major && col_vector) || (row_major && row_vector)) + ? (StrideType::OuterStrideAtCompileTime > 0 ? Index(StrideType::OuterStrideAtCompileTime) + : rows * cols * inner_stride) + : swap_stride ? expr_inner_actual + : expr_outer_actual; // Check if given inner/outer strides are compatible with compile-time strides. - const bool inner_valid = (StrideType::InnerStrideAtCompileTime == Dynamic) - || (resolveInnerStride(Index(StrideType::InnerStrideAtCompileTime)) == inner_stride); + const bool inner_valid = (StrideType::InnerStrideAtCompileTime == Dynamic) || + (resolveInnerStride(Index(StrideType::InnerStrideAtCompileTime)) == inner_stride); if (!inner_valid) { return false; } - const bool outer_valid = (StrideType::OuterStrideAtCompileTime == Dynamic) - || (resolveOuterStride( - inner_stride, - Index(StrideType::OuterStrideAtCompileTime), - rows, cols, PlainObjectType::IsVectorAtCompileTime != 0, - row_major) - == outer_stride); + const bool outer_valid = + (StrideType::OuterStrideAtCompileTime == Dynamic) || + (resolveOuterStride(inner_stride, Index(StrideType::OuterStrideAtCompileTime), rows, cols, + PlainObjectType::IsVectorAtCompileTime != 0, row_major) == outer_stride); if (!outer_valid) { return false; } - ::new (static_cast(this)) Base(expr.data(), rows, cols); - ::new (&m_stride) StrideBase( - (StrideType::OuterStrideAtCompileTime == 0) ? 0 : outer_stride, - (StrideType::InnerStrideAtCompileTime == 0) ? 0 : inner_stride ); + internal::construct_at(this, expr.data(), rows, cols); + internal::construct_at(&m_stride, (StrideType::OuterStrideAtCompileTime == 0) ? 0 : outer_stride, + (StrideType::InnerStrideAtCompileTime == 0) ? 0 : inner_stride); return true; } @@ -208,174 +196,188 @@ template class RefBase }; /** \class Ref - * \ingroup Core_Module - * - * \brief A matrix or vector expression mapping an existing expression - * - * \tparam PlainObjectType the equivalent matrix type of the mapped data - * \tparam Options specifies the pointer alignment in bytes. It can be: \c #Aligned128, , \c #Aligned64, \c #Aligned32, \c #Aligned16, \c #Aligned8 or \c #Unaligned. - * The default is \c #Unaligned. - * \tparam StrideType optionally specifies strides. By default, Ref implies a contiguous storage along the inner dimension (inner stride==1), - * but accepts a variable outer stride (leading dimension). - * This can be overridden by specifying strides. - * The type passed here must be a specialization of the Stride template, see examples below. - * - * This class provides a way to write non-template functions taking Eigen objects as parameters while limiting the number of copies. - * A Ref<> object can represent either a const expression or a l-value: - * \code - * // in-out argument: - * void foo1(Ref x); - * - * // read-only const argument: - * void foo2(const Ref& x); - * \endcode - * - * In the in-out case, the input argument must satisfy the constraints of the actual Ref<> type, otherwise a compilation issue will be triggered. - * By default, a Ref can reference any dense vector expression of float having a contiguous memory layout. - * Likewise, a Ref can reference any column-major dense matrix expression of float whose column's elements are contiguously stored with - * the possibility to have a constant space in-between each column, i.e. the inner stride must be equal to 1, but the outer stride (or leading dimension) - * can be greater than the number of rows. - * - * In the const case, if the input expression does not match the above requirement, then it is evaluated into a temporary before being passed to the function. - * Here are some examples: - * \code - * MatrixXf A; - * VectorXf a; - * foo1(a.head()); // OK - * foo1(A.col()); // OK - * foo1(A.row()); // Compilation error because here innerstride!=1 - * foo2(A.row()); // Compilation error because A.row() is a 1xN object while foo2 is expecting a Nx1 object - * foo2(A.row().transpose()); // The row is copied into a contiguous temporary - * foo2(2*a); // The expression is evaluated into a temporary - * foo2(A.col().segment(2,4)); // No temporary - * \endcode - * - * The range of inputs that can be referenced without temporary can be enlarged using the last two template parameters. - * Here is an example accepting an innerstride!=1: - * \code - * // in-out argument: - * void foo3(Ref > x); - * foo3(A.row()); // OK - * \endcode - * The downside here is that the function foo3 might be significantly slower than foo1 because it won't be able to exploit vectorization, and will involve more - * expensive address computations even if the input is contiguously stored in memory. To overcome this issue, one might propose to overload internally calling a - * template function, e.g.: - * \code - * // in the .h: - * void foo(const Ref& A); - * void foo(const Ref >& A); - * - * // in the .cpp: - * template void foo_impl(const TypeOfA& A) { - * ... // crazy code goes here - * } - * void foo(const Ref& A) { foo_impl(A); } - * void foo(const Ref >& A) { foo_impl(A); } - * \endcode - * - * See also the following stackoverflow questions for further references: - * - Correct usage of the Eigen::Ref<> class - * - * \sa PlainObjectBase::Map(), \ref TopicStorageOrders - */ -template class Ref - : public RefBase > -{ - private: - typedef internal::traits Traits; - template - EIGEN_DEVICE_FUNC inline Ref(const PlainObjectBase& expr, - typename internal::enable_if::MatchAtCompileTime),Derived>::type* = 0); - public: - - typedef RefBase Base; - EIGEN_DENSE_PUBLIC_INTERFACE(Ref) - - - #ifndef EIGEN_PARSED_BY_DOXYGEN - template - EIGEN_DEVICE_FUNC inline Ref(PlainObjectBase& expr, - typename internal::enable_if::MatchAtCompileTime),Derived>::type* = 0) - { - EIGEN_STATIC_ASSERT(bool(Traits::template match::MatchAtCompileTime), STORAGE_LAYOUT_DOES_NOT_MATCH); - // Construction must pass since we will not create temprary storage in the non-const case. - const bool success = Base::construct(expr.derived()); - EIGEN_UNUSED_VARIABLE(success) - eigen_assert(success); - } - template - EIGEN_DEVICE_FUNC inline Ref(const DenseBase& expr, - typename internal::enable_if::MatchAtCompileTime),Derived>::type* = 0) - #else - /** Implicit constructor from any dense expression */ - template - inline Ref(DenseBase& expr) - #endif - { - EIGEN_STATIC_ASSERT(bool(internal::is_lvalue::value), THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY); - EIGEN_STATIC_ASSERT(bool(Traits::template match::MatchAtCompileTime), STORAGE_LAYOUT_DOES_NOT_MATCH); - EIGEN_STATIC_ASSERT(!Derived::IsPlainObjectBase,THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY); - // Construction must pass since we will not create temporary storage in the non-const case. - const bool success = Base::construct(expr.const_cast_derived()); - EIGEN_UNUSED_VARIABLE(success) - eigen_assert(success); - } - - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Ref) + * \ingroup Core_Module + * + * \brief A matrix or vector expression mapping an existing expression + * + * \tparam PlainObjectType the equivalent matrix type of the mapped data + * \tparam Options specifies the pointer alignment in bytes. It can be: \c #Aligned128, , \c #Aligned64, \c #Aligned32, + * \c #Aligned16, \c #Aligned8 or \c #Unaligned. The default is \c #Unaligned. \tparam StrideType optionally specifies + * strides. By default, Ref implies a contiguous storage along the inner dimension (inner stride==1), but accepts a + * variable outer stride (leading dimension). This can be overridden by specifying strides. The type passed here must be + * a specialization of the Stride template, see examples below. + * + * This class provides a way to write non-template functions taking Eigen objects as parameters while limiting the + * number of copies. A Ref<> object can represent either a const expression or a l-value: \code + * // in-out argument: + * void foo1(Ref x); + * + * // read-only const argument: + * void foo2(const Ref& x); + * \endcode + * + * In the in-out case, the input argument must satisfy the constraints of the actual Ref<> type, otherwise a compilation + * issue will be triggered. By default, a Ref can reference any dense vector expression of float having a + * contiguous memory layout. Likewise, a Ref can reference any column-major dense matrix expression of float + * whose column's elements are contiguously stored with the possibility to have a constant space in-between each column, + * i.e. the inner stride must be equal to 1, but the outer stride (or leading dimension) can be greater than the number + * of rows. + * + * In the const case, if the input expression does not match the above requirement, then it is evaluated into a + * temporary before being passed to the function. Here are some examples: \code MatrixXf A; VectorXf a; foo1(a.head()); + * // OK foo1(A.col()); // OK foo1(A.row()); // Compilation error because here innerstride!=1 + * foo2(A.row()); // Compilation error because A.row() is a 1xN object while foo2 is expecting a Nx1 object + * foo2(A.row().transpose()); // The row is copied into a contiguous temporary + * foo2(2*a); // The expression is evaluated into a temporary + * foo2(A.col().segment(2,4)); // No temporary + * \endcode + * + * The range of inputs that can be referenced without temporary can be enlarged using the last two template parameters. + * Here is an example accepting an innerstride!=1: + * \code + * // in-out argument: + * void foo3(Ref > x); + * foo3(A.row()); // OK + * \endcode + * The downside here is that the function foo3 might be significantly slower than foo1 because it won't be able to + * exploit vectorization, and will involve more expensive address computations even if the input is contiguously stored + * in memory. To overcome this issue, one might propose to overload internally calling a template function, e.g.: \code + * // in the .h: + * void foo(const Ref& A); + * void foo(const Ref >& A); + * + * // in the .cpp: + * template void foo_impl(const TypeOfA& A) { + * ... // crazy code goes here + * } + * void foo(const Ref& A) { foo_impl(A); } + * void foo(const Ref >& A) { foo_impl(A); } + * \endcode + * + * See also the following stackoverflow questions for further references: + * - Correct usage of the + * Eigen::Ref<> class + * + * \sa PlainObjectBase::Map(), \ref TopicStorageOrders + */ +template +class Ref : public RefBase > { + private: + typedef internal::traits Traits; + template + EIGEN_DEVICE_FUNC inline Ref( + const PlainObjectBase& expr, + std::enable_if_t::MatchAtCompileTime), Derived>* = 0); + + public: + typedef RefBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Ref) + +#ifndef EIGEN_PARSED_BY_DOXYGEN + template + EIGEN_DEVICE_FUNC inline Ref( + PlainObjectBase& expr, + std::enable_if_t::MatchAtCompileTime), Derived>* = 0) { + EIGEN_STATIC_ASSERT(bool(Traits::template match::MatchAtCompileTime), STORAGE_LAYOUT_DOES_NOT_MATCH); + // Construction must pass since we will not create temporary storage in the non-const case. + const bool success = Base::construct(expr.derived()); + EIGEN_UNUSED_VARIABLE(success) + eigen_assert(success); + } + template + EIGEN_DEVICE_FUNC inline Ref( + const DenseBase& expr, + std::enable_if_t::MatchAtCompileTime), Derived>* = 0) +#else + /** Implicit constructor from any dense expression */ + template + inline Ref(DenseBase& expr) +#endif + { + EIGEN_STATIC_ASSERT(bool(internal::is_lvalue::value), THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY); + EIGEN_STATIC_ASSERT(bool(Traits::template match::MatchAtCompileTime), STORAGE_LAYOUT_DOES_NOT_MATCH); + EIGEN_STATIC_ASSERT(!Derived::IsPlainObjectBase, THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY); + // Construction must pass since we will not create temporary storage in the non-const case. + const bool success = Base::construct(expr.const_cast_derived()); + EIGEN_UNUSED_VARIABLE(success) + eigen_assert(success); + } + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Ref) }; // this is the const ref version -template class Ref - : public RefBase > -{ - typedef internal::traits Traits; - public: - - typedef RefBase Base; - EIGEN_DENSE_PUBLIC_INTERFACE(Ref) - - template - EIGEN_DEVICE_FUNC inline Ref(const DenseBase& expr, - typename internal::enable_if::ScalarTypeMatch),Derived>::type* = 0) - { -// std::cout << match_helper::HasDirectAccess << "," << match_helper::OuterStrideMatch << "," << match_helper::InnerStrideMatch << "\n"; -// std::cout << int(StrideType::OuterStrideAtCompileTime) << " - " << int(Derived::OuterStrideAtCompileTime) << "\n"; -// std::cout << int(StrideType::InnerStrideAtCompileTime) << " - " << int(Derived::InnerStrideAtCompileTime) << "\n"; - construct(expr.derived(), typename Traits::template match::type()); - } +template +class Ref + : public RefBase > { + typedef internal::traits Traits; + + static constexpr bool may_map_m_object_successfully = + (static_cast(StrideType::InnerStrideAtCompileTime) == 0 || + static_cast(StrideType::InnerStrideAtCompileTime) == 1 || + static_cast(StrideType::InnerStrideAtCompileTime) == Dynamic) && + (TPlainObjectType::IsVectorAtCompileTime || static_cast(StrideType::OuterStrideAtCompileTime) == 0 || + static_cast(StrideType::OuterStrideAtCompileTime) == Dynamic || + static_cast(StrideType::OuterStrideAtCompileTime) == + static_cast(TPlainObjectType::InnerSizeAtCompileTime) || + static_cast(TPlainObjectType::InnerSizeAtCompileTime) == Dynamic); + + public: + typedef RefBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Ref) + + template + EIGEN_DEVICE_FUNC inline Ref(const DenseBase& expr, + std::enable_if_t::ScalarTypeMatch), Derived>* = 0) { + // std::cout << match_helper::HasDirectAccess << "," << match_helper::OuterStrideMatch << "," + // << match_helper::InnerStrideMatch << "\n"; std::cout << int(StrideType::OuterStrideAtCompileTime) + // << " - " << int(Derived::OuterStrideAtCompileTime) << "\n"; std::cout << + // int(StrideType::InnerStrideAtCompileTime) << " - " << int(Derived::InnerStrideAtCompileTime) << "\n"; + EIGEN_STATIC_ASSERT(Traits::template match::type::value || may_map_m_object_successfully, + STORAGE_LAYOUT_DOES_NOT_MATCH); + construct(expr.derived(), typename Traits::template match::type()); + } - EIGEN_DEVICE_FUNC inline Ref(const Ref& other) : Base(other) { - // copy constructor shall not copy the m_object, to avoid unnecessary malloc and copy - } + EIGEN_DEVICE_FUNC inline Ref(const Ref& other) : Base(other) { + // copy constructor shall not copy the m_object, to avoid unnecessary malloc and copy + } - template - EIGEN_DEVICE_FUNC inline Ref(const RefBase& other) { - construct(other.derived(), typename Traits::template match::type()); - } + EIGEN_DEVICE_FUNC inline Ref(Ref&& other) { + if (other.data() == other.m_object.data()) { + m_object = std::move(other.m_object); + Base::construct(m_object); + } else + Base::construct(other); + } - protected: + template + EIGEN_DEVICE_FUNC inline Ref(const RefBase& other) { + EIGEN_STATIC_ASSERT(Traits::template match::type::value || may_map_m_object_successfully, + STORAGE_LAYOUT_DOES_NOT_MATCH); + construct(other.derived(), typename Traits::template match::type()); + } - template - EIGEN_DEVICE_FUNC void construct(const Expression& expr,internal::true_type) - { - // Check if we can use the underlying expr's storage directly, otherwise call the copy version. - if (!Base::construct(expr)) { - construct(expr, internal::false_type()); - } + protected: + template + EIGEN_DEVICE_FUNC void construct(const Expression& expr, internal::true_type) { + // Check if we can use the underlying expr's storage directly, otherwise call the copy version. + if (!Base::construct(expr)) { + construct(expr, internal::false_type()); } + } - template - EIGEN_DEVICE_FUNC void construct(const Expression& expr, internal::false_type) - { - internal::call_assignment_no_alias(m_object,expr,internal::assign_op()); - Base::construct(m_object); - } + template + EIGEN_DEVICE_FUNC void construct(const Expression& expr, internal::false_type) { + internal::call_assignment_no_alias(m_object, expr, internal::assign_op()); + const bool success = Base::construct(m_object); + EIGEN_ONLY_USED_FOR_DEBUG(success) + eigen_assert(success); + } - protected: - TPlainObjectType m_object; + protected: + TPlainObjectType m_object; }; -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_REF_H +#endif // EIGEN_REF_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Replicate.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Replicate.h index ab5be7e64bc..c01c62737e9 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Replicate.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Replicate.h @@ -10,133 +10,124 @@ #ifndef EIGEN_REPLICATE_H #define EIGEN_REPLICATE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > - : traits -{ +template +struct traits > : traits { typedef typename MatrixType::Scalar Scalar; typedef typename traits::StorageKind StorageKind; typedef typename traits::XprKind XprKind; typedef typename ref_selector::type MatrixTypeNested; - typedef typename remove_reference::type _MatrixTypeNested; + typedef std::remove_reference_t MatrixTypeNested_; enum { - RowsAtCompileTime = RowFactor==Dynamic || int(MatrixType::RowsAtCompileTime)==Dynamic - ? Dynamic - : RowFactor * MatrixType::RowsAtCompileTime, - ColsAtCompileTime = ColFactor==Dynamic || int(MatrixType::ColsAtCompileTime)==Dynamic - ? Dynamic - : ColFactor * MatrixType::ColsAtCompileTime, - //FIXME we don't propagate the max sizes !!! + RowsAtCompileTime = RowFactor == Dynamic || int(MatrixType::RowsAtCompileTime) == Dynamic + ? Dynamic + : RowFactor * MatrixType::RowsAtCompileTime, + ColsAtCompileTime = ColFactor == Dynamic || int(MatrixType::ColsAtCompileTime) == Dynamic + ? Dynamic + : ColFactor * MatrixType::ColsAtCompileTime, + // FIXME we don't propagate the max sizes !!! MaxRowsAtCompileTime = RowsAtCompileTime, MaxColsAtCompileTime = ColsAtCompileTime, - IsRowMajor = MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1 ? 1 - : MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1 ? 0 - : (MatrixType::Flags & RowMajorBit) ? 1 : 0, + IsRowMajor = MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1 ? 1 + : MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1 ? 0 + : (MatrixType::Flags & RowMajorBit) ? 1 + : 0, // FIXME enable DirectAccess with negative strides? Flags = IsRowMajor ? RowMajorBit : 0 }; }; -} +} // namespace internal /** - * \class Replicate - * \ingroup Core_Module - * - * \brief Expression of the multiple replication of a matrix or vector - * - * \tparam MatrixType the type of the object we are replicating - * \tparam RowFactor number of repetitions at compile time along the vertical direction, can be Dynamic. - * \tparam ColFactor number of repetitions at compile time along the horizontal direction, can be Dynamic. - * - * This class represents an expression of the multiple replication of a matrix or vector. - * It is the return type of DenseBase::replicate() and most of the time - * this is the only way it is used. - * - * \sa DenseBase::replicate() - */ -template class Replicate - : public internal::dense_xpr_base< Replicate >::type -{ - typedef typename internal::traits::MatrixTypeNested MatrixTypeNested; - typedef typename internal::traits::_MatrixTypeNested _MatrixTypeNested; - public: - - typedef typename internal::dense_xpr_base::type Base; - EIGEN_DENSE_PUBLIC_INTERFACE(Replicate) - typedef typename internal::remove_all::type NestedExpression; - - template - EIGEN_DEVICE_FUNC - inline explicit Replicate(const OriginalMatrixType& matrix) - : m_matrix(matrix), m_rowFactor(RowFactor), m_colFactor(ColFactor) - { - EIGEN_STATIC_ASSERT((internal::is_same::type,OriginalMatrixType>::value), - THE_MATRIX_OR_EXPRESSION_THAT_YOU_PASSED_DOES_NOT_HAVE_THE_EXPECTED_TYPE) - eigen_assert(RowFactor!=Dynamic && ColFactor!=Dynamic); - } - - template - EIGEN_DEVICE_FUNC - inline Replicate(const OriginalMatrixType& matrix, Index rowFactor, Index colFactor) - : m_matrix(matrix), m_rowFactor(rowFactor), m_colFactor(colFactor) - { - EIGEN_STATIC_ASSERT((internal::is_same::type,OriginalMatrixType>::value), - THE_MATRIX_OR_EXPRESSION_THAT_YOU_PASSED_DOES_NOT_HAVE_THE_EXPECTED_TYPE) - } - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rows() const { return m_matrix.rows() * m_rowFactor.value(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index cols() const { return m_matrix.cols() * m_colFactor.value(); } - - EIGEN_DEVICE_FUNC - const _MatrixTypeNested& nestedExpression() const - { - return m_matrix; - } - - protected: - MatrixTypeNested m_matrix; - const internal::variable_if_dynamic m_rowFactor; - const internal::variable_if_dynamic m_colFactor; + * \class Replicate + * \ingroup Core_Module + * + * \brief Expression of the multiple replication of a matrix or vector + * + * \tparam MatrixType the type of the object we are replicating + * \tparam RowFactor number of repetitions at compile time along the vertical direction, can be Dynamic. + * \tparam ColFactor number of repetitions at compile time along the horizontal direction, can be Dynamic. + * + * This class represents an expression of the multiple replication of a matrix or vector. + * It is the return type of DenseBase::replicate() and most of the time + * this is the only way it is used. + * + * \sa DenseBase::replicate() + */ +template +class Replicate : public internal::dense_xpr_base >::type { + typedef typename internal::traits::MatrixTypeNested MatrixTypeNested; + typedef typename internal::traits::MatrixTypeNested_ MatrixTypeNested_; + + public: + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Replicate) + typedef internal::remove_all_t NestedExpression; + + template + EIGEN_DEVICE_FUNC inline explicit Replicate(const OriginalMatrixType& matrix) + : m_matrix(matrix), m_rowFactor(RowFactor), m_colFactor(ColFactor) { + EIGEN_STATIC_ASSERT((internal::is_same, OriginalMatrixType>::value), + THE_MATRIX_OR_EXPRESSION_THAT_YOU_PASSED_DOES_NOT_HAVE_THE_EXPECTED_TYPE) + eigen_assert(RowFactor != Dynamic && ColFactor != Dynamic); + } + + template + EIGEN_DEVICE_FUNC inline Replicate(const OriginalMatrixType& matrix, Index rowFactor, Index colFactor) + : m_matrix(matrix), + m_rowFactor(rowFactor), + m_colFactor(colFactor){ + EIGEN_STATIC_ASSERT((internal::is_same, OriginalMatrixType>::value), + THE_MATRIX_OR_EXPRESSION_THAT_YOU_PASSED_DOES_NOT_HAVE_THE_EXPECTED_TYPE)} + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const { + return m_matrix.rows() * m_rowFactor.value(); + } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const { return m_matrix.cols() * m_colFactor.value(); } + + EIGEN_DEVICE_FUNC const MatrixTypeNested_& nestedExpression() const { return m_matrix; } + + protected: + MatrixTypeNested m_matrix; + const internal::variable_if_dynamic m_rowFactor; + const internal::variable_if_dynamic m_colFactor; }; /** - * \return an expression of the replication of \c *this - * - * Example: \include MatrixBase_replicate.cpp - * Output: \verbinclude MatrixBase_replicate.out - * - * \sa VectorwiseOp::replicate(), DenseBase::replicate(Index,Index), class Replicate - */ -template -template -EIGEN_DEVICE_FUNC const Replicate -DenseBase::replicate() const -{ - return Replicate(derived()); + * \return an expression of the replication of \c *this + * + * Example: \include MatrixBase_replicate.cpp + * Output: \verbinclude MatrixBase_replicate.out + * + * \sa VectorwiseOp::replicate(), DenseBase::replicate(Index,Index), class Replicate + */ +template +template +EIGEN_DEVICE_FUNC const Replicate DenseBase::replicate() const { + return Replicate(derived()); } /** - * \return an expression of the replication of each column (or row) of \c *this - * - * Example: \include DirectionWise_replicate_int.cpp - * Output: \verbinclude DirectionWise_replicate_int.out - * - * \sa VectorwiseOp::replicate(), DenseBase::replicate(), class Replicate - */ -template -EIGEN_DEVICE_FUNC const typename VectorwiseOp::ReplicateReturnType -VectorwiseOp::replicate(Index factor) const -{ - return typename VectorwiseOp::ReplicateReturnType - (_expression(),Direction==Vertical?factor:1,Direction==Horizontal?factor:1); + * \return an expression of the replication of each column (or row) of \c *this + * + * Example: \include DirectionWise_replicate_int.cpp + * Output: \verbinclude DirectionWise_replicate_int.out + * + * \sa VectorwiseOp::replicate(), DenseBase::replicate(), class Replicate + */ +template +EIGEN_DEVICE_FUNC const typename VectorwiseOp::ReplicateReturnType +VectorwiseOp::replicate(Index factor) const { + return typename VectorwiseOp::ReplicateReturnType( + _expression(), Direction == Vertical ? factor : 1, Direction == Horizontal ? factor : 1); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_REPLICATE_H +#endif // EIGEN_REPLICATE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Reshaped.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Reshaped.h index 52de73b6fc3..b881dd6cd4f 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Reshaped.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Reshaped.h @@ -11,47 +11,48 @@ #ifndef EIGEN_RESHAPED_H #define EIGEN_RESHAPED_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { /** \class Reshaped - * \ingroup Core_Module - * - * \brief Expression of a fixed-size or dynamic-size reshape - * - * \tparam XprType the type of the expression in which we are taking a reshape - * \tparam Rows the number of rows of the reshape we are taking at compile time (optional) - * \tparam Cols the number of columns of the reshape we are taking at compile time (optional) - * \tparam Order can be ColMajor or RowMajor, default is ColMajor. - * - * This class represents an expression of either a fixed-size or dynamic-size reshape. - * It is the return type of DenseBase::reshaped(NRowsType,NColsType) and - * most of the time this is the only way it is used. - * - * However, in C++98, if you want to directly maniputate reshaped expressions, - * for instance if you want to write a function returning such an expression, you - * will need to use this class. In C++11, it is advised to use the \em auto - * keyword for such use cases. - * - * Here is an example illustrating the dynamic case: - * \include class_Reshaped.cpp - * Output: \verbinclude class_Reshaped.out - * - * Here is an example illustrating the fixed-size case: - * \include class_FixedReshaped.cpp - * Output: \verbinclude class_FixedReshaped.out - * - * \sa DenseBase::reshaped(NRowsType,NColsType) - */ + * \ingroup Core_Module + * + * \brief Expression of a fixed-size or dynamic-size reshape + * + * \tparam XprType the type of the expression in which we are taking a reshape + * \tparam Rows the number of rows of the reshape we are taking at compile time (optional) + * \tparam Cols the number of columns of the reshape we are taking at compile time (optional) + * \tparam Order can be ColMajor or RowMajor, default is ColMajor. + * + * This class represents an expression of either a fixed-size or dynamic-size reshape. + * It is the return type of DenseBase::reshaped(NRowsType,NColsType) and + * most of the time this is the only way it is used. + * + * If you want to directly manipulate reshaped expressions, + * for instance if you want to write a function returning such an expression, + * it is advised to use the \em auto keyword for such use cases. + * + * Here is an example illustrating the dynamic case: + * \include class_Reshaped.cpp + * Output: \verbinclude class_Reshaped.out + * + * Here is an example illustrating the fixed-size case: + * \include class_FixedReshaped.cpp + * Output: \verbinclude class_FixedReshaped.out + * + * \sa DenseBase::reshaped(NRowsType,NColsType) + */ namespace internal { -template -struct traits > : traits -{ +template +struct traits > : traits { typedef typename traits::Scalar Scalar; typedef typename traits::StorageKind StorageKind; typedef typename traits::XprKind XprKind; - enum{ + enum { MatrixRows = traits::RowsAtCompileTime, MatrixCols = traits::ColsAtCompileTime, RowsAtCompileTime = Rows, @@ -59,212 +60,179 @@ struct traits > : traits MaxRowsAtCompileTime = Rows, MaxColsAtCompileTime = Cols, XpxStorageOrder = ((int(traits::Flags) & RowMajorBit) == RowMajorBit) ? RowMajor : ColMajor, - ReshapedStorageOrder = (RowsAtCompileTime == 1 && ColsAtCompileTime != 1) ? RowMajor - : (ColsAtCompileTime == 1 && RowsAtCompileTime != 1) ? ColMajor - : XpxStorageOrder, + ReshapedStorageOrder = (RowsAtCompileTime == 1 && ColsAtCompileTime != 1) ? RowMajor + : (ColsAtCompileTime == 1 && RowsAtCompileTime != 1) ? ColMajor + : XpxStorageOrder, HasSameStorageOrderAsXprType = (ReshapedStorageOrder == XpxStorageOrder), - InnerSize = (ReshapedStorageOrder==int(RowMajor)) ? int(ColsAtCompileTime) : int(RowsAtCompileTime), - InnerStrideAtCompileTime = HasSameStorageOrderAsXprType - ? int(inner_stride_at_compile_time::ret) - : Dynamic, + InnerSize = (ReshapedStorageOrder == int(RowMajor)) ? int(ColsAtCompileTime) : int(RowsAtCompileTime), + InnerStrideAtCompileTime = HasSameStorageOrderAsXprType ? int(inner_stride_at_compile_time::ret) : Dynamic, OuterStrideAtCompileTime = Dynamic, - HasDirectAccess = internal::has_direct_access::ret - && (Order==int(XpxStorageOrder)) - && ((evaluator::Flags&LinearAccessBit)==LinearAccessBit), + HasDirectAccess = internal::has_direct_access::ret && (Order == int(XpxStorageOrder)) && + ((evaluator::Flags & LinearAccessBit) == LinearAccessBit), - MaskPacketAccessBit = (InnerSize == Dynamic || (InnerSize % packet_traits::size) == 0) - && (InnerStrideAtCompileTime == 1) - ? PacketAccessBit : 0, - //MaskAlignedBit = ((OuterStrideAtCompileTime!=Dynamic) && (((OuterStrideAtCompileTime * int(sizeof(Scalar))) % 16) == 0)) ? AlignedBit : 0, + MaskPacketAccessBit = + (InnerSize == Dynamic || (InnerSize % packet_traits::size) == 0) && (InnerStrideAtCompileTime == 1) + ? PacketAccessBit + : 0, + // MaskAlignedBit = ((OuterStrideAtCompileTime!=Dynamic) && (((OuterStrideAtCompileTime * int(sizeof(Scalar))) % 16) + // == 0)) ? AlignedBit : 0, FlagsLinearAccessBit = (RowsAtCompileTime == 1 || ColsAtCompileTime == 1) ? LinearAccessBit : 0, FlagsLvalueBit = is_lvalue::value ? LvalueBit : 0, - FlagsRowMajorBit = (ReshapedStorageOrder==int(RowMajor)) ? RowMajorBit : 0, + FlagsRowMajorBit = (ReshapedStorageOrder == int(RowMajor)) ? RowMajorBit : 0, FlagsDirectAccessBit = HasDirectAccess ? DirectAccessBit : 0, - Flags0 = traits::Flags & ( (HereditaryBits & ~RowMajorBit) | MaskPacketAccessBit), + Flags0 = traits::Flags & ((HereditaryBits & ~RowMajorBit) | MaskPacketAccessBit), Flags = (Flags0 | FlagsLinearAccessBit | FlagsLvalueBit | FlagsRowMajorBit | FlagsDirectAccessBit) }; }; -template class ReshapedImpl_dense; - -} // end namespace internal - -template class ReshapedImpl; - -template class Reshaped - : public ReshapedImpl::StorageKind> -{ - typedef ReshapedImpl::StorageKind> Impl; - public: - //typedef typename Impl::Base Base; - typedef Impl Base; - EIGEN_GENERIC_PUBLIC_INTERFACE(Reshaped) - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Reshaped) - - /** Fixed-size constructor - */ - EIGEN_DEVICE_FUNC - inline Reshaped(XprType& xpr) - : Impl(xpr) - { - EIGEN_STATIC_ASSERT(RowsAtCompileTime!=Dynamic && ColsAtCompileTime!=Dynamic,THIS_METHOD_IS_ONLY_FOR_FIXED_SIZE) - eigen_assert(Rows * Cols == xpr.rows() * xpr.cols()); - } +template +class ReshapedImpl_dense; - /** Dynamic-size constructor - */ - EIGEN_DEVICE_FUNC - inline Reshaped(XprType& xpr, - Index reshapeRows, Index reshapeCols) - : Impl(xpr, reshapeRows, reshapeCols) - { - eigen_assert((RowsAtCompileTime==Dynamic || RowsAtCompileTime==reshapeRows) - && (ColsAtCompileTime==Dynamic || ColsAtCompileTime==reshapeCols)); - eigen_assert(reshapeRows * reshapeCols == xpr.rows() * xpr.cols()); - } +} // end namespace internal + +template +class ReshapedImpl; + +template +class Reshaped : public ReshapedImpl::StorageKind> { + typedef ReshapedImpl::StorageKind> Impl; + + public: + // typedef typename Impl::Base Base; + typedef Impl Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(Reshaped) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Reshaped) + + /** Fixed-size constructor + */ + EIGEN_DEVICE_FUNC inline Reshaped(XprType& xpr) : Impl(xpr) { + EIGEN_STATIC_ASSERT(RowsAtCompileTime != Dynamic && ColsAtCompileTime != Dynamic, + THIS_METHOD_IS_ONLY_FOR_FIXED_SIZE) + eigen_assert(Rows * Cols == xpr.rows() * xpr.cols()); + } + + /** Dynamic-size constructor + */ + EIGEN_DEVICE_FUNC inline Reshaped(XprType& xpr, Index reshapeRows, Index reshapeCols) + : Impl(xpr, reshapeRows, reshapeCols) { + eigen_assert((RowsAtCompileTime == Dynamic || RowsAtCompileTime == reshapeRows) && + (ColsAtCompileTime == Dynamic || ColsAtCompileTime == reshapeCols)); + eigen_assert(reshapeRows * reshapeCols == xpr.rows() * xpr.cols()); + } }; // The generic default implementation for dense reshape simply forward to the internal::ReshapedImpl_dense // that must be specialized for direct and non-direct access... -template +template class ReshapedImpl - : public internal::ReshapedImpl_dense >::HasDirectAccess> -{ - typedef internal::ReshapedImpl_dense >::HasDirectAccess> Impl; - public: - typedef Impl Base; - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(ReshapedImpl) - EIGEN_DEVICE_FUNC inline ReshapedImpl(XprType& xpr) : Impl(xpr) {} - EIGEN_DEVICE_FUNC inline ReshapedImpl(XprType& xpr, Index reshapeRows, Index reshapeCols) + : public internal::ReshapedImpl_dense >::HasDirectAccess> { + typedef internal::ReshapedImpl_dense >::HasDirectAccess> + Impl; + + public: + typedef Impl Base; + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(ReshapedImpl) + EIGEN_DEVICE_FUNC inline ReshapedImpl(XprType& xpr) : Impl(xpr) {} + EIGEN_DEVICE_FUNC inline ReshapedImpl(XprType& xpr, Index reshapeRows, Index reshapeCols) : Impl(xpr, reshapeRows, reshapeCols) {} }; namespace internal { /** \internal Internal implementation of dense Reshaped in the general case. */ -template -class ReshapedImpl_dense - : public internal::dense_xpr_base >::type -{ - typedef Reshaped ReshapedType; - public: - - typedef typename internal::dense_xpr_base::type Base; - EIGEN_DENSE_PUBLIC_INTERFACE(ReshapedType) - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(ReshapedImpl_dense) - - typedef typename internal::ref_selector::non_const_type MatrixTypeNested; - typedef typename internal::remove_all::type NestedExpression; - - class InnerIterator; - - /** Fixed-size constructor - */ - EIGEN_DEVICE_FUNC - inline ReshapedImpl_dense(XprType& xpr) - : m_xpr(xpr), m_rows(Rows), m_cols(Cols) - {} - - /** Dynamic-size constructor - */ - EIGEN_DEVICE_FUNC - inline ReshapedImpl_dense(XprType& xpr, Index nRows, Index nCols) - : m_xpr(xpr), m_rows(nRows), m_cols(nCols) - {} - - EIGEN_DEVICE_FUNC Index rows() const { return m_rows; } - EIGEN_DEVICE_FUNC Index cols() const { return m_cols; } - - #ifdef EIGEN_PARSED_BY_DOXYGEN - /** \sa MapBase::data() */ - EIGEN_DEVICE_FUNC inline const Scalar* data() const; - EIGEN_DEVICE_FUNC inline Index innerStride() const; - EIGEN_DEVICE_FUNC inline Index outerStride() const; - #endif - - /** \returns the nested expression */ - EIGEN_DEVICE_FUNC - const typename internal::remove_all::type& - nestedExpression() const { return m_xpr; } - - /** \returns the nested expression */ - EIGEN_DEVICE_FUNC - typename internal::remove_reference::type& - nestedExpression() { return m_xpr; } - - protected: - - MatrixTypeNested m_xpr; - const internal::variable_if_dynamic m_rows; - const internal::variable_if_dynamic m_cols; -}; +template +class ReshapedImpl_dense + : public internal::dense_xpr_base >::type { + typedef Reshaped ReshapedType; + + public: + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(ReshapedType) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(ReshapedImpl_dense) + + typedef typename internal::ref_selector::non_const_type MatrixTypeNested; + typedef internal::remove_all_t NestedExpression; + + class InnerIterator; + + /** Fixed-size constructor + */ + EIGEN_DEVICE_FUNC inline ReshapedImpl_dense(XprType& xpr) : m_xpr(xpr), m_rows(Rows), m_cols(Cols) {} + + /** Dynamic-size constructor + */ + EIGEN_DEVICE_FUNC inline ReshapedImpl_dense(XprType& xpr, Index nRows, Index nCols) + : m_xpr(xpr), m_rows(nRows), m_cols(nCols) {} + + EIGEN_DEVICE_FUNC Index rows() const { return m_rows; } + EIGEN_DEVICE_FUNC Index cols() const { return m_cols; } + +#ifdef EIGEN_PARSED_BY_DOXYGEN + /** \sa MapBase::data() */ + EIGEN_DEVICE_FUNC inline const Scalar* data() const; + EIGEN_DEVICE_FUNC inline Index innerStride() const; + EIGEN_DEVICE_FUNC inline Index outerStride() const; +#endif + + /** \returns the nested expression */ + EIGEN_DEVICE_FUNC const internal::remove_all_t& nestedExpression() const { return m_xpr; } + + /** \returns the nested expression */ + EIGEN_DEVICE_FUNC std::remove_reference_t& nestedExpression() { return m_xpr; } + protected: + MatrixTypeNested m_xpr; + const internal::variable_if_dynamic m_rows; + const internal::variable_if_dynamic m_cols; +}; /** \internal Internal implementation of dense Reshaped in the direct access case. */ -template -class ReshapedImpl_dense - : public MapBase > -{ - typedef Reshaped ReshapedType; - typedef typename internal::ref_selector::non_const_type XprTypeNested; - public: - - typedef MapBase Base; - EIGEN_DENSE_PUBLIC_INTERFACE(ReshapedType) - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(ReshapedImpl_dense) - - /** Fixed-size constructor - */ - EIGEN_DEVICE_FUNC - inline ReshapedImpl_dense(XprType& xpr) - : Base(xpr.data()), m_xpr(xpr) - {} - - /** Dynamic-size constructor - */ - EIGEN_DEVICE_FUNC - inline ReshapedImpl_dense(XprType& xpr, Index nRows, Index nCols) - : Base(xpr.data(), nRows, nCols), - m_xpr(xpr) - {} - - EIGEN_DEVICE_FUNC - const typename internal::remove_all::type& nestedExpression() const - { - return m_xpr; - } +template +class ReshapedImpl_dense : public MapBase > { + typedef Reshaped ReshapedType; + typedef typename internal::ref_selector::non_const_type XprTypeNested; - EIGEN_DEVICE_FUNC - XprType& nestedExpression() { return m_xpr; } + public: + typedef MapBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(ReshapedType) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(ReshapedImpl_dense) - /** \sa MapBase::innerStride() */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index innerStride() const - { - return m_xpr.innerStride(); - } + /** Fixed-size constructor + */ + EIGEN_DEVICE_FUNC inline ReshapedImpl_dense(XprType& xpr) : Base(xpr.data()), m_xpr(xpr) {} - /** \sa MapBase::outerStride() */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outerStride() const - { - return ((Flags&RowMajorBit)==RowMajorBit) ? this->cols() : this->rows(); - } + /** Dynamic-size constructor + */ + EIGEN_DEVICE_FUNC inline ReshapedImpl_dense(XprType& xpr, Index nRows, Index nCols) + : Base(xpr.data(), nRows, nCols), m_xpr(xpr) {} + + EIGEN_DEVICE_FUNC const internal::remove_all_t& nestedExpression() const { return m_xpr; } + + EIGEN_DEVICE_FUNC XprType& nestedExpression() { return m_xpr; } - protected: + /** \sa MapBase::innerStride() */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const { return m_xpr.innerStride(); } + + /** \sa MapBase::outerStride() */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const { + return (((Flags & RowMajorBit) == RowMajorBit) ? this->cols() : this->rows()) * m_xpr.innerStride(); + } - XprTypeNested m_xpr; + protected: + XprTypeNested m_xpr; }; // Evaluators -template struct reshaped_evaluator; +template +struct reshaped_evaluator; -template +template struct evaluator > - : reshaped_evaluator >::HasDirectAccess> -{ + : reshaped_evaluator >::HasDirectAccess> { typedef Reshaped XprType; typedef typename XprType::Scalar Scalar; // TODO: should check for smaller packet types @@ -274,19 +242,22 @@ struct evaluator > CoeffReadCost = evaluator::CoeffReadCost, HasDirectAccess = traits::HasDirectAccess, -// RowsAtCompileTime = traits::RowsAtCompileTime, -// ColsAtCompileTime = traits::ColsAtCompileTime, -// MaxRowsAtCompileTime = traits::MaxRowsAtCompileTime, -// MaxColsAtCompileTime = traits::MaxColsAtCompileTime, -// -// InnerStrideAtCompileTime = traits::HasSameStorageOrderAsXprType -// ? int(inner_stride_at_compile_time::ret) -// : Dynamic, -// OuterStrideAtCompileTime = Dynamic, - - FlagsLinearAccessBit = (traits::RowsAtCompileTime == 1 || traits::ColsAtCompileTime == 1 || HasDirectAccess) ? LinearAccessBit : 0, - FlagsRowMajorBit = (traits::ReshapedStorageOrder==int(RowMajor)) ? RowMajorBit : 0, - FlagsDirectAccessBit = HasDirectAccess ? DirectAccessBit : 0, + // RowsAtCompileTime = traits::RowsAtCompileTime, + // ColsAtCompileTime = traits::ColsAtCompileTime, + // MaxRowsAtCompileTime = traits::MaxRowsAtCompileTime, + // MaxColsAtCompileTime = traits::MaxColsAtCompileTime, + // + // InnerStrideAtCompileTime = traits::HasSameStorageOrderAsXprType + // ? int(inner_stride_at_compile_time::ret) + // : Dynamic, + // OuterStrideAtCompileTime = Dynamic, + + FlagsLinearAccessBit = + (traits::RowsAtCompileTime == 1 || traits::ColsAtCompileTime == 1 || HasDirectAccess) + ? LinearAccessBit + : 0, + FlagsRowMajorBit = (traits::ReshapedStorageOrder == int(RowMajor)) ? RowMajorBit : 0, + FlagsDirectAccessBit = HasDirectAccess ? DirectAccessBit : 0, Flags0 = evaluator::Flags & (HereditaryBits & ~RowMajorBit), Flags = Flags0 | FlagsLinearAccessBit | FlagsRowMajorBit | FlagsDirectAccessBit, @@ -294,16 +265,14 @@ struct evaluator > Alignment = evaluator::Alignment }; typedef reshaped_evaluator reshaped_evaluator_type; - EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) : reshaped_evaluator_type(xpr) - { + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) : reshaped_evaluator_type(xpr) { EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } }; -template +template struct reshaped_evaluator - : evaluator_base > -{ + : evaluator_base > { typedef Reshaped XprType; enum { @@ -314,8 +283,7 @@ struct reshaped_evaluator RowCol; - inline RowCol index_remap(Index rowId, Index colId) const - { - if(Order==ColMajor) - { + EIGEN_DEVICE_FUNC inline RowCol index_remap(Index rowId, Index colId) const { + if (Order == ColMajor) { const Index nth_elem_idx = colId * m_xpr.rows() + rowId; - return RowCol(nth_elem_idx % m_xpr.nestedExpression().rows(), - nth_elem_idx / m_xpr.nestedExpression().rows()); - } - else - { + return RowCol(nth_elem_idx % m_xpr.nestedExpression().rows(), nth_elem_idx / m_xpr.nestedExpression().rows()); + } else { const Index nth_elem_idx = colId + rowId * m_xpr.cols(); - return RowCol(nth_elem_idx / m_xpr.nestedExpression().cols(), - nth_elem_idx % m_xpr.nestedExpression().cols()); + return RowCol(nth_elem_idx / m_xpr.nestedExpression().cols(), nth_elem_idx % m_xpr.nestedExpression().cols()); } } - EIGEN_DEVICE_FUNC - inline Scalar& coeffRef(Index rowId, Index colId) - { + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index rowId, Index colId) { EIGEN_STATIC_ASSERT_LVALUE(XprType) const RowCol row_col = index_remap(rowId, colId); return m_argImpl.coeffRef(row_col.first, row_col.second); } - EIGEN_DEVICE_FUNC - inline const Scalar& coeffRef(Index rowId, Index colId) const - { + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index rowId, Index colId) const { const RowCol row_col = index_remap(rowId, colId); return m_argImpl.coeffRef(row_col.first, row_col.second); } - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index rowId, Index colId) const - { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index rowId, Index colId) const { const RowCol row_col = index_remap(rowId, colId); return m_argImpl.coeff(row_col.first, row_col.second); } - EIGEN_DEVICE_FUNC - inline Scalar& coeffRef(Index index) - { + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index index) { EIGEN_STATIC_ASSERT_LVALUE(XprType) - const RowCol row_col = index_remap(Rows == 1 ? 0 : index, - Rows == 1 ? index : 0); + const RowCol row_col = index_remap(Rows == 1 ? 0 : index, Rows == 1 ? index : 0); return m_argImpl.coeffRef(row_col.first, row_col.second); - } - EIGEN_DEVICE_FUNC - inline const Scalar& coeffRef(Index index) const - { - const RowCol row_col = index_remap(Rows == 1 ? 0 : index, - Rows == 1 ? index : 0); + EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index index) const { + const RowCol row_col = index_remap(Rows == 1 ? 0 : index, Rows == 1 ? index : 0); return m_argImpl.coeffRef(row_col.first, row_col.second); } - EIGEN_DEVICE_FUNC - inline const CoeffReturnType coeff(Index index) const - { - const RowCol row_col = index_remap(Rows == 1 ? 0 : index, - Rows == 1 ? index : 0); + EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index index) const { + const RowCol row_col = index_remap(Rows == 1 ? 0 : index, Rows == 1 ? index : 0); return m_argImpl.coeff(row_col.first, row_col.second); } #if 0 @@ -424,31 +370,29 @@ struct reshaped_evaluator(row_col.first, row_col.second, val); } #endif -protected: - + protected: evaluator m_argImpl; const XprType& m_xpr; - }; -template +template struct reshaped_evaluator -: mapbase_evaluator, - typename Reshaped::PlainObject> -{ + : mapbase_evaluator, + typename Reshaped::PlainObject> { typedef Reshaped XprType; typedef typename XprType::Scalar Scalar; EIGEN_DEVICE_FUNC explicit reshaped_evaluator(const XprType& xpr) - : mapbase_evaluator(xpr) - { - // TODO: for the 3.4 release, this should be turned to an internal assertion, but let's keep it as is for the beta lifetime - eigen_assert(((internal::UIntPtr(xpr.data()) % EIGEN_PLAIN_ENUM_MAX(1,evaluator::Alignment)) == 0) && "data is not aligned"); + : mapbase_evaluator(xpr) { + // TODO: for the 3.4 release, this should be turned to an internal assertion, but let's keep it as is for the beta + // lifetime + eigen_assert(((std::uintptr_t(xpr.data()) % plain_enum_max(1, evaluator::Alignment)) == 0) && + "data is not aligned"); } }; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_RESHAPED_H +#endif // EIGEN_RESHAPED_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ReturnByValue.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ReturnByValue.h index 4dad13ea118..3b5e470ce42 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ReturnByValue.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/ReturnByValue.h @@ -11,20 +11,20 @@ #ifndef EIGEN_RETURNBYVALUE_H #define EIGEN_RETURNBYVALUE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > - : public traits::ReturnType> -{ +template +struct traits > : public traits::ReturnType> { enum { // We're disabling the DirectAccess because e.g. the constructor of // the Block-with-DirectAccess expression requires to have a coeffRef method. // Also, we don't want to have to implement the stride stuff. - Flags = (traits::ReturnType>::Flags - | EvalBeforeNestingBit) & ~DirectAccessBit + Flags = (traits::ReturnType>::Flags | EvalBeforeNestingBit) & ~DirectAccessBit }; }; @@ -35,54 +35,54 @@ struct traits > * FIXME: I don't understand why we need this specialization: isn't this taken care of by the EvalBeforeNestingBit ?? * Answer: EvalBeforeNestingBit should be deprecated since we have the evaluators */ -template -struct nested_eval, n, PlainObject> -{ +template +struct nested_eval, n, PlainObject> { typedef typename traits::ReturnType type; }; -} // end namespace internal +} // end namespace internal /** \class ReturnByValue - * \ingroup Core_Module - * - */ -template class ReturnByValue - : public internal::dense_xpr_base< ReturnByValue >::type, internal::no_assignment_operator -{ - public: - typedef typename internal::traits::ReturnType ReturnType; - - typedef typename internal::dense_xpr_base::type Base; - EIGEN_DENSE_PUBLIC_INTERFACE(ReturnByValue) - - template - EIGEN_DEVICE_FUNC - inline void evalTo(Dest& dst) const - { static_cast(this)->evalTo(dst); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rows() const EIGEN_NOEXCEPT { return static_cast(this)->rows(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index cols() const EIGEN_NOEXCEPT { return static_cast(this)->cols(); } + * \ingroup Core_Module + * + */ +template +class ReturnByValue : public internal::dense_xpr_base >::type, internal::no_assignment_operator { + public: + typedef typename internal::traits::ReturnType ReturnType; + + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(ReturnByValue) + + template + EIGEN_DEVICE_FUNC inline void evalTo(Dest& dst) const { + static_cast(this)->evalTo(dst); + } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { + return static_cast(this)->rows(); + } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { + return static_cast(this)->cols(); + } #ifndef EIGEN_PARSED_BY_DOXYGEN -#define Unusable YOU_ARE_TRYING_TO_ACCESS_A_SINGLE_COEFFICIENT_IN_A_SPECIAL_EXPRESSION_WHERE_THAT_IS_NOT_ALLOWED_BECAUSE_THAT_WOULD_BE_INEFFICIENT - class Unusable{ - Unusable(const Unusable&) {} - Unusable& operator=(const Unusable&) {return *this;} - }; - const Unusable& coeff(Index) const { return *reinterpret_cast(this); } - const Unusable& coeff(Index,Index) const { return *reinterpret_cast(this); } - Unusable& coeffRef(Index) { return *reinterpret_cast(this); } - Unusable& coeffRef(Index,Index) { return *reinterpret_cast(this); } +#define Unusable \ + YOU_ARE_TRYING_TO_ACCESS_A_SINGLE_COEFFICIENT_IN_A_SPECIAL_EXPRESSION_WHERE_THAT_IS_NOT_ALLOWED_BECAUSE_THAT_WOULD_BE_INEFFICIENT + class Unusable { + Unusable(const Unusable&) {} + Unusable& operator=(const Unusable&) { return *this; } + }; + const Unusable& coeff(Index) const { return *reinterpret_cast(this); } + const Unusable& coeff(Index, Index) const { return *reinterpret_cast(this); } + Unusable& coeffRef(Index) { return *reinterpret_cast(this); } + Unusable& coeffRef(Index, Index) { return *reinterpret_cast(this); } #undef Unusable #endif }; -template -template -EIGEN_DEVICE_FUNC Derived& DenseBase::operator=(const ReturnByValue& other) -{ +template +template +EIGEN_DEVICE_FUNC Derived& DenseBase::operator=(const ReturnByValue& other) { other.evalTo(derived()); return derived(); } @@ -93,27 +93,23 @@ namespace internal { // when a ReturnByValue expression is assigned, the evaluator is not constructed. // TODO: Finalize port to new regime; ReturnByValue should not exist in the expression world -template -struct evaluator > - : public evaluator::ReturnType> -{ +template +struct evaluator > : public evaluator::ReturnType> { typedef ReturnByValue XprType; typedef typename internal::traits::ReturnType PlainObject; typedef evaluator Base; - EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) - : m_result(xpr.rows(), xpr.cols()) - { - ::new (static_cast(this)) Base(m_result); + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) : m_result(xpr.rows(), xpr.cols()) { + internal::construct_at(this, m_result); xpr.evalTo(m_result); } -protected: + protected: PlainObject m_result; }; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_RETURNBYVALUE_H +#endif // EIGEN_RETURNBYVALUE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Reverse.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Reverse.h index 28cdd76acaa..66116aa4ee3 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Reverse.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Reverse.h @@ -12,151 +12,133 @@ #ifndef EIGEN_REVERSE_H #define EIGEN_REVERSE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > - : traits -{ +template +struct traits > : traits { typedef typename MatrixType::Scalar Scalar; typedef typename traits::StorageKind StorageKind; typedef typename traits::XprKind XprKind; typedef typename ref_selector::type MatrixTypeNested; - typedef typename remove_reference::type _MatrixTypeNested; + typedef std::remove_reference_t MatrixTypeNested_; enum { RowsAtCompileTime = MatrixType::RowsAtCompileTime, ColsAtCompileTime = MatrixType::ColsAtCompileTime, MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime, - Flags = _MatrixTypeNested::Flags & (RowMajorBit | LvalueBit) + Flags = MatrixTypeNested_::Flags & (RowMajorBit | LvalueBit) }; }; -template struct reverse_packet_cond -{ +template +struct reverse_packet_cond { static inline PacketType run(const PacketType& x) { return preverse(x); } }; -template struct reverse_packet_cond -{ +template +struct reverse_packet_cond { static inline PacketType run(const PacketType& x) { return x; } }; -} // end namespace internal +} // end namespace internal /** \class Reverse - * \ingroup Core_Module - * - * \brief Expression of the reverse of a vector or matrix - * - * \tparam MatrixType the type of the object of which we are taking the reverse - * \tparam Direction defines the direction of the reverse operation, can be Vertical, Horizontal, or BothDirections - * - * This class represents an expression of the reverse of a vector. - * It is the return type of MatrixBase::reverse() and VectorwiseOp::reverse() - * and most of the time this is the only way it is used. - * - * \sa MatrixBase::reverse(), VectorwiseOp::reverse() - */ -template class Reverse - : public internal::dense_xpr_base< Reverse >::type -{ - public: - - typedef typename internal::dense_xpr_base::type Base; - EIGEN_DENSE_PUBLIC_INTERFACE(Reverse) - typedef typename internal::remove_all::type NestedExpression; - using Base::IsRowMajor; - - protected: - enum { - PacketSize = internal::packet_traits::size, - IsColMajor = !IsRowMajor, - ReverseRow = (Direction == Vertical) || (Direction == BothDirections), - ReverseCol = (Direction == Horizontal) || (Direction == BothDirections), - OffsetRow = ReverseRow && IsColMajor ? PacketSize : 1, - OffsetCol = ReverseCol && IsRowMajor ? PacketSize : 1, - ReversePacket = (Direction == BothDirections) - || ((Direction == Vertical) && IsColMajor) - || ((Direction == Horizontal) && IsRowMajor) - }; - typedef internal::reverse_packet_cond reverse_packet; - public: - - EIGEN_DEVICE_FUNC explicit inline Reverse(const MatrixType& matrix) : m_matrix(matrix) { } - - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Reverse) - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rows() const EIGEN_NOEXCEPT { return m_matrix.rows(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index cols() const EIGEN_NOEXCEPT { return m_matrix.cols(); } - - EIGEN_DEVICE_FUNC inline Index innerStride() const - { - return -m_matrix.innerStride(); - } + * \ingroup Core_Module + * + * \brief Expression of the reverse of a vector or matrix + * + * \tparam MatrixType the type of the object of which we are taking the reverse + * \tparam Direction defines the direction of the reverse operation, can be Vertical, Horizontal, or BothDirections + * + * This class represents an expression of the reverse of a vector. + * It is the return type of MatrixBase::reverse() and VectorwiseOp::reverse() + * and most of the time this is the only way it is used. + * + * \sa MatrixBase::reverse(), VectorwiseOp::reverse() + */ +template +class Reverse : public internal::dense_xpr_base >::type { + public: + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Reverse) + typedef internal::remove_all_t NestedExpression; + using Base::IsRowMajor; + + protected: + enum { + PacketSize = internal::packet_traits::size, + IsColMajor = !IsRowMajor, + ReverseRow = (Direction == Vertical) || (Direction == BothDirections), + ReverseCol = (Direction == Horizontal) || (Direction == BothDirections), + OffsetRow = ReverseRow && IsColMajor ? PacketSize : 1, + OffsetCol = ReverseCol && IsRowMajor ? PacketSize : 1, + ReversePacket = (Direction == BothDirections) || ((Direction == Vertical) && IsColMajor) || + ((Direction == Horizontal) && IsRowMajor) + }; + typedef internal::reverse_packet_cond reverse_packet; - EIGEN_DEVICE_FUNC const typename internal::remove_all::type& - nestedExpression() const - { - return m_matrix; - } + public: + EIGEN_DEVICE_FUNC explicit inline Reverse(const MatrixType& matrix) : m_matrix(matrix) {} + + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Reverse) - protected: - typename MatrixType::Nested m_matrix; + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { return m_matrix.rows(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return m_matrix.cols(); } + + EIGEN_DEVICE_FUNC inline Index innerStride() const { return -m_matrix.innerStride(); } + + EIGEN_DEVICE_FUNC const internal::remove_all_t& nestedExpression() const { + return m_matrix; + } + + protected: + typename MatrixType::Nested m_matrix; }; /** \returns an expression of the reverse of *this. - * - * Example: \include MatrixBase_reverse.cpp - * Output: \verbinclude MatrixBase_reverse.out - * - */ -template -EIGEN_DEVICE_FUNC inline typename DenseBase::ReverseReturnType -DenseBase::reverse() -{ + * + * Example: \include MatrixBase_reverse.cpp + * Output: \verbinclude MatrixBase_reverse.out + * + */ +template +EIGEN_DEVICE_FUNC inline typename DenseBase::ReverseReturnType DenseBase::reverse() { return ReverseReturnType(derived()); } - -//reverse const overload moved DenseBase.h due to a CUDA compiler bug +// reverse const overload moved DenseBase.h due to a CUDA compiler bug /** This is the "in place" version of reverse: it reverses \c *this. - * - * In most cases it is probably better to simply use the reversed expression - * of a matrix. However, when reversing the matrix data itself is really needed, - * then this "in-place" version is probably the right choice because it provides - * the following additional benefits: - * - less error prone: doing the same operation with .reverse() requires special care: - * \code m = m.reverse().eval(); \endcode - * - this API enables reverse operations without the need for a temporary - * - it allows future optimizations (cache friendliness, etc.) - * - * \sa VectorwiseOp::reverseInPlace(), reverse() */ -template -EIGEN_DEVICE_FUNC inline void DenseBase::reverseInPlace() -{ - if(cols()>rows()) - { - Index half = cols()/2; + * + * In most cases it is probably better to simply use the reversed expression + * of a matrix. However, when reversing the matrix data itself is really needed, + * then this "in-place" version is probably the right choice because it provides + * the following additional benefits: + * - less error prone: doing the same operation with .reverse() requires special care: + * \code m = m.reverse().eval(); \endcode + * - this API enables reverse operations without the need for a temporary + * - it allows future optimizations (cache friendliness, etc.) + * + * \sa VectorwiseOp::reverseInPlace(), reverse() */ +template +EIGEN_DEVICE_FUNC inline void DenseBase::reverseInPlace() { + if (cols() > rows()) { + Index half = cols() / 2; leftCols(half).swap(rightCols(half).reverse()); - if((cols()%2)==1) - { - Index half2 = rows()/2; + if ((cols() % 2) == 1) { + Index half2 = rows() / 2; col(half).head(half2).swap(col(half).tail(half2).reverse()); } - } - else - { - Index half = rows()/2; + } else { + Index half = rows() / 2; topRows(half).swap(bottomRows(half).reverse()); - if((rows()%2)==1) - { - Index half2 = cols()/2; + if ((rows() % 2) == 1) { + Index half2 = cols() / 2; row(half).head(half2).swap(row(half).tail(half2).reverse()); } } @@ -164,54 +146,51 @@ EIGEN_DEVICE_FUNC inline void DenseBase::reverseInPlace() namespace internal { -template +template struct vectorwise_reverse_inplace_impl; -template<> -struct vectorwise_reverse_inplace_impl -{ - template - static void run(ExpressionType &xpr) - { - const int HalfAtCompileTime = ExpressionType::RowsAtCompileTime==Dynamic?Dynamic:ExpressionType::RowsAtCompileTime/2; - Index half = xpr.rows()/2; - xpr.topRows(fix(half)) - .swap(xpr.bottomRows(fix(half)).colwise().reverse()); +template <> +struct vectorwise_reverse_inplace_impl { + template + static void run(ExpressionType& xpr) { + constexpr Index HalfAtCompileTime = + ExpressionType::RowsAtCompileTime == Dynamic ? Dynamic : ExpressionType::RowsAtCompileTime / 2; + Index half = xpr.rows() / 2; + xpr.template topRows(half).swap( + xpr.template bottomRows(half).colwise().reverse()); } }; -template<> -struct vectorwise_reverse_inplace_impl -{ - template - static void run(ExpressionType &xpr) - { - const int HalfAtCompileTime = ExpressionType::ColsAtCompileTime==Dynamic?Dynamic:ExpressionType::ColsAtCompileTime/2; - Index half = xpr.cols()/2; - xpr.leftCols(fix(half)) - .swap(xpr.rightCols(fix(half)).rowwise().reverse()); +template <> +struct vectorwise_reverse_inplace_impl { + template + static void run(ExpressionType& xpr) { + constexpr Index HalfAtCompileTime = + ExpressionType::ColsAtCompileTime == Dynamic ? Dynamic : ExpressionType::ColsAtCompileTime / 2; + Index half = xpr.cols() / 2; + xpr.template leftCols(half).swap( + xpr.template rightCols(half).rowwise().reverse()); } }; -} // end namespace internal +} // end namespace internal /** This is the "in place" version of VectorwiseOp::reverse: it reverses each column or row of \c *this. - * - * In most cases it is probably better to simply use the reversed expression - * of a matrix. However, when reversing the matrix data itself is really needed, - * then this "in-place" version is probably the right choice because it provides - * the following additional benefits: - * - less error prone: doing the same operation with .reverse() requires special care: - * \code m = m.reverse().eval(); \endcode - * - this API enables reverse operations without the need for a temporary - * - * \sa DenseBase::reverseInPlace(), reverse() */ -template -EIGEN_DEVICE_FUNC void VectorwiseOp::reverseInPlace() -{ + * + * In most cases it is probably better to simply use the reversed expression + * of a matrix. However, when reversing the matrix data itself is really needed, + * then this "in-place" version is probably the right choice because it provides + * the following additional benefits: + * - less error prone: doing the same operation with .reverse() requires special care: + * \code m = m.reverse().eval(); \endcode + * - this API enables reverse operations without the need for a temporary + * + * \sa DenseBase::reverseInPlace(), reverse() */ +template +EIGEN_DEVICE_FUNC void VectorwiseOp::reverseInPlace() { internal::vectorwise_reverse_inplace_impl::run(m_matrix); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_REVERSE_H +#endif // EIGEN_REVERSE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Select.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Select.h index 7c86bf87c17..9f4612047ab 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Select.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Select.h @@ -10,28 +10,29 @@ #ifndef EIGEN_SELECT_H #define EIGEN_SELECT_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { /** \class Select - * \ingroup Core_Module - * - * \brief Expression of a coefficient wise version of the C++ ternary operator ?: - * - * \param ConditionMatrixType the type of the \em condition expression which must be a boolean matrix - * \param ThenMatrixType the type of the \em then expression - * \param ElseMatrixType the type of the \em else expression - * - * This class represents an expression of a coefficient wise version of the C++ ternary operator ?:. - * It is the return type of DenseBase::select() and most of the time this is the only way it is used. - * - * \sa DenseBase::select(const DenseBase&, const DenseBase&) const - */ + * \ingroup Core_Module + * + * \brief Expression of a coefficient wise version of the C++ ternary operator ?: + * + * \tparam ConditionMatrixType the type of the \em condition expression which must be a boolean matrix + * \tparam ThenMatrixType the type of the \em then expression + * \tparam ElseMatrixType the type of the \em else expression + * + * This class represents an expression of a coefficient wise version of the C++ ternary operator ?:. + * It is the return type of DenseBase::select() and most of the time this is the only way it is used. + * + * \sa DenseBase::select(const DenseBase&, const DenseBase&) const + */ namespace internal { -template -struct traits > - : traits -{ +template +struct traits > : traits { typedef typename traits::Scalar Scalar; typedef Dense StorageKind; typedef typename traits::XprKind XprKind; @@ -46,119 +47,110 @@ struct traits > Flags = (unsigned int)ThenMatrixType::Flags & ElseMatrixType::Flags & RowMajorBit }; }; -} - -template -class Select : public internal::dense_xpr_base< Select >::type, - internal::no_assignment_operator -{ - public: - - typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Select) + + inline EIGEN_DEVICE_FUNC Select(const ConditionMatrixType& a_conditionMatrix, const ThenMatrixType& a_thenMatrix, + const ElseMatrixType& a_elseMatrix) + : m_condition(a_conditionMatrix), m_then(a_thenMatrix), m_else(a_elseMatrix) { + eigen_assert(m_condition.rows() == m_then.rows() && m_condition.rows() == m_else.rows()); + eigen_assert(m_condition.cols() == m_then.cols() && m_condition.cols() == m_else.cols()); + } + + inline EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_condition.rows(); } + inline EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_condition.cols(); } + + inline EIGEN_DEVICE_FUNC const Scalar coeff(Index i, Index j) const { + if (m_condition.coeff(i, j)) + return m_then.coeff(i, j); + else + return m_else.coeff(i, j); + } + + inline EIGEN_DEVICE_FUNC const Scalar coeff(Index i) const { + if (m_condition.coeff(i)) + return m_then.coeff(i); + else + return m_else.coeff(i); + } + + inline EIGEN_DEVICE_FUNC const ConditionMatrixType& conditionMatrix() const { return m_condition; } + + inline EIGEN_DEVICE_FUNC const ThenMatrixType& thenMatrix() const { return m_then; } + + inline EIGEN_DEVICE_FUNC const ElseMatrixType& elseMatrix() const { return m_else; } + + protected: + typename ConditionMatrixType::Nested m_condition; + typename ThenMatrixType::Nested m_then; + typename ElseMatrixType::Nested m_else; }; - /** \returns a matrix where each coefficient (i,j) is equal to \a thenMatrix(i,j) - * if \c *this(i,j), and \a elseMatrix(i,j) otherwise. - * - * Example: \include MatrixBase_select.cpp - * Output: \verbinclude MatrixBase_select.out - * - * \sa class Select - */ -template -template -inline EIGEN_DEVICE_FUNC const Select -DenseBase::select(const DenseBase& thenMatrix, - const DenseBase& elseMatrix) const -{ - return Select(derived(), thenMatrix.derived(), elseMatrix.derived()); + * if \c *this(i,j) != Scalar(0), and \a elseMatrix(i,j) otherwise. + * + * Example: \include MatrixBase_select.cpp + * Output: \verbinclude MatrixBase_select.out + * + * \sa DenseBase::bitwiseSelect(const DenseBase&, const DenseBase&) + */ +template +template +inline EIGEN_DEVICE_FUNC CwiseTernaryOp< + internal::scalar_boolean_select_op::Scalar, typename DenseBase::Scalar, + typename DenseBase::Scalar>, + ThenDerived, ElseDerived, Derived> +DenseBase::select(const DenseBase& thenMatrix, const DenseBase& elseMatrix) const { + using Op = internal::scalar_boolean_select_op::Scalar, + typename DenseBase::Scalar, Scalar>; + return CwiseTernaryOp(thenMatrix.derived(), elseMatrix.derived(), derived(), + Op()); } - /** Version of DenseBase::select(const DenseBase&, const DenseBase&) with - * the \em else expression being a scalar value. - * - * \sa DenseBase::select(const DenseBase&, const DenseBase&) const, class Select - */ -template -template -inline EIGEN_DEVICE_FUNC const Select + * the \em else expression being a scalar value. + * + * \sa DenseBase::booleanSelect(const DenseBase&, const DenseBase&) const, class Select + */ +template +template +inline EIGEN_DEVICE_FUNC CwiseTernaryOp< + internal::scalar_boolean_select_op::Scalar, typename DenseBase::Scalar, + typename DenseBase::Scalar>, + ThenDerived, typename DenseBase::ConstantReturnType, Derived> DenseBase::select(const DenseBase& thenMatrix, - const typename ThenDerived::Scalar& elseScalar) const -{ - return Select( - derived(), thenMatrix.derived(), ThenDerived::Constant(rows(),cols(),elseScalar)); + const typename DenseBase::Scalar& elseScalar) const { + using ElseConstantType = typename DenseBase::ConstantReturnType; + using Op = internal::scalar_boolean_select_op::Scalar, + typename DenseBase::Scalar, Scalar>; + return CwiseTernaryOp( + thenMatrix.derived(), ElseConstantType(rows(), cols(), elseScalar), derived(), Op()); } - /** Version of DenseBase::select(const DenseBase&, const DenseBase&) with - * the \em then expression being a scalar value. - * - * \sa DenseBase::select(const DenseBase&, const DenseBase&) const, class Select - */ -template -template -inline EIGEN_DEVICE_FUNC const Select -DenseBase::select(const typename ElseDerived::Scalar& thenScalar, - const DenseBase& elseMatrix) const -{ - return Select( - derived(), ElseDerived::Constant(rows(),cols(),thenScalar), elseMatrix.derived()); + * the \em then expression being a scalar value. + * + * \sa DenseBase::booleanSelect(const DenseBase&, const DenseBase&) const, class Select + */ +template +template +inline EIGEN_DEVICE_FUNC CwiseTernaryOp< + internal::scalar_boolean_select_op::Scalar, typename DenseBase::Scalar, + typename DenseBase::Scalar>, + typename DenseBase::ConstantReturnType, ElseDerived, Derived> +DenseBase::select(const typename DenseBase::Scalar& thenScalar, + const DenseBase& elseMatrix) const { + using ThenConstantType = typename DenseBase::ConstantReturnType; + using Op = internal::scalar_boolean_select_op::Scalar, + typename DenseBase::Scalar, Scalar>; + return CwiseTernaryOp(ThenConstantType(rows(), cols(), thenScalar), + elseMatrix.derived(), derived(), Op()); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_SELECT_H +#endif // EIGEN_SELECT_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SelfAdjointView.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SelfAdjointView.h index 8ce3b372a0f..4e9a923a421 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SelfAdjointView.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SelfAdjointView.h @@ -10,268 +10,238 @@ #ifndef EIGEN_SELFADJOINTMATRIX_H #define EIGEN_SELFADJOINTMATRIX_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { /** \class SelfAdjointView - * \ingroup Core_Module - * - * - * \brief Expression of a selfadjoint matrix from a triangular part of a dense matrix - * - * \param MatrixType the type of the dense matrix storing the coefficients - * \param TriangularPart can be either \c #Lower or \c #Upper - * - * This class is an expression of a sefladjoint matrix from a triangular part of a matrix - * with given dense storage of the coefficients. It is the return type of MatrixBase::selfadjointView() - * and most of the time this is the only way that it is used. - * - * \sa class TriangularBase, MatrixBase::selfadjointView() - */ + * \ingroup Core_Module + * + * + * \brief Expression of a selfadjoint matrix from a triangular part of a dense matrix + * + * \tparam MatrixType the type of the dense matrix storing the coefficients + * \tparam TriangularPart can be either \c #Lower or \c #Upper + * + * This class is an expression of a sefladjoint matrix from a triangular part of a matrix + * with given dense storage of the coefficients. It is the return type of MatrixBase::selfadjointView() + * and most of the time this is the only way that it is used. + * + * \sa class TriangularBase, MatrixBase::selfadjointView() + */ namespace internal { -template -struct traits > : traits -{ +template +struct traits > : traits { typedef typename ref_selector::non_const_type MatrixTypeNested; - typedef typename remove_all::type MatrixTypeNestedCleaned; + typedef remove_all_t MatrixTypeNestedCleaned; typedef MatrixType ExpressionType; typedef typename MatrixType::PlainObject FullMatrixType; enum { Mode = UpLo | SelfAdjoint, FlagsLvalueBit = is_lvalue::value ? LvalueBit : 0, - Flags = MatrixTypeNestedCleaned::Flags & (HereditaryBits|FlagsLvalueBit) - & (~(PacketAccessBit | DirectAccessBit | LinearAccessBit)) // FIXME these flags should be preserved + Flags = MatrixTypeNestedCleaned::Flags & (HereditaryBits | FlagsLvalueBit) & + (~(PacketAccessBit | DirectAccessBit | LinearAccessBit)) // FIXME these flags should be preserved }; }; -} +} // namespace internal +template +class SelfAdjointView : public TriangularBase > { + public: + EIGEN_STATIC_ASSERT(UpLo == Lower || UpLo == Upper, SELFADJOINTVIEW_ACCEPTS_UPPER_AND_LOWER_MODE_ONLY) -template class SelfAdjointView - : public TriangularBase > -{ - public: - - typedef _MatrixType MatrixType; - typedef TriangularBase Base; - typedef typename internal::traits::MatrixTypeNested MatrixTypeNested; - typedef typename internal::traits::MatrixTypeNestedCleaned MatrixTypeNestedCleaned; - typedef MatrixTypeNestedCleaned NestedExpression; - - /** \brief The type of coefficients in this matrix */ - typedef typename internal::traits::Scalar Scalar; - typedef typename MatrixType::StorageIndex StorageIndex; - typedef typename internal::remove_all::type MatrixConjugateReturnType; - typedef SelfAdjointView::type, UpLo> ConstSelfAdjointView; - - enum { - Mode = internal::traits::Mode, - Flags = internal::traits::Flags, - TransposeMode = ((int(Mode) & int(Upper)) ? Lower : 0) | ((int(Mode) & int(Lower)) ? Upper : 0) - }; - typedef typename MatrixType::PlainObject PlainObject; - - EIGEN_DEVICE_FUNC - explicit inline SelfAdjointView(MatrixType& matrix) : m_matrix(matrix) - { - EIGEN_STATIC_ASSERT(UpLo==Lower || UpLo==Upper,SELFADJOINTVIEW_ACCEPTS_UPPER_AND_LOWER_MODE_ONLY); - } - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rows() const EIGEN_NOEXCEPT { return m_matrix.rows(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index cols() const EIGEN_NOEXCEPT { return m_matrix.cols(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outerStride() const EIGEN_NOEXCEPT { return m_matrix.outerStride(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index innerStride() const EIGEN_NOEXCEPT { return m_matrix.innerStride(); } - - /** \sa MatrixBase::coeff() - * \warning the coordinates must fit into the referenced triangular part - */ - EIGEN_DEVICE_FUNC - inline Scalar coeff(Index row, Index col) const - { - Base::check_coordinates_internal(row, col); - return m_matrix.coeff(row, col); - } - - /** \sa MatrixBase::coeffRef() - * \warning the coordinates must fit into the referenced triangular part - */ - EIGEN_DEVICE_FUNC - inline Scalar& coeffRef(Index row, Index col) - { - EIGEN_STATIC_ASSERT_LVALUE(SelfAdjointView); - Base::check_coordinates_internal(row, col); - return m_matrix.coeffRef(row, col); - } - - /** \internal */ - EIGEN_DEVICE_FUNC - const MatrixTypeNestedCleaned& _expression() const { return m_matrix; } - - EIGEN_DEVICE_FUNC - const MatrixTypeNestedCleaned& nestedExpression() const { return m_matrix; } - EIGEN_DEVICE_FUNC - MatrixTypeNestedCleaned& nestedExpression() { return m_matrix; } - - /** Efficient triangular matrix times vector/matrix product */ - template - EIGEN_DEVICE_FUNC - const Product - operator*(const MatrixBase& rhs) const - { - return Product(*this, rhs.derived()); - } - - /** Efficient vector/matrix times triangular matrix product */ - template friend - EIGEN_DEVICE_FUNC - const Product - operator*(const MatrixBase& lhs, const SelfAdjointView& rhs) - { - return Product(lhs.derived(),rhs); - } - - friend EIGEN_DEVICE_FUNC - const SelfAdjointView - operator*(const Scalar& s, const SelfAdjointView& mat) - { - return (s*mat.nestedExpression()).template selfadjointView(); - } - - /** Perform a symmetric rank 2 update of the selfadjoint matrix \c *this: - * \f$ this = this + \alpha u v^* + conj(\alpha) v u^* \f$ - * \returns a reference to \c *this - * - * The vectors \a u and \c v \b must be column vectors, however they can be - * a adjoint expression without any overhead. Only the meaningful triangular - * part of the matrix is updated, the rest is left unchanged. - * - * \sa rankUpdate(const MatrixBase&, Scalar) - */ - template - EIGEN_DEVICE_FUNC - SelfAdjointView& rankUpdate(const MatrixBase& u, const MatrixBase& v, const Scalar& alpha = Scalar(1)); - - /** Perform a symmetric rank K update of the selfadjoint matrix \c *this: - * \f$ this = this + \alpha ( u u^* ) \f$ where \a u is a vector or matrix. - * - * \returns a reference to \c *this - * - * Note that to perform \f$ this = this + \alpha ( u^* u ) \f$ you can simply - * call this function with u.adjoint(). - * - * \sa rankUpdate(const MatrixBase&, const MatrixBase&, Scalar) - */ - template - EIGEN_DEVICE_FUNC - SelfAdjointView& rankUpdate(const MatrixBase& u, const Scalar& alpha = Scalar(1)); - - /** \returns an expression of a triangular view extracted from the current selfadjoint view of a given triangular part - * - * The parameter \a TriMode can have the following values: \c #Upper, \c #StrictlyUpper, \c #UnitUpper, - * \c #Lower, \c #StrictlyLower, \c #UnitLower. - * - * If \c TriMode references the same triangular part than \c *this, then this method simply return a \c TriangularView of the nested expression, - * otherwise, the nested expression is first transposed, thus returning a \c TriangularView> object. - * - * \sa MatrixBase::triangularView(), class TriangularView - */ - template - EIGEN_DEVICE_FUNC - typename internal::conditional<(TriMode&(Upper|Lower))==(UpLo&(Upper|Lower)), - TriangularView, - TriangularView >::type - triangularView() const - { - typename internal::conditional<(TriMode&(Upper|Lower))==(UpLo&(Upper|Lower)), MatrixType&, typename MatrixType::ConstTransposeReturnType>::type tmp1(m_matrix); - typename internal::conditional<(TriMode&(Upper|Lower))==(UpLo&(Upper|Lower)), MatrixType&, typename MatrixType::AdjointReturnType>::type tmp2(tmp1); - return typename internal::conditional<(TriMode&(Upper|Lower))==(UpLo&(Upper|Lower)), - TriangularView, - TriangularView >::type(tmp2); - } - - typedef SelfAdjointView ConjugateReturnType; - /** \sa MatrixBase::conjugate() const */ - EIGEN_DEVICE_FUNC - inline const ConjugateReturnType conjugate() const - { return ConjugateReturnType(m_matrix.conjugate()); } - - /** \returns an expression of the complex conjugate of \c *this if Cond==true, - * returns \c *this otherwise. - */ - template - EIGEN_DEVICE_FUNC - inline typename internal::conditional::type - conjugateIf() const - { - typedef typename internal::conditional::type ReturnType; - return ReturnType(m_matrix.template conjugateIf()); - } - - typedef SelfAdjointView AdjointReturnType; - /** \sa MatrixBase::adjoint() const */ - EIGEN_DEVICE_FUNC - inline const AdjointReturnType adjoint() const - { return AdjointReturnType(m_matrix.adjoint()); } - - typedef SelfAdjointView TransposeReturnType; - /** \sa MatrixBase::transpose() */ - EIGEN_DEVICE_FUNC - inline TransposeReturnType transpose() - { - EIGEN_STATIC_ASSERT_LVALUE(MatrixType) - typename MatrixType::TransposeReturnType tmp(m_matrix); - return TransposeReturnType(tmp); - } - - typedef SelfAdjointView ConstTransposeReturnType; - /** \sa MatrixBase::transpose() const */ - EIGEN_DEVICE_FUNC - inline const ConstTransposeReturnType transpose() const - { - return ConstTransposeReturnType(m_matrix.transpose()); - } - - /** \returns a const expression of the main diagonal of the matrix \c *this - * - * This method simply returns the diagonal of the nested expression, thus by-passing the SelfAdjointView decorator. - * - * \sa MatrixBase::diagonal(), class Diagonal */ - EIGEN_DEVICE_FUNC - typename MatrixType::ConstDiagonalReturnType diagonal() const - { - return typename MatrixType::ConstDiagonalReturnType(m_matrix); - } - -/////////// Cholesky module /////////// - - const LLT llt() const; - const LDLT ldlt() const; - -/////////// Eigenvalue module /////////// - - /** Real part of #Scalar */ - typedef typename NumTraits::Real RealScalar; - /** Return type of eigenvalues() */ - typedef Matrix::ColsAtCompileTime, 1> EigenvaluesReturnType; - - EIGEN_DEVICE_FUNC - EigenvaluesReturnType eigenvalues() const; - EIGEN_DEVICE_FUNC - RealScalar operatorNorm() const; - - protected: - MatrixTypeNested m_matrix; -}; + typedef MatrixType_ MatrixType; + typedef TriangularBase Base; + typedef typename internal::traits::MatrixTypeNested MatrixTypeNested; + typedef typename internal::traits::MatrixTypeNestedCleaned MatrixTypeNestedCleaned; + typedef MatrixTypeNestedCleaned NestedExpression; + + /** \brief The type of coefficients in this matrix */ + typedef typename internal::traits::Scalar Scalar; + typedef typename MatrixType::StorageIndex StorageIndex; + typedef internal::remove_all_t MatrixConjugateReturnType; + typedef SelfAdjointView, UpLo> ConstSelfAdjointView; + + enum { + Mode = internal::traits::Mode, + Flags = internal::traits::Flags, + TransposeMode = ((int(Mode) & int(Upper)) ? Lower : 0) | ((int(Mode) & int(Lower)) ? Upper : 0) + }; + typedef typename MatrixType::PlainObject PlainObject; + + EIGEN_DEVICE_FUNC explicit inline SelfAdjointView(MatrixType& matrix) : m_matrix(matrix) {} + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { return m_matrix.rows(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return m_matrix.cols(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outerStride() const EIGEN_NOEXCEPT { return m_matrix.outerStride(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index innerStride() const EIGEN_NOEXCEPT { return m_matrix.innerStride(); } + + /** \sa MatrixBase::coeff() + * \warning the coordinates must fit into the referenced triangular part + */ + EIGEN_DEVICE_FUNC inline Scalar coeff(Index row, Index col) const { + Base::check_coordinates_internal(row, col); + return m_matrix.coeff(row, col); + } + /** \sa MatrixBase::coeffRef() + * \warning the coordinates must fit into the referenced triangular part + */ + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index row, Index col) { + EIGEN_STATIC_ASSERT_LVALUE(SelfAdjointView); + Base::check_coordinates_internal(row, col); + return m_matrix.coeffRef(row, col); + } + + /** \internal */ + EIGEN_DEVICE_FUNC const MatrixTypeNestedCleaned& _expression() const { return m_matrix; } + + EIGEN_DEVICE_FUNC const MatrixTypeNestedCleaned& nestedExpression() const { return m_matrix; } + EIGEN_DEVICE_FUNC MatrixTypeNestedCleaned& nestedExpression() { return m_matrix; } + + /** Efficient triangular matrix times vector/matrix product */ + template + EIGEN_DEVICE_FUNC const Product operator*(const MatrixBase& rhs) const { + return Product(*this, rhs.derived()); + } + + /** Efficient vector/matrix times triangular matrix product */ + template + friend EIGEN_DEVICE_FUNC const Product operator*(const MatrixBase& lhs, + const SelfAdjointView& rhs) { + return Product(lhs.derived(), rhs); + } + + friend EIGEN_DEVICE_FUNC const + SelfAdjointView + operator*(const Scalar& s, const SelfAdjointView& mat) { + return (s * mat.nestedExpression()).template selfadjointView(); + } + + /** Perform a symmetric rank 2 update of the selfadjoint matrix \c *this: + * \f$ this = this + \alpha u v^* + conj(\alpha) v u^* \f$ + * \returns a reference to \c *this + * + * The vectors \a u and \c v \b must be column vectors, however they can be + * a adjoint expression without any overhead. Only the meaningful triangular + * part of the matrix is updated, the rest is left unchanged. + * + * \sa rankUpdate(const MatrixBase&, Scalar) + */ + template + EIGEN_DEVICE_FUNC SelfAdjointView& rankUpdate(const MatrixBase& u, const MatrixBase& v, + const Scalar& alpha = Scalar(1)); + + /** Perform a symmetric rank K update of the selfadjoint matrix \c *this: + * \f$ this = this + \alpha ( u u^* ) \f$ where \a u is a vector or matrix. + * + * \returns a reference to \c *this + * + * Note that to perform \f$ this = this + \alpha ( u^* u ) \f$ you can simply + * call this function with u.adjoint(). + * + * \sa rankUpdate(const MatrixBase&, const MatrixBase&, Scalar) + */ + template + EIGEN_DEVICE_FUNC SelfAdjointView& rankUpdate(const MatrixBase& u, const Scalar& alpha = Scalar(1)); + + /** \returns an expression of a triangular view extracted from the current selfadjoint view of a given triangular part + * + * The parameter \a TriMode can have the following values: \c #Upper, \c #StrictlyUpper, \c #UnitUpper, + * \c #Lower, \c #StrictlyLower, \c #UnitLower. + * + * If \c TriMode references the same triangular part than \c *this, then this method simply return a \c TriangularView + * of the nested expression, otherwise, the nested expression is first transposed, thus returning a \c + * TriangularView> object. + * + * \sa MatrixBase::triangularView(), class TriangularView + */ + template + EIGEN_DEVICE_FUNC + std::conditional_t<(TriMode & (Upper | Lower)) == (UpLo & (Upper | Lower)), TriangularView, + TriangularView > + triangularView() const { + std::conditional_t<(TriMode & (Upper | Lower)) == (UpLo & (Upper | Lower)), MatrixType&, + typename MatrixType::ConstTransposeReturnType> + tmp1(m_matrix); + std::conditional_t<(TriMode & (Upper | Lower)) == (UpLo & (Upper | Lower)), MatrixType&, + typename MatrixType::AdjointReturnType> + tmp2(tmp1); + return std::conditional_t<(TriMode & (Upper | Lower)) == (UpLo & (Upper | Lower)), + TriangularView, + TriangularView >(tmp2); + } + + typedef SelfAdjointView ConjugateReturnType; + /** \sa MatrixBase::conjugate() const */ + EIGEN_DEVICE_FUNC inline const ConjugateReturnType conjugate() const { + return ConjugateReturnType(m_matrix.conjugate()); + } + + /** \returns an expression of the complex conjugate of \c *this if Cond==true, + * returns \c *this otherwise. + */ + template + EIGEN_DEVICE_FUNC inline std::conditional_t conjugateIf() const { + typedef std::conditional_t ReturnType; + return ReturnType(m_matrix.template conjugateIf()); + } + + typedef SelfAdjointView AdjointReturnType; + /** \sa MatrixBase::adjoint() const */ + EIGEN_DEVICE_FUNC inline const AdjointReturnType adjoint() const { return AdjointReturnType(m_matrix.adjoint()); } + + typedef SelfAdjointView TransposeReturnType; + /** \sa MatrixBase::transpose() */ + template + EIGEN_DEVICE_FUNC inline TransposeReturnType transpose( + std::enable_if_t::value, Dummy*> = nullptr) { + typename MatrixType::TransposeReturnType tmp(m_matrix); + return TransposeReturnType(tmp); + } + + typedef SelfAdjointView ConstTransposeReturnType; + /** \sa MatrixBase::transpose() const */ + EIGEN_DEVICE_FUNC inline const ConstTransposeReturnType transpose() const { + return ConstTransposeReturnType(m_matrix.transpose()); + } + + /** \returns a const expression of the main diagonal of the matrix \c *this + * + * This method simply returns the diagonal of the nested expression, thus by-passing the SelfAdjointView decorator. + * + * \sa MatrixBase::diagonal(), class Diagonal */ + EIGEN_DEVICE_FUNC typename MatrixType::ConstDiagonalReturnType diagonal() const { + return typename MatrixType::ConstDiagonalReturnType(m_matrix); + } + + /////////// Cholesky module /////////// + + const LLT llt() const; + const LDLT ldlt() const; + + /////////// Eigenvalue module /////////// + + /** Real part of #Scalar */ + typedef typename NumTraits::Real RealScalar; + /** Return type of eigenvalues() */ + typedef Matrix::ColsAtCompileTime, 1> EigenvaluesReturnType; + + EIGEN_DEVICE_FUNC EigenvaluesReturnType eigenvalues() const; + EIGEN_DEVICE_FUNC RealScalar operatorNorm() const; + + protected: + MatrixTypeNested m_matrix; +}; // template // internal::selfadjoint_matrix_product_returntype > // operator*(const MatrixBase& lhs, const SelfAdjointView& rhs) // { -// return internal::matrix_selfadjoint_product_returntype >(lhs.derived(),rhs); +// return internal::matrix_selfadjoint_product_returntype +// >(lhs.derived(),rhs); // } // selfadjoint to dense matrix @@ -280,86 +250,80 @@ namespace internal { // TODO currently a selfadjoint expression has the form SelfAdjointView<.,.> // in the future selfadjoint-ness should be defined by the expression traits -// such that Transpose > is valid. (currently TriangularBase::transpose() is overloaded to make it work) -template -struct evaluator_traits > -{ +// such that Transpose > is valid. (currently TriangularBase::transpose() is overloaded to +// make it work) +template +struct evaluator_traits > { typedef typename storage_kind_to_evaluator_kind::Kind Kind; typedef SelfAdjointShape Shape; }; -template -class triangular_dense_assignment_kernel - : public generic_dense_assignment_kernel -{ -protected: +template +class triangular_dense_assignment_kernel + : public generic_dense_assignment_kernel { + protected: typedef generic_dense_assignment_kernel Base; typedef typename Base::DstXprType DstXprType; typedef typename Base::SrcXprType SrcXprType; using Base::m_dst; - using Base::m_src; using Base::m_functor; -public: + using Base::m_src; + public: typedef typename Base::DstEvaluatorType DstEvaluatorType; typedef typename Base::SrcEvaluatorType SrcEvaluatorType; typedef typename Base::Scalar Scalar; typedef typename Base::AssignmentTraits AssignmentTraits; + EIGEN_DEVICE_FUNC triangular_dense_assignment_kernel(DstEvaluatorType& dst, const SrcEvaluatorType& src, + const Functor& func, DstXprType& dstExpr) + : Base(dst, src, func, dstExpr) {} - EIGEN_DEVICE_FUNC triangular_dense_assignment_kernel(DstEvaluatorType &dst, const SrcEvaluatorType &src, const Functor &func, DstXprType& dstExpr) - : Base(dst, src, func, dstExpr) - {} - - EIGEN_DEVICE_FUNC void assignCoeff(Index row, Index col) - { - eigen_internal_assert(row!=col); - Scalar tmp = m_src.coeff(row,col); - m_functor.assignCoeff(m_dst.coeffRef(row,col), tmp); - m_functor.assignCoeff(m_dst.coeffRef(col,row), numext::conj(tmp)); + EIGEN_DEVICE_FUNC void assignCoeff(Index row, Index col) { + eigen_internal_assert(row != col); + Scalar tmp = m_src.coeff(row, col); + m_functor.assignCoeff(m_dst.coeffRef(row, col), tmp); + m_functor.assignCoeff(m_dst.coeffRef(col, row), numext::conj(tmp)); } - EIGEN_DEVICE_FUNC void assignDiagonalCoeff(Index id) - { - Base::assignCoeff(id,id); - } + EIGEN_DEVICE_FUNC void assignDiagonalCoeff(Index id) { Base::assignCoeff(id, id); } - EIGEN_DEVICE_FUNC void assignOppositeCoeff(Index, Index) - { eigen_internal_assert(false && "should never be called"); } + EIGEN_DEVICE_FUNC void assignOppositeCoeff(Index, Index) { eigen_internal_assert(false && "should never be called"); } }; -} // end namespace internal +} // end namespace internal /*************************************************************************** -* Implementation of MatrixBase methods -***************************************************************************/ + * Implementation of MatrixBase methods + ***************************************************************************/ /** This is the const version of MatrixBase::selfadjointView() */ -template -template +template +template EIGEN_DEVICE_FUNC typename MatrixBase::template ConstSelfAdjointViewReturnType::Type -MatrixBase::selfadjointView() const -{ +MatrixBase::selfadjointView() const { return typename ConstSelfAdjointViewReturnType::Type(derived()); } -/** \returns an expression of a symmetric/self-adjoint view extracted from the upper or lower triangular part of the current matrix - * - * The parameter \a UpLo can be either \c #Upper or \c #Lower - * - * Example: \include MatrixBase_selfadjointView.cpp - * Output: \verbinclude MatrixBase_selfadjointView.out - * - * \sa class SelfAdjointView - */ -template -template +/** \returns an expression of a symmetric/self-adjoint view extracted from the upper or lower triangular part of the + * current matrix + * + * The parameter \a UpLo can be either \c #Upper or \c #Lower + * + * Example: \include MatrixBase_selfadjointView.cpp + * Output: \verbinclude MatrixBase_selfadjointView.out + * + * \sa class SelfAdjointView + */ +template +template EIGEN_DEVICE_FUNC typename MatrixBase::template SelfAdjointViewReturnType::Type -MatrixBase::selfadjointView() -{ +MatrixBase::selfadjointView() { return typename SelfAdjointViewReturnType::Type(derived()); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_SELFADJOINTMATRIX_H +#endif // EIGEN_SELFADJOINTMATRIX_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SelfCwiseBinaryOp.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SelfCwiseBinaryOp.h index 7c89c2e23c6..4dc92f174e0 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SelfCwiseBinaryOp.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SelfCwiseBinaryOp.h @@ -10,38 +10,41 @@ #ifndef EIGEN_SELFCWISEBINARYOP_H #define EIGEN_SELFCWISEBINARYOP_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { // TODO generalize the scalar type of 'other' -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::operator*=(const Scalar& other) -{ - internal::call_assignment(this->derived(), PlainObject::Constant(rows(),cols(),other), internal::mul_assign_op()); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::operator*=(const Scalar& other) { + internal::call_assignment(this->derived(), PlainObject::Constant(rows(), cols(), other), + internal::mul_assign_op()); return derived(); } -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& ArrayBase::operator+=(const Scalar& other) -{ - internal::call_assignment(this->derived(), PlainObject::Constant(rows(),cols(),other), internal::add_assign_op()); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& ArrayBase::operator+=(const Scalar& other) { + internal::call_assignment(this->derived(), PlainObject::Constant(rows(), cols(), other), + internal::add_assign_op()); return derived(); } -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& ArrayBase::operator-=(const Scalar& other) -{ - internal::call_assignment(this->derived(), PlainObject::Constant(rows(),cols(),other), internal::sub_assign_op()); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& ArrayBase::operator-=(const Scalar& other) { + internal::call_assignment(this->derived(), PlainObject::Constant(rows(), cols(), other), + internal::sub_assign_op()); return derived(); } -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::operator/=(const Scalar& other) -{ - internal::call_assignment(this->derived(), PlainObject::Constant(rows(),cols(),other), internal::div_assign_op()); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::operator/=(const Scalar& other) { + internal::call_assignment(this->derived(), PlainObject::Constant(rows(), cols(), other), + internal::div_assign_op()); return derived(); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_SELFCWISEBINARYOP_H +#endif // EIGEN_SELFCWISEBINARYOP_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SkewSymmetricMatrix3.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SkewSymmetricMatrix3.h new file mode 100644 index 00000000000..b3fcc3a005c --- /dev/null +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SkewSymmetricMatrix3.h @@ -0,0 +1,382 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// Copyright (C) 2007-2009 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SKEWSYMMETRICMATRIX3_H +#define EIGEN_SKEWSYMMETRICMATRIX3_H + +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class SkewSymmetricBase + * \ingroup Core_Module + * + * \brief Base class for skew symmetric matrices and expressions + * + * This is the base class that is inherited by SkewSymmetricMatrix3 and related expression + * types, which internally use a three vector for storing the entries. SkewSymmetric + * types always represent square three times three matrices. + * + * This implementations follows class DiagonalMatrix + * + * \tparam Derived is the derived type, a SkewSymmetricMatrix3 or SkewSymmetricWrapper. + * + * \sa class SkewSymmetricMatrix3, class SkewSymmetricWrapper + */ +template +class SkewSymmetricBase : public EigenBase { + public: + typedef typename internal::traits::SkewSymmetricVectorType SkewSymmetricVectorType; + typedef typename SkewSymmetricVectorType::Scalar Scalar; + typedef typename SkewSymmetricVectorType::RealScalar RealScalar; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::StorageIndex StorageIndex; + + enum { + RowsAtCompileTime = SkewSymmetricVectorType::SizeAtCompileTime, + ColsAtCompileTime = SkewSymmetricVectorType::SizeAtCompileTime, + MaxRowsAtCompileTime = SkewSymmetricVectorType::MaxSizeAtCompileTime, + MaxColsAtCompileTime = SkewSymmetricVectorType::MaxSizeAtCompileTime, + IsVectorAtCompileTime = 0, + Flags = NoPreferredStorageOrderBit + }; + + typedef Matrix + DenseMatrixType; + typedef DenseMatrixType DenseType; + typedef SkewSymmetricMatrix3 PlainObject; + + /** \returns a reference to the derived object. */ + EIGEN_DEVICE_FUNC inline const Derived& derived() const { return *static_cast(this); } + /** \returns a const reference to the derived object. */ + EIGEN_DEVICE_FUNC inline Derived& derived() { return *static_cast(this); } + + /** + * Constructs a dense matrix from \c *this. Note, this directly returns a dense matrix type, + * not an expression. + * \returns A dense matrix, with its entries set from the the derived object. */ + EIGEN_DEVICE_FUNC DenseMatrixType toDenseMatrix() const { return derived(); } + + /** Determinant vanishes */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Scalar determinant() const { return 0; } + + /** A.transpose() = -A */ + EIGEN_DEVICE_FUNC PlainObject transpose() const { return (-vector()).asSkewSymmetric(); } + + /** \returns the exponential of this matrix using Rodrigues’ formula */ + EIGEN_DEVICE_FUNC DenseMatrixType exponential() const { + DenseMatrixType retVal = DenseMatrixType::Identity(); + const SkewSymmetricVectorType& v = vector(); + if (v.isZero()) { + return retVal; + } + const Scalar norm2 = v.squaredNorm(); + const Scalar norm = numext::sqrt(norm2); + retVal += ((((1 - numext::cos(norm)) / norm2) * derived()) * derived()) + + (numext::sin(norm) / norm) * derived().toDenseMatrix(); + return retVal; + } + + /** \returns a reference to the derived object's vector of coefficients. */ + EIGEN_DEVICE_FUNC inline const SkewSymmetricVectorType& vector() const { return derived().vector(); } + /** \returns a const reference to the derived object's vector of coefficients. */ + EIGEN_DEVICE_FUNC inline SkewSymmetricVectorType& vector() { return derived().vector(); } + + /** \returns the number of rows. */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const { return 3; } + /** \returns the number of columns. */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const { return 3; } + + /** \returns the matrix product of \c *this by the dense matrix, \a matrix */ + template + EIGEN_DEVICE_FUNC Product operator*( + const MatrixBase& matrix) const { + return Product(derived(), matrix.derived()); + } + + /** \returns the matrix product of \c *this by the skew symmetric matrix, \a matrix */ + template + EIGEN_DEVICE_FUNC Product operator*( + const SkewSymmetricBase& matrix) const { + return Product(derived(), matrix.derived()); + } + + template + using SkewSymmetricProductReturnType = SkewSymmetricWrapper; + + /** \returns the wedge product of \c *this by the skew symmetric matrix \a other + * A wedge B = AB - BA */ + template + EIGEN_DEVICE_FUNC SkewSymmetricProductReturnType wedge( + const SkewSymmetricBase& other) const { + return vector().cross(other.vector()).asSkewSymmetric(); + } + + using SkewSymmetricScaleReturnType = + SkewSymmetricWrapper; + + /** \returns the product of \c *this by the scalar \a scalar */ + EIGEN_DEVICE_FUNC inline SkewSymmetricScaleReturnType operator*(const Scalar& scalar) const { + return (vector() * scalar).asSkewSymmetric(); + } + + using ScaleSkewSymmetricReturnType = + SkewSymmetricWrapper; + + /** \returns the product of a scalar and the skew symmetric matrix \a other */ + EIGEN_DEVICE_FUNC friend inline ScaleSkewSymmetricReturnType operator*(const Scalar& scalar, + const SkewSymmetricBase& other) { + return (scalar * other.vector()).asSkewSymmetric(); + } + + template + using SkewSymmetricSumReturnType = SkewSymmetricWrapper; + + /** \returns the sum of \c *this and the skew symmetric matrix \a other */ + template + EIGEN_DEVICE_FUNC inline SkewSymmetricSumReturnType operator+( + const SkewSymmetricBase& other) const { + return (vector() + other.vector()).asSkewSymmetric(); + } + + template + using SkewSymmetricDifferenceReturnType = SkewSymmetricWrapper; + + /** \returns the difference of \c *this and the skew symmetric matrix \a other */ + template + EIGEN_DEVICE_FUNC inline SkewSymmetricDifferenceReturnType operator-( + const SkewSymmetricBase& other) const { + return (vector() - other.vector()).asSkewSymmetric(); + } +}; + +/** \class SkewSymmetricMatrix3 + * \ingroup Core_Module + * + * \brief Represents a 3x3 skew symmetric matrix with its storage + * + * \tparam Scalar_ the type of coefficients + * + * \sa class SkewSymmetricBase, class SkewSymmetricWrapper + */ + +namespace internal { +template +struct traits> : traits> { + typedef Matrix SkewSymmetricVectorType; + typedef SkewSymmetricShape StorageKind; + enum { Flags = LvalueBit | NoPreferredStorageOrderBit | NestByRefBit }; +}; +} // namespace internal +template +class SkewSymmetricMatrix3 : public SkewSymmetricBase> { + public: +#ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename internal::traits::SkewSymmetricVectorType SkewSymmetricVectorType; + typedef const SkewSymmetricMatrix3& Nested; + typedef Scalar_ Scalar; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::StorageIndex StorageIndex; +#endif + + protected: + SkewSymmetricVectorType m_vector; + + public: + /** const version of vector(). */ + EIGEN_DEVICE_FUNC inline const SkewSymmetricVectorType& vector() const { return m_vector; } + /** \returns a reference to the stored vector of coefficients. */ + EIGEN_DEVICE_FUNC inline SkewSymmetricVectorType& vector() { return m_vector; } + + /** Default constructor without initialization */ + EIGEN_DEVICE_FUNC inline SkewSymmetricMatrix3() {} + + /** Constructor from three scalars */ + EIGEN_DEVICE_FUNC inline SkewSymmetricMatrix3(const Scalar& x, const Scalar& y, const Scalar& z) + : m_vector(x, y, z) {} + + /** \brief Constructs a SkewSymmetricMatrix3 from an r-value vector type */ + EIGEN_DEVICE_FUNC explicit inline SkewSymmetricMatrix3(SkewSymmetricVectorType&& vec) : m_vector(std::move(vec)) {} + + /** generic constructor from expression of the coefficients */ + template + EIGEN_DEVICE_FUNC explicit inline SkewSymmetricMatrix3(const MatrixBase& other) : m_vector(other) {} + + /** Copy constructor. */ + template + EIGEN_DEVICE_FUNC inline SkewSymmetricMatrix3(const SkewSymmetricBase& other) + : m_vector(other.vector()) {} + +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** copy constructor. prevent a default copy constructor from hiding the other templated constructor */ + inline SkewSymmetricMatrix3(const SkewSymmetricMatrix3& other) : m_vector(other.vector()) {} +#endif + + /** Copy operator. */ + template + EIGEN_DEVICE_FUNC SkewSymmetricMatrix3& operator=(const SkewSymmetricBase& other) { + m_vector = other.vector(); + return *this; + } + +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** This is a special case of the templated operator=. Its purpose is to + * prevent a default operator= from hiding the templated operator=. + */ + EIGEN_DEVICE_FUNC SkewSymmetricMatrix3& operator=(const SkewSymmetricMatrix3& other) { + m_vector = other.vector(); + return *this; + } +#endif + + typedef SkewSymmetricWrapper, SkewSymmetricVectorType>> + InitializeReturnType; + + /** Initializes a skew symmetric matrix with coefficients set to zero */ + EIGEN_DEVICE_FUNC static InitializeReturnType Zero() { return SkewSymmetricVectorType::Zero().asSkewSymmetric(); } + + /** Sets all coefficients to zero. */ + EIGEN_DEVICE_FUNC inline void setZero() { m_vector.setZero(); } +}; + +/** \class SkewSymmetricWrapper + * \ingroup Core_Module + * + * \brief Expression of a skew symmetric matrix + * + * \tparam SkewSymmetricVectorType_ the type of the vector of coefficients + * + * This class is an expression of a skew symmetric matrix, but not storing its own vector of coefficients, + * instead wrapping an existing vector expression. It is the return type of MatrixBase::asSkewSymmetric() + * and most of the time this is the only way that it is used. + * + * \sa class SkewSymmetricMatrix3, class SkewSymmetricBase, MatrixBase::asSkewSymmetric() + */ + +namespace internal { +template +struct traits> { + typedef SkewSymmetricVectorType_ SkewSymmetricVectorType; + typedef typename SkewSymmetricVectorType::Scalar Scalar; + typedef typename SkewSymmetricVectorType::StorageIndex StorageIndex; + typedef SkewSymmetricShape StorageKind; + typedef typename traits::XprKind XprKind; + enum { + RowsAtCompileTime = SkewSymmetricVectorType::SizeAtCompileTime, + ColsAtCompileTime = SkewSymmetricVectorType::SizeAtCompileTime, + MaxRowsAtCompileTime = SkewSymmetricVectorType::MaxSizeAtCompileTime, + MaxColsAtCompileTime = SkewSymmetricVectorType::MaxSizeAtCompileTime, + Flags = (traits::Flags & LvalueBit) | NoPreferredStorageOrderBit + }; +}; +} // namespace internal + +template +class SkewSymmetricWrapper : public SkewSymmetricBase>, + internal::no_assignment_operator { + public: +#ifndef EIGEN_PARSED_BY_DOXYGEN + typedef SkewSymmetricVectorType_ SkewSymmetricVectorType; + typedef SkewSymmetricWrapper Nested; +#endif + + /** Constructor from expression of coefficients to wrap. */ + EIGEN_DEVICE_FUNC explicit inline SkewSymmetricWrapper(SkewSymmetricVectorType& a_vector) : m_vector(a_vector) {} + + /** \returns a const reference to the wrapped expression of coefficients. */ + EIGEN_DEVICE_FUNC const SkewSymmetricVectorType& vector() const { return m_vector; } + + protected: + typename SkewSymmetricVectorType::Nested m_vector; +}; + +/** \returns a pseudo-expression of a skew symmetric matrix with *this as vector of coefficients + * + * \only_for_vectors + * + * \sa class SkewSymmetricWrapper, class SkewSymmetricMatrix3, vector(), isSkewSymmetric() + **/ +template +EIGEN_DEVICE_FUNC inline const SkewSymmetricWrapper MatrixBase::asSkewSymmetric() const { + return SkewSymmetricWrapper(derived()); +} + +/** \returns true if *this is approximately equal to a skew symmetric matrix, + * within the precision given by \a prec. + */ +template +bool MatrixBase::isSkewSymmetric(const RealScalar& prec) const { + if (cols() != rows()) return false; + return (this->transpose() + *this).isZero(prec); +} + +/** \returns the matrix product of \c *this by the skew symmetric matrix \skew. + */ +template +template +EIGEN_DEVICE_FUNC inline const Product MatrixBase::operator*( + const SkewSymmetricBase& skew) const { + return Product(derived(), skew.derived()); +} + +namespace internal { + +template <> +struct storage_kind_to_shape { + typedef SkewSymmetricShape Shape; +}; + +struct SkewSymmetric2Dense {}; + +template <> +struct AssignmentKind { + typedef SkewSymmetric2Dense Kind; +}; + +// SkewSymmetric matrix to Dense assignment +template +struct Assignment { + EIGEN_DEVICE_FUNC static void run( + DstXprType& dst, const SrcXprType& src, + const internal::assign_op& /*func*/) { + if ((dst.rows() != 3) || (dst.cols() != 3)) { + dst.resize(3, 3); + } + dst.diagonal().setZero(); + const typename SrcXprType::SkewSymmetricVectorType v = src.vector(); + dst(0, 1) = -v(2); + dst(1, 0) = v(2); + dst(0, 2) = v(1); + dst(2, 0) = -v(1); + dst(1, 2) = -v(0); + dst(2, 1) = v(0); + } + EIGEN_DEVICE_FUNC static void run( + DstXprType& dst, const SrcXprType& src, + const internal::add_assign_op& /*func*/) { + dst.vector() += src.vector(); + } + + EIGEN_DEVICE_FUNC static void run( + DstXprType& dst, const SrcXprType& src, + const internal::sub_assign_op& /*func*/) { + dst.vector() -= src.vector(); + } +}; + +} // namespace internal + +} // end namespace Eigen + +#endif // EIGEN_SKEWSYMMETRICMATRIX3_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Solve.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Solve.h index 23d5cb70728..dfea9c6fb81 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Solve.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Solve.h @@ -10,179 +10,165 @@ #ifndef EIGEN_SOLVE_H #define EIGEN_SOLVE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { -template class SolveImpl; +template +class SolveImpl; /** \class Solve - * \ingroup Core_Module - * - * \brief Pseudo expression representing a solving operation - * - * \tparam Decomposition the type of the matrix or decomposition object - * \tparam Rhstype the type of the right-hand side - * - * This class represents an expression of A.solve(B) - * and most of the time this is the only way it is used. - * - */ + * \ingroup Core_Module + * + * \brief Pseudo expression representing a solving operation + * + * \tparam Decomposition the type of the matrix or decomposition object + * \tparam Rhstype the type of the right-hand side + * + * This class represents an expression of A.solve(B) + * and most of the time this is the only way it is used. + * + */ namespace internal { // this solve_traits class permits to determine the evaluation type with respect to storage kind (Dense vs Sparse) -template struct solve_traits; - -template -struct solve_traits -{ - typedef typename make_proper_matrix_type::type PlainObject; +template +struct solve_traits; + +template +struct solve_traits { + typedef typename make_proper_matrix_type::type + PlainObject; }; -template +template struct traits > - : traits::StorageKind>::PlainObject> -{ - typedef typename solve_traits::StorageKind>::PlainObject PlainObject; - typedef typename promote_index_type::type StorageIndex; + : traits< + typename solve_traits::StorageKind>::PlainObject> { + typedef typename solve_traits::StorageKind>::PlainObject + PlainObject; + typedef typename promote_index_type::type + StorageIndex; typedef traits BaseTraits; - enum { - Flags = BaseTraits::Flags & RowMajorBit, - CoeffReadCost = HugeCost - }; + enum { Flags = BaseTraits::Flags & RowMajorBit, CoeffReadCost = HugeCost }; }; -} - +} // namespace internal -template -class Solve : public SolveImpl::StorageKind> -{ -public: +template +class Solve : public SolveImpl::StorageKind> { + public: typedef typename internal::traits::PlainObject PlainObject; typedef typename internal::traits::StorageIndex StorageIndex; - Solve(const Decomposition &dec, const RhsType &rhs) - : m_dec(dec), m_rhs(rhs) - {} + Solve(const Decomposition &dec, const RhsType &rhs) : m_dec(dec), m_rhs(rhs) {} EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_dec.cols(); } EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_rhs.cols(); } - EIGEN_DEVICE_FUNC const Decomposition& dec() const { return m_dec; } - EIGEN_DEVICE_FUNC const RhsType& rhs() const { return m_rhs; } + EIGEN_DEVICE_FUNC const Decomposition &dec() const { return m_dec; } + EIGEN_DEVICE_FUNC const RhsType &rhs() const { return m_rhs; } -protected: + protected: const Decomposition &m_dec; - const RhsType &m_rhs; + const typename internal::ref_selector::type m_rhs; }; - // Specialization of the Solve expression for dense results -template -class SolveImpl - : public MatrixBase > -{ - typedef Solve Derived; +template +class SolveImpl : public MatrixBase > { + typedef Solve Derived; -public: - - typedef MatrixBase > Base; + public: + typedef MatrixBase > Base; EIGEN_DENSE_PUBLIC_INTERFACE(Derived) -private: - + private: Scalar coeff(Index row, Index col) const; Scalar coeff(Index i) const; }; // Generic API dispatcher -template -class SolveImpl : public internal::generic_xpr_base, MatrixXpr, StorageKind>::type -{ - public: - typedef typename internal::generic_xpr_base, MatrixXpr, StorageKind>::type Base; +template +class SolveImpl : public internal::generic_xpr_base, MatrixXpr, StorageKind>::type { + public: + typedef typename internal::generic_xpr_base, MatrixXpr, StorageKind>::type Base; }; namespace internal { // Evaluator of Solve -> eval into a temporary -template -struct evaluator > - : public evaluator::PlainObject> -{ - typedef Solve SolveType; +template +struct evaluator > + : public evaluator::PlainObject> { + typedef Solve SolveType; typedef typename SolveType::PlainObject PlainObject; typedef evaluator Base; enum { Flags = Base::Flags | EvalBeforeNestingBit }; - EIGEN_DEVICE_FUNC explicit evaluator(const SolveType& solve) - : m_result(solve.rows(), solve.cols()) - { - ::new (static_cast(this)) Base(m_result); + EIGEN_DEVICE_FUNC explicit evaluator(const SolveType &solve) : m_result(solve.rows(), solve.cols()) { + internal::construct_at(this, m_result); solve.dec()._solve_impl(solve.rhs(), m_result); } -protected: + protected: PlainObject m_result; }; // Specialization for "dst = dec.solve(rhs)" -// NOTE we need to specialize it for Dense2Dense to avoid ambiguous specialization error and a Sparse2Sparse specialization must exist somewhere -template -struct Assignment, internal::assign_op, Dense2Dense> -{ - typedef Solve SrcXprType; - static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &) - { +// NOTE we need to specialize it for Dense2Dense to avoid ambiguous specialization error and a Sparse2Sparse +// specialization must exist somewhere +template +struct Assignment, internal::assign_op, Dense2Dense> { + typedef Solve SrcXprType; + static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &) { Index dstRows = src.rows(); Index dstCols = src.cols(); - if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) - dst.resize(dstRows, dstCols); + if ((dst.rows() != dstRows) || (dst.cols() != dstCols)) dst.resize(dstRows, dstCols); src.dec()._solve_impl(src.rhs(), dst); } }; // Specialization for "dst = dec.transpose().solve(rhs)" -template -struct Assignment,RhsType>, internal::assign_op, Dense2Dense> -{ - typedef Solve,RhsType> SrcXprType; - static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &) - { +template +struct Assignment, RhsType>, internal::assign_op, + Dense2Dense> { + typedef Solve, RhsType> SrcXprType; + static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &) { Index dstRows = src.rows(); Index dstCols = src.cols(); - if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) - dst.resize(dstRows, dstCols); + if ((dst.rows() != dstRows) || (dst.cols() != dstCols)) dst.resize(dstRows, dstCols); src.dec().nestedExpression().template _solve_impl_transposed(src.rhs(), dst); } }; // Specialization for "dst = dec.adjoint().solve(rhs)" -template -struct Assignment, const Transpose >,RhsType>, - internal::assign_op, Dense2Dense> -{ - typedef Solve, const Transpose >,RhsType> SrcXprType; - static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &) - { +template +struct Assignment< + DstXprType, + Solve, const Transpose >, + RhsType>, + internal::assign_op, Dense2Dense> { + typedef Solve, const Transpose >, + RhsType> + SrcXprType; + static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &) { Index dstRows = src.rows(); Index dstCols = src.cols(); - if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) - dst.resize(dstRows, dstCols); + if ((dst.rows() != dstRows) || (dst.cols() != dstCols)) dst.resize(dstRows, dstCols); src.dec().nestedExpression().nestedExpression().template _solve_impl_transposed(src.rhs(), dst); } }; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_SOLVE_H +#endif // EIGEN_SOLVE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SolveTriangular.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SolveTriangular.h index dfbf99523a9..26d62ffa45b 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SolveTriangular.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SolveTriangular.h @@ -10,226 +10,228 @@ #ifndef EIGEN_SOLVETRIANGULAR_H #define EIGEN_SOLVETRIANGULAR_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { // Forward declarations: // The following two routines are implemented in the products/TriangularSolver*.h files -template +template struct triangular_solve_vector; -template +template struct triangular_solve_matrix; // small helper struct extracting some traits on the underlying solver operation -template -class trsolve_traits -{ - private: - enum { - RhsIsVectorAtCompileTime = (Side==OnTheLeft ? Rhs::ColsAtCompileTime : Rhs::RowsAtCompileTime)==1 - }; - public: - enum { - Unrolling = (RhsIsVectorAtCompileTime && Rhs::SizeAtCompileTime != Dynamic && Rhs::SizeAtCompileTime <= 8) - ? CompleteUnrolling : NoUnrolling, - RhsVectors = RhsIsVectorAtCompileTime ? 1 : Dynamic - }; +template +class trsolve_traits { + private: + enum { RhsIsVectorAtCompileTime = (Side == OnTheLeft ? Rhs::ColsAtCompileTime : Rhs::RowsAtCompileTime) == 1 }; + + public: + enum { + Unrolling = (RhsIsVectorAtCompileTime && Rhs::SizeAtCompileTime != Dynamic && Rhs::SizeAtCompileTime <= 8) + ? CompleteUnrolling + : NoUnrolling, + RhsVectors = RhsIsVectorAtCompileTime ? 1 : Dynamic + }; }; -template::Unrolling, - int RhsVectors = trsolve_traits::RhsVectors - > +template ::Unrolling, + int RhsVectors = trsolve_traits::RhsVectors> struct triangular_solver_selector; -template -struct triangular_solver_selector -{ +template +struct triangular_solver_selector { typedef typename Lhs::Scalar LhsScalar; typedef typename Rhs::Scalar RhsScalar; typedef blas_traits LhsProductTraits; typedef typename LhsProductTraits::ExtractType ActualLhsType; - typedef Map, Aligned> MappedRhs; - static EIGEN_DEVICE_FUNC void run(const Lhs& lhs, Rhs& rhs) - { + typedef Map, Aligned> MappedRhs; + static EIGEN_DEVICE_FUNC void run(const Lhs& lhs, Rhs& rhs) { ActualLhsType actualLhs = LhsProductTraits::extract(lhs); // FIXME find a way to allow an inner stride if packet_traits::size==1 - bool useRhsDirectly = Rhs::InnerStrideAtCompileTime==1 || rhs.innerStride()==1; + bool useRhsDirectly = Rhs::InnerStrideAtCompileTime == 1 || rhs.innerStride() == 1; - ei_declare_aligned_stack_constructed_variable(RhsScalar,actualRhs,rhs.size(), - (useRhsDirectly ? rhs.data() : 0)); + ei_declare_aligned_stack_constructed_variable(RhsScalar, actualRhs, rhs.size(), (useRhsDirectly ? rhs.data() : 0)); - if(!useRhsDirectly) - MappedRhs(actualRhs,rhs.size()) = rhs; + if (!useRhsDirectly) MappedRhs(actualRhs, rhs.size()) = rhs; triangular_solve_vector - ::run(actualLhs.cols(), actualLhs.data(), actualLhs.outerStride(), actualRhs); + (int(Lhs::Flags) & RowMajorBit) ? RowMajor : ColMajor>::run(actualLhs.cols(), + actualLhs.data(), + actualLhs.outerStride(), + actualRhs); - if(!useRhsDirectly) - rhs = MappedRhs(actualRhs, rhs.size()); + if (!useRhsDirectly) rhs = MappedRhs(actualRhs, rhs.size()); } }; // the rhs is a matrix -template -struct triangular_solver_selector -{ +template +struct triangular_solver_selector { typedef typename Rhs::Scalar Scalar; typedef blas_traits LhsProductTraits; typedef typename LhsProductTraits::DirectLinearAccessType ActualLhsType; - static EIGEN_DEVICE_FUNC void run(const Lhs& lhs, Rhs& rhs) - { - typename internal::add_const_on_value_type::type actualLhs = LhsProductTraits::extract(lhs); + static EIGEN_DEVICE_FUNC void run(const Lhs& lhs, Rhs& rhs) { + add_const_on_value_type_t actualLhs = LhsProductTraits::extract(lhs); const Index size = lhs.rows(); - const Index othersize = Side==OnTheLeft? rhs.cols() : rhs.rows(); + const Index othersize = Side == OnTheLeft ? rhs.cols() : rhs.rows(); + + typedef internal::gemm_blocking_space<(Rhs::Flags & RowMajorBit) ? RowMajor : ColMajor, Scalar, Scalar, + Rhs::MaxRowsAtCompileTime, Rhs::MaxColsAtCompileTime, + Lhs::MaxRowsAtCompileTime, 4> + BlockingType; - typedef internal::gemm_blocking_space<(Rhs::Flags&RowMajorBit) ? RowMajor : ColMajor,Scalar,Scalar, - Rhs::MaxRowsAtCompileTime, Rhs::MaxColsAtCompileTime, Lhs::MaxRowsAtCompileTime,4> BlockingType; + // Nothing to solve. + if (actualLhs.size() == 0 || rhs.size() == 0) { + return; + } BlockingType blocking(rhs.rows(), rhs.cols(), size, 1, false); - triangular_solve_matrix - ::run(size, othersize, &actualLhs.coeffRef(0,0), actualLhs.outerStride(), &rhs.coeffRef(0,0), rhs.innerStride(), rhs.outerStride(), blocking); + triangular_solve_matrix::run(size, othersize, &actualLhs.coeffRef(0, 0), + actualLhs.outerStride(), &rhs.coeffRef(0, 0), + rhs.innerStride(), rhs.outerStride(), blocking); } }; /*************************************************************************** -* meta-unrolling implementation -***************************************************************************/ + * meta-unrolling implementation + ***************************************************************************/ -template +template struct triangular_solver_unroller; -template -struct triangular_solver_unroller { +template +struct triangular_solver_unroller { enum { - IsLower = ((Mode&Lower)==Lower), - DiagIndex = IsLower ? LoopIndex : Size - LoopIndex - 1, - StartIndex = IsLower ? 0 : DiagIndex+1 + IsLower = ((Mode & Lower) == Lower), + DiagIndex = IsLower ? LoopIndex : Size - LoopIndex - 1, + StartIndex = IsLower ? 0 : DiagIndex + 1 }; - static EIGEN_DEVICE_FUNC void run(const Lhs& lhs, Rhs& rhs) - { - if (LoopIndex>0) - rhs.coeffRef(DiagIndex) -= lhs.row(DiagIndex).template segment(StartIndex).transpose() - .cwiseProduct(rhs.template segment(StartIndex)).sum(); + static EIGEN_DEVICE_FUNC void run(const Lhs& lhs, Rhs& rhs) { + if (LoopIndex > 0) + rhs.coeffRef(DiagIndex) -= lhs.row(DiagIndex) + .template segment(StartIndex) + .transpose() + .cwiseProduct(rhs.template segment(StartIndex)) + .sum(); - if(!(Mode & UnitDiag)) - rhs.coeffRef(DiagIndex) /= lhs.coeff(DiagIndex,DiagIndex); + if (!(Mode & UnitDiag)) rhs.coeffRef(DiagIndex) /= lhs.coeff(DiagIndex, DiagIndex); - triangular_solver_unroller::run(lhs,rhs); + triangular_solver_unroller::run(lhs, rhs); } }; -template -struct triangular_solver_unroller { +template +struct triangular_solver_unroller { static EIGEN_DEVICE_FUNC void run(const Lhs&, Rhs&) {} }; -template -struct triangular_solver_selector { - static EIGEN_DEVICE_FUNC void run(const Lhs& lhs, Rhs& rhs) - { triangular_solver_unroller::run(lhs,rhs); } +template +struct triangular_solver_selector { + static EIGEN_DEVICE_FUNC void run(const Lhs& lhs, Rhs& rhs) { + triangular_solver_unroller::run(lhs, rhs); + } }; -template -struct triangular_solver_selector { - static EIGEN_DEVICE_FUNC void run(const Lhs& lhs, Rhs& rhs) - { +template +struct triangular_solver_selector { + static EIGEN_DEVICE_FUNC void run(const Lhs& lhs, Rhs& rhs) { Transpose trLhs(lhs); Transpose trRhs(rhs); - triangular_solver_unroller,Transpose, - ((Mode&Upper)==Upper ? Lower : Upper) | (Mode&UnitDiag), - 0,Rhs::SizeAtCompileTime>::run(trLhs,trRhs); + triangular_solver_unroller, Transpose, + ((Mode & Upper) == Upper ? Lower : Upper) | (Mode & UnitDiag), 0, + Rhs::SizeAtCompileTime>::run(trLhs, trRhs); } }; -} // end namespace internal +} // end namespace internal /*************************************************************************** -* TriangularView methods -***************************************************************************/ + * TriangularView methods + ***************************************************************************/ #ifndef EIGEN_PARSED_BY_DOXYGEN -template -template -EIGEN_DEVICE_FUNC void TriangularViewImpl::solveInPlace(const MatrixBase& _other) const -{ +template +template +EIGEN_DEVICE_FUNC void TriangularViewImpl::solveInPlace( + const MatrixBase& _other) const { OtherDerived& other = _other.const_cast_derived(); - eigen_assert( derived().cols() == derived().rows() && ((Side==OnTheLeft && derived().cols() == other.rows()) || (Side==OnTheRight && derived().cols() == other.cols())) ); + eigen_assert(derived().cols() == derived().rows() && ((Side == OnTheLeft && derived().cols() == other.rows()) || + (Side == OnTheRight && derived().cols() == other.cols()))); eigen_assert((!(int(Mode) & int(ZeroDiag))) && bool(int(Mode) & (int(Upper) | int(Lower)))); // If solving for a 0x0 matrix, nothing to do, simply return. - if (derived().cols() == 0) - return; + if (derived().cols() == 0) return; - enum { copy = (internal::traits::Flags & RowMajorBit) && OtherDerived::IsVectorAtCompileTime && OtherDerived::SizeAtCompileTime!=1}; - typedef typename internal::conditional::type, OtherDerived&>::type OtherCopy; + enum { + copy = (internal::traits::Flags & RowMajorBit) && OtherDerived::IsVectorAtCompileTime && + OtherDerived::SizeAtCompileTime != 1 + }; + typedef std::conditional_t::type, OtherDerived&> + OtherCopy; OtherCopy otherCopy(other); - internal::triangular_solver_selector::type, - Side, Mode>::run(derived().nestedExpression(), otherCopy); + internal::triangular_solver_selector, Side, Mode>::run( + derived().nestedExpression(), otherCopy); - if (copy) - other = otherCopy; + if (copy) other = otherCopy; } -template -template -const internal::triangular_solve_retval,Other> -TriangularViewImpl::solve(const MatrixBase& other) const -{ - return internal::triangular_solve_retval(derived(), other.derived()); +template +template +const internal::triangular_solve_retval, Other> +TriangularViewImpl::solve(const MatrixBase& other) const { + return internal::triangular_solve_retval(derived(), other.derived()); } #endif namespace internal { - -template -struct traits > -{ +template +struct traits > { typedef typename internal::plain_matrix_type_column_major::type ReturnType; }; -template struct triangular_solve_retval - : public ReturnByValue > -{ - typedef typename remove_all::type RhsNestedCleaned; +template +struct triangular_solve_retval : public ReturnByValue > { + typedef remove_all_t RhsNestedCleaned; typedef ReturnByValue Base; - triangular_solve_retval(const TriangularType& tri, const Rhs& rhs) - : m_triangularMatrix(tri), m_rhs(rhs) - {} + triangular_solve_retval(const TriangularType& tri, const Rhs& rhs) : m_triangularMatrix(tri), m_rhs(rhs) {} inline EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_rhs.rows(); } inline EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_rhs.cols(); } - template inline void evalTo(Dest& dst) const - { - if(!is_same_dense(dst,m_rhs)) - dst = m_rhs; + template + inline void evalTo(Dest& dst) const { + if (!is_same_dense(dst, m_rhs)) dst = m_rhs; m_triangularMatrix.template solveInPlace(dst); } - protected: - const TriangularType& m_triangularMatrix; - typename Rhs::Nested m_rhs; + protected: + const TriangularType& m_triangularMatrix; + typename Rhs::Nested m_rhs; }; -} // namespace internal +} // namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_SOLVETRIANGULAR_H +#endif // EIGEN_SOLVETRIANGULAR_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SolverBase.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SolverBase.h index 5014610420f..df2ac837100 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SolverBase.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/SolverBase.h @@ -10,159 +10,150 @@ #ifndef EIGEN_SOLVERBASE_H #define EIGEN_SOLVERBASE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template +template struct solve_assertion { - template - static void run(const Derived& solver, const Rhs& b) { solver.template _check_solve_assertion(b); } + template + static void run(const Derived& solver, const Rhs& b) { + solver.template _check_solve_assertion(b); + } }; -template -struct solve_assertion > -{ - typedef Transpose type; +template +struct solve_assertion> { + typedef Transpose type; - template - static void run(const type& transpose, const Rhs& b) - { - internal::solve_assertion::type>::template run(transpose.nestedExpression(), b); - } + template + static void run(const type& transpose, const Rhs& b) { + internal::solve_assertion>::template run(transpose.nestedExpression(), b); + } }; -template -struct solve_assertion, const Transpose > > -{ - typedef CwiseUnaryOp, const Transpose > type; +template +struct solve_assertion, const Transpose>> { + typedef CwiseUnaryOp, const Transpose> type; - template - static void run(const type& adjoint, const Rhs& b) - { - internal::solve_assertion >::type>::template run(adjoint.nestedExpression(), b); - } + template + static void run(const type& adjoint, const Rhs& b) { + internal::solve_assertion>>::template run( + adjoint.nestedExpression(), b); + } }; -} // end namespace internal +} // end namespace internal /** \class SolverBase - * \brief A base class for matrix decomposition and solvers - * - * \tparam Derived the actual type of the decomposition/solver. - * - * Any matrix decomposition inheriting this base class provide the following API: - * - * \code - * MatrixType A, b, x; - * DecompositionType dec(A); - * x = dec.solve(b); // solve A * x = b - * x = dec.transpose().solve(b); // solve A^T * x = b - * x = dec.adjoint().solve(b); // solve A' * x = b - * \endcode - * - * \warning Currently, any other usage of transpose() and adjoint() are not supported and will produce compilation errors. - * - * \sa class PartialPivLU, class FullPivLU, class HouseholderQR, class ColPivHouseholderQR, class FullPivHouseholderQR, class CompleteOrthogonalDecomposition, class LLT, class LDLT, class SVDBase - */ -template -class SolverBase : public EigenBase -{ - public: - - typedef EigenBase Base; - typedef typename internal::traits::Scalar Scalar; - typedef Scalar CoeffReturnType; - - template - friend struct internal::solve_assertion; - - enum { - RowsAtCompileTime = internal::traits::RowsAtCompileTime, - ColsAtCompileTime = internal::traits::ColsAtCompileTime, - SizeAtCompileTime = (internal::size_at_compile_time::RowsAtCompileTime, - internal::traits::ColsAtCompileTime>::ret), - MaxRowsAtCompileTime = internal::traits::MaxRowsAtCompileTime, - MaxColsAtCompileTime = internal::traits::MaxColsAtCompileTime, - MaxSizeAtCompileTime = (internal::size_at_compile_time::MaxRowsAtCompileTime, - internal::traits::MaxColsAtCompileTime>::ret), - IsVectorAtCompileTime = internal::traits::MaxRowsAtCompileTime == 1 - || internal::traits::MaxColsAtCompileTime == 1, - NumDimensions = int(MaxSizeAtCompileTime) == 1 ? 0 : bool(IsVectorAtCompileTime) ? 1 : 2 - }; - - /** Default constructor */ - SolverBase() - {} - - ~SolverBase() - {} - - using Base::derived; - - /** \returns an expression of the solution x of \f$ A x = b \f$ using the current decomposition of A. - */ - template - inline const Solve - solve(const MatrixBase& b) const - { - internal::solve_assertion::type>::template run(derived(), b); - return Solve(derived(), b.derived()); - } - - /** \internal the return type of transpose() */ - typedef typename internal::add_const >::type ConstTransposeReturnType; - /** \returns an expression of the transposed of the factored matrix. - * - * A typical usage is to solve for the transposed problem A^T x = b: - * \code x = dec.transpose().solve(b); \endcode - * - * \sa adjoint(), solve() - */ - inline ConstTransposeReturnType transpose() const - { - return ConstTransposeReturnType(derived()); - } - - /** \internal the return type of adjoint() */ - typedef typename internal::conditional::IsComplex, - CwiseUnaryOp, ConstTransposeReturnType>, - ConstTransposeReturnType - >::type AdjointReturnType; - /** \returns an expression of the adjoint of the factored matrix - * - * A typical usage is to solve for the adjoint problem A' x = b: - * \code x = dec.adjoint().solve(b); \endcode - * - * For real scalar types, this function is equivalent to transpose(). - * - * \sa transpose(), solve() - */ - inline AdjointReturnType adjoint() const - { - return AdjointReturnType(derived().transpose()); - } - - protected: - - template - void _check_solve_assertion(const Rhs& b) const { - EIGEN_ONLY_USED_FOR_DEBUG(b); - eigen_assert(derived().m_isInitialized && "Solver is not initialized."); - eigen_assert((Transpose_?derived().cols():derived().rows())==b.rows() && "SolverBase::solve(): invalid number of rows of the right hand side matrix b"); - } + * \brief A base class for matrix decomposition and solvers + * + * \tparam Derived the actual type of the decomposition/solver. + * + * Any matrix decomposition inheriting this base class provide the following API: + * + * \code + * MatrixType A, b, x; + * DecompositionType dec(A); + * x = dec.solve(b); // solve A * x = b + * x = dec.transpose().solve(b); // solve A^T * x = b + * x = dec.adjoint().solve(b); // solve A' * x = b + * \endcode + * + * \warning Currently, any other usage of transpose() and adjoint() are not supported and will produce compilation + * errors. + * + * \sa class PartialPivLU, class FullPivLU, class HouseholderQR, class ColPivHouseholderQR, class FullPivHouseholderQR, + * class CompleteOrthogonalDecomposition, class LLT, class LDLT, class SVDBase + */ +template +class SolverBase : public EigenBase { + public: + typedef EigenBase Base; + typedef typename internal::traits::Scalar Scalar; + typedef Scalar CoeffReturnType; + + template + friend struct internal::solve_assertion; + + enum { + RowsAtCompileTime = internal::traits::RowsAtCompileTime, + ColsAtCompileTime = internal::traits::ColsAtCompileTime, + SizeAtCompileTime = (internal::size_of_xpr_at_compile_time::ret), + MaxRowsAtCompileTime = internal::traits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = internal::traits::MaxColsAtCompileTime, + MaxSizeAtCompileTime = internal::size_at_compile_time(internal::traits::MaxRowsAtCompileTime, + internal::traits::MaxColsAtCompileTime), + IsVectorAtCompileTime = + internal::traits::MaxRowsAtCompileTime == 1 || internal::traits::MaxColsAtCompileTime == 1, + NumDimensions = int(MaxSizeAtCompileTime) == 1 ? 0 + : bool(IsVectorAtCompileTime) ? 1 + : 2 + }; + + /** Default constructor */ + SolverBase() {} + + ~SolverBase() {} + + using Base::derived; + + /** \returns an expression of the solution x of \f$ A x = b \f$ using the current decomposition of A. + */ + template + inline const Solve solve(const MatrixBase& b) const { + internal::solve_assertion>::template run(derived(), b); + return Solve(derived(), b.derived()); + } + + /** \internal the return type of transpose() */ + typedef Transpose ConstTransposeReturnType; + /** \returns an expression of the transposed of the factored matrix. + * + * A typical usage is to solve for the transposed problem A^T x = b: + * \code x = dec.transpose().solve(b); \endcode + * + * \sa adjoint(), solve() + */ + inline const ConstTransposeReturnType transpose() const { return ConstTransposeReturnType(derived()); } + + /** \internal the return type of adjoint() */ + typedef std::conditional_t::IsComplex, + CwiseUnaryOp, const ConstTransposeReturnType>, + const ConstTransposeReturnType> + AdjointReturnType; + /** \returns an expression of the adjoint of the factored matrix + * + * A typical usage is to solve for the adjoint problem A' x = b: + * \code x = dec.adjoint().solve(b); \endcode + * + * For real scalar types, this function is equivalent to transpose(). + * + * \sa transpose(), solve() + */ + inline const AdjointReturnType adjoint() const { return AdjointReturnType(derived().transpose()); } + + protected: + template + void _check_solve_assertion(const Rhs& b) const { + EIGEN_ONLY_USED_FOR_DEBUG(b); + eigen_assert(derived().m_isInitialized && "Solver is not initialized."); + eigen_assert((Transpose_ ? derived().cols() : derived().rows()) == b.rows() && + "SolverBase::solve(): invalid number of rows of the right hand side matrix b"); + } }; namespace internal { -template -struct generic_xpr_base -{ +template +struct generic_xpr_base { typedef SolverBase type; - }; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_SOLVERBASE_H +#endif // EIGEN_SOLVERBASE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/StableNorm.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/StableNorm.h index 4a3f0cca8c4..6513120e0fb 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/StableNorm.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/StableNorm.h @@ -10,119 +10,114 @@ #ifndef EIGEN_STABLENORM_H #define EIGEN_STABLENORM_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { namespace internal { -template -inline void stable_norm_kernel(const ExpressionType& bl, Scalar& ssq, Scalar& scale, Scalar& invScale) -{ +template +inline void stable_norm_kernel(const ExpressionType& bl, Scalar& ssq, Scalar& scale, Scalar& invScale) { Scalar maxCoeff = bl.cwiseAbs().maxCoeff(); - - if(maxCoeff>scale) - { - ssq = ssq * numext::abs2(scale/maxCoeff); - Scalar tmp = Scalar(1)/maxCoeff; - if(tmp > NumTraits::highest()) - { + + if (maxCoeff > scale) { + ssq = ssq * numext::abs2(scale / maxCoeff); + Scalar tmp = Scalar(1) / maxCoeff; + if (tmp > NumTraits::highest()) { invScale = NumTraits::highest(); - scale = Scalar(1)/invScale; - } - else if(maxCoeff>NumTraits::highest()) // we got a INF + scale = Scalar(1) / invScale; + } else if (maxCoeff > NumTraits::highest()) // we got a INF { invScale = Scalar(1); scale = maxCoeff; - } - else - { + } else { scale = maxCoeff; invScale = tmp; } - } - else if(maxCoeff!=maxCoeff) // we got a NaN + } else if (maxCoeff != maxCoeff) // we got a NaN { scale = maxCoeff; } - + // TODO if the maxCoeff is much much smaller than the current scale, // then we can neglect this sub vector - if(scale>Scalar(0)) // if scale==0, then bl is 0 - ssq += (bl*invScale).squaredNorm(); + if (scale > Scalar(0)) // if scale==0, then bl is 0 + ssq += (bl * invScale).squaredNorm(); } -template -void stable_norm_impl_inner_step(const VectorType &vec, RealScalar& ssq, RealScalar& scale, RealScalar& invScale) -{ +template +void stable_norm_impl_inner_step(const VectorType& vec, RealScalar& ssq, RealScalar& scale, RealScalar& invScale) { typedef typename VectorType::Scalar Scalar; const Index blockSize = 4096; - - typedef typename internal::nested_eval::type VectorTypeCopy; - typedef typename internal::remove_all::type VectorTypeCopyClean; + + typedef typename internal::nested_eval::type VectorTypeCopy; + typedef internal::remove_all_t VectorTypeCopyClean; const VectorTypeCopy copy(vec); - + enum { - CanAlign = ( (int(VectorTypeCopyClean::Flags)&DirectAccessBit) - || (int(internal::evaluator::Alignment)>0) // FIXME Alignment)>0 might not be enough - ) && (blockSize*sizeof(Scalar)*20) // if we cannot allocate on the stack, then let's not bother about this optimization + CanAlign = + ((int(VectorTypeCopyClean::Flags) & DirectAccessBit) || + (int(internal::evaluator::Alignment) > 0) // FIXME Alignment)>0 might not be enough + ) && + (blockSize * sizeof(Scalar) * 2 < EIGEN_STACK_ALLOCATION_LIMIT) && + (EIGEN_MAX_STATIC_ALIGN_BYTES > + 0) // if we cannot allocate on the stack, then let's not bother about this optimization }; - typedef typename internal::conditional, internal::evaluator::Alignment>, - typename VectorTypeCopyClean::ConstSegmentReturnType>::type SegmentWrapper; + typedef std::conditional_t< + CanAlign, + Ref, internal::evaluator::Alignment>, + typename VectorTypeCopyClean::ConstSegmentReturnType> + SegmentWrapper; Index n = vec.size(); - + Index bi = internal::first_default_aligned(copy); - if (bi>0) - internal::stable_norm_kernel(copy.head(bi), ssq, scale, invScale); - for (; bi 0) internal::stable_norm_kernel(copy.head(bi), ssq, scale, invScale); + for (; bi < n; bi += blockSize) + internal::stable_norm_kernel(SegmentWrapper(copy.segment(bi, numext::mini(blockSize, n - bi))), ssq, scale, + invScale); } -template -typename VectorType::RealScalar -stable_norm_impl(const VectorType &vec, typename enable_if::type* = 0 ) -{ - using std::sqrt; +template +typename VectorType::RealScalar stable_norm_impl(const VectorType& vec, + std::enable_if_t* = 0) { using std::abs; + using std::sqrt; Index n = vec.size(); - if(n==1) - return abs(vec.coeff(0)); + if (n == 1) return abs(vec.coeff(0)); typedef typename VectorType::RealScalar RealScalar; RealScalar scale(0); RealScalar invScale(1); - RealScalar ssq(0); // sum of squares + RealScalar ssq(0); // sum of squares stable_norm_impl_inner_step(vec, ssq, scale, invScale); - + return scale * sqrt(ssq); } -template -typename MatrixType::RealScalar -stable_norm_impl(const MatrixType &mat, typename enable_if::type* = 0 ) -{ +template +typename MatrixType::RealScalar stable_norm_impl(const MatrixType& mat, + std::enable_if_t* = 0) { using std::sqrt; typedef typename MatrixType::RealScalar RealScalar; RealScalar scale(0); RealScalar invScale(1); - RealScalar ssq(0); // sum of squares + RealScalar ssq(0); // sum of squares - for(Index j=0; j -inline typename NumTraits::Scalar>::Real -blueNorm_impl(const EigenBase& _vec) -{ - typedef typename Derived::RealScalar RealScalar; +template +inline typename NumTraits::Scalar>::Real blueNorm_impl(const EigenBase& _vec) { + typedef typename Derived::RealScalar RealScalar; + using std::abs; using std::pow; using std::sqrt; - using std::abs; // This program calculates the machine-dependent constants // bl, b2, slm, s2m, relerr overfl @@ -133,15 +128,19 @@ blueNorm_impl(const EigenBase& _vec) // are used. For any specific computer, each of the assignment // statements can be replaced static const int ibeta = std::numeric_limits::radix; // base for floating-point numbers - static const int it = NumTraits::digits(); // number of base-beta digits in mantissa - static const int iemin = NumTraits::min_exponent(); // minimum exponent - static const int iemax = NumTraits::max_exponent(); // maximum exponent - static const RealScalar rbig = NumTraits::highest(); // largest floating-point number - static const RealScalar b1 = RealScalar(pow(RealScalar(ibeta),RealScalar(-((1-iemin)/2)))); // lower boundary of midrange - static const RealScalar b2 = RealScalar(pow(RealScalar(ibeta),RealScalar((iemax + 1 - it)/2))); // upper boundary of midrange - static const RealScalar s1m = RealScalar(pow(RealScalar(ibeta),RealScalar((2-iemin)/2))); // scaling factor for lower range - static const RealScalar s2m = RealScalar(pow(RealScalar(ibeta),RealScalar(- ((iemax+it)/2)))); // scaling factor for upper range - static const RealScalar eps = RealScalar(pow(double(ibeta), 1-it)); + static const int it = NumTraits::digits(); // number of base-beta digits in mantissa + static const int iemin = NumTraits::min_exponent(); // minimum exponent + static const int iemax = NumTraits::max_exponent(); // maximum exponent + static const RealScalar rbig = NumTraits::highest(); // largest floating-point number + static const RealScalar b1 = + RealScalar(pow(RealScalar(ibeta), RealScalar(-((1 - iemin) / 2)))); // lower boundary of midrange + static const RealScalar b2 = + RealScalar(pow(RealScalar(ibeta), RealScalar((iemax + 1 - it) / 2))); // upper boundary of midrange + static const RealScalar s1m = + RealScalar(pow(RealScalar(ibeta), RealScalar((2 - iemin) / 2))); // scaling factor for lower range + static const RealScalar s2m = + RealScalar(pow(RealScalar(ibeta), RealScalar(-((iemax + it) / 2)))); // scaling factor for upper range + static const RealScalar eps = RealScalar(pow(double(ibeta), 1 - it)); static const RealScalar relerr = sqrt(eps); // tolerance for neglecting asml const Derived& vec(_vec.derived()); @@ -151,101 +150,87 @@ blueNorm_impl(const EigenBase& _vec) RealScalar amed = RealScalar(0); RealScalar abig = RealScalar(0); - for(Index j=0; j ab2) abig += numext::abs2(ax*s2m); - else if(ax < b1) asml += numext::abs2(ax*s1m); - else amed += numext::abs2(ax); + if (ax > ab2) + abig += numext::abs2(ax * s2m); + else if (ax < b1) + asml += numext::abs2(ax * s1m); + else + amed += numext::abs2(ax); } } - if(amed!=amed) - return amed; // we got a NaN - if(abig > RealScalar(0)) - { + if (amed != amed) return amed; // we got a NaN + if (abig > RealScalar(0)) { abig = sqrt(abig); - if(abig > rbig) // overflow, or *this contains INF values - return abig; // return INF - if(amed > RealScalar(0)) - { - abig = abig/s2m; + if (abig > rbig) // overflow, or *this contains INF values + return abig; // return INF + if (amed > RealScalar(0)) { + abig = abig / s2m; amed = sqrt(amed); - } - else - return abig/s2m; - } - else if(asml > RealScalar(0)) - { - if (amed > RealScalar(0)) - { + } else + return abig / s2m; + } else if (asml > RealScalar(0)) { + if (amed > RealScalar(0)) { abig = sqrt(amed); amed = sqrt(asml) / s1m; - } - else - return sqrt(asml)/s1m; - } - else + } else + return sqrt(asml) / s1m; + } else return sqrt(amed); asml = numext::mini(abig, amed); abig = numext::maxi(abig, amed); - if(asml <= abig*relerr) + if (asml <= abig * relerr) return abig; else - return abig * sqrt(RealScalar(1) + numext::abs2(asml/abig)); + return abig * sqrt(RealScalar(1) + numext::abs2(asml / abig)); } -} // end namespace internal +} // end namespace internal /** \returns the \em l2 norm of \c *this avoiding underflow and overflow. - * This version use a blockwise two passes algorithm: - * 1 - find the absolute largest coefficient \c s - * 2 - compute \f$ s \Vert \frac{*this}{s} \Vert \f$ in a standard way - * - * For architecture/scalar types supporting vectorization, this version - * is faster than blueNorm(). Otherwise the blueNorm() is much faster. - * - * \sa norm(), blueNorm(), hypotNorm() - */ -template -inline typename NumTraits::Scalar>::Real -MatrixBase::stableNorm() const -{ + * This version use a blockwise two passes algorithm: + * 1 - find the absolute largest coefficient \c s + * 2 - compute \f$ s \Vert \frac{*this}{s} \Vert \f$ in a standard way + * + * For architecture/scalar types supporting vectorization, this version + * is faster than blueNorm(). Otherwise the blueNorm() is much faster. + * + * \sa norm(), blueNorm(), hypotNorm() + */ +template +inline typename NumTraits::Scalar>::Real MatrixBase::stableNorm() const { return internal::stable_norm_impl(derived()); } /** \returns the \em l2 norm of \c *this using the Blue's algorithm. - * A Portable Fortran Program to Find the Euclidean Norm of a Vector, - * ACM TOMS, Vol 4, Issue 1, 1978. - * - * For architecture/scalar types without vectorization, this version - * is much faster than stableNorm(). Otherwise the stableNorm() is faster. - * - * \sa norm(), stableNorm(), hypotNorm() - */ -template -inline typename NumTraits::Scalar>::Real -MatrixBase::blueNorm() const -{ + * A Portable Fortran Program to Find the Euclidean Norm of a Vector, + * ACM TOMS, Vol 4, Issue 1, 1978. + * + * For architecture/scalar types without vectorization, this version + * is much faster than stableNorm(). Otherwise the stableNorm() is faster. + * + * \sa norm(), stableNorm(), hypotNorm() + */ +template +inline typename NumTraits::Scalar>::Real MatrixBase::blueNorm() const { return internal::blueNorm_impl(*this); } /** \returns the \em l2 norm of \c *this avoiding undeflow and overflow. - * This version use a concatenation of hypot() calls, and it is very slow. - * - * \sa norm(), stableNorm() - */ -template -inline typename NumTraits::Scalar>::Real -MatrixBase::hypotNorm() const -{ - if(size()==1) - return numext::abs(coeff(0,0)); + * This version use a concatenation of hypot() calls, and it is very slow. + * + * \sa norm(), stableNorm() + */ +template +inline typename NumTraits::Scalar>::Real MatrixBase::hypotNorm() const { + if (size() == 1) + return numext::abs(coeff(0, 0)); else return this->cwiseAbs().redux(internal::scalar_hypot_op()); } -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_STABLENORM_H +#endif // EIGEN_STABLENORM_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/StlIterators.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/StlIterators.h index 09041db1d55..3ab7d210123 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/StlIterators.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/StlIterators.h @@ -10,105 +10,175 @@ #ifndef EIGEN_STLITERATORS_H #define EIGEN_STLITERATORS_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template +template struct indexed_based_stl_iterator_traits; -template -class indexed_based_stl_iterator_base -{ -protected: +template +class indexed_based_stl_iterator_base { + protected: typedef indexed_based_stl_iterator_traits traits; typedef typename traits::XprType XprType; typedef indexed_based_stl_iterator_base non_const_iterator; typedef indexed_based_stl_iterator_base const_iterator; - typedef typename internal::conditional::value,non_const_iterator,const_iterator>::type other_iterator; + typedef std::conditional_t::value, non_const_iterator, const_iterator> other_iterator; // NOTE: in C++03 we cannot declare friend classes through typedefs because we need to write friend class: friend class indexed_based_stl_iterator_base; friend class indexed_based_stl_iterator_base; -public: + + public: typedef Index difference_type; typedef std::random_access_iterator_tag iterator_category; indexed_based_stl_iterator_base() EIGEN_NO_THROW : mp_xpr(0), m_index(0) {} indexed_based_stl_iterator_base(XprType& xpr, Index index) EIGEN_NO_THROW : mp_xpr(&xpr), m_index(index) {} - indexed_based_stl_iterator_base(const non_const_iterator& other) EIGEN_NO_THROW - : mp_xpr(other.mp_xpr), m_index(other.m_index) - {} + indexed_based_stl_iterator_base(const non_const_iterator& other) EIGEN_NO_THROW : mp_xpr(other.mp_xpr), + m_index(other.m_index) {} - indexed_based_stl_iterator_base& operator=(const non_const_iterator& other) - { + indexed_based_stl_iterator_base& operator=(const non_const_iterator& other) { mp_xpr = other.mp_xpr; m_index = other.m_index; return *this; } - Derived& operator++() { ++m_index; return derived(); } - Derived& operator--() { --m_index; return derived(); } + Derived& operator++() { + ++m_index; + return derived(); + } + Derived& operator--() { + --m_index; + return derived(); + } + + Derived operator++(int) { + Derived prev(derived()); + operator++(); + return prev; + } + Derived operator--(int) { + Derived prev(derived()); + operator--(); + return prev; + } - Derived operator++(int) { Derived prev(derived()); operator++(); return prev;} - Derived operator--(int) { Derived prev(derived()); operator--(); return prev;} + friend Derived operator+(const indexed_based_stl_iterator_base& a, Index b) { + Derived ret(a.derived()); + ret += b; + return ret; + } + friend Derived operator-(const indexed_based_stl_iterator_base& a, Index b) { + Derived ret(a.derived()); + ret -= b; + return ret; + } + friend Derived operator+(Index a, const indexed_based_stl_iterator_base& b) { + Derived ret(b.derived()); + ret += a; + return ret; + } + friend Derived operator-(Index a, const indexed_based_stl_iterator_base& b) { + Derived ret(b.derived()); + ret -= a; + return ret; + } - friend Derived operator+(const indexed_based_stl_iterator_base& a, Index b) { Derived ret(a.derived()); ret += b; return ret; } - friend Derived operator-(const indexed_based_stl_iterator_base& a, Index b) { Derived ret(a.derived()); ret -= b; return ret; } - friend Derived operator+(Index a, const indexed_based_stl_iterator_base& b) { Derived ret(b.derived()); ret += a; return ret; } - friend Derived operator-(Index a, const indexed_based_stl_iterator_base& b) { Derived ret(b.derived()); ret -= a; return ret; } - - Derived& operator+=(Index b) { m_index += b; return derived(); } - Derived& operator-=(Index b) { m_index -= b; return derived(); } + Derived& operator+=(Index b) { + m_index += b; + return derived(); + } + Derived& operator-=(Index b) { + m_index -= b; + return derived(); + } - difference_type operator-(const indexed_based_stl_iterator_base& other) const - { + difference_type operator-(const indexed_based_stl_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index - other.m_index; } - difference_type operator-(const other_iterator& other) const - { + difference_type operator-(const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index - other.m_index; } - bool operator==(const indexed_based_stl_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index == other.m_index; } - bool operator!=(const indexed_based_stl_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index != other.m_index; } - bool operator< (const indexed_based_stl_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index < other.m_index; } - bool operator<=(const indexed_based_stl_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index <= other.m_index; } - bool operator> (const indexed_based_stl_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index > other.m_index; } - bool operator>=(const indexed_based_stl_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index >= other.m_index; } - - bool operator==(const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index == other.m_index; } - bool operator!=(const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index != other.m_index; } - bool operator< (const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index < other.m_index; } - bool operator<=(const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index <= other.m_index; } - bool operator> (const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index > other.m_index; } - bool operator>=(const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index >= other.m_index; } + bool operator==(const indexed_based_stl_iterator_base& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index == other.m_index; + } + bool operator!=(const indexed_based_stl_iterator_base& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index != other.m_index; + } + bool operator<(const indexed_based_stl_iterator_base& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index < other.m_index; + } + bool operator<=(const indexed_based_stl_iterator_base& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index <= other.m_index; + } + bool operator>(const indexed_based_stl_iterator_base& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index > other.m_index; + } + bool operator>=(const indexed_based_stl_iterator_base& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index >= other.m_index; + } -protected: + bool operator==(const other_iterator& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index == other.m_index; + } + bool operator!=(const other_iterator& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index != other.m_index; + } + bool operator<(const other_iterator& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index < other.m_index; + } + bool operator<=(const other_iterator& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index <= other.m_index; + } + bool operator>(const other_iterator& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index > other.m_index; + } + bool operator>=(const other_iterator& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index >= other.m_index; + } + protected: Derived& derived() { return static_cast(*this); } const Derived& derived() const { return static_cast(*this); } - XprType *mp_xpr; + XprType* mp_xpr; Index m_index; }; -template -class indexed_based_stl_reverse_iterator_base -{ -protected: +template +class indexed_based_stl_reverse_iterator_base { + protected: typedef indexed_based_stl_iterator_traits traits; typedef typename traits::XprType XprType; typedef indexed_based_stl_reverse_iterator_base non_const_iterator; typedef indexed_based_stl_reverse_iterator_base const_iterator; - typedef typename internal::conditional::value,non_const_iterator,const_iterator>::type other_iterator; + typedef std::conditional_t::value, non_const_iterator, const_iterator> other_iterator; // NOTE: in C++03 we cannot declare friend classes through typedefs because we need to write friend class: friend class indexed_based_stl_reverse_iterator_base; friend class indexed_based_stl_reverse_iterator_base; -public: + + public: typedef Index difference_type; typedef std::random_access_iterator_tag iterator_category; @@ -116,165 +186,259 @@ class indexed_based_stl_reverse_iterator_base indexed_based_stl_reverse_iterator_base(XprType& xpr, Index index) : mp_xpr(&xpr), m_index(index) {} indexed_based_stl_reverse_iterator_base(const non_const_iterator& other) - : mp_xpr(other.mp_xpr), m_index(other.m_index) - {} + : mp_xpr(other.mp_xpr), m_index(other.m_index) {} - indexed_based_stl_reverse_iterator_base& operator=(const non_const_iterator& other) - { + indexed_based_stl_reverse_iterator_base& operator=(const non_const_iterator& other) { mp_xpr = other.mp_xpr; m_index = other.m_index; return *this; } - Derived& operator++() { --m_index; return derived(); } - Derived& operator--() { ++m_index; return derived(); } + Derived& operator++() { + --m_index; + return derived(); + } + Derived& operator--() { + ++m_index; + return derived(); + } - Derived operator++(int) { Derived prev(derived()); operator++(); return prev;} - Derived operator--(int) { Derived prev(derived()); operator--(); return prev;} + Derived operator++(int) { + Derived prev(derived()); + operator++(); + return prev; + } + Derived operator--(int) { + Derived prev(derived()); + operator--(); + return prev; + } - friend Derived operator+(const indexed_based_stl_reverse_iterator_base& a, Index b) { Derived ret(a.derived()); ret += b; return ret; } - friend Derived operator-(const indexed_based_stl_reverse_iterator_base& a, Index b) { Derived ret(a.derived()); ret -= b; return ret; } - friend Derived operator+(Index a, const indexed_based_stl_reverse_iterator_base& b) { Derived ret(b.derived()); ret += a; return ret; } - friend Derived operator-(Index a, const indexed_based_stl_reverse_iterator_base& b) { Derived ret(b.derived()); ret -= a; return ret; } - - Derived& operator+=(Index b) { m_index -= b; return derived(); } - Derived& operator-=(Index b) { m_index += b; return derived(); } + friend Derived operator+(const indexed_based_stl_reverse_iterator_base& a, Index b) { + Derived ret(a.derived()); + ret += b; + return ret; + } + friend Derived operator-(const indexed_based_stl_reverse_iterator_base& a, Index b) { + Derived ret(a.derived()); + ret -= b; + return ret; + } + friend Derived operator+(Index a, const indexed_based_stl_reverse_iterator_base& b) { + Derived ret(b.derived()); + ret += a; + return ret; + } + friend Derived operator-(Index a, const indexed_based_stl_reverse_iterator_base& b) { + Derived ret(b.derived()); + ret -= a; + return ret; + } - difference_type operator-(const indexed_based_stl_reverse_iterator_base& other) const - { + Derived& operator+=(Index b) { + m_index -= b; + return derived(); + } + Derived& operator-=(Index b) { + m_index += b; + return derived(); + } + + difference_type operator-(const indexed_based_stl_reverse_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return other.m_index - m_index; } - difference_type operator-(const other_iterator& other) const - { + difference_type operator-(const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return other.m_index - m_index; } - bool operator==(const indexed_based_stl_reverse_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index == other.m_index; } - bool operator!=(const indexed_based_stl_reverse_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index != other.m_index; } - bool operator< (const indexed_based_stl_reverse_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index > other.m_index; } - bool operator<=(const indexed_based_stl_reverse_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index >= other.m_index; } - bool operator> (const indexed_based_stl_reverse_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index < other.m_index; } - bool operator>=(const indexed_based_stl_reverse_iterator_base& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index <= other.m_index; } - - bool operator==(const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index == other.m_index; } - bool operator!=(const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index != other.m_index; } - bool operator< (const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index > other.m_index; } - bool operator<=(const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index >= other.m_index; } - bool operator> (const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index < other.m_index; } - bool operator>=(const other_iterator& other) const { eigen_assert(mp_xpr == other.mp_xpr); return m_index <= other.m_index; } + bool operator==(const indexed_based_stl_reverse_iterator_base& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index == other.m_index; + } + bool operator!=(const indexed_based_stl_reverse_iterator_base& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index != other.m_index; + } + bool operator<(const indexed_based_stl_reverse_iterator_base& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index > other.m_index; + } + bool operator<=(const indexed_based_stl_reverse_iterator_base& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index >= other.m_index; + } + bool operator>(const indexed_based_stl_reverse_iterator_base& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index < other.m_index; + } + bool operator>=(const indexed_based_stl_reverse_iterator_base& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index <= other.m_index; + } -protected: + bool operator==(const other_iterator& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index == other.m_index; + } + bool operator!=(const other_iterator& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index != other.m_index; + } + bool operator<(const other_iterator& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index > other.m_index; + } + bool operator<=(const other_iterator& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index >= other.m_index; + } + bool operator>(const other_iterator& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index < other.m_index; + } + bool operator>=(const other_iterator& other) const { + eigen_assert(mp_xpr == other.mp_xpr); + return m_index <= other.m_index; + } + protected: Derived& derived() { return static_cast(*this); } const Derived& derived() const { return static_cast(*this); } - XprType *mp_xpr; + XprType* mp_xpr; Index m_index; }; -template -class pointer_based_stl_iterator -{ - enum { is_lvalue = internal::is_lvalue::value }; - typedef pointer_based_stl_iterator::type> non_const_iterator; - typedef pointer_based_stl_iterator::type> const_iterator; - typedef typename internal::conditional::value,non_const_iterator,const_iterator>::type other_iterator; +template +class pointer_based_stl_iterator { + enum { is_lvalue = internal::is_lvalue::value }; + typedef pointer_based_stl_iterator> non_const_iterator; + typedef pointer_based_stl_iterator> const_iterator; + typedef std::conditional_t::value, non_const_iterator, const_iterator> other_iterator; // NOTE: in C++03 we cannot declare friend classes through typedefs because we need to write friend class: - friend class pointer_based_stl_iterator::type>; - friend class pointer_based_stl_iterator::type>; -public: + friend class pointer_based_stl_iterator>; + friend class pointer_based_stl_iterator>; + + public: typedef Index difference_type; typedef typename XprType::Scalar value_type; typedef std::random_access_iterator_tag iterator_category; - typedef typename internal::conditional::type pointer; - typedef typename internal::conditional::type reference; - + typedef std::conditional_t pointer; + typedef std::conditional_t reference; pointer_based_stl_iterator() EIGEN_NO_THROW : m_ptr(0) {} - pointer_based_stl_iterator(XprType& xpr, Index index) EIGEN_NO_THROW : m_incr(xpr.innerStride()) - { + pointer_based_stl_iterator(XprType& xpr, Index index) EIGEN_NO_THROW : m_incr(xpr.innerStride()) { m_ptr = xpr.data() + index * m_incr.value(); } - pointer_based_stl_iterator(const non_const_iterator& other) EIGEN_NO_THROW - : m_ptr(other.m_ptr), m_incr(other.m_incr) - {} + pointer_based_stl_iterator(const non_const_iterator& other) EIGEN_NO_THROW : m_ptr(other.m_ptr), + m_incr(other.m_incr) {} - pointer_based_stl_iterator& operator=(const non_const_iterator& other) EIGEN_NO_THROW - { + pointer_based_stl_iterator& operator=(const non_const_iterator& other) EIGEN_NO_THROW { m_ptr = other.m_ptr; m_incr.setValue(other.m_incr); return *this; } - reference operator*() const { return *m_ptr; } - reference operator[](Index i) const { return *(m_ptr+i*m_incr.value()); } - pointer operator->() const { return m_ptr; } + reference operator*() const { return *m_ptr; } + reference operator[](Index i) const { return *(m_ptr + i * m_incr.value()); } + pointer operator->() const { return m_ptr; } + + pointer_based_stl_iterator& operator++() { + m_ptr += m_incr.value(); + return *this; + } + pointer_based_stl_iterator& operator--() { + m_ptr -= m_incr.value(); + return *this; + } - pointer_based_stl_iterator& operator++() { m_ptr += m_incr.value(); return *this; } - pointer_based_stl_iterator& operator--() { m_ptr -= m_incr.value(); return *this; } + pointer_based_stl_iterator operator++(int) { + pointer_based_stl_iterator prev(*this); + operator++(); + return prev; + } + pointer_based_stl_iterator operator--(int) { + pointer_based_stl_iterator prev(*this); + operator--(); + return prev; + } - pointer_based_stl_iterator operator++(int) { pointer_based_stl_iterator prev(*this); operator++(); return prev;} - pointer_based_stl_iterator operator--(int) { pointer_based_stl_iterator prev(*this); operator--(); return prev;} + friend pointer_based_stl_iterator operator+(const pointer_based_stl_iterator& a, Index b) { + pointer_based_stl_iterator ret(a); + ret += b; + return ret; + } + friend pointer_based_stl_iterator operator-(const pointer_based_stl_iterator& a, Index b) { + pointer_based_stl_iterator ret(a); + ret -= b; + return ret; + } + friend pointer_based_stl_iterator operator+(Index a, const pointer_based_stl_iterator& b) { + pointer_based_stl_iterator ret(b); + ret += a; + return ret; + } + friend pointer_based_stl_iterator operator-(Index a, const pointer_based_stl_iterator& b) { + pointer_based_stl_iterator ret(b); + ret -= a; + return ret; + } - friend pointer_based_stl_iterator operator+(const pointer_based_stl_iterator& a, Index b) { pointer_based_stl_iterator ret(a); ret += b; return ret; } - friend pointer_based_stl_iterator operator-(const pointer_based_stl_iterator& a, Index b) { pointer_based_stl_iterator ret(a); ret -= b; return ret; } - friend pointer_based_stl_iterator operator+(Index a, const pointer_based_stl_iterator& b) { pointer_based_stl_iterator ret(b); ret += a; return ret; } - friend pointer_based_stl_iterator operator-(Index a, const pointer_based_stl_iterator& b) { pointer_based_stl_iterator ret(b); ret -= a; return ret; } - - pointer_based_stl_iterator& operator+=(Index b) { m_ptr += b*m_incr.value(); return *this; } - pointer_based_stl_iterator& operator-=(Index b) { m_ptr -= b*m_incr.value(); return *this; } + pointer_based_stl_iterator& operator+=(Index b) { + m_ptr += b * m_incr.value(); + return *this; + } + pointer_based_stl_iterator& operator-=(Index b) { + m_ptr -= b * m_incr.value(); + return *this; + } difference_type operator-(const pointer_based_stl_iterator& other) const { - return (m_ptr - other.m_ptr)/m_incr.value(); + return (m_ptr - other.m_ptr) / m_incr.value(); } - difference_type operator-(const other_iterator& other) const { - return (m_ptr - other.m_ptr)/m_incr.value(); - } + difference_type operator-(const other_iterator& other) const { return (m_ptr - other.m_ptr) / m_incr.value(); } bool operator==(const pointer_based_stl_iterator& other) const { return m_ptr == other.m_ptr; } bool operator!=(const pointer_based_stl_iterator& other) const { return m_ptr != other.m_ptr; } - bool operator< (const pointer_based_stl_iterator& other) const { return m_ptr < other.m_ptr; } + bool operator<(const pointer_based_stl_iterator& other) const { return m_ptr < other.m_ptr; } bool operator<=(const pointer_based_stl_iterator& other) const { return m_ptr <= other.m_ptr; } - bool operator> (const pointer_based_stl_iterator& other) const { return m_ptr > other.m_ptr; } + bool operator>(const pointer_based_stl_iterator& other) const { return m_ptr > other.m_ptr; } bool operator>=(const pointer_based_stl_iterator& other) const { return m_ptr >= other.m_ptr; } bool operator==(const other_iterator& other) const { return m_ptr == other.m_ptr; } bool operator!=(const other_iterator& other) const { return m_ptr != other.m_ptr; } - bool operator< (const other_iterator& other) const { return m_ptr < other.m_ptr; } + bool operator<(const other_iterator& other) const { return m_ptr < other.m_ptr; } bool operator<=(const other_iterator& other) const { return m_ptr <= other.m_ptr; } - bool operator> (const other_iterator& other) const { return m_ptr > other.m_ptr; } + bool operator>(const other_iterator& other) const { return m_ptr > other.m_ptr; } bool operator>=(const other_iterator& other) const { return m_ptr >= other.m_ptr; } -protected: - + protected: pointer m_ptr; internal::variable_if_dynamic m_incr; }; -template -struct indexed_based_stl_iterator_traits > -{ - typedef _XprType XprType; - typedef generic_randaccess_stl_iterator::type> non_const_iterator; - typedef generic_randaccess_stl_iterator::type> const_iterator; +template +struct indexed_based_stl_iterator_traits> { + typedef XprType_ XprType; + typedef generic_randaccess_stl_iterator> non_const_iterator; + typedef generic_randaccess_stl_iterator> const_iterator; }; -template -class generic_randaccess_stl_iterator : public indexed_based_stl_iterator_base > -{ -public: +template +class generic_randaccess_stl_iterator + : public indexed_based_stl_iterator_base> { + public: typedef typename XprType::Scalar value_type; -protected: - + protected: enum { has_direct_access = (internal::traits::Flags & DirectAccessBit) ? 1 : 0, - is_lvalue = internal::is_lvalue::value + is_lvalue = internal::is_lvalue::value }; typedef indexed_based_stl_iterator_base Base; @@ -283,181 +447,168 @@ class generic_randaccess_stl_iterator : public indexed_based_stl_iterator_base::type read_only_ref_t; + // typedef std::conditional_t read_only_ref_t; typedef const value_type read_only_ref_t; -public: - - typedef typename internal::conditional::type pointer; - typedef typename internal::conditional::type reference; - + public: + typedef std::conditional_t pointer; + typedef std::conditional_t reference; + generic_randaccess_stl_iterator() : Base() {} - generic_randaccess_stl_iterator(XprType& xpr, Index index) : Base(xpr,index) {} + generic_randaccess_stl_iterator(XprType& xpr, Index index) : Base(xpr, index) {} generic_randaccess_stl_iterator(const typename Base::non_const_iterator& other) : Base(other) {} using Base::operator=; - reference operator*() const { return (*mp_xpr)(m_index); } - reference operator[](Index i) const { return (*mp_xpr)(m_index+i); } - pointer operator->() const { return &((*mp_xpr)(m_index)); } + reference operator*() const { return (*mp_xpr)(m_index); } + reference operator[](Index i) const { return (*mp_xpr)(m_index + i); } + pointer operator->() const { return &((*mp_xpr)(m_index)); } }; -template -struct indexed_based_stl_iterator_traits > -{ - typedef _XprType XprType; - typedef subvector_stl_iterator::type, Direction> non_const_iterator; - typedef subvector_stl_iterator::type, Direction> const_iterator; +template +struct indexed_based_stl_iterator_traits> { + typedef XprType_ XprType; + typedef subvector_stl_iterator, Direction> non_const_iterator; + typedef subvector_stl_iterator, Direction> const_iterator; }; -template -class subvector_stl_iterator : public indexed_based_stl_iterator_base > -{ -protected: - - enum { is_lvalue = internal::is_lvalue::value }; +template +class subvector_stl_iterator : public indexed_based_stl_iterator_base> { + protected: + enum { is_lvalue = internal::is_lvalue::value }; typedef indexed_based_stl_iterator_base Base; using Base::m_index; using Base::mp_xpr; - typedef typename internal::conditional::type SubVectorType; - typedef typename internal::conditional::type ConstSubVectorType; - + typedef std::conditional_t SubVectorType; + typedef std::conditional_t + ConstSubVectorType; -public: - typedef typename internal::conditional::type reference; + public: + typedef std::conditional_t reference; typedef typename reference::PlainObject value_type; -private: - class subvector_stl_iterator_ptr - { - public: - subvector_stl_iterator_ptr(const reference &subvector) : m_subvector(subvector) {} - reference* operator->() { return &m_subvector; } - private: - reference m_subvector; + private: + class subvector_stl_iterator_ptr { + public: + subvector_stl_iterator_ptr(const reference& subvector) : m_subvector(subvector) {} + reference* operator->() { return &m_subvector; } + + private: + reference m_subvector; }; -public: + public: typedef subvector_stl_iterator_ptr pointer; - + subvector_stl_iterator() : Base() {} - subvector_stl_iterator(XprType& xpr, Index index) : Base(xpr,index) {} + subvector_stl_iterator(XprType& xpr, Index index) : Base(xpr, index) {} - reference operator*() const { return (*mp_xpr).template subVector(m_index); } - reference operator[](Index i) const { return (*mp_xpr).template subVector(m_index+i); } - pointer operator->() const { return (*mp_xpr).template subVector(m_index); } + reference operator*() const { return (*mp_xpr).template subVector(m_index); } + reference operator[](Index i) const { return (*mp_xpr).template subVector(m_index + i); } + pointer operator->() const { return (*mp_xpr).template subVector(m_index); } }; -template -struct indexed_based_stl_iterator_traits > -{ - typedef _XprType XprType; - typedef subvector_stl_reverse_iterator::type, Direction> non_const_iterator; - typedef subvector_stl_reverse_iterator::type, Direction> const_iterator; +template +struct indexed_based_stl_iterator_traits> { + typedef XprType_ XprType; + typedef subvector_stl_reverse_iterator, Direction> non_const_iterator; + typedef subvector_stl_reverse_iterator, Direction> const_iterator; }; -template -class subvector_stl_reverse_iterator : public indexed_based_stl_reverse_iterator_base > -{ -protected: - - enum { is_lvalue = internal::is_lvalue::value }; +template +class subvector_stl_reverse_iterator + : public indexed_based_stl_reverse_iterator_base> { + protected: + enum { is_lvalue = internal::is_lvalue::value }; typedef indexed_based_stl_reverse_iterator_base Base; using Base::m_index; using Base::mp_xpr; - typedef typename internal::conditional::type SubVectorType; - typedef typename internal::conditional::type ConstSubVectorType; - + typedef std::conditional_t SubVectorType; + typedef std::conditional_t + ConstSubVectorType; -public: - typedef typename internal::conditional::type reference; + public: + typedef std::conditional_t reference; typedef typename reference::PlainObject value_type; -private: - class subvector_stl_reverse_iterator_ptr - { - public: - subvector_stl_reverse_iterator_ptr(const reference &subvector) : m_subvector(subvector) {} - reference* operator->() { return &m_subvector; } - private: - reference m_subvector; + private: + class subvector_stl_reverse_iterator_ptr { + public: + subvector_stl_reverse_iterator_ptr(const reference& subvector) : m_subvector(subvector) {} + reference* operator->() { return &m_subvector; } + + private: + reference m_subvector; }; -public: + public: typedef subvector_stl_reverse_iterator_ptr pointer; - + subvector_stl_reverse_iterator() : Base() {} - subvector_stl_reverse_iterator(XprType& xpr, Index index) : Base(xpr,index) {} + subvector_stl_reverse_iterator(XprType& xpr, Index index) : Base(xpr, index) {} - reference operator*() const { return (*mp_xpr).template subVector(m_index); } - reference operator[](Index i) const { return (*mp_xpr).template subVector(m_index+i); } - pointer operator->() const { return (*mp_xpr).template subVector(m_index); } + reference operator*() const { return (*mp_xpr).template subVector(m_index); } + reference operator[](Index i) const { return (*mp_xpr).template subVector(m_index + i); } + pointer operator->() const { return (*mp_xpr).template subVector(m_index); } }; -} // namespace internal - +} // namespace internal /** returns an iterator to the first element of the 1D vector or array - * \only_for_vectors - * \sa end(), cbegin() - */ -template -inline typename DenseBase::iterator DenseBase::begin() -{ + * \only_for_vectors + * \sa end(), cbegin() + */ +template +inline typename DenseBase::iterator DenseBase::begin() { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived); return iterator(derived(), 0); } /** const version of begin() */ -template -inline typename DenseBase::const_iterator DenseBase::begin() const -{ +template +inline typename DenseBase::const_iterator DenseBase::begin() const { return cbegin(); } /** returns a read-only const_iterator to the first element of the 1D vector or array - * \only_for_vectors - * \sa cend(), begin() - */ -template -inline typename DenseBase::const_iterator DenseBase::cbegin() const -{ + * \only_for_vectors + * \sa cend(), begin() + */ +template +inline typename DenseBase::const_iterator DenseBase::cbegin() const { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived); return const_iterator(derived(), 0); } /** returns an iterator to the element following the last element of the 1D vector or array - * \only_for_vectors - * \sa begin(), cend() - */ -template -inline typename DenseBase::iterator DenseBase::end() -{ + * \only_for_vectors + * \sa begin(), cend() + */ +template +inline typename DenseBase::iterator DenseBase::end() { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived); return iterator(derived(), size()); } /** const version of end() */ -template -inline typename DenseBase::const_iterator DenseBase::end() const -{ +template +inline typename DenseBase::const_iterator DenseBase::end() const { return cend(); } /** returns a read-only const_iterator to the element following the last element of the 1D vector or array - * \only_for_vectors - * \sa begin(), cend() - */ -template -inline typename DenseBase::const_iterator DenseBase::cend() const -{ + * \only_for_vectors + * \sa begin(), cend() + */ +template +inline typename DenseBase::const_iterator DenseBase::cend() const { EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived); return const_iterator(derived(), size()); } -} // namespace Eigen +} // namespace Eigen -#endif // EIGEN_STLITERATORS_H +#endif // EIGEN_STLITERATORS_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Stride.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Stride.h index 6494d51420a..a8fdeaf3753 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Stride.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Stride.h @@ -10,107 +10,98 @@ #ifndef EIGEN_STRIDE_H #define EIGEN_STRIDE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { /** \class Stride - * \ingroup Core_Module - * - * \brief Holds strides information for Map - * - * This class holds the strides information for mapping arrays with strides with class Map. - * - * It holds two values: the inner stride and the outer stride. - * - * The inner stride is the pointer increment between two consecutive entries within a given row of a - * row-major matrix or within a given column of a column-major matrix. - * - * The outer stride is the pointer increment between two consecutive rows of a row-major matrix or - * between two consecutive columns of a column-major matrix. - * - * These two values can be passed either at compile-time as template parameters, or at runtime as - * arguments to the constructor. - * - * Indeed, this class takes two template parameters: - * \tparam _OuterStrideAtCompileTime the outer stride, or Dynamic if you want to specify it at runtime. - * \tparam _InnerStrideAtCompileTime the inner stride, or Dynamic if you want to specify it at runtime. - * - * Here is an example: - * \include Map_general_stride.cpp - * Output: \verbinclude Map_general_stride.out - * - * Both strides can be negative, however, a negative stride of -1 cannot be specified at compiletime - * because of the ambiguity with Dynamic which is defined to -1 (historically, negative strides were - * not allowed). - * - * \sa class InnerStride, class OuterStride, \ref TopicStorageOrders - */ -template -class Stride -{ - public: - typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3 - enum { - InnerStrideAtCompileTime = _InnerStrideAtCompileTime, - OuterStrideAtCompileTime = _OuterStrideAtCompileTime - }; + * \ingroup Core_Module + * + * \brief Holds strides information for Map + * + * This class holds the strides information for mapping arrays with strides with class Map. + * + * It holds two values: the inner stride and the outer stride. + * + * The inner stride is the pointer increment between two consecutive entries within a given row of a + * row-major matrix or within a given column of a column-major matrix. + * + * The outer stride is the pointer increment between two consecutive rows of a row-major matrix or + * between two consecutive columns of a column-major matrix. + * + * These two values can be passed either at compile-time as template parameters, or at runtime as + * arguments to the constructor. + * + * Indeed, this class takes two template parameters: + * \tparam OuterStrideAtCompileTime_ the outer stride, or Dynamic if you want to specify it at runtime. + * \tparam InnerStrideAtCompileTime_ the inner stride, or Dynamic if you want to specify it at runtime. + * + * Here is an example: + * \include Map_general_stride.cpp + * Output: \verbinclude Map_general_stride.out + * + * Both strides can be negative. However, a negative stride of -1 cannot be specified at compile time + * because of the ambiguity with Dynamic which is defined to -1 (historically, negative strides were + * not allowed). + * + * Note that for compile-time vectors (ColsAtCompileTime==1 or RowsAtCompile==1), + * the inner stride is the pointer increment between two consecutive elements, + * regardless of storage layout. + * + * \sa class InnerStride, class OuterStride, \ref TopicStorageOrders + */ +template +class Stride { + public: + typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3 + enum { InnerStrideAtCompileTime = InnerStrideAtCompileTime_, OuterStrideAtCompileTime = OuterStrideAtCompileTime_ }; - /** Default constructor, for use when strides are fixed at compile time */ - EIGEN_DEVICE_FUNC - Stride() - : m_outer(OuterStrideAtCompileTime), m_inner(InnerStrideAtCompileTime) - { - // FIXME: for Eigen 4 we should use DynamicIndex instead of Dynamic. - // FIXME: for Eigen 4 we should also unify this API with fix<> - eigen_assert(InnerStrideAtCompileTime != Dynamic && OuterStrideAtCompileTime != Dynamic); - } + /** Default constructor, for use when strides are fixed at compile time */ + EIGEN_DEVICE_FUNC Stride() : m_outer(OuterStrideAtCompileTime), m_inner(InnerStrideAtCompileTime) { + // FIXME: for Eigen 4 we should use DynamicIndex instead of Dynamic. + // FIXME: for Eigen 4 we should also unify this API with fix<> + eigen_assert(InnerStrideAtCompileTime != Dynamic && OuterStrideAtCompileTime != Dynamic); + } - /** Constructor allowing to pass the strides at runtime */ - EIGEN_DEVICE_FUNC - Stride(Index outerStride, Index innerStride) - : m_outer(outerStride), m_inner(innerStride) - { - } + /** Constructor allowing to pass the strides at runtime */ + EIGEN_DEVICE_FUNC Stride(Index outerStride, Index innerStride) : m_outer(outerStride), m_inner(innerStride) {} - /** Copy constructor */ - EIGEN_DEVICE_FUNC - Stride(const Stride& other) - : m_outer(other.outer()), m_inner(other.inner()) - {} + /** Copy constructor */ + EIGEN_DEVICE_FUNC Stride(const Stride& other) : m_outer(other.outer()), m_inner(other.inner()) {} - /** \returns the outer stride */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outer() const { return m_outer.value(); } - /** \returns the inner stride */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index inner() const { return m_inner.value(); } + /** \returns the outer stride */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index outer() const { return m_outer.value(); } + /** \returns the inner stride */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index inner() const { return m_inner.value(); } - protected: - internal::variable_if_dynamic m_outer; - internal::variable_if_dynamic m_inner; + protected: + internal::variable_if_dynamic m_outer; + internal::variable_if_dynamic m_inner; }; /** \brief Convenience specialization of Stride to specify only an inner stride - * See class Map for some examples */ -template -class InnerStride : public Stride<0, Value> -{ - typedef Stride<0, Value> Base; - public: - EIGEN_DEVICE_FUNC InnerStride() : Base() {} - EIGEN_DEVICE_FUNC InnerStride(Index v) : Base(0, v) {} // FIXME making this explicit could break valid code + * See class Map for some examples */ +template +class InnerStride : public Stride<0, Value> { + typedef Stride<0, Value> Base; + + public: + EIGEN_DEVICE_FUNC InnerStride() : Base() {} + EIGEN_DEVICE_FUNC InnerStride(Index v) : Base(0, v) {} // FIXME making this explicit could break valid code }; /** \brief Convenience specialization of Stride to specify only an outer stride - * See class Map for some examples */ -template -class OuterStride : public Stride -{ - typedef Stride Base; - public: - EIGEN_DEVICE_FUNC OuterStride() : Base() {} - EIGEN_DEVICE_FUNC OuterStride(Index v) : Base(v,0) {} // FIXME making this explicit could break valid code + * See class Map for some examples */ +template +class OuterStride : public Stride { + typedef Stride Base; + + public: + EIGEN_DEVICE_FUNC OuterStride() : Base() {} + EIGEN_DEVICE_FUNC OuterStride(Index v) : Base(v, 0) {} // FIXME making this explicit could break valid code }; -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_STRIDE_H +#endif // EIGEN_STRIDE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Swap.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Swap.h index 180a4e5adff..d417c1ad1ee 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Swap.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Swap.h @@ -10,59 +10,65 @@ #ifndef EIGEN_SWAP_H #define EIGEN_SWAP_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { namespace internal { // Overload default assignPacket behavior for swapping them -template -class generic_dense_assignment_kernel, Specialized> - : public generic_dense_assignment_kernel, BuiltIn> -{ -protected: - typedef generic_dense_assignment_kernel, BuiltIn> Base; +template +class generic_dense_assignment_kernel, Specialized> + : public generic_dense_assignment_kernel, BuiltIn> { + protected: + typedef generic_dense_assignment_kernel, BuiltIn> + Base; using Base::m_dst; - using Base::m_src; using Base::m_functor; - -public: + using Base::m_src; + + public: typedef typename Base::Scalar Scalar; typedef typename Base::DstXprType DstXprType; typedef swap_assign_op Functor; - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - generic_dense_assignment_kernel(DstEvaluatorTypeT &dst, const SrcEvaluatorTypeT &src, const Functor &func, DstXprType& dstExpr) - : Base(dst, src, func, dstExpr) - {} - - template - EIGEN_STRONG_INLINE void assignPacket(Index row, Index col) - { - PacketType tmp = m_src.template packet(row,col); - const_cast(m_src).template writePacket(row,col, m_dst.template packet(row,col)); - m_dst.template writePacket(row,col,tmp); + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE generic_dense_assignment_kernel(DstEvaluatorTypeT &dst, + const SrcEvaluatorTypeT &src, + const Functor &func, DstXprType &dstExpr) + : Base(dst, src, func, dstExpr) {} + + template + EIGEN_STRONG_INLINE void assignPacket(Index row, Index col) { + PacketType tmp = m_src.template packet(row, col); + const_cast(m_src).template writePacket( + row, col, m_dst.template packet(row, col)); + m_dst.template writePacket(row, col, tmp); } - - template - EIGEN_STRONG_INLINE void assignPacket(Index index) - { - PacketType tmp = m_src.template packet(index); - const_cast(m_src).template writePacket(index, m_dst.template packet(index)); - m_dst.template writePacket(index,tmp); + + template + EIGEN_STRONG_INLINE void assignPacket(Index index) { + PacketType tmp = m_src.template packet(index); + const_cast(m_src).template writePacket( + index, m_dst.template packet(index)); + m_dst.template writePacket(index, tmp); } - - // TODO find a simple way not to have to copy/paste this function from generic_dense_assignment_kernel, by simple I mean no CRTP (Gael) - template - EIGEN_STRONG_INLINE void assignPacketByOuterInner(Index outer, Index inner) - { - Index row = Base::rowIndexByOuterInner(outer, inner); + + // TODO find a simple way not to have to copy/paste this function from generic_dense_assignment_kernel, by simple I + // mean no CRTP (Gael) + template + EIGEN_STRONG_INLINE void assignPacketByOuterInner(Index outer, Index inner) { + Index row = Base::rowIndexByOuterInner(outer, inner); Index col = Base::colIndexByOuterInner(outer, inner); - assignPacket(row, col); + assignPacket(row, col); } }; -} // namespace internal +} // namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_SWAP_H +#endif // EIGEN_SWAP_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Transpose.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Transpose.h index 2bc658f40b8..1cc7a286766 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Transpose.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Transpose.h @@ -11,14 +11,16 @@ #ifndef EIGEN_TRANSPOSE_H #define EIGEN_TRANSPOSE_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template -struct traits > : public traits -{ +template +struct traits > : public traits { typedef typename ref_selector::type MatrixTypeNested; - typedef typename remove_reference::type MatrixTypeNestedPlain; + typedef std::remove_reference_t MatrixTypeNestedPlain; enum { RowsAtCompileTime = MatrixType::ColsAtCompileTime, ColsAtCompileTime = MatrixType::RowsAtCompileTime, @@ -32,234 +34,205 @@ struct traits > : public traits OuterStrideAtCompileTime = outer_stride_at_compile_time::ret }; }; -} +} // namespace internal -template class TransposeImpl; +template +class TransposeImpl; /** \class Transpose - * \ingroup Core_Module - * - * \brief Expression of the transpose of a matrix - * - * \tparam MatrixType the type of the object of which we are taking the transpose - * - * This class represents an expression of the transpose of a matrix. - * It is the return type of MatrixBase::transpose() and MatrixBase::adjoint() - * and most of the time this is the only way it is used. - * - * \sa MatrixBase::transpose(), MatrixBase::adjoint() - */ -template class Transpose - : public TransposeImpl::StorageKind> -{ - public: - - typedef typename internal::ref_selector::non_const_type MatrixTypeNested; - - typedef typename TransposeImpl::StorageKind>::Base Base; - EIGEN_GENERIC_PUBLIC_INTERFACE(Transpose) - typedef typename internal::remove_all::type NestedExpression; - - EIGEN_DEVICE_FUNC - explicit EIGEN_STRONG_INLINE Transpose(MatrixType& matrix) : m_matrix(matrix) {} - - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Transpose) - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index rows() const EIGEN_NOEXCEPT { return m_matrix.cols(); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR - Index cols() const EIGEN_NOEXCEPT { return m_matrix.rows(); } - - /** \returns the nested expression */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const typename internal::remove_all::type& - nestedExpression() const { return m_matrix; } - - /** \returns the nested expression */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - typename internal::remove_reference::type& - nestedExpression() { return m_matrix; } - - /** \internal */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - void resize(Index nrows, Index ncols) { - m_matrix.resize(ncols,nrows); - } + * \ingroup Core_Module + * + * \brief Expression of the transpose of a matrix + * + * \tparam MatrixType the type of the object of which we are taking the transpose + * + * This class represents an expression of the transpose of a matrix. + * It is the return type of MatrixBase::transpose() and MatrixBase::adjoint() + * and most of the time this is the only way it is used. + * + * \sa MatrixBase::transpose(), MatrixBase::adjoint() + */ +template +class Transpose : public TransposeImpl::StorageKind> { + public: + typedef typename internal::ref_selector::non_const_type MatrixTypeNested; + + typedef typename TransposeImpl::StorageKind>::Base Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(Transpose) + typedef internal::remove_all_t NestedExpression; + + EIGEN_DEVICE_FUNC explicit EIGEN_STRONG_INLINE Transpose(MatrixType& matrix) : m_matrix(matrix) {} + + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Transpose) + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_matrix.cols(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_matrix.rows(); } + + /** \returns the nested expression */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const internal::remove_all_t& nestedExpression() const { + return m_matrix; + } + + /** \returns the nested expression */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::remove_reference_t& nestedExpression() { + return m_matrix; + } + + /** \internal */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resize(Index nrows, Index ncols) { m_matrix.resize(ncols, nrows); } - protected: - typename internal::ref_selector::non_const_type m_matrix; + protected: + typename internal::ref_selector::non_const_type m_matrix; }; namespace internal { -template::ret> -struct TransposeImpl_base -{ +template ::ret> +struct TransposeImpl_base { typedef typename dense_xpr_base >::type type; }; -template -struct TransposeImpl_base -{ +template +struct TransposeImpl_base { typedef typename dense_xpr_base >::type type; }; -} // end namespace internal +} // end namespace internal // Generic API dispatcher -template -class TransposeImpl - : public internal::generic_xpr_base >::type -{ -public: +template +class TransposeImpl : public internal::generic_xpr_base >::type { + public: typedef typename internal::generic_xpr_base >::type Base; }; -template class TransposeImpl - : public internal::TransposeImpl_base::type -{ - public: - - typedef typename internal::TransposeImpl_base::type Base; - using Base::coeffRef; - EIGEN_DENSE_PUBLIC_INTERFACE(Transpose) - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(TransposeImpl) - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Index innerStride() const { return derived().nestedExpression().innerStride(); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - Index outerStride() const { return derived().nestedExpression().outerStride(); } - - typedef typename internal::conditional< - internal::is_lvalue::value, - Scalar, - const Scalar - >::type ScalarWithConstIfNotLvalue; - - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - ScalarWithConstIfNotLvalue* data() { return derived().nestedExpression().data(); } - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const Scalar* data() const { return derived().nestedExpression().data(); } - - // FIXME: shall we keep the const version of coeffRef? - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const Scalar& coeffRef(Index rowId, Index colId) const - { - return derived().nestedExpression().coeffRef(colId, rowId); - } +template +class TransposeImpl : public internal::TransposeImpl_base::type { + public: + typedef typename internal::TransposeImpl_base::type Base; + using Base::coeffRef; + EIGEN_DENSE_PUBLIC_INTERFACE(Transpose) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(TransposeImpl) - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - const Scalar& coeffRef(Index index) const - { - return derived().nestedExpression().coeffRef(index); - } - protected: - EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(TransposeImpl) + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index innerStride() const { return derived().nestedExpression().innerStride(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index outerStride() const { return derived().nestedExpression().outerStride(); } + + typedef std::conditional_t::value, Scalar, const Scalar> ScalarWithConstIfNotLvalue; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ScalarWithConstIfNotLvalue* data() { + return derived().nestedExpression().data(); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar* data() const { return derived().nestedExpression().data(); } + + // FIXME: shall we keep the const version of coeffRef? + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeffRef(Index rowId, Index colId) const { + return derived().nestedExpression().coeffRef(colId, rowId); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeffRef(Index index) const { + return derived().nestedExpression().coeffRef(index); + } + + protected: + EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(TransposeImpl) }; /** \returns an expression of the transpose of *this. - * - * Example: \include MatrixBase_transpose.cpp - * Output: \verbinclude MatrixBase_transpose.out - * - * \warning If you want to replace a matrix by its own transpose, do \b NOT do this: - * \code - * m = m.transpose(); // bug!!! caused by aliasing effect - * \endcode - * Instead, use the transposeInPlace() method: - * \code - * m.transposeInPlace(); - * \endcode - * which gives Eigen good opportunities for optimization, or alternatively you can also do: - * \code - * m = m.transpose().eval(); - * \endcode - * - * \sa transposeInPlace(), adjoint() */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -Transpose -DenseBase::transpose() -{ + * + * Example: \include MatrixBase_transpose.cpp + * Output: \verbinclude MatrixBase_transpose.out + * + * \warning If you want to replace a matrix by its own transpose, do \b NOT do this: + * \code + * m = m.transpose(); // bug!!! caused by aliasing effect + * \endcode + * Instead, use the transposeInPlace() method: + * \code + * m.transposeInPlace(); + * \endcode + * which gives Eigen good opportunities for optimization, or alternatively you can also do: + * \code + * m = m.transpose().eval(); + * \endcode + * + * \sa transposeInPlace(), adjoint() */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename DenseBase::TransposeReturnType DenseBase::transpose() { return TransposeReturnType(derived()); } /** This is the const version of transpose(). - * - * Make sure you read the warning for transpose() ! - * - * \sa transposeInPlace(), adjoint() */ -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -typename DenseBase::ConstTransposeReturnType -DenseBase::transpose() const -{ + * + * Make sure you read the warning for transpose() ! + * + * \sa transposeInPlace(), adjoint() */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstTransposeReturnType +DenseBase::transpose() const { return ConstTransposeReturnType(derived()); } /** \returns an expression of the adjoint (i.e. conjugate transpose) of *this. - * - * Example: \include MatrixBase_adjoint.cpp - * Output: \verbinclude MatrixBase_adjoint.out - * - * \warning If you want to replace a matrix by its own adjoint, do \b NOT do this: - * \code - * m = m.adjoint(); // bug!!! caused by aliasing effect - * \endcode - * Instead, use the adjointInPlace() method: - * \code - * m.adjointInPlace(); - * \endcode - * which gives Eigen good opportunities for optimization, or alternatively you can also do: - * \code - * m = m.adjoint().eval(); - * \endcode - * - * \sa adjointInPlace(), transpose(), conjugate(), class Transpose, class internal::scalar_conjugate_op */ -template -EIGEN_DEVICE_FUNC inline const typename MatrixBase::AdjointReturnType -MatrixBase::adjoint() const -{ + * + * Example: \include MatrixBase_adjoint.cpp + * Output: \verbinclude MatrixBase_adjoint.out + * + * \warning If you want to replace a matrix by its own adjoint, do \b NOT do this: + * \code + * m = m.adjoint(); // bug!!! caused by aliasing effect + * \endcode + * Instead, use the adjointInPlace() method: + * \code + * m.adjointInPlace(); + * \endcode + * which gives Eigen good opportunities for optimization, or alternatively you can also do: + * \code + * m = m.adjoint().eval(); + * \endcode + * + * \sa adjointInPlace(), transpose(), conjugate(), class Transpose, class internal::scalar_conjugate_op */ +template +EIGEN_DEVICE_FUNC inline const typename MatrixBase::AdjointReturnType MatrixBase::adjoint() const { return AdjointReturnType(this->transpose()); } /*************************************************************************** -* "in place" transpose implementation -***************************************************************************/ + * "in place" transpose implementation + ***************************************************************************/ namespace internal { -template::size)) - && (internal::evaluator::Flags&PacketAccessBit) > +template ::size)) && + (internal::evaluator::Flags & PacketAccessBit)> struct inplace_transpose_selector; -template -struct inplace_transpose_selector { // square matrix +template +struct inplace_transpose_selector { // square matrix static void run(MatrixType& m) { - m.matrix().template triangularView().swap(m.matrix().transpose().template triangularView()); + m.matrix().template triangularView().swap( + m.matrix().transpose().template triangularView()); } }; -template -struct inplace_transpose_selector { // PacketSize x PacketSize +template +struct inplace_transpose_selector { // PacketSize x PacketSize static void run(MatrixType& m) { typedef typename MatrixType::Scalar Scalar; typedef typename internal::packet_traits::type Packet; const Index PacketSize = internal::packet_traits::size; const Index Alignment = internal::evaluator::Alignment; PacketBlock A; - for (Index i=0; i(i,0); + for (Index i = 0; i < PacketSize; ++i) A.packet[i] = m.template packetByOuterInner(i, 0); internal::ptranspose(A); - for (Index i=0; i(m.rowIndexByOuterInner(i,0), m.colIndexByOuterInner(i,0), A.packet[i]); + for (Index i = 0; i < PacketSize; ++i) + m.template writePacket(m.rowIndexByOuterInner(i, 0), m.colIndexByOuterInner(i, 0), A.packet[i]); } }; - template void BlockedInPlaceTranspose(MatrixType& m) { typedef typename MatrixType::Scalar Scalar; @@ -271,46 +244,48 @@ void BlockedInPlaceTranspose(MatrixType& m) { for (int col_start = row_start; col_start + PacketSize <= m.cols(); col_start += PacketSize) { PacketBlock A; if (row_start == col_start) { - for (Index i=0; i(row_start + i,col_start); + for (Index i = 0; i < PacketSize; ++i) + A.packet[i] = m.template packetByOuterInner(row_start + i, col_start); internal::ptranspose(A); - for (Index i=0; i(m.rowIndexByOuterInner(row_start + i, col_start), m.colIndexByOuterInner(row_start + i,col_start), A.packet[i]); + for (Index i = 0; i < PacketSize; ++i) + m.template writePacket(m.rowIndexByOuterInner(row_start + i, col_start), + m.colIndexByOuterInner(row_start + i, col_start), A.packet[i]); } else { PacketBlock B; - for (Index i=0; i(row_start + i,col_start); + for (Index i = 0; i < PacketSize; ++i) { + A.packet[i] = m.template packetByOuterInner(row_start + i, col_start); B.packet[i] = m.template packetByOuterInner(col_start + i, row_start); } internal::ptranspose(A); internal::ptranspose(B); - for (Index i=0; i(m.rowIndexByOuterInner(row_start + i, col_start), m.colIndexByOuterInner(row_start + i,col_start), B.packet[i]); - m.template writePacket(m.rowIndexByOuterInner(col_start + i, row_start), m.colIndexByOuterInner(col_start + i,row_start), A.packet[i]); + for (Index i = 0; i < PacketSize; ++i) { + m.template writePacket(m.rowIndexByOuterInner(row_start + i, col_start), + m.colIndexByOuterInner(row_start + i, col_start), B.packet[i]); + m.template writePacket(m.rowIndexByOuterInner(col_start + i, row_start), + m.colIndexByOuterInner(col_start + i, row_start), A.packet[i]); } } } } for (Index row = row_start; row < m.rows(); ++row) { - m.matrix().row(row).head(row).swap( - m.matrix().col(row).head(row).transpose()); + m.matrix().row(row).head(row).swap(m.matrix().col(row).head(row).transpose()); } } -template -struct inplace_transpose_selector { // non square or dynamic matrix +template +struct inplace_transpose_selector { // non square or dynamic matrix static void run(MatrixType& m) { typedef typename MatrixType::Scalar Scalar; if (m.rows() == m.cols()) { const Index PacketSize = internal::packet_traits::size; if (!NumTraits::IsComplex && m.rows() >= PacketSize) { if ((m.rows() % PacketSize) == 0) - BlockedInPlaceTranspose::Alignment>(m); + BlockedInPlaceTranspose::Alignment>(m); else - BlockedInPlaceTranspose(m); - } - else { - m.matrix().template triangularView().swap(m.matrix().transpose().template triangularView()); + BlockedInPlaceTranspose(m); + } else { + m.matrix().template triangularView().swap( + m.matrix().transpose().template triangularView()); } } else { m = m.transpose().eval(); @@ -318,62 +293,59 @@ struct inplace_transpose_selector { // non squ } }; - -} // end namespace internal +} // end namespace internal /** This is the "in place" version of transpose(): it replaces \c *this by its own transpose. - * Thus, doing - * \code - * m.transposeInPlace(); - * \endcode - * has the same effect on m as doing - * \code - * m = m.transpose().eval(); - * \endcode - * and is faster and also safer because in the latter line of code, forgetting the eval() results - * in a bug caused by \ref TopicAliasing "aliasing". - * - * Notice however that this method is only useful if you want to replace a matrix by its own transpose. - * If you just need the transpose of a matrix, use transpose(). - * - * \note if the matrix is not square, then \c *this must be a resizable matrix. - * This excludes (non-square) fixed-size matrices, block-expressions and maps. - * - * \sa transpose(), adjoint(), adjointInPlace() */ -template -EIGEN_DEVICE_FUNC inline void DenseBase::transposeInPlace() -{ - eigen_assert((rows() == cols() || (RowsAtCompileTime == Dynamic && ColsAtCompileTime == Dynamic)) - && "transposeInPlace() called on a non-square non-resizable matrix"); + * Thus, doing + * \code + * m.transposeInPlace(); + * \endcode + * has the same effect on m as doing + * \code + * m = m.transpose().eval(); + * \endcode + * and is faster and also safer because in the latter line of code, forgetting the eval() results + * in a bug caused by \ref TopicAliasing "aliasing". + * + * Notice however that this method is only useful if you want to replace a matrix by its own transpose. + * If you just need the transpose of a matrix, use transpose(). + * + * \note if the matrix is not square, then \c *this must be a resizable matrix. + * This excludes (non-square) fixed-size matrices, block-expressions and maps. + * + * \sa transpose(), adjoint(), adjointInPlace() */ +template +EIGEN_DEVICE_FUNC inline void DenseBase::transposeInPlace() { + eigen_assert((rows() == cols() || (RowsAtCompileTime == Dynamic && ColsAtCompileTime == Dynamic)) && + "transposeInPlace() called on a non-square non-resizable matrix"); internal::inplace_transpose_selector::run(derived()); } /*************************************************************************** -* "in place" adjoint implementation -***************************************************************************/ + * "in place" adjoint implementation + ***************************************************************************/ /** This is the "in place" version of adjoint(): it replaces \c *this by its own transpose. - * Thus, doing - * \code - * m.adjointInPlace(); - * \endcode - * has the same effect on m as doing - * \code - * m = m.adjoint().eval(); - * \endcode - * and is faster and also safer because in the latter line of code, forgetting the eval() results - * in a bug caused by aliasing. - * - * Notice however that this method is only useful if you want to replace a matrix by its own adjoint. - * If you just need the adjoint of a matrix, use adjoint(). - * - * \note if the matrix is not square, then \c *this must be a resizable matrix. - * This excludes (non-square) fixed-size matrices, block-expressions and maps. - * - * \sa transpose(), adjoint(), transposeInPlace() */ -template -EIGEN_DEVICE_FUNC inline void MatrixBase::adjointInPlace() -{ + * Thus, doing + * \code + * m.adjointInPlace(); + * \endcode + * has the same effect on m as doing + * \code + * m = m.adjoint().eval(); + * \endcode + * and is faster and also safer because in the latter line of code, forgetting the eval() results + * in a bug caused by aliasing. + * + * Notice however that this method is only useful if you want to replace a matrix by its own adjoint. + * If you just need the adjoint of a matrix, use adjoint(). + * + * \note if the matrix is not square, then \c *this must be a resizable matrix. + * This excludes (non-square) fixed-size matrices, block-expressions and maps. + * + * \sa transpose(), adjoint(), transposeInPlace() */ +template +EIGEN_DEVICE_FUNC inline void MatrixBase::adjointInPlace() { derived() = adjoint().eval(); } @@ -383,36 +355,34 @@ EIGEN_DEVICE_FUNC inline void MatrixBase::adjointInPlace() namespace internal { -template -struct check_transpose_aliasing_compile_time_selector -{ +template +struct check_transpose_aliasing_compile_time_selector { enum { ret = bool(blas_traits::IsTransposed) != DestIsTransposed }; }; -template -struct check_transpose_aliasing_compile_time_selector > -{ - enum { ret = bool(blas_traits::IsTransposed) != DestIsTransposed - || bool(blas_traits::IsTransposed) != DestIsTransposed +template +struct check_transpose_aliasing_compile_time_selector > { + enum { + ret = bool(blas_traits::IsTransposed) != DestIsTransposed || + bool(blas_traits::IsTransposed) != DestIsTransposed }; }; -template -struct check_transpose_aliasing_run_time_selector -{ - static bool run(const Scalar* dest, const OtherDerived& src) - { - return (bool(blas_traits::IsTransposed) != DestIsTransposed) && (dest!=0 && dest==(const Scalar*)extract_data(src)); +template +struct check_transpose_aliasing_run_time_selector { + EIGEN_DEVICE_FUNC static bool run(const Scalar* dest, const OtherDerived& src) { + return (bool(blas_traits::IsTransposed) != DestIsTransposed) && + (dest != 0 && dest == (const Scalar*)extract_data(src)); } }; -template -struct check_transpose_aliasing_run_time_selector > -{ - static bool run(const Scalar* dest, const CwiseBinaryOp& src) - { - return ((blas_traits::IsTransposed != DestIsTransposed) && (dest!=0 && dest==(const Scalar*)extract_data(src.lhs()))) - || ((blas_traits::IsTransposed != DestIsTransposed) && (dest!=0 && dest==(const Scalar*)extract_data(src.rhs()))); +template +struct check_transpose_aliasing_run_time_selector > { + EIGEN_DEVICE_FUNC static bool run(const Scalar* dest, const CwiseBinaryOp& src) { + return ((blas_traits::IsTransposed != DestIsTransposed) && + (dest != 0 && dest == (const Scalar*)extract_data(src.lhs()))) || + ((blas_traits::IsTransposed != DestIsTransposed) && + (dest != 0 && dest == (const Scalar*)extract_data(src.rhs()))); } }; @@ -422,43 +392,34 @@ struct check_transpose_aliasing_run_time_selector::IsTransposed,OtherDerived>::ret - > -struct checkTransposeAliasing_impl -{ - static void run(const Derived& dst, const OtherDerived& other) - { - eigen_assert((!check_transpose_aliasing_run_time_selector - ::IsTransposed,OtherDerived> - ::run(extract_data(dst), other)) - && "aliasing detected during transposition, use transposeInPlace() " - "or evaluate the rhs into a temporary using .eval()"); - - } +template ::IsTransposed, OtherDerived>::ret> +struct checkTransposeAliasing_impl { + EIGEN_DEVICE_FUNC static void run(const Derived& dst, const OtherDerived& other) { + eigen_assert( + (!check_transpose_aliasing_run_time_selector::IsTransposed, + OtherDerived>::run(extract_data(dst), other)) && + "aliasing detected during transposition, use transposeInPlace() " + "or evaluate the rhs into a temporary using .eval()"); + } }; -template -struct checkTransposeAliasing_impl -{ - static void run(const Derived&, const OtherDerived&) - { - } +template +struct checkTransposeAliasing_impl { + EIGEN_DEVICE_FUNC static void run(const Derived&, const OtherDerived&) {} }; -template -void check_for_aliasing(const Dst &dst, const Src &src) -{ - if((!Dst::IsVectorAtCompileTime) && dst.rows()>1 && dst.cols()>1) +template +EIGEN_DEVICE_FUNC inline void check_for_aliasing(const Dst& dst, const Src& src) { + if ((!Dst::IsVectorAtCompileTime) && dst.rows() > 1 && dst.cols() > 1) internal::checkTransposeAliasing_impl::run(dst, src); } -} // end namespace internal +} // end namespace internal -#endif // EIGEN_NO_DEBUG +#endif // EIGEN_NO_DEBUG -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_TRANSPOSE_H +#endif // EIGEN_TRANSPOSE_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Transpositions.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Transpositions.h index 38a7b01cb51..ad136d3aeea 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Transpositions.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/Transpositions.h @@ -10,377 +10,314 @@ #ifndef EIGEN_TRANSPOSITIONS_H #define EIGEN_TRANSPOSITIONS_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { -template -class TranspositionsBase -{ - typedef internal::traits Traits; - - public: - - typedef typename Traits::IndicesType IndicesType; - typedef typename IndicesType::Scalar StorageIndex; - typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3 - - EIGEN_DEVICE_FUNC - Derived& derived() { return *static_cast(this); } - EIGEN_DEVICE_FUNC - const Derived& derived() const { return *static_cast(this); } - - /** Copies the \a other transpositions into \c *this */ - template - Derived& operator=(const TranspositionsBase& other) - { - indices() = other.indices(); - return derived(); - } - - /** \returns the number of transpositions */ - EIGEN_DEVICE_FUNC - Index size() const { return indices().size(); } - /** \returns the number of rows of the equivalent permutation matrix */ - EIGEN_DEVICE_FUNC - Index rows() const { return indices().size(); } - /** \returns the number of columns of the equivalent permutation matrix */ - EIGEN_DEVICE_FUNC - Index cols() const { return indices().size(); } - - /** Direct access to the underlying index vector */ - EIGEN_DEVICE_FUNC - inline const StorageIndex& coeff(Index i) const { return indices().coeff(i); } - /** Direct access to the underlying index vector */ - inline StorageIndex& coeffRef(Index i) { return indices().coeffRef(i); } - /** Direct access to the underlying index vector */ - inline const StorageIndex& operator()(Index i) const { return indices()(i); } - /** Direct access to the underlying index vector */ - inline StorageIndex& operator()(Index i) { return indices()(i); } - /** Direct access to the underlying index vector */ - inline const StorageIndex& operator[](Index i) const { return indices()(i); } - /** Direct access to the underlying index vector */ - inline StorageIndex& operator[](Index i) { return indices()(i); } - - /** const version of indices(). */ - EIGEN_DEVICE_FUNC - const IndicesType& indices() const { return derived().indices(); } - /** \returns a reference to the stored array representing the transpositions. */ - EIGEN_DEVICE_FUNC - IndicesType& indices() { return derived().indices(); } - - /** Resizes to given size. */ - inline void resize(Index newSize) - { - indices().resize(newSize); - } - - /** Sets \c *this to represents an identity transformation */ - void setIdentity() - { - for(StorageIndex i = 0; i < indices().size(); ++i) - coeffRef(i) = i; - } - - // FIXME: do we want such methods ? - // might be useful when the target matrix expression is complex, e.g.: - // object.matrix().block(..,..,..,..) = trans * object.matrix().block(..,..,..,..); - /* - template - void applyForwardToRows(MatrixType& mat) const - { - for(Index k=0 ; k - void applyBackwardToRows(MatrixType& mat) const - { - for(Index k=size()-1 ; k>=0 ; --k) - if(m_indices(k)!=k) - mat.row(k).swap(mat.row(m_indices(k))); - } - */ - - /** \returns the inverse transformation */ - inline Transpose inverse() const - { return Transpose(derived()); } - - /** \returns the tranpose transformation */ - inline Transpose transpose() const - { return Transpose(derived()); } - - protected: +template +class TranspositionsBase { + typedef internal::traits Traits; + + public: + typedef typename Traits::IndicesType IndicesType; + typedef typename IndicesType::Scalar StorageIndex; + typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3 + + EIGEN_DEVICE_FUNC Derived& derived() { return *static_cast(this); } + EIGEN_DEVICE_FUNC const Derived& derived() const { return *static_cast(this); } + + /** Copies the \a other transpositions into \c *this */ + template + Derived& operator=(const TranspositionsBase& other) { + indices() = other.indices(); + return derived(); + } + + /** \returns the number of transpositions */ + EIGEN_DEVICE_FUNC Index size() const { return indices().size(); } + /** \returns the number of rows of the equivalent permutation matrix */ + EIGEN_DEVICE_FUNC Index rows() const { return indices().size(); } + /** \returns the number of columns of the equivalent permutation matrix */ + EIGEN_DEVICE_FUNC Index cols() const { return indices().size(); } + + /** Direct access to the underlying index vector */ + EIGEN_DEVICE_FUNC inline const StorageIndex& coeff(Index i) const { return indices().coeff(i); } + /** Direct access to the underlying index vector */ + inline StorageIndex& coeffRef(Index i) { return indices().coeffRef(i); } + /** Direct access to the underlying index vector */ + inline const StorageIndex& operator()(Index i) const { return indices()(i); } + /** Direct access to the underlying index vector */ + inline StorageIndex& operator()(Index i) { return indices()(i); } + /** Direct access to the underlying index vector */ + inline const StorageIndex& operator[](Index i) const { return indices()(i); } + /** Direct access to the underlying index vector */ + inline StorageIndex& operator[](Index i) { return indices()(i); } + + /** const version of indices(). */ + EIGEN_DEVICE_FUNC const IndicesType& indices() const { return derived().indices(); } + /** \returns a reference to the stored array representing the transpositions. */ + EIGEN_DEVICE_FUNC IndicesType& indices() { return derived().indices(); } + + /** Resizes to given size. */ + inline void resize(Index newSize) { indices().resize(newSize); } + + /** Sets \c *this to represents an identity transformation */ + void setIdentity() { + for (StorageIndex i = 0; i < indices().size(); ++i) coeffRef(i) = i; + } + + // FIXME: do we want such methods ? + // might be useful when the target matrix expression is complex, e.g.: + // object.matrix().block(..,..,..,..) = trans * object.matrix().block(..,..,..,..); + /* + template + void applyForwardToRows(MatrixType& mat) const + { + for(Index k=0 ; k + void applyBackwardToRows(MatrixType& mat) const + { + for(Index k=size()-1 ; k>=0 ; --k) + if(m_indices(k)!=k) + mat.row(k).swap(mat.row(m_indices(k))); + } + */ + + /** \returns the inverse transformation */ + inline Transpose inverse() const { return Transpose(derived()); } + + /** \returns the tranpose transformation */ + inline Transpose transpose() const { return Transpose(derived()); } + + protected: }; namespace internal { -template -struct traits > - : traits > -{ - typedef Matrix<_StorageIndex, SizeAtCompileTime, 1, 0, MaxSizeAtCompileTime, 1> IndicesType; +template +struct traits > + : traits > { + typedef Matrix IndicesType; typedef TranspositionsStorage StorageKind; }; -} +} // namespace internal /** \class Transpositions - * \ingroup Core_Module - * - * \brief Represents a sequence of transpositions (row/column interchange) - * - * \tparam SizeAtCompileTime the number of transpositions, or Dynamic - * \tparam MaxSizeAtCompileTime the maximum number of transpositions, or Dynamic. This optional parameter defaults to SizeAtCompileTime. Most of the time, you should not have to specify it. - * - * This class represents a permutation transformation as a sequence of \em n transpositions - * \f$[T_{n-1} \ldots T_{i} \ldots T_{0}]\f$. It is internally stored as a vector of integers \c indices. - * Each transposition \f$ T_{i} \f$ applied on the left of a matrix (\f$ T_{i} M\f$) interchanges - * the rows \c i and \c indices[i] of the matrix \c M. - * A transposition applied on the right (e.g., \f$ M T_{i}\f$) yields a column interchange. - * - * Compared to the class PermutationMatrix, such a sequence of transpositions is what is - * computed during a decomposition with pivoting, and it is faster when applying the permutation in-place. - * - * To apply a sequence of transpositions to a matrix, simply use the operator * as in the following example: - * \code - * Transpositions tr; - * MatrixXf mat; - * mat = tr * mat; - * \endcode - * In this example, we detect that the matrix appears on both side, and so the transpositions - * are applied in-place without any temporary or extra copy. - * - * \sa class PermutationMatrix - */ - -template -class Transpositions : public TranspositionsBase > -{ - typedef internal::traits Traits; - public: - - typedef TranspositionsBase Base; - typedef typename Traits::IndicesType IndicesType; - typedef typename IndicesType::Scalar StorageIndex; - - inline Transpositions() {} - - /** Copy constructor. */ - template - inline Transpositions(const TranspositionsBase& other) - : m_indices(other.indices()) {} - - /** Generic constructor from expression of the transposition indices. */ - template - explicit inline Transpositions(const MatrixBase& indices) : m_indices(indices) - {} - - /** Copies the \a other transpositions into \c *this */ - template - Transpositions& operator=(const TranspositionsBase& other) - { - return Base::operator=(other); - } - - /** Constructs an uninitialized permutation matrix of given size. - */ - inline Transpositions(Index size) : m_indices(size) - {} - - /** const version of indices(). */ - EIGEN_DEVICE_FUNC - const IndicesType& indices() const { return m_indices; } - /** \returns a reference to the stored array representing the transpositions. */ - EIGEN_DEVICE_FUNC - IndicesType& indices() { return m_indices; } - - protected: - - IndicesType m_indices; + * \ingroup Core_Module + * + * \brief Represents a sequence of transpositions (row/column interchange) + * + * \tparam SizeAtCompileTime the number of transpositions, or Dynamic + * \tparam MaxSizeAtCompileTime the maximum number of transpositions, or Dynamic. This optional parameter defaults to + * SizeAtCompileTime. Most of the time, you should not have to specify it. + * + * This class represents a permutation transformation as a sequence of \em n transpositions + * \f$[T_{n-1} \ldots T_{i} \ldots T_{0}]\f$. It is internally stored as a vector of integers \c indices. + * Each transposition \f$ T_{i} \f$ applied on the left of a matrix (\f$ T_{i} M\f$) interchanges + * the rows \c i and \c indices[i] of the matrix \c M. + * A transposition applied on the right (e.g., \f$ M T_{i}\f$) yields a column interchange. + * + * Compared to the class PermutationMatrix, such a sequence of transpositions is what is + * computed during a decomposition with pivoting, and it is faster when applying the permutation in-place. + * + * To apply a sequence of transpositions to a matrix, simply use the operator * as in the following example: + * \code + * Transpositions tr; + * MatrixXf mat; + * mat = tr * mat; + * \endcode + * In this example, we detect that the matrix appears on both side, and so the transpositions + * are applied in-place without any temporary or extra copy. + * + * \sa class PermutationMatrix + */ + +template +class Transpositions + : public TranspositionsBase > { + typedef internal::traits Traits; + + public: + typedef TranspositionsBase Base; + typedef typename Traits::IndicesType IndicesType; + typedef typename IndicesType::Scalar StorageIndex; + + inline Transpositions() {} + + /** Copy constructor. */ + template + inline Transpositions(const TranspositionsBase& other) : m_indices(other.indices()) {} + + /** Generic constructor from expression of the transposition indices. */ + template + explicit inline Transpositions(const MatrixBase& indices) : m_indices(indices) {} + + /** Copies the \a other transpositions into \c *this */ + template + Transpositions& operator=(const TranspositionsBase& other) { + return Base::operator=(other); + } + + /** Constructs an uninitialized permutation matrix of given size. + */ + inline Transpositions(Index size) : m_indices(size) {} + + /** const version of indices(). */ + EIGEN_DEVICE_FUNC const IndicesType& indices() const { return m_indices; } + /** \returns a reference to the stored array representing the transpositions. */ + EIGEN_DEVICE_FUNC IndicesType& indices() { return m_indices; } + + protected: + IndicesType m_indices; }; - namespace internal { -template -struct traits,_PacketAccess> > - : traits > -{ - typedef Map, _PacketAccess> IndicesType; - typedef _StorageIndex StorageIndex; +template +struct traits, PacketAccess_> > + : traits > { + typedef Map, PacketAccess_> IndicesType; + typedef StorageIndex_ StorageIndex; typedef TranspositionsStorage StorageKind; }; -} - -template -class Map,PacketAccess> - : public TranspositionsBase,PacketAccess> > -{ - typedef internal::traits Traits; - public: - - typedef TranspositionsBase Base; - typedef typename Traits::IndicesType IndicesType; - typedef typename IndicesType::Scalar StorageIndex; - - explicit inline Map(const StorageIndex* indicesPtr) - : m_indices(indicesPtr) - {} - - inline Map(const StorageIndex* indicesPtr, Index size) - : m_indices(indicesPtr,size) - {} - - /** Copies the \a other transpositions into \c *this */ - template - Map& operator=(const TranspositionsBase& other) - { - return Base::operator=(other); - } - - #ifndef EIGEN_PARSED_BY_DOXYGEN - /** This is a special case of the templated operator=. Its purpose is to - * prevent a default operator= from hiding the templated operator=. - */ - Map& operator=(const Map& other) - { - m_indices = other.m_indices; - return *this; - } - #endif - - /** const version of indices(). */ - EIGEN_DEVICE_FUNC - const IndicesType& indices() const { return m_indices; } - - /** \returns a reference to the stored array representing the transpositions. */ - EIGEN_DEVICE_FUNC - IndicesType& indices() { return m_indices; } - - protected: - - IndicesType m_indices; +} // namespace internal + +template +class Map, PacketAccess> + : public TranspositionsBase< + Map, PacketAccess> > { + typedef internal::traits Traits; + + public: + typedef TranspositionsBase Base; + typedef typename Traits::IndicesType IndicesType; + typedef typename IndicesType::Scalar StorageIndex; + + explicit inline Map(const StorageIndex* indicesPtr) : m_indices(indicesPtr) {} + + inline Map(const StorageIndex* indicesPtr, Index size) : m_indices(indicesPtr, size) {} + + /** Copies the \a other transpositions into \c *this */ + template + Map& operator=(const TranspositionsBase& other) { + return Base::operator=(other); + } + +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** This is a special case of the templated operator=. Its purpose is to + * prevent a default operator= from hiding the templated operator=. + */ + Map& operator=(const Map& other) { + m_indices = other.m_indices; + return *this; + } +#endif + + /** const version of indices(). */ + EIGEN_DEVICE_FUNC const IndicesType& indices() const { return m_indices; } + + /** \returns a reference to the stored array representing the transpositions. */ + EIGEN_DEVICE_FUNC IndicesType& indices() { return m_indices; } + + protected: + IndicesType m_indices; }; namespace internal { -template -struct traits > - : traits > -{ +template +struct traits > : traits > { typedef TranspositionsStorage StorageKind; }; -} - -template -class TranspositionsWrapper - : public TranspositionsBase > -{ - typedef internal::traits Traits; - public: +} // namespace internal - typedef TranspositionsBase Base; - typedef typename Traits::IndicesType IndicesType; - typedef typename IndicesType::Scalar StorageIndex; +template +class TranspositionsWrapper : public TranspositionsBase > { + typedef internal::traits Traits; - explicit inline TranspositionsWrapper(IndicesType& indices) - : m_indices(indices) - {} + public: + typedef TranspositionsBase Base; + typedef typename Traits::IndicesType IndicesType; + typedef typename IndicesType::Scalar StorageIndex; - /** Copies the \a other transpositions into \c *this */ - template - TranspositionsWrapper& operator=(const TranspositionsBase& other) - { - return Base::operator=(other); - } + explicit inline TranspositionsWrapper(IndicesType& indices) : m_indices(indices) {} - /** const version of indices(). */ - EIGEN_DEVICE_FUNC - const IndicesType& indices() const { return m_indices; } + /** Copies the \a other transpositions into \c *this */ + template + TranspositionsWrapper& operator=(const TranspositionsBase& other) { + return Base::operator=(other); + } - /** \returns a reference to the stored array representing the transpositions. */ - EIGEN_DEVICE_FUNC - IndicesType& indices() { return m_indices; } + /** const version of indices(). */ + EIGEN_DEVICE_FUNC const IndicesType& indices() const { return m_indices; } - protected: + /** \returns a reference to the stored array representing the transpositions. */ + EIGEN_DEVICE_FUNC IndicesType& indices() { return m_indices; } - typename IndicesType::Nested m_indices; + protected: + typename IndicesType::Nested m_indices; }; - - /** \returns the \a matrix with the \a transpositions applied to the columns. - */ -template -EIGEN_DEVICE_FUNC -const Product -operator*(const MatrixBase &matrix, - const TranspositionsBase& transpositions) -{ - return Product - (matrix.derived(), transpositions.derived()); + */ +template +EIGEN_DEVICE_FUNC const Product operator*( + const MatrixBase& matrix, const TranspositionsBase& transpositions) { + return Product(matrix.derived(), transpositions.derived()); } /** \returns the \a matrix with the \a transpositions applied to the rows. - */ -template -EIGEN_DEVICE_FUNC -const Product -operator*(const TranspositionsBase &transpositions, - const MatrixBase& matrix) -{ - return Product - (transpositions.derived(), matrix.derived()); + */ +template +EIGEN_DEVICE_FUNC const Product operator*( + const TranspositionsBase& transpositions, const MatrixBase& matrix) { + return Product(transpositions.derived(), matrix.derived()); } // Template partial specialization for transposed/inverse transpositions namespace internal { -template -struct traits > > - : traits -{}; - -} // end namespace internal - -template -class Transpose > -{ - typedef TranspositionsDerived TranspositionType; - typedef typename TranspositionType::IndicesType IndicesType; - public: - - explicit Transpose(const TranspositionType& t) : m_transpositions(t) {} - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - Index size() const EIGEN_NOEXCEPT { return m_transpositions.size(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - Index rows() const EIGEN_NOEXCEPT { return m_transpositions.size(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - Index cols() const EIGEN_NOEXCEPT { return m_transpositions.size(); } - - /** \returns the \a matrix with the inverse transpositions applied to the columns. - */ - template friend - const Product - operator*(const MatrixBase& matrix, const Transpose& trt) - { - return Product(matrix.derived(), trt); - } - - /** \returns the \a matrix with the inverse transpositions applied to the rows. - */ - template - const Product - operator*(const MatrixBase& matrix) const - { - return Product(*this, matrix.derived()); - } - - EIGEN_DEVICE_FUNC - const TranspositionType& nestedExpression() const { return m_transpositions; } - - protected: - const TranspositionType& m_transpositions; +template +struct traits > > : traits {}; + +} // end namespace internal + +template +class Transpose > { + typedef TranspositionsDerived TranspositionType; + typedef typename TranspositionType::IndicesType IndicesType; + + public: + explicit Transpose(const TranspositionType& t) : m_transpositions(t) {} + + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index size() const EIGEN_NOEXCEPT { return m_transpositions.size(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { return m_transpositions.size(); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { return m_transpositions.size(); } + + /** \returns the \a matrix with the inverse transpositions applied to the columns. + */ + template + friend const Product operator*(const MatrixBase& matrix, + const Transpose& trt) { + return Product(matrix.derived(), trt); + } + + /** \returns the \a matrix with the inverse transpositions applied to the rows. + */ + template + const Product operator*(const MatrixBase& matrix) const { + return Product(*this, matrix.derived()); + } + + EIGEN_DEVICE_FUNC const TranspositionType& nestedExpression() const { return m_transpositions; } + + protected: + const TranspositionType& m_transpositions; }; -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_TRANSPOSITIONS_H +#endif // EIGEN_TRANSPOSITIONS_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/TriangularMatrix.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/TriangularMatrix.h index fdb8bc15a5b..2b1683be950 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/TriangularMatrix.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/TriangularMatrix.h @@ -11,702 +11,615 @@ #ifndef EIGEN_TRIANGULARMATRIX_H #define EIGEN_TRIANGULARMATRIX_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { namespace internal { -template struct triangular_solve_retval; +template +struct triangular_solve_retval; } /** \class TriangularBase - * \ingroup Core_Module - * - * \brief Base class for triangular part in a matrix - */ -template class TriangularBase : public EigenBase -{ - public: - - enum { - Mode = internal::traits::Mode, - RowsAtCompileTime = internal::traits::RowsAtCompileTime, - ColsAtCompileTime = internal::traits::ColsAtCompileTime, - MaxRowsAtCompileTime = internal::traits::MaxRowsAtCompileTime, - MaxColsAtCompileTime = internal::traits::MaxColsAtCompileTime, - - SizeAtCompileTime = (internal::size_at_compile_time::RowsAtCompileTime, - internal::traits::ColsAtCompileTime>::ret), - /**< This is equal to the number of coefficients, i.e. the number of - * rows times the number of columns, or to \a Dynamic if this is not - * known at compile-time. \sa RowsAtCompileTime, ColsAtCompileTime */ - - MaxSizeAtCompileTime = (internal::size_at_compile_time::MaxRowsAtCompileTime, - internal::traits::MaxColsAtCompileTime>::ret) - - }; - typedef typename internal::traits::Scalar Scalar; - typedef typename internal::traits::StorageKind StorageKind; - typedef typename internal::traits::StorageIndex StorageIndex; - typedef typename internal::traits::FullMatrixType DenseMatrixType; - typedef DenseMatrixType DenseType; - typedef Derived const& Nested; - - EIGEN_DEVICE_FUNC - inline TriangularBase() { eigen_assert(!((int(Mode) & int(UnitDiag)) && (int(Mode) & int(ZeroDiag)))); } - - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rows() const EIGEN_NOEXCEPT { return derived().rows(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index cols() const EIGEN_NOEXCEPT { return derived().cols(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index outerStride() const EIGEN_NOEXCEPT { return derived().outerStride(); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index innerStride() const EIGEN_NOEXCEPT { return derived().innerStride(); } - - // dummy resize function - EIGEN_DEVICE_FUNC - void resize(Index rows, Index cols) - { - EIGEN_UNUSED_VARIABLE(rows); - EIGEN_UNUSED_VARIABLE(cols); - eigen_assert(rows==this->rows() && cols==this->cols()); - } + * \ingroup Core_Module + * + * \brief Base class for triangular part in a matrix + */ +template +class TriangularBase : public EigenBase { + public: + enum { + Mode = internal::traits::Mode, + RowsAtCompileTime = internal::traits::RowsAtCompileTime, + ColsAtCompileTime = internal::traits::ColsAtCompileTime, + MaxRowsAtCompileTime = internal::traits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = internal::traits::MaxColsAtCompileTime, - EIGEN_DEVICE_FUNC - inline Scalar coeff(Index row, Index col) const { return derived().coeff(row,col); } - EIGEN_DEVICE_FUNC - inline Scalar& coeffRef(Index row, Index col) { return derived().coeffRef(row,col); } - - /** \see MatrixBase::copyCoeff(row,col) - */ - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void copyCoeff(Index row, Index col, Other& other) - { - derived().coeffRef(row, col) = other.coeff(row, col); - } + SizeAtCompileTime = (internal::size_of_xpr_at_compile_time::ret), + /**< This is equal to the number of coefficients, i.e. the number of + * rows times the number of columns, or to \a Dynamic if this is not + * known at compile-time. \sa RowsAtCompileTime, ColsAtCompileTime */ - EIGEN_DEVICE_FUNC - inline Scalar operator()(Index row, Index col) const - { - check_coordinates(row, col); - return coeff(row,col); - } - EIGEN_DEVICE_FUNC - inline Scalar& operator()(Index row, Index col) - { - check_coordinates(row, col); - return coeffRef(row,col); - } + MaxSizeAtCompileTime = internal::size_at_compile_time(internal::traits::MaxRowsAtCompileTime, + internal::traits::MaxColsAtCompileTime) - #ifndef EIGEN_PARSED_BY_DOXYGEN - EIGEN_DEVICE_FUNC - inline const Derived& derived() const { return *static_cast(this); } - EIGEN_DEVICE_FUNC - inline Derived& derived() { return *static_cast(this); } - #endif // not EIGEN_PARSED_BY_DOXYGEN - - template - EIGEN_DEVICE_FUNC - void evalTo(MatrixBase &other) const; - template - EIGEN_DEVICE_FUNC - void evalToLazy(MatrixBase &other) const; - - EIGEN_DEVICE_FUNC - DenseMatrixType toDenseMatrix() const - { - DenseMatrixType res(rows(), cols()); - evalToLazy(res); - return res; - } + }; + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::StorageIndex StorageIndex; + typedef typename internal::traits::FullMatrixType DenseMatrixType; + typedef DenseMatrixType DenseType; + typedef Derived const& Nested; + + EIGEN_DEVICE_FUNC inline TriangularBase() { + eigen_assert(!((int(Mode) & int(UnitDiag)) && (int(Mode) & int(ZeroDiag)))); + } - protected: - - void check_coordinates(Index row, Index col) const - { - EIGEN_ONLY_USED_FOR_DEBUG(row); - EIGEN_ONLY_USED_FOR_DEBUG(col); - eigen_assert(col>=0 && col=0 && row=row) - || (mode==Lower && col<=row) - || ((mode==StrictlyUpper || mode==UnitUpper) && col>row) - || ((mode==StrictlyLower || mode==UnitLower) && colrows() && cols == this->cols()); + } + + EIGEN_DEVICE_FUNC inline Scalar coeff(Index row, Index col) const { return derived().coeff(row, col); } + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index row, Index col) { return derived().coeffRef(row, col); } + + /** \see MatrixBase::copyCoeff(row,col) + */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void copyCoeff(Index row, Index col, Other& other) { + derived().coeffRef(row, col) = other.coeff(row, col); + } + + EIGEN_DEVICE_FUNC inline Scalar operator()(Index row, Index col) const { + check_coordinates(row, col); + return coeff(row, col); + } + EIGEN_DEVICE_FUNC inline Scalar& operator()(Index row, Index col) { + check_coordinates(row, col); + return coeffRef(row, col); + } + +#ifndef EIGEN_PARSED_BY_DOXYGEN + EIGEN_DEVICE_FUNC inline const Derived& derived() const { return *static_cast(this); } + EIGEN_DEVICE_FUNC inline Derived& derived() { return *static_cast(this); } +#endif // not EIGEN_PARSED_BY_DOXYGEN + + template + EIGEN_DEVICE_FUNC void evalTo(MatrixBase& other) const; + template + EIGEN_DEVICE_FUNC void evalToLazy(MatrixBase& other) const; + + EIGEN_DEVICE_FUNC DenseMatrixType toDenseMatrix() const { + DenseMatrixType res(rows(), cols()); + evalToLazy(res); + return res; + } + + protected: + void check_coordinates(Index row, Index col) const { + EIGEN_ONLY_USED_FOR_DEBUG(row); + EIGEN_ONLY_USED_FOR_DEBUG(col); + eigen_assert(col >= 0 && col < cols() && row >= 0 && row < rows()); + const int mode = int(Mode) & ~SelfAdjoint; + EIGEN_ONLY_USED_FOR_DEBUG(mode); + eigen_assert((mode == Upper && col >= row) || (mode == Lower && col <= row) || + ((mode == StrictlyUpper || mode == UnitUpper) && col > row) || + ((mode == StrictlyLower || mode == UnitLower) && col < row)); + } +#ifdef EIGEN_INTERNAL_DEBUGGING + void check_coordinates_internal(Index row, Index col) const { check_coordinates(row, col); } +#else + void check_coordinates_internal(Index, Index) const {} +#endif }; /** \class TriangularView - * \ingroup Core_Module - * - * \brief Expression of a triangular part in a matrix - * - * \param MatrixType the type of the object in which we are taking the triangular part - * \param Mode the kind of triangular matrix expression to construct. Can be #Upper, - * #Lower, #UnitUpper, #UnitLower, #StrictlyUpper, or #StrictlyLower. - * This is in fact a bit field; it must have either #Upper or #Lower, - * and additionally it may have #UnitDiag or #ZeroDiag or neither. - * - * This class represents a triangular part of a matrix, not necessarily square. Strictly speaking, for rectangular - * matrices one should speak of "trapezoid" parts. This class is the return type - * of MatrixBase::triangularView() and SparseMatrixBase::triangularView(), and most of the time this is the only way it is used. - * - * \sa MatrixBase::triangularView() - */ + * \ingroup Core_Module + * + * \brief Expression of a triangular part in a matrix + * + * \tparam MatrixType the type of the object in which we are taking the triangular part + * \tparam Mode the kind of triangular matrix expression to construct. Can be #Upper, + * #Lower, #UnitUpper, #UnitLower, #StrictlyUpper, or #StrictlyLower. + * This is in fact a bit field; it must have either #Upper or #Lower, + * and additionally it may have #UnitDiag or #ZeroDiag or neither. + * + * This class represents a triangular part of a matrix, not necessarily square. Strictly speaking, for rectangular + * matrices one should speak of "trapezoid" parts. This class is the return type + * of MatrixBase::triangularView() and SparseMatrixBase::triangularView(), and most of the time this is the only way it + * is used. + * + * \sa MatrixBase::triangularView() + */ namespace internal { -template -struct traits > : traits -{ +template +struct traits> : traits { typedef typename ref_selector::non_const_type MatrixTypeNested; - typedef typename remove_reference::type MatrixTypeNestedNonRef; - typedef typename remove_all::type MatrixTypeNestedCleaned; + typedef std::remove_reference_t MatrixTypeNestedNonRef; + typedef remove_all_t MatrixTypeNestedCleaned; typedef typename MatrixType::PlainObject FullMatrixType; typedef MatrixType ExpressionType; enum { - Mode = _Mode, + Mode = Mode_, FlagsLvalueBit = is_lvalue::value ? LvalueBit : 0, - Flags = (MatrixTypeNestedCleaned::Flags & (HereditaryBits | FlagsLvalueBit) & (~(PacketAccessBit | DirectAccessBit | LinearAccessBit))) + Flags = (MatrixTypeNestedCleaned::Flags & (HereditaryBits | FlagsLvalueBit) & + (~(PacketAccessBit | DirectAccessBit | LinearAccessBit))) }; }; -} +} // namespace internal -template class TriangularViewImpl; - -template class TriangularView - : public TriangularViewImpl<_MatrixType, _Mode, typename internal::traits<_MatrixType>::StorageKind > -{ - public: - - typedef TriangularViewImpl<_MatrixType, _Mode, typename internal::traits<_MatrixType>::StorageKind > Base; - typedef typename internal::traits::Scalar Scalar; - typedef _MatrixType MatrixType; - - protected: - typedef typename internal::traits::MatrixTypeNested MatrixTypeNested; - typedef typename internal::traits::MatrixTypeNestedNonRef MatrixTypeNestedNonRef; - - typedef typename internal::remove_all::type MatrixConjugateReturnType; - typedef TriangularView::type, _Mode> ConstTriangularView; - - public: - - typedef typename internal::traits::StorageKind StorageKind; - typedef typename internal::traits::MatrixTypeNestedCleaned NestedExpression; - - enum { - Mode = _Mode, - Flags = internal::traits::Flags, - TransposeMode = (Mode & Upper ? Lower : 0) - | (Mode & Lower ? Upper : 0) - | (Mode & (UnitDiag)) - | (Mode & (ZeroDiag)), - IsVectorAtCompileTime = false - }; - - EIGEN_DEVICE_FUNC - explicit inline TriangularView(MatrixType& matrix) : m_matrix(matrix) - {} - - EIGEN_INHERIT_ASSIGNMENT_OPERATORS(TriangularView) - - /** \copydoc EigenBase::rows() */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index rows() const EIGEN_NOEXCEPT { return m_matrix.rows(); } - /** \copydoc EigenBase::cols() */ - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - inline Index cols() const EIGEN_NOEXCEPT { return m_matrix.cols(); } - - /** \returns a const reference to the nested expression */ - EIGEN_DEVICE_FUNC - const NestedExpression& nestedExpression() const { return m_matrix; } - - /** \returns a reference to the nested expression */ - EIGEN_DEVICE_FUNC - NestedExpression& nestedExpression() { return m_matrix; } - - typedef TriangularView ConjugateReturnType; - /** \sa MatrixBase::conjugate() const */ - EIGEN_DEVICE_FUNC - inline const ConjugateReturnType conjugate() const - { return ConjugateReturnType(m_matrix.conjugate()); } - - /** \returns an expression of the complex conjugate of \c *this if Cond==true, - * returns \c *this otherwise. - */ - template - EIGEN_DEVICE_FUNC - inline typename internal::conditional::type - conjugateIf() const - { - typedef typename internal::conditional::type ReturnType; - return ReturnType(m_matrix.template conjugateIf()); - } +template +class TriangularViewImpl; - typedef TriangularView AdjointReturnType; - /** \sa MatrixBase::adjoint() const */ - EIGEN_DEVICE_FUNC - inline const AdjointReturnType adjoint() const - { return AdjointReturnType(m_matrix.adjoint()); } - - typedef TriangularView TransposeReturnType; - /** \sa MatrixBase::transpose() */ - EIGEN_DEVICE_FUNC - inline TransposeReturnType transpose() - { - EIGEN_STATIC_ASSERT_LVALUE(MatrixType) - typename MatrixType::TransposeReturnType tmp(m_matrix); - return TransposeReturnType(tmp); - } +template +class TriangularView + : public TriangularViewImpl::StorageKind> { + public: + typedef TriangularViewImpl::StorageKind> Base; + typedef typename internal::traits::Scalar Scalar; + typedef MatrixType_ MatrixType; - typedef TriangularView ConstTransposeReturnType; - /** \sa MatrixBase::transpose() const */ - EIGEN_DEVICE_FUNC - inline const ConstTransposeReturnType transpose() const - { - return ConstTransposeReturnType(m_matrix.transpose()); - } + protected: + typedef typename internal::traits::MatrixTypeNested MatrixTypeNested; + typedef typename internal::traits::MatrixTypeNestedNonRef MatrixTypeNestedNonRef; - template - EIGEN_DEVICE_FUNC - inline const Solve - solve(const MatrixBase& other) const - { return Solve(*this, other.derived()); } - - // workaround MSVC ICE - #if EIGEN_COMP_MSVC - template - EIGEN_DEVICE_FUNC - inline const internal::triangular_solve_retval - solve(const MatrixBase& other) const - { return Base::template solve(other); } - #else - using Base::solve; - #endif - - /** \returns a selfadjoint view of the referenced triangular part which must be either \c #Upper or \c #Lower. - * - * This is a shortcut for \code this->nestedExpression().selfadjointView<(*this)::Mode>() \endcode - * \sa MatrixBase::selfadjointView() */ - EIGEN_DEVICE_FUNC - SelfAdjointView selfadjointView() - { - EIGEN_STATIC_ASSERT((Mode&(UnitDiag|ZeroDiag))==0,PROGRAMMING_ERROR); - return SelfAdjointView(m_matrix); - } + typedef internal::remove_all_t MatrixConjugateReturnType; + typedef TriangularView, Mode_> ConstTriangularView; - /** This is the const version of selfadjointView() */ - EIGEN_DEVICE_FUNC - const SelfAdjointView selfadjointView() const - { - EIGEN_STATIC_ASSERT((Mode&(UnitDiag|ZeroDiag))==0,PROGRAMMING_ERROR); - return SelfAdjointView(m_matrix); - } + public: + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::MatrixTypeNestedCleaned NestedExpression; + enum { + Mode = Mode_, + Flags = internal::traits::Flags, + TransposeMode = (int(Mode) & int(Upper) ? Lower : 0) | (int(Mode) & int(Lower) ? Upper : 0) | + (int(Mode) & int(UnitDiag)) | (int(Mode) & int(ZeroDiag)), + IsVectorAtCompileTime = false + }; - /** \returns the determinant of the triangular matrix - * \sa MatrixBase::determinant() */ - EIGEN_DEVICE_FUNC - Scalar determinant() const - { - if (Mode & UnitDiag) - return 1; - else if (Mode & ZeroDiag) - return 0; - else - return m_matrix.diagonal().prod(); - } + EIGEN_DEVICE_FUNC explicit inline TriangularView(MatrixType& matrix) : m_matrix(matrix) {} + + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(TriangularView) + + /** \copydoc EigenBase::rows() */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index rows() const EIGEN_NOEXCEPT { return m_matrix.rows(); } + /** \copydoc EigenBase::cols() */ + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR inline Index cols() const EIGEN_NOEXCEPT { return m_matrix.cols(); } + + /** \returns a const reference to the nested expression */ + EIGEN_DEVICE_FUNC const NestedExpression& nestedExpression() const { return m_matrix; } + + /** \returns a reference to the nested expression */ + EIGEN_DEVICE_FUNC NestedExpression& nestedExpression() { return m_matrix; } + + typedef TriangularView ConjugateReturnType; + /** \sa MatrixBase::conjugate() const */ + EIGEN_DEVICE_FUNC inline const ConjugateReturnType conjugate() const { + return ConjugateReturnType(m_matrix.conjugate()); + } + + /** \returns an expression of the complex conjugate of \c *this if Cond==true, + * returns \c *this otherwise. + */ + template + EIGEN_DEVICE_FUNC inline std::conditional_t conjugateIf() const { + typedef std::conditional_t ReturnType; + return ReturnType(m_matrix.template conjugateIf()); + } + + typedef TriangularView AdjointReturnType; + /** \sa MatrixBase::adjoint() const */ + EIGEN_DEVICE_FUNC inline const AdjointReturnType adjoint() const { return AdjointReturnType(m_matrix.adjoint()); } + + typedef TriangularView TransposeReturnType; + /** \sa MatrixBase::transpose() */ + template + EIGEN_DEVICE_FUNC inline TransposeReturnType transpose( + std::enable_if_t::value, Dummy*> = nullptr) { + typename MatrixType::TransposeReturnType tmp(m_matrix); + return TransposeReturnType(tmp); + } + + typedef TriangularView ConstTransposeReturnType; + /** \sa MatrixBase::transpose() const */ + EIGEN_DEVICE_FUNC inline const ConstTransposeReturnType transpose() const { + return ConstTransposeReturnType(m_matrix.transpose()); + } + + template + EIGEN_DEVICE_FUNC inline const Solve solve(const MatrixBase& other) const { + return Solve(*this, other.derived()); + } + +// workaround MSVC ICE +#if EIGEN_COMP_MSVC + template + EIGEN_DEVICE_FUNC inline const internal::triangular_solve_retval solve( + const MatrixBase& other) const { + return Base::template solve(other); + } +#else + using Base::solve; +#endif + + /** \returns a selfadjoint view of the referenced triangular part which must be either \c #Upper or \c #Lower. + * + * This is a shortcut for \code this->nestedExpression().selfadjointView<(*this)::Mode>() \endcode + * \sa MatrixBase::selfadjointView() */ + EIGEN_DEVICE_FUNC SelfAdjointView selfadjointView() { + EIGEN_STATIC_ASSERT((Mode & (UnitDiag | ZeroDiag)) == 0, PROGRAMMING_ERROR); + return SelfAdjointView(m_matrix); + } + + /** This is the const version of selfadjointView() */ + EIGEN_DEVICE_FUNC const SelfAdjointView selfadjointView() const { + EIGEN_STATIC_ASSERT((Mode & (UnitDiag | ZeroDiag)) == 0, PROGRAMMING_ERROR); + return SelfAdjointView(m_matrix); + } - protected: + /** \returns the determinant of the triangular matrix + * \sa MatrixBase::determinant() */ + EIGEN_DEVICE_FUNC Scalar determinant() const { + if (Mode & UnitDiag) + return 1; + else if (Mode & ZeroDiag) + return 0; + else + return m_matrix.diagonal().prod(); + } - MatrixTypeNested m_matrix; + protected: + MatrixTypeNested m_matrix; }; /** \ingroup Core_Module - * - * \brief Base class for a triangular part in a \b dense matrix - * - * This class is an abstract base class of class TriangularView, and objects of type TriangularViewImpl cannot be instantiated. - * It extends class TriangularView with additional methods which available for dense expressions only. - * - * \sa class TriangularView, MatrixBase::triangularView() - */ -template class TriangularViewImpl<_MatrixType,_Mode,Dense> - : public TriangularBase > -{ - public: - - typedef TriangularView<_MatrixType, _Mode> TriangularViewType; - typedef TriangularBase Base; - typedef typename internal::traits::Scalar Scalar; - - typedef _MatrixType MatrixType; - typedef typename MatrixType::PlainObject DenseMatrixType; - typedef DenseMatrixType PlainObject; - - public: - using Base::evalToLazy; - using Base::derived; - - typedef typename internal::traits::StorageKind StorageKind; - - enum { - Mode = _Mode, - Flags = internal::traits::Flags - }; - - /** \returns the outer-stride of the underlying dense matrix - * \sa DenseCoeffsBase::outerStride() */ - EIGEN_DEVICE_FUNC - inline Index outerStride() const { return derived().nestedExpression().outerStride(); } - /** \returns the inner-stride of the underlying dense matrix - * \sa DenseCoeffsBase::innerStride() */ - EIGEN_DEVICE_FUNC - inline Index innerStride() const { return derived().nestedExpression().innerStride(); } - - /** \sa MatrixBase::operator+=() */ - template - EIGEN_DEVICE_FUNC - TriangularViewType& operator+=(const DenseBase& other) { - internal::call_assignment_no_alias(derived(), other.derived(), internal::add_assign_op()); - return derived(); - } - /** \sa MatrixBase::operator-=() */ - template - EIGEN_DEVICE_FUNC - TriangularViewType& operator-=(const DenseBase& other) { - internal::call_assignment_no_alias(derived(), other.derived(), internal::sub_assign_op()); - return derived(); - } + * + * \brief Base class for a triangular part in a \b dense matrix + * + * This class is an abstract base class of class TriangularView, and objects of type TriangularViewImpl cannot be + * instantiated. It extends class TriangularView with additional methods which available for dense expressions only. + * + * \sa class TriangularView, MatrixBase::triangularView() + */ +template +class TriangularViewImpl : public TriangularBase> { + public: + typedef TriangularView TriangularViewType; + + typedef TriangularBase Base; + typedef typename internal::traits::Scalar Scalar; + + typedef MatrixType_ MatrixType; + typedef typename MatrixType::PlainObject DenseMatrixType; + typedef DenseMatrixType PlainObject; + + public: + using Base::derived; + using Base::evalToLazy; + + typedef typename internal::traits::StorageKind StorageKind; + + enum { Mode = Mode_, Flags = internal::traits::Flags }; + + /** \returns the outer-stride of the underlying dense matrix + * \sa DenseCoeffsBase::outerStride() */ + EIGEN_DEVICE_FUNC inline Index outerStride() const { return derived().nestedExpression().outerStride(); } + /** \returns the inner-stride of the underlying dense matrix + * \sa DenseCoeffsBase::innerStride() */ + EIGEN_DEVICE_FUNC inline Index innerStride() const { return derived().nestedExpression().innerStride(); } + + /** \sa MatrixBase::operator+=() */ + template + EIGEN_DEVICE_FUNC TriangularViewType& operator+=(const DenseBase& other) { + internal::call_assignment_no_alias(derived(), other.derived(), + internal::add_assign_op()); + return derived(); + } + /** \sa MatrixBase::operator-=() */ + template + EIGEN_DEVICE_FUNC TriangularViewType& operator-=(const DenseBase& other) { + internal::call_assignment_no_alias(derived(), other.derived(), + internal::sub_assign_op()); + return derived(); + } - /** \sa MatrixBase::operator*=() */ - EIGEN_DEVICE_FUNC - TriangularViewType& operator*=(const typename internal::traits::Scalar& other) { return *this = derived().nestedExpression() * other; } - /** \sa DenseBase::operator/=() */ - EIGEN_DEVICE_FUNC - TriangularViewType& operator/=(const typename internal::traits::Scalar& other) { return *this = derived().nestedExpression() / other; } - - /** \sa MatrixBase::fill() */ - EIGEN_DEVICE_FUNC - void fill(const Scalar& value) { setConstant(value); } - /** \sa MatrixBase::setConstant() */ - EIGEN_DEVICE_FUNC - TriangularViewType& setConstant(const Scalar& value) - { return *this = MatrixType::Constant(derived().rows(), derived().cols(), value); } - /** \sa MatrixBase::setZero() */ - EIGEN_DEVICE_FUNC - TriangularViewType& setZero() { return setConstant(Scalar(0)); } - /** \sa MatrixBase::setOnes() */ - EIGEN_DEVICE_FUNC - TriangularViewType& setOnes() { return setConstant(Scalar(1)); } - - /** \sa MatrixBase::coeff() - * \warning the coordinates must fit into the referenced triangular part - */ - EIGEN_DEVICE_FUNC - inline Scalar coeff(Index row, Index col) const - { - Base::check_coordinates_internal(row, col); - return derived().nestedExpression().coeff(row, col); - } + /** \sa MatrixBase::operator*=() */ + EIGEN_DEVICE_FUNC TriangularViewType& operator*=(const typename internal::traits::Scalar& other) { + return *this = derived().nestedExpression() * other; + } + /** \sa DenseBase::operator/=() */ + EIGEN_DEVICE_FUNC TriangularViewType& operator/=(const typename internal::traits::Scalar& other) { + return *this = derived().nestedExpression() / other; + } - /** \sa MatrixBase::coeffRef() - * \warning the coordinates must fit into the referenced triangular part - */ - EIGEN_DEVICE_FUNC - inline Scalar& coeffRef(Index row, Index col) - { - EIGEN_STATIC_ASSERT_LVALUE(TriangularViewType); - Base::check_coordinates_internal(row, col); - return derived().nestedExpression().coeffRef(row, col); - } + /** \sa MatrixBase::fill() */ + EIGEN_DEVICE_FUNC void fill(const Scalar& value) { setConstant(value); } + /** \sa MatrixBase::setConstant() */ + EIGEN_DEVICE_FUNC TriangularViewType& setConstant(const Scalar& value) { + return *this = MatrixType::Constant(derived().rows(), derived().cols(), value); + } + /** \sa MatrixBase::setZero() */ + EIGEN_DEVICE_FUNC TriangularViewType& setZero() { return setConstant(Scalar(0)); } + /** \sa MatrixBase::setOnes() */ + EIGEN_DEVICE_FUNC TriangularViewType& setOnes() { return setConstant(Scalar(1)); } + + /** \sa MatrixBase::coeff() + * \warning the coordinates must fit into the referenced triangular part + */ + EIGEN_DEVICE_FUNC inline Scalar coeff(Index row, Index col) const { + Base::check_coordinates_internal(row, col); + return derived().nestedExpression().coeff(row, col); + } - /** Assigns a triangular matrix to a triangular part of a dense matrix */ - template - EIGEN_DEVICE_FUNC - TriangularViewType& operator=(const TriangularBase& other); + /** \sa MatrixBase::coeffRef() + * \warning the coordinates must fit into the referenced triangular part + */ + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index row, Index col) { + EIGEN_STATIC_ASSERT_LVALUE(TriangularViewType); + Base::check_coordinates_internal(row, col); + return derived().nestedExpression().coeffRef(row, col); + } + + /** Assigns a triangular matrix to a triangular part of a dense matrix */ + template + EIGEN_DEVICE_FUNC TriangularViewType& operator=(const TriangularBase& other); - /** Shortcut for\code *this = other.other.triangularView<(*this)::Mode>() \endcode */ - template - EIGEN_DEVICE_FUNC - TriangularViewType& operator=(const MatrixBase& other); + /** Shortcut for\code *this = other.other.triangularView<(*this)::Mode>() \endcode */ + template + EIGEN_DEVICE_FUNC TriangularViewType& operator=(const MatrixBase& other); #ifndef EIGEN_PARSED_BY_DOXYGEN - EIGEN_DEVICE_FUNC - TriangularViewType& operator=(const TriangularViewImpl& other) - { return *this = other.derived().nestedExpression(); } - - template - /** \deprecated */ - EIGEN_DEPRECATED EIGEN_DEVICE_FUNC - void lazyAssign(const TriangularBase& other); - - template - /** \deprecated */ - EIGEN_DEPRECATED EIGEN_DEVICE_FUNC - void lazyAssign(const MatrixBase& other); + EIGEN_DEVICE_FUNC TriangularViewType& operator=(const TriangularViewImpl& other) { + return *this = other.derived().nestedExpression(); + } + + template + /** \deprecated */ + EIGEN_DEPRECATED EIGEN_DEVICE_FUNC void lazyAssign(const TriangularBase& other); + + template + /** \deprecated */ + EIGEN_DEPRECATED EIGEN_DEVICE_FUNC void lazyAssign(const MatrixBase& other); #endif - /** Efficient triangular matrix times vector/matrix product */ - template - EIGEN_DEVICE_FUNC - const Product - operator*(const MatrixBase& rhs) const - { - return Product(derived(), rhs.derived()); - } + /** Efficient triangular matrix times vector/matrix product */ + template + EIGEN_DEVICE_FUNC const Product operator*( + const MatrixBase& rhs) const { + return Product(derived(), rhs.derived()); + } - /** Efficient vector/matrix times triangular matrix product */ - template friend - EIGEN_DEVICE_FUNC - const Product - operator*(const MatrixBase& lhs, const TriangularViewImpl& rhs) - { - return Product(lhs.derived(),rhs.derived()); - } + /** Efficient vector/matrix times triangular matrix product */ + template + friend EIGEN_DEVICE_FUNC const Product operator*( + const MatrixBase& lhs, const TriangularViewImpl& rhs) { + return Product(lhs.derived(), rhs.derived()); + } + + /** \returns the product of the inverse of \c *this with \a other, \a *this being triangular. + * + * This function computes the inverse-matrix matrix product inverse(\c *this) * \a other if + * \a Side==OnTheLeft (the default), or the right-inverse-multiply \a other * inverse(\c *this) if + * \a Side==OnTheRight. + * + * Note that the template parameter \c Side can be omitted, in which case \c Side==OnTheLeft + * + * The matrix \c *this must be triangular and invertible (i.e., all the coefficients of the + * diagonal must be non zero). It works as a forward (resp. backward) substitution if \c *this + * is an upper (resp. lower) triangular matrix. + * + * Example: \include Triangular_solve.cpp + * Output: \verbinclude Triangular_solve.out + * + * This function returns an expression of the inverse-multiply and can works in-place if it is assigned + * to the same matrix or vector \a other. + * + * For users coming from BLAS, this function (and more specifically solveInPlace()) offer + * all the operations supported by the \c *TRSV and \c *TRSM BLAS routines. + * + * \sa TriangularView::solveInPlace() + */ + template + inline const internal::triangular_solve_retval solve( + const MatrixBase& other) const; + + /** "in-place" version of TriangularView::solve() where the result is written in \a other + * + * \warning The parameter is only marked 'const' to make the C++ compiler accept a temporary expression here. + * This function will const_cast it, so constness isn't honored here. + * + * Note that the template parameter \c Side can be omitted, in which case \c Side==OnTheLeft + * + * See TriangularView:solve() for the details. + */ + template + EIGEN_DEVICE_FUNC void solveInPlace(const MatrixBase& other) const; + + template + EIGEN_DEVICE_FUNC void solveInPlace(const MatrixBase& other) const { + return solveInPlace(other); + } - /** \returns the product of the inverse of \c *this with \a other, \a *this being triangular. - * - * This function computes the inverse-matrix matrix product inverse(\c *this) * \a other if - * \a Side==OnTheLeft (the default), or the right-inverse-multiply \a other * inverse(\c *this) if - * \a Side==OnTheRight. - * - * Note that the template parameter \c Side can be omitted, in which case \c Side==OnTheLeft - * - * The matrix \c *this must be triangular and invertible (i.e., all the coefficients of the - * diagonal must be non zero). It works as a forward (resp. backward) substitution if \c *this - * is an upper (resp. lower) triangular matrix. - * - * Example: \include Triangular_solve.cpp - * Output: \verbinclude Triangular_solve.out - * - * This function returns an expression of the inverse-multiply and can works in-place if it is assigned - * to the same matrix or vector \a other. - * - * For users coming from BLAS, this function (and more specifically solveInPlace()) offer - * all the operations supported by the \c *TRSV and \c *TRSM BLAS routines. - * - * \sa TriangularView::solveInPlace() - */ - template - inline const internal::triangular_solve_retval - solve(const MatrixBase& other) const; - - /** "in-place" version of TriangularView::solve() where the result is written in \a other - * - * \warning The parameter is only marked 'const' to make the C++ compiler accept a temporary expression here. - * This function will const_cast it, so constness isn't honored here. - * - * Note that the template parameter \c Side can be omitted, in which case \c Side==OnTheLeft - * - * See TriangularView:solve() for the details. - */ - template - EIGEN_DEVICE_FUNC - void solveInPlace(const MatrixBase& other) const; - - template - EIGEN_DEVICE_FUNC - void solveInPlace(const MatrixBase& other) const - { return solveInPlace(other); } - - /** Swaps the coefficients of the common triangular parts of two matrices */ - template - EIGEN_DEVICE_FUNC + /** Swaps the coefficients of the common triangular parts of two matrices */ + template + EIGEN_DEVICE_FUNC #ifdef EIGEN_PARSED_BY_DOXYGEN - void swap(TriangularBase &other) + void + swap(TriangularBase& other) #else - void swap(TriangularBase const & other) + void + swap(TriangularBase const& other) #endif - { - EIGEN_STATIC_ASSERT_LVALUE(OtherDerived); - call_assignment(derived(), other.const_cast_derived(), internal::swap_assign_op()); - } + { + EIGEN_STATIC_ASSERT_LVALUE(OtherDerived); + call_assignment(derived(), other.const_cast_derived(), internal::swap_assign_op()); + } - /** Shortcut for \code (*this).swap(other.triangularView<(*this)::Mode>()) \endcode */ - template - /** \deprecated */ - EIGEN_DEPRECATED EIGEN_DEVICE_FUNC - void swap(MatrixBase const & other) - { - EIGEN_STATIC_ASSERT_LVALUE(OtherDerived); - call_assignment(derived(), other.const_cast_derived(), internal::swap_assign_op()); - } + /** Shortcut for \code (*this).swap(other.triangularView<(*this)::Mode>()) \endcode */ + template + /** \deprecated */ + EIGEN_DEPRECATED EIGEN_DEVICE_FUNC void swap(MatrixBase const& other) { + EIGEN_STATIC_ASSERT_LVALUE(OtherDerived); + call_assignment(derived(), other.const_cast_derived(), internal::swap_assign_op()); + } - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE void _solve_impl(const RhsType &rhs, DstType &dst) const { - if(!internal::is_same_dense(dst,rhs)) - dst = rhs; - this->solveInPlace(dst); - } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void _solve_impl(const RhsType& rhs, DstType& dst) const { + if (!internal::is_same_dense(dst, rhs)) dst = rhs; + this->solveInPlace(dst); + } - template - EIGEN_DEVICE_FUNC - EIGEN_STRONG_INLINE TriangularViewType& _assignProduct(const ProductType& prod, const Scalar& alpha, bool beta); - protected: - EIGEN_DEFAULT_COPY_CONSTRUCTOR(TriangularViewImpl) - EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(TriangularViewImpl) + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TriangularViewType& _assignProduct(const ProductType& prod, const Scalar& alpha, + bool beta); + protected: + EIGEN_DEFAULT_COPY_CONSTRUCTOR(TriangularViewImpl) + EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(TriangularViewImpl) }; /*************************************************************************** -* Implementation of triangular evaluation/assignment -***************************************************************************/ + * Implementation of triangular evaluation/assignment + ***************************************************************************/ #ifndef EIGEN_PARSED_BY_DOXYGEN // FIXME should we keep that possibility -template -template -EIGEN_DEVICE_FUNC inline TriangularView& -TriangularViewImpl::operator=(const MatrixBase& other) -{ - internal::call_assignment_no_alias(derived(), other.derived(), internal::assign_op()); +template +template +EIGEN_DEVICE_FUNC inline TriangularView& TriangularViewImpl::operator=( + const MatrixBase& other) { + internal::call_assignment_no_alias(derived(), other.derived(), + internal::assign_op()); return derived(); } // FIXME should we keep that possibility -template -template -EIGEN_DEVICE_FUNC void TriangularViewImpl::lazyAssign(const MatrixBase& other) -{ +template +template +EIGEN_DEVICE_FUNC void TriangularViewImpl::lazyAssign(const MatrixBase& other) { internal::call_assignment_no_alias(derived(), other.template triangularView()); } - - -template -template -EIGEN_DEVICE_FUNC inline TriangularView& -TriangularViewImpl::operator=(const TriangularBase& other) -{ +template +template +EIGEN_DEVICE_FUNC inline TriangularView& TriangularViewImpl::operator=( + const TriangularBase& other) { eigen_assert(Mode == int(OtherDerived::Mode)); internal::call_assignment(derived(), other.derived()); return derived(); } -template -template -EIGEN_DEVICE_FUNC void TriangularViewImpl::lazyAssign(const TriangularBase& other) -{ +template +template +EIGEN_DEVICE_FUNC void TriangularViewImpl::lazyAssign( + const TriangularBase& other) { eigen_assert(Mode == int(OtherDerived::Mode)); internal::call_assignment_no_alias(derived(), other.derived()); } #endif /*************************************************************************** -* Implementation of TriangularBase methods -***************************************************************************/ + * Implementation of TriangularBase methods + ***************************************************************************/ /** Assigns a triangular or selfadjoint matrix to a dense matrix. - * If the matrix is triangular, the opposite part is set to zero. */ -template -template -EIGEN_DEVICE_FUNC void TriangularBase::evalTo(MatrixBase &other) const -{ + * If the matrix is triangular, the opposite part is set to zero. */ +template +template +EIGEN_DEVICE_FUNC void TriangularBase::evalTo(MatrixBase& other) const { evalToLazy(other.derived()); } /*************************************************************************** -* Implementation of TriangularView methods -***************************************************************************/ + * Implementation of TriangularView methods + ***************************************************************************/ /*************************************************************************** -* Implementation of MatrixBase methods -***************************************************************************/ + * Implementation of MatrixBase methods + ***************************************************************************/ /** - * \returns an expression of a triangular view extracted from the current matrix - * - * The parameter \a Mode can have the following values: \c #Upper, \c #StrictlyUpper, \c #UnitUpper, - * \c #Lower, \c #StrictlyLower, \c #UnitLower. - * - * Example: \include MatrixBase_triangularView.cpp - * Output: \verbinclude MatrixBase_triangularView.out - * - * \sa class TriangularView - */ -template -template -EIGEN_DEVICE_FUNC -typename MatrixBase::template TriangularViewReturnType::Type -MatrixBase::triangularView() -{ + * \returns an expression of a triangular view extracted from the current matrix + * + * The parameter \a Mode can have the following values: \c #Upper, \c #StrictlyUpper, \c #UnitUpper, + * \c #Lower, \c #StrictlyLower, \c #UnitLower. + * + * Example: \include MatrixBase_triangularView.cpp + * Output: \verbinclude MatrixBase_triangularView.out + * + * \sa class TriangularView + */ +template +template +EIGEN_DEVICE_FUNC typename MatrixBase::template TriangularViewReturnType::Type +MatrixBase::triangularView() { return typename TriangularViewReturnType::Type(derived()); } /** This is the const version of MatrixBase::triangularView() */ -template -template -EIGEN_DEVICE_FUNC -typename MatrixBase::template ConstTriangularViewReturnType::Type -MatrixBase::triangularView() const -{ +template +template +EIGEN_DEVICE_FUNC typename MatrixBase::template ConstTriangularViewReturnType::Type +MatrixBase::triangularView() const { return typename ConstTriangularViewReturnType::Type(derived()); } /** \returns true if *this is approximately equal to an upper triangular matrix, - * within the precision given by \a prec. - * - * \sa isLowerTriangular() - */ -template -bool MatrixBase::isUpperTriangular(const RealScalar& prec) const -{ + * within the precision given by \a prec. + * + * \sa isLowerTriangular() + */ +template +bool MatrixBase::isUpperTriangular(const RealScalar& prec) const { RealScalar maxAbsOnUpperPart = static_cast(-1); - for(Index j = 0; j < cols(); ++j) - { - Index maxi = numext::mini(j, rows()-1); - for(Index i = 0; i <= maxi; ++i) - { - RealScalar absValue = numext::abs(coeff(i,j)); - if(absValue > maxAbsOnUpperPart) maxAbsOnUpperPart = absValue; + for (Index j = 0; j < cols(); ++j) { + Index maxi = numext::mini(j, rows() - 1); + for (Index i = 0; i <= maxi; ++i) { + RealScalar absValue = numext::abs(coeff(i, j)); + if (absValue > maxAbsOnUpperPart) maxAbsOnUpperPart = absValue; } } RealScalar threshold = maxAbsOnUpperPart * prec; - for(Index j = 0; j < cols(); ++j) - for(Index i = j+1; i < rows(); ++i) - if(numext::abs(coeff(i, j)) > threshold) return false; + for (Index j = 0; j < cols(); ++j) + for (Index i = j + 1; i < rows(); ++i) + if (numext::abs(coeff(i, j)) > threshold) return false; return true; } /** \returns true if *this is approximately equal to a lower triangular matrix, - * within the precision given by \a prec. - * - * \sa isUpperTriangular() - */ -template -bool MatrixBase::isLowerTriangular(const RealScalar& prec) const -{ + * within the precision given by \a prec. + * + * \sa isUpperTriangular() + */ +template +bool MatrixBase::isLowerTriangular(const RealScalar& prec) const { RealScalar maxAbsOnLowerPart = static_cast(-1); - for(Index j = 0; j < cols(); ++j) - for(Index i = j; i < rows(); ++i) - { - RealScalar absValue = numext::abs(coeff(i,j)); - if(absValue > maxAbsOnLowerPart) maxAbsOnLowerPart = absValue; + for (Index j = 0; j < cols(); ++j) + for (Index i = j; i < rows(); ++i) { + RealScalar absValue = numext::abs(coeff(i, j)); + if (absValue > maxAbsOnLowerPart) maxAbsOnLowerPart = absValue; } RealScalar threshold = maxAbsOnLowerPart * prec; - for(Index j = 1; j < cols(); ++j) - { - Index maxi = numext::mini(j, rows()-1); - for(Index i = 0; i < maxi; ++i) - if(numext::abs(coeff(i, j)) > threshold) return false; + for (Index j = 1; j < cols(); ++j) { + Index maxi = numext::mini(j, rows() - 1); + for (Index i = 0; i < maxi; ++i) + if (numext::abs(coeff(i, j)) > threshold) return false; } return true; } - /*************************************************************************** **************************************************************************** * Evaluators and Assignment of triangular expressions @@ -715,92 +628,85 @@ bool MatrixBase::isLowerTriangular(const RealScalar& prec) const namespace internal { - // TODO currently a triangular expression has the form TriangularView<.,.> // in the future triangular-ness should be defined by the expression traits -// such that Transpose > is valid. (currently TriangularBase::transpose() is overloaded to make it work) -template -struct evaluator_traits > -{ +// such that Transpose > is valid. (currently TriangularBase::transpose() is overloaded to make +// it work) +template +struct evaluator_traits> { typedef typename storage_kind_to_evaluator_kind::Kind Kind; typedef typename glue_shapes::Shape, TriangularShape>::type Shape; }; -template -struct unary_evaluator, IndexBased> - : evaluator::type> -{ - typedef TriangularView XprType; - typedef evaluator::type> Base; - EIGEN_DEVICE_FUNC - unary_evaluator(const XprType &xpr) : Base(xpr.nestedExpression()) {} +template +struct unary_evaluator, IndexBased> : evaluator> { + typedef TriangularView XprType; + typedef evaluator> Base; + EIGEN_DEVICE_FUNC unary_evaluator(const XprType& xpr) : Base(xpr.nestedExpression()) {} }; // Additional assignment kinds: -struct Triangular2Triangular {}; -struct Triangular2Dense {}; -struct Dense2Triangular {}; - - -template struct triangular_assignment_loop; +struct Triangular2Triangular {}; +struct Triangular2Dense {}; +struct Dense2Triangular {}; +template +struct triangular_assignment_loop; /** \internal Specialization of the dense assignment kernel for triangular matrices. - * The main difference is that the triangular, diagonal, and opposite parts are processed through three different functions. - * \tparam UpLo must be either Lower or Upper - * \tparam Mode must be either 0, UnitDiag, ZeroDiag, or SelfAdjoint - */ -template -class triangular_dense_assignment_kernel : public generic_dense_assignment_kernel -{ -protected: + * The main difference is that the triangular, diagonal, and opposite parts are processed through three different + * functions. \tparam UpLo must be either Lower or Upper \tparam Mode must be either 0, UnitDiag, ZeroDiag, or + * SelfAdjoint + */ +template +class triangular_dense_assignment_kernel + : public generic_dense_assignment_kernel { + protected: typedef generic_dense_assignment_kernel Base; typedef typename Base::DstXprType DstXprType; typedef typename Base::SrcXprType SrcXprType; using Base::m_dst; - using Base::m_src; using Base::m_functor; -public: + using Base::m_src; + public: typedef typename Base::DstEvaluatorType DstEvaluatorType; typedef typename Base::SrcEvaluatorType SrcEvaluatorType; typedef typename Base::Scalar Scalar; typedef typename Base::AssignmentTraits AssignmentTraits; - - EIGEN_DEVICE_FUNC triangular_dense_assignment_kernel(DstEvaluatorType &dst, const SrcEvaluatorType &src, const Functor &func, DstXprType& dstExpr) - : Base(dst, src, func, dstExpr) - {} + EIGEN_DEVICE_FUNC triangular_dense_assignment_kernel(DstEvaluatorType& dst, const SrcEvaluatorType& src, + const Functor& func, DstXprType& dstExpr) + : Base(dst, src, func, dstExpr) {} #ifdef EIGEN_INTERNAL_DEBUGGING - EIGEN_DEVICE_FUNC void assignCoeff(Index row, Index col) - { - eigen_internal_assert(row!=col); - Base::assignCoeff(row,col); + EIGEN_DEVICE_FUNC void assignCoeff(Index row, Index col) { + eigen_internal_assert(row != col); + Base::assignCoeff(row, col); } #else using Base::assignCoeff; #endif - EIGEN_DEVICE_FUNC void assignDiagonalCoeff(Index id) - { - if(Mode==UnitDiag && SetOpposite) m_functor.assignCoeff(m_dst.coeffRef(id,id), Scalar(1)); - else if(Mode==ZeroDiag && SetOpposite) m_functor.assignCoeff(m_dst.coeffRef(id,id), Scalar(0)); - else if(Mode==0) Base::assignCoeff(id,id); + EIGEN_DEVICE_FUNC void assignDiagonalCoeff(Index id) { + if (Mode == UnitDiag && SetOpposite) + m_functor.assignCoeff(m_dst.coeffRef(id, id), Scalar(1)); + else if (Mode == ZeroDiag && SetOpposite) + m_functor.assignCoeff(m_dst.coeffRef(id, id), Scalar(0)); + else if (Mode == 0) + Base::assignCoeff(id, id); } - EIGEN_DEVICE_FUNC void assignOppositeCoeff(Index row, Index col) - { - eigen_internal_assert(row!=col); - if(SetOpposite) - m_functor.assignCoeff(m_dst.coeffRef(row,col), Scalar(0)); + EIGEN_DEVICE_FUNC void assignOppositeCoeff(Index row, Index col) { + eigen_internal_assert(row != col); + if (SetOpposite) m_functor.assignCoeff(m_dst.coeffRef(row, col), Scalar(0)); } }; -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void call_triangular_assignment_loop(DstXprType& dst, const SrcXprType& src, const Functor &func) -{ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_triangular_assignment_loop(DstXprType& dst, const SrcXprType& src, + const Functor& func) { typedef evaluator DstEvaluatorType; typedef evaluator SrcEvaluatorType; @@ -808,194 +714,187 @@ void call_triangular_assignment_loop(DstXprType& dst, const SrcXprType& src, con Index dstRows = src.rows(); Index dstCols = src.cols(); - if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) - dst.resize(dstRows, dstCols); + if ((dst.rows() != dstRows) || (dst.cols() != dstCols)) dst.resize(dstRows, dstCols); DstEvaluatorType dstEvaluator(dst); - typedef triangular_dense_assignment_kernel< Mode&(Lower|Upper),Mode&(UnitDiag|ZeroDiag|SelfAdjoint),SetOpposite, - DstEvaluatorType,SrcEvaluatorType,Functor> Kernel; + typedef triangular_dense_assignment_kernel + Kernel; Kernel kernel(dstEvaluator, srcEvaluator, func, dst.const_cast_derived()); enum { - unroll = DstXprType::SizeAtCompileTime != Dynamic - && SrcEvaluatorType::CoeffReadCost < HugeCost - && DstXprType::SizeAtCompileTime * (int(DstEvaluatorType::CoeffReadCost) + int(SrcEvaluatorType::CoeffReadCost)) / 2 <= EIGEN_UNROLLING_LIMIT - }; + unroll = DstXprType::SizeAtCompileTime != Dynamic && SrcEvaluatorType::CoeffReadCost < HugeCost && + DstXprType::SizeAtCompileTime * + (int(DstEvaluatorType::CoeffReadCost) + int(SrcEvaluatorType::CoeffReadCost)) / 2 <= + EIGEN_UNROLLING_LIMIT + }; - triangular_assignment_loop::run(kernel); + triangular_assignment_loop::run( + kernel); } -template -EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE -void call_triangular_assignment_loop(DstXprType& dst, const SrcXprType& src) -{ - call_triangular_assignment_loop(dst, src, internal::assign_op()); +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_triangular_assignment_loop(DstXprType& dst, const SrcXprType& src) { + call_triangular_assignment_loop( + dst, src, internal::assign_op()); } -template<> struct AssignmentKind { typedef Triangular2Triangular Kind; }; -template<> struct AssignmentKind { typedef Triangular2Dense Kind; }; -template<> struct AssignmentKind { typedef Dense2Triangular Kind; }; - +template <> +struct AssignmentKind { + typedef Triangular2Triangular Kind; +}; +template <> +struct AssignmentKind { + typedef Triangular2Dense Kind; +}; +template <> +struct AssignmentKind { + typedef Dense2Triangular Kind; +}; -template< typename DstXprType, typename SrcXprType, typename Functor> -struct Assignment -{ - EIGEN_DEVICE_FUNC static void run(DstXprType &dst, const SrcXprType &src, const Functor &func) - { +template +struct Assignment { + EIGEN_DEVICE_FUNC static void run(DstXprType& dst, const SrcXprType& src, const Functor& func) { eigen_assert(int(DstXprType::Mode) == int(SrcXprType::Mode)); call_triangular_assignment_loop(dst, src, func); } }; -template< typename DstXprType, typename SrcXprType, typename Functor> -struct Assignment -{ - EIGEN_DEVICE_FUNC static void run(DstXprType &dst, const SrcXprType &src, const Functor &func) - { +template +struct Assignment { + EIGEN_DEVICE_FUNC static void run(DstXprType& dst, const SrcXprType& src, const Functor& func) { call_triangular_assignment_loop(dst, src, func); } }; -template< typename DstXprType, typename SrcXprType, typename Functor> -struct Assignment -{ - EIGEN_DEVICE_FUNC static void run(DstXprType &dst, const SrcXprType &src, const Functor &func) - { +template +struct Assignment { + EIGEN_DEVICE_FUNC static void run(DstXprType& dst, const SrcXprType& src, const Functor& func) { call_triangular_assignment_loop(dst, src, func); } }; - -template -struct triangular_assignment_loop -{ +template +struct triangular_assignment_loop { // FIXME: this is not very clean, perhaps this information should be provided by the kernel? typedef typename Kernel::DstEvaluatorType DstEvaluatorType; typedef typename DstEvaluatorType::XprType DstXprType; enum { - col = (UnrollCount-1) / DstXprType::RowsAtCompileTime, - row = (UnrollCount-1) % DstXprType::RowsAtCompileTime + col = (UnrollCount - 1) / DstXprType::RowsAtCompileTime, + row = (UnrollCount - 1) % DstXprType::RowsAtCompileTime }; typedef typename Kernel::Scalar Scalar; - EIGEN_DEVICE_FUNC - static inline void run(Kernel &kernel) - { - triangular_assignment_loop::run(kernel); + EIGEN_DEVICE_FUNC static inline void run(Kernel& kernel) { + triangular_assignment_loop::run(kernel); - if(row==col) + if (row == col) kernel.assignDiagonalCoeff(row); - else if( ((Mode&Lower) && row>col) || ((Mode&Upper) && row col) || ((Mode & Upper) && row < col)) + kernel.assignCoeff(row, col); + else if (SetOpposite) + kernel.assignOppositeCoeff(row, col); } }; // prevent buggy user code from causing an infinite recursion -template -struct triangular_assignment_loop -{ - EIGEN_DEVICE_FUNC - static inline void run(Kernel &) {} +template +struct triangular_assignment_loop { + EIGEN_DEVICE_FUNC static inline void run(Kernel&) {} }; - - // TODO: experiment with a recursive assignment procedure splitting the current // triangular part into one rectangular and two triangular parts. - -template -struct triangular_assignment_loop -{ +template +struct triangular_assignment_loop { typedef typename Kernel::Scalar Scalar; - EIGEN_DEVICE_FUNC - static inline void run(Kernel &kernel) - { - for(Index j = 0; j < kernel.cols(); ++j) - { + EIGEN_DEVICE_FUNC static inline void run(Kernel& kernel) { + for (Index j = 0; j < kernel.cols(); ++j) { Index maxi = numext::mini(j, kernel.rows()); Index i = 0; - if (((Mode&Lower) && SetOpposite) || (Mode&Upper)) - { - for(; i < maxi; ++i) - if(Mode&Upper) kernel.assignCoeff(i, j); - else kernel.assignOppositeCoeff(i, j); - } - else + if (((Mode & Lower) && SetOpposite) || (Mode & Upper)) { + for (; i < maxi; ++i) + if (Mode & Upper) + kernel.assignCoeff(i, j); + else + kernel.assignOppositeCoeff(i, j); + } else i = maxi; - if(i -template -EIGEN_DEVICE_FUNC void TriangularBase::evalToLazy(MatrixBase &other) const -{ + * If the matrix is triangular, the opposite part is set to zero. */ +template +template +EIGEN_DEVICE_FUNC void TriangularBase::evalToLazy(MatrixBase& other) const { other.derived().resize(this->rows(), this->cols()); - internal::call_triangular_assignment_loop(other.derived(), derived().nestedExpression()); + internal::call_triangular_assignment_loop( + other.derived(), derived().nestedExpression()); } namespace internal { // Triangular = Product -template< typename DstXprType, typename Lhs, typename Rhs, typename Scalar> -struct Assignment, internal::assign_op::Scalar>, Dense2Triangular> -{ - typedef Product SrcXprType; - static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &) - { +template +struct Assignment, + internal::assign_op::Scalar>, Dense2Triangular> { + typedef Product SrcXprType; + static void run(DstXprType& dst, const SrcXprType& src, + const internal::assign_op&) { Index dstRows = src.rows(); Index dstCols = src.cols(); - if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) - dst.resize(dstRows, dstCols); + if ((dst.rows() != dstRows) || (dst.cols() != dstCols)) dst.resize(dstRows, dstCols); dst._assignProduct(src, Scalar(1), false); } }; // Triangular += Product -template< typename DstXprType, typename Lhs, typename Rhs, typename Scalar> -struct Assignment, internal::add_assign_op::Scalar>, Dense2Triangular> -{ - typedef Product SrcXprType; - static void run(DstXprType &dst, const SrcXprType &src, const internal::add_assign_op &) - { +template +struct Assignment, + internal::add_assign_op::Scalar>, + Dense2Triangular> { + typedef Product SrcXprType; + static void run(DstXprType& dst, const SrcXprType& src, + const internal::add_assign_op&) { dst._assignProduct(src, Scalar(1), true); } }; // Triangular -= Product -template< typename DstXprType, typename Lhs, typename Rhs, typename Scalar> -struct Assignment, internal::sub_assign_op::Scalar>, Dense2Triangular> -{ - typedef Product SrcXprType; - static void run(DstXprType &dst, const SrcXprType &src, const internal::sub_assign_op &) - { +template +struct Assignment, + internal::sub_assign_op::Scalar>, + Dense2Triangular> { + typedef Product SrcXprType; + static void run(DstXprType& dst, const SrcXprType& src, + const internal::sub_assign_op&) { dst._assignProduct(src, Scalar(-1), true); } }; -} // end namespace internal +} // end namespace internal -} // end namespace Eigen +} // end namespace Eigen -#endif // EIGEN_TRIANGULARMATRIX_H +#endif // EIGEN_TRIANGULARMATRIX_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/VectorBlock.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/VectorBlock.h index 71c5b95eec1..5ac13eb8e41 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/VectorBlock.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/VectorBlock.h @@ -11,86 +11,73 @@ #ifndef EIGEN_VECTORBLOCK_H #define EIGEN_VECTORBLOCK_H -namespace Eigen { +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { namespace internal { -template +template struct traits > - : public traits::Flags & RowMajorBit ? 1 : Size, - traits::Flags & RowMajorBit ? Size : 1> > -{ -}; -} + : public traits::Flags & RowMajorBit ? 1 : Size, + traits::Flags & RowMajorBit ? Size : 1> > {}; +} // namespace internal /** \class VectorBlock - * \ingroup Core_Module - * - * \brief Expression of a fixed-size or dynamic-size sub-vector - * - * \tparam VectorType the type of the object in which we are taking a sub-vector - * \tparam Size size of the sub-vector we are taking at compile time (optional) - * - * This class represents an expression of either a fixed-size or dynamic-size sub-vector. - * It is the return type of DenseBase::segment(Index,Index) and DenseBase::segment(Index) and - * most of the time this is the only way it is used. - * - * However, if you want to directly manipulate sub-vector expressions, - * for instance if you want to write a function returning such an expression, you - * will need to use this class. - * - * Here is an example illustrating the dynamic case: - * \include class_VectorBlock.cpp - * Output: \verbinclude class_VectorBlock.out - * - * \note Even though this expression has dynamic size, in the case where \a VectorType - * has fixed size, this expression inherits a fixed maximal size which means that evaluating - * it does not cause a dynamic memory allocation. - * - * Here is an example illustrating the fixed-size case: - * \include class_FixedVectorBlock.cpp - * Output: \verbinclude class_FixedVectorBlock.out - * - * \sa class Block, DenseBase::segment(Index,Index,Index,Index), DenseBase::segment(Index,Index) - */ -template class VectorBlock - : public Block::Flags & RowMajorBit ? 1 : Size, - internal::traits::Flags & RowMajorBit ? Size : 1> -{ - typedef Block::Flags & RowMajorBit ? 1 : Size, - internal::traits::Flags & RowMajorBit ? Size : 1> Base; - enum { - IsColVector = !(internal::traits::Flags & RowMajorBit) - }; - public: - EIGEN_DENSE_PUBLIC_INTERFACE(VectorBlock) + * \ingroup Core_Module + * + * \brief Expression of a fixed-size or dynamic-size sub-vector + * + * \tparam VectorType the type of the object in which we are taking a sub-vector + * \tparam Size size of the sub-vector we are taking at compile time (optional) + * + * This class represents an expression of either a fixed-size or dynamic-size sub-vector. + * It is the return type of DenseBase::segment(Index,Index) and DenseBase::segment(Index) and + * most of the time this is the only way it is used. + * + * However, if you want to directly manipulate sub-vector expressions, + * for instance if you want to write a function returning such an expression, you + * will need to use this class. + * + * Here is an example illustrating the dynamic case: + * \include class_VectorBlock.cpp + * Output: \verbinclude class_VectorBlock.out + * + * \note Even though this expression has dynamic size, in the case where \a VectorType + * has fixed size, this expression inherits a fixed maximal size which means that evaluating + * it does not cause a dynamic memory allocation. + * + * Here is an example illustrating the fixed-size case: + * \include class_FixedVectorBlock.cpp + * Output: \verbinclude class_FixedVectorBlock.out + * + * \sa class Block, DenseBase::segment(Index,Index,Index,Index), DenseBase::segment(Index,Index) + */ +template +class VectorBlock : public Block::Flags & RowMajorBit ? 1 : Size, + internal::traits::Flags & RowMajorBit ? Size : 1> { + typedef Block::Flags & RowMajorBit ? 1 : Size, + internal::traits::Flags & RowMajorBit ? Size : 1> + Base; + enum { IsColVector = !(internal::traits::Flags & RowMajorBit) }; - using Base::operator=; + public: + EIGEN_DENSE_PUBLIC_INTERFACE(VectorBlock) + EIGEN_STATIC_ASSERT_VECTOR_ONLY(VectorBlock) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(VectorBlock) - /** Dynamic-size constructor - */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - VectorBlock(VectorType& vector, Index start, Index size) - : Base(vector, - IsColVector ? start : 0, IsColVector ? 0 : start, - IsColVector ? size : 1, IsColVector ? 1 : size) - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(VectorBlock); - } + /** Dynamic-size constructor + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE VectorBlock(VectorType& vector, Index start, Index size) + : Base(vector, IsColVector ? start : 0, IsColVector ? 0 : start, IsColVector ? size : 1, IsColVector ? 1 : size) { + } - /** Fixed-size constructor - */ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE - VectorBlock(VectorType& vector, Index start) - : Base(vector, IsColVector ? start : 0, IsColVector ? 0 : start) - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(VectorBlock); - } + /** Fixed-size constructor + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE VectorBlock(VectorType& vector, Index start) + : Base(vector, IsColVector ? start : 0, IsColVector ? 0 : start) {} }; +} // end namespace Eigen -} // end namespace Eigen - -#endif // EIGEN_VECTORBLOCK_H +#endif // EIGEN_VECTORBLOCK_H diff --git a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/VectorwiseOp.h b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/VectorwiseOp.h index 870f4f1e40b..9887db67a49 100644 --- a/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/VectorwiseOp.h +++ b/wpimath/src/main/native/thirdparty/eigen/include/Eigen/src/Core/VectorwiseOp.h @@ -11,774 +11,703 @@ #ifndef EIGEN_PARTIAL_REDUX_H #define EIGEN_PARTIAL_REDUX_H +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + namespace Eigen { /** \class PartialReduxExpr - * \ingroup Core_Module - * - * \brief Generic expression of a partially reduxed matrix - * - * \tparam MatrixType the type of the matrix we are applying the redux operation - * \tparam MemberOp type of the member functor - * \tparam Direction indicates the direction of the redux (#Vertical or #Horizontal) - * - * This class represents an expression of a partial redux operator of a matrix. - * It is the return type of some VectorwiseOp functions, - * and most of the time this is the only way it is used. - * - * \sa class VectorwiseOp - */ - -template< typename MatrixType, typename MemberOp, int Direction> + * \ingroup Core_Module + * + * \brief Generic expression of a partially reduxed matrix + * + * \tparam MatrixType the type of the matrix we are applying the redux operation + * \tparam MemberOp type of the member functor + * \tparam Direction indicates the direction of the redux (#Vertical or #Horizontal) + * + * This class represents an expression of a partial redux operator of a matrix. + * It is the return type of some VectorwiseOp functions, + * and most of the time this is the only way it is used. + * + * \sa class VectorwiseOp + */ + +template class PartialReduxExpr; namespace internal { -template -struct traits > - : traits -{ +template +struct traits > : traits { typedef typename MemberOp::result_type Scalar; typedef typename traits::StorageKind StorageKind; typedef typename traits::XprKind XprKind; typedef typename MatrixType::Scalar InputScalar; enum { - RowsAtCompileTime = Direction==Vertical ? 1 : MatrixType::RowsAtCompileTime, - ColsAtCompileTime = Direction==Horizontal ? 1 : MatrixType::ColsAtCompileTime, - MaxRowsAtCompileTime = Direction==Vertical ? 1 : MatrixType::MaxRowsAtCompileTime, - MaxColsAtCompileTime = Direction==Horizontal ? 1 : MatrixType::MaxColsAtCompileTime, + RowsAtCompileTime = Direction == Vertical ? 1 : MatrixType::RowsAtCompileTime, + ColsAtCompileTime = Direction == Horizontal ? 1 : MatrixType::ColsAtCompileTime, + MaxRowsAtCompileTime = Direction == Vertical ? 1 : MatrixType::MaxRowsAtCompileTime, + MaxColsAtCompileTime = Direction == Horizontal ? 1 : MatrixType::MaxColsAtCompileTime, Flags = RowsAtCompileTime == 1 ? RowMajorBit : 0, - TraversalSize = Direction==Vertical ? MatrixType::RowsAtCompileTime : MatrixType::ColsAtCompileTime + TraversalSize = Direction == Vertical ? MatrixType::RowsAtCompileTime : MatrixType::ColsAtCompileTime }; }; -} - -template< typename MatrixType, typename MemberOp, int Direction> -class PartialReduxExpr : public internal::dense_xpr_base< PartialReduxExpr >::type, - internal::no_assignment_operator -{ - public: +} // namespace internal - typedef typename internal::dense_xpr_base::type Base; - EIGEN_DENSE_PUBLIC_INTERFACE(PartialReduxExpr) +template +class PartialReduxExpr : public internal::dense_xpr_base >::type, + internal::no_assignment_operator { + public: + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(PartialReduxExpr) - EIGEN_DEVICE_FUNC - explicit PartialReduxExpr(const MatrixType& mat, const MemberOp& func = MemberOp()) + EIGEN_DEVICE_FUNC explicit PartialReduxExpr(const MatrixType& mat, const MemberOp& func = MemberOp()) : m_matrix(mat), m_functor(func) {} - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - Index rows() const EIGEN_NOEXCEPT { return (Direction==Vertical ? 1 : m_matrix.rows()); } - EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR - Index cols() const EIGEN_NOEXCEPT { return (Direction==Horizontal ? 1 : m_matrix.cols()); } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { + return (Direction == Vertical ? 1 : m_matrix.rows()); + } + EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { + return (Direction == Horizontal ? 1 : m_matrix.cols()); + } - EIGEN_DEVICE_FUNC - typename MatrixType::Nested nestedExpression() const { return m_matrix; } + EIGEN_DEVICE_FUNC typename MatrixType::Nested nestedExpression() const { return m_matrix; } - EIGEN_DEVICE_FUNC - const MemberOp& functor() const { return m_functor; } + EIGEN_DEVICE_FUNC const MemberOp& functor() const { return m_functor; } - protected: - typename MatrixType::Nested m_matrix; - const MemberOp m_functor; + protected: + typename MatrixType::Nested m_matrix; + const MemberOp m_functor; }; -template struct partial_redux_dummy_func; +template +struct partial_redux_dummy_func; -#define EIGEN_MAKE_PARTIAL_REDUX_FUNCTOR(MEMBER,COST,VECTORIZABLE,BINARYOP) \ - template \ +#define EIGEN_MAKE_PARTIAL_REDUX_FUNCTOR(MEMBER, COST, VECTORIZABLE, BINARYOP) \ + template \ struct member_##MEMBER { \ - EIGEN_EMPTY_STRUCT_CTOR(member_##MEMBER) \ typedef ResultType result_type; \ - typedef BINARYOP BinaryOp; \ - template struct Cost { enum { value = COST }; }; \ + typedef BINARYOP BinaryOp; \ + template \ + struct Cost { \ + enum { value = COST }; \ + }; \ enum { Vectorizable = VECTORIZABLE }; \ - template \ - EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE \ - ResultType operator()(const XprType& mat) const \ - { return mat.MEMBER(); } \ + template \ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ResultType operator()(const XprType& mat) const { \ + return mat.MEMBER(); \ + } \ BinaryOp binaryFunc() const { return BinaryOp(); } \ } -#define EIGEN_MEMBER_FUNCTOR(MEMBER,COST) \ - EIGEN_MAKE_PARTIAL_REDUX_FUNCTOR(MEMBER,COST,0,partial_redux_dummy_func) +#define EIGEN_MEMBER_FUNCTOR(MEMBER, COST) EIGEN_MAKE_PARTIAL_REDUX_FUNCTOR(MEMBER, COST, 0, partial_redux_dummy_func) namespace internal { -EIGEN_MEMBER_FUNCTOR(norm, (Size+5) * NumTraits::MulCost + (Size-1)*NumTraits::AddCost); -EIGEN_MEMBER_FUNCTOR(stableNorm, (Size+5) * NumTraits::MulCost + (Size-1)*NumTraits::AddCost); -EIGEN_MEMBER_FUNCTOR(blueNorm, (Size+5) * NumTraits::MulCost + (Size-1)*NumTraits::AddCost); -EIGEN_MEMBER_FUNCTOR(hypotNorm, (Size-1) * functor_traits >::Cost ); -EIGEN_MEMBER_FUNCTOR(all, (Size-1)*NumTraits::AddCost); -EIGEN_MEMBER_FUNCTOR(any, (Size-1)*NumTraits::AddCost); -EIGEN_MEMBER_FUNCTOR(count, (Size-1)*NumTraits::AddCost); +EIGEN_MEMBER_FUNCTOR(norm, (Size + 5) * NumTraits::MulCost + (Size - 1) * NumTraits::AddCost); +EIGEN_MEMBER_FUNCTOR(stableNorm, (Size + 5) * NumTraits::MulCost + (Size - 1) * NumTraits::AddCost); +EIGEN_MEMBER_FUNCTOR(blueNorm, (Size + 5) * NumTraits::MulCost + (Size - 1) * NumTraits::AddCost); +EIGEN_MEMBER_FUNCTOR(hypotNorm, (Size - 1) * functor_traits >::Cost); +EIGEN_MEMBER_FUNCTOR(all, (Size - 1) * NumTraits::AddCost); +EIGEN_MEMBER_FUNCTOR(any, (Size - 1) * NumTraits::AddCost); +EIGEN_MEMBER_FUNCTOR(count, (Size - 1) * NumTraits::AddCost); -EIGEN_MAKE_PARTIAL_REDUX_FUNCTOR(sum, (Size-1)*NumTraits::AddCost, 1, internal::scalar_sum_op); -EIGEN_MAKE_PARTIAL_REDUX_FUNCTOR(minCoeff, (Size-1)*NumTraits::AddCost, 1, internal::scalar_min_op); -EIGEN_MAKE_PARTIAL_REDUX_FUNCTOR(maxCoeff, (Size-1)*NumTraits::AddCost, 1, internal::scalar_max_op); -EIGEN_MAKE_PARTIAL_REDUX_FUNCTOR(prod, (Size-1)*NumTraits::MulCost, 1, internal::scalar_product_op); +EIGEN_MAKE_PARTIAL_REDUX_FUNCTOR(sum, (Size - 1) * NumTraits::AddCost, 1, internal::scalar_sum_op); +EIGEN_MAKE_PARTIAL_REDUX_FUNCTOR(minCoeff, (Size - 1) * NumTraits::AddCost, 1, internal::scalar_min_op); +EIGEN_MAKE_PARTIAL_REDUX_FUNCTOR(maxCoeff, (Size - 1) * NumTraits::AddCost, 1, internal::scalar_max_op); +EIGEN_MAKE_PARTIAL_REDUX_FUNCTOR(prod, (Size - 1) * NumTraits::MulCost, 1, internal::scalar_product_op); -template +template struct member_lpnorm { typedef ResultType result_type; enum { Vectorizable = 0 }; - template struct Cost - { enum { value = (Size+5) * NumTraits::MulCost + (Size-1)*NumTraits::AddCost }; }; + template + struct Cost { + enum { value = (Size + 5) * NumTraits::MulCost + (Size - 1) * NumTraits::AddCost }; + }; EIGEN_DEVICE_FUNC member_lpnorm() {} - template - EIGEN_DEVICE_FUNC inline ResultType operator()(const XprType& mat) const - { return mat.template lpNorm

    (); } + template + EIGEN_DEVICE_FUNC inline ResultType operator()(const XprType& mat) const { + return mat.template lpNorm

    (); + } }; template struct member_redux { typedef BinaryOpT BinaryOp; - typedef typename result_of< - BinaryOp(const Scalar&,const Scalar&) - >::type result_type; + typedef typename result_of::type result_type; enum { Vectorizable = functor_traits::PacketAccess }; - template struct Cost { enum { value = (Size-1) * functor_traits::Cost }; }; + template + struct Cost { + enum { value = (Size - 1) * functor_traits::Cost }; + }; EIGEN_DEVICE_FUNC explicit member_redux(const BinaryOp func) : m_functor(func) {} - template - EIGEN_DEVICE_FUNC inline result_type operator()(const DenseBase& mat) const - { return mat.redux(m_functor); } + template + EIGEN_DEVICE_FUNC inline result_type operator()(const DenseBase& mat) const { + return mat.redux(m_functor); + } const BinaryOp& binaryFunc() const { return m_functor; } const BinaryOp m_functor; }; -} +} // namespace internal /** \class VectorwiseOp - * \ingroup Core_Module - * - * \brief Pseudo expression providing broadcasting and partial reduction operations - * - * \tparam ExpressionType the type of the object on which to do partial reductions - * \tparam Direction indicates whether to operate on columns (#Vertical) or rows (#Horizontal) - * - * This class represents a pseudo expression with broadcasting and partial reduction features. - * It is the return type of DenseBase::colwise() and DenseBase::rowwise() - * and most of the time this is the only way it is explicitly used. - * - * To understand the logic of rowwise/colwise expression, let's consider a generic case `A.colwise().foo()` - * where `foo` is any method of `VectorwiseOp`. This expression is equivalent to applying `foo()` to each - * column of `A` and then re-assemble the outputs in a matrix expression: - * \code [A.col(0).foo(), A.col(1).foo(), ..., A.col(A.cols()-1).foo()] \endcode - * - * Example: \include MatrixBase_colwise.cpp - * Output: \verbinclude MatrixBase_colwise.out - * - * The begin() and end() methods are obviously exceptions to the previous rule as they - * return STL-compatible begin/end iterators to the rows or columns of the nested expression. - * Typical use cases include for-range-loop and calls to STL algorithms: - * - * Example: \include MatrixBase_colwise_iterator_cxx11.cpp - * Output: \verbinclude MatrixBase_colwise_iterator_cxx11.out - * - * For a partial reduction on an empty input, some rules apply. - * For the sake of clarity, let's consider a vertical reduction: - * - If the number of columns is zero, then a 1x0 row-major vector expression is returned. - * - Otherwise, if the number of rows is zero, then - * - a row vector of zeros is returned for sum-like reductions (sum, squaredNorm, norm, etc.) - * - a row vector of ones is returned for a product reduction (e.g., MatrixXd(n,0).colwise().prod()) - * - an assert is triggered for all other reductions (minCoeff,maxCoeff,redux(bin_op)) - * - * \sa DenseBase::colwise(), DenseBase::rowwise(), class PartialReduxExpr - */ -template class VectorwiseOp -{ - public: - - typedef typename ExpressionType::Scalar Scalar; - typedef typename ExpressionType::RealScalar RealScalar; - typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3 - typedef typename internal::ref_selector::non_const_type ExpressionTypeNested; - typedef typename internal::remove_all::type ExpressionTypeNestedCleaned; - - template class Functor, - typename ReturnScalar=Scalar> struct ReturnType - { - typedef PartialReduxExpr, - Direction - > Type; - }; - - template struct ReduxReturnType - { - typedef PartialReduxExpr, - Direction - > Type; - }; - - enum { - isVertical = (Direction==Vertical) ? 1 : 0, - isHorizontal = (Direction==Horizontal) ? 1 : 0 - }; - - protected: - - template struct ExtendedType { - typedef Replicate Type; - }; - - /** \internal - * Replicates a vector to match the size of \c *this */ - template - EIGEN_DEVICE_FUNC - typename ExtendedType::Type - extendedTo(const DenseBase& other) const - { - EIGEN_STATIC_ASSERT(EIGEN_IMPLIES(isVertical, OtherDerived::MaxColsAtCompileTime==1), - YOU_PASSED_A_ROW_VECTOR_BUT_A_COLUMN_VECTOR_WAS_EXPECTED) - EIGEN_STATIC_ASSERT(EIGEN_IMPLIES(isHorizontal, OtherDerived::MaxRowsAtCompileTime==1), - YOU_PASSED_A_COLUMN_VECTOR_BUT_A_ROW_VECTOR_WAS_EXPECTED) - return typename ExtendedType::Type - (other.derived(), - isVertical ? 1 : m_matrix.rows(), - isHorizontal ? 1 : m_matrix.cols()); - } - - template struct OppositeExtendedType { - typedef Replicate Type; - }; - - /** \internal - * Replicates a vector in the opposite direction to match the size of \c *this */ - template - EIGEN_DEVICE_FUNC - typename OppositeExtendedType::Type - extendedToOpposite(const DenseBase& other) const - { - EIGEN_STATIC_ASSERT(EIGEN_IMPLIES(isHorizontal, OtherDerived::MaxColsAtCompileTime==1), - YOU_PASSED_A_ROW_VECTOR_BUT_A_COLUMN_VECTOR_WAS_EXPECTED) - EIGEN_STATIC_ASSERT(EIGEN_IMPLIES(isVertical, OtherDerived::MaxRowsAtCompileTime==1), - YOU_PASSED_A_COLUMN_VECTOR_BUT_A_ROW_VECTOR_WAS_EXPECTED) - return typename OppositeExtendedType::Type - (other.derived(), - isHorizontal ? 1 : m_matrix.rows(), - isVertical ? 1 : m_matrix.cols()); - } - - public: - EIGEN_DEVICE_FUNC - explicit inline VectorwiseOp(ExpressionType& matrix) : m_matrix(matrix) {} - - /** \internal */ - EIGEN_DEVICE_FUNC - inline const ExpressionType& _expression() const { return m_matrix; } - - #ifdef EIGEN_PARSED_BY_DOXYGEN - /** STL-like RandomAccessIterator - * iterator type over the columns or rows as returned by the begin() and end() methods. - */ - random_access_iterator_type iterator; - /** This is the const version of iterator (aka read-only) */ - random_access_iterator_type const_iterator; - #else - typedef internal::subvector_stl_iterator iterator; - typedef internal::subvector_stl_iterator const_iterator; - typedef internal::subvector_stl_reverse_iterator reverse_iterator; - typedef internal::subvector_stl_reverse_iterator const_reverse_iterator; - #endif - - /** returns an iterator to the first row (rowwise) or column (colwise) of the nested expression. - * \sa end(), cbegin() - */ - iterator begin() { return iterator (m_matrix, 0); } - /** const version of begin() */ - const_iterator begin() const { return const_iterator(m_matrix, 0); } - /** const version of begin() */ - const_iterator cbegin() const { return const_iterator(m_matrix, 0); } - - /** returns a reverse iterator to the last row (rowwise) or column (colwise) of the nested expression. - * \sa rend(), crbegin() - */ - reverse_iterator rbegin() { return reverse_iterator (m_matrix, m_matrix.template subVectors()-1); } - /** const version of rbegin() */ - const_reverse_iterator rbegin() const { return const_reverse_iterator (m_matrix, m_matrix.template subVectors()-1); } - /** const version of rbegin() */ - const_reverse_iterator crbegin() const { return const_reverse_iterator (m_matrix, m_matrix.template subVectors()-1); } - - /** returns an iterator to the row (resp. column) following the last row (resp. column) of the nested expression - * \sa begin(), cend() - */ - iterator end() { return iterator (m_matrix, m_matrix.template subVectors()); } - /** const version of end() */ - const_iterator end() const { return const_iterator(m_matrix, m_matrix.template subVectors()); } - /** const version of end() */ - const_iterator cend() const { return const_iterator(m_matrix, m_matrix.template subVectors()); } - - /** returns a reverse iterator to the row (resp. column) before the first row (resp. column) of the nested expression - * \sa begin(), cend() - */ - reverse_iterator rend() { return reverse_iterator (m_matrix, -1); } - /** const version of rend() */ - const_reverse_iterator rend() const { return const_reverse_iterator (m_matrix, -1); } - /** const version of rend() */ - const_reverse_iterator crend() const { return const_reverse_iterator (m_matrix, -1); } - - /** \returns a row or column vector expression of \c *this reduxed by \a func - * - * The template parameter \a BinaryOp is the type of the functor - * of the custom redux operator. Note that func must be an associative operator. - * - * \warning the size along the reduction direction must be strictly positive, - * otherwise an assertion is triggered. - * - * \sa class VectorwiseOp, DenseBase::colwise(), DenseBase::rowwise() - */ - template - EIGEN_DEVICE_FUNC - const typename ReduxReturnType::Type - redux(const BinaryOp& func = BinaryOp()) const - { - eigen_assert(redux_length()>0 && "you are using an empty matrix"); - return typename ReduxReturnType::Type(_expression(), internal::member_redux(func)); - } - - typedef typename ReturnType::Type MinCoeffReturnType; - typedef typename ReturnType::Type MaxCoeffReturnType; - typedef PartialReduxExpr, const ExpressionTypeNestedCleaned>,internal::member_sum,Direction> SquaredNormReturnType; - typedef CwiseUnaryOp, const SquaredNormReturnType> NormReturnType; - typedef typename ReturnType::Type BlueNormReturnType; - typedef typename ReturnType::Type StableNormReturnType; - typedef typename ReturnType::Type HypotNormReturnType; - typedef typename ReturnType::Type SumReturnType; - typedef EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(SumReturnType,Scalar,quotient) MeanReturnType; - typedef typename ReturnType::Type AllReturnType; - typedef typename ReturnType::Type AnyReturnType; - typedef PartialReduxExpr, Direction> CountReturnType; - typedef typename ReturnType::Type ProdReturnType; - typedef Reverse ConstReverseReturnType; - typedef Reverse ReverseReturnType; - - template struct LpNormReturnType { - typedef PartialReduxExpr,Direction> Type; - }; - - /** \returns a row (or column) vector expression of the smallest coefficient - * of each column (or row) of the referenced expression. - * - * \warning the size along the reduction direction must be strictly positive, - * otherwise an assertion is triggered. - * - * \warning the result is undefined if \c *this contains NaN. - * - * Example: \include PartialRedux_minCoeff.cpp - * Output: \verbinclude PartialRedux_minCoeff.out - * - * \sa DenseBase::minCoeff() */ - EIGEN_DEVICE_FUNC - const MinCoeffReturnType minCoeff() const - { - eigen_assert(redux_length()>0 && "you are using an empty matrix"); - return MinCoeffReturnType(_expression()); - } - - /** \returns a row (or column) vector expression of the largest coefficient - * of each column (or row) of the referenced expression. - * - * \warning the size along the reduction direction must be strictly positive, - * otherwise an assertion is triggered. - * - * \warning the result is undefined if \c *this contains NaN. - * - * Example: \include PartialRedux_maxCoeff.cpp - * Output: \verbinclude PartialRedux_maxCoeff.out - * - * \sa DenseBase::maxCoeff() */ - EIGEN_DEVICE_FUNC - const MaxCoeffReturnType maxCoeff() const - { - eigen_assert(redux_length()>0 && "you are using an empty matrix"); - return MaxCoeffReturnType(_expression()); - } - - /** \returns a row (or column) vector expression of the squared norm - * of each column (or row) of the referenced expression. - * This is a vector with real entries, even if the original matrix has complex entries. - * - * Example: \include PartialRedux_squaredNorm.cpp - * Output: \verbinclude PartialRedux_squaredNorm.out - * - * \sa DenseBase::squaredNorm() */ - EIGEN_DEVICE_FUNC - const SquaredNormReturnType squaredNorm() const - { return SquaredNormReturnType(m_matrix.cwiseAbs2()); } - - /** \returns a row (or column) vector expression of the norm - * of each column (or row) of the referenced expression. - * This is a vector with real entries, even if the original matrix has complex entries. - * - * Example: \include PartialRedux_norm.cpp - * Output: \verbinclude PartialRedux_norm.out - * - * \sa DenseBase::norm() */ - EIGEN_DEVICE_FUNC - const NormReturnType norm() const - { return NormReturnType(squaredNorm()); } - - /** \returns a row (or column) vector expression of the norm - * of each column (or row) of the referenced expression. - * This is a vector with real entries, even if the original matrix has complex entries. - * - * Example: \include PartialRedux_norm.cpp - * Output: \verbinclude PartialRedux_norm.out - * - * \sa DenseBase::norm() */ - template - EIGEN_DEVICE_FUNC - const typename LpNormReturnType

    ::Type lpNorm() const - { return typename LpNormReturnType

    ::Type(_expression()); } - - - /** \returns a row (or column) vector expression of the norm - * of each column (or row) of the referenced expression, using - * Blue's algorithm. - * This is a vector with real entries, even if the original matrix has complex entries. - * - * \sa DenseBase::blueNorm() */ - EIGEN_DEVICE_FUNC - const BlueNormReturnType blueNorm() const - { return BlueNormReturnType(_expression()); } - - - /** \returns a row (or column) vector expression of the norm - * of each column (or row) of the referenced expression, avoiding - * underflow and overflow. - * This is a vector with real entries, even if the original matrix has complex entries. - * - * \sa DenseBase::stableNorm() */ - EIGEN_DEVICE_FUNC - const StableNormReturnType stableNorm() const - { return StableNormReturnType(_expression()); } - - - /** \returns a row (or column) vector expression of the norm - * of each column (or row) of the referenced expression, avoiding - * underflow and overflow using a concatenation of hypot() calls. - * This is a vector with real entries, even if the original matrix has complex entries. - * - * \sa DenseBase::hypotNorm() */ - EIGEN_DEVICE_FUNC - const HypotNormReturnType hypotNorm() const - { return HypotNormReturnType(_expression()); } - - /** \returns a row (or column) vector expression of the sum - * of each column (or row) of the referenced expression. - * - * Example: \include PartialRedux_sum.cpp - * Output: \verbinclude PartialRedux_sum.out - * - * \sa DenseBase::sum() */ - EIGEN_DEVICE_FUNC - const SumReturnType sum() const - { return SumReturnType(_expression()); } - - /** \returns a row (or column) vector expression of the mean - * of each column (or row) of the referenced expression. - * - * \sa DenseBase::mean() */ - EIGEN_DEVICE_FUNC - const MeanReturnType mean() const - { return sum() / Scalar(Direction==Vertical?m_matrix.rows():m_matrix.cols()); } - - /** \returns a row (or column) vector expression representing - * whether \b all coefficients of each respective column (or row) are \c true. - * This expression can be assigned to a vector with entries of type \c bool. - * - * \sa DenseBase::all() */ - EIGEN_DEVICE_FUNC - const AllReturnType all() const - { return AllReturnType(_expression()); } - - /** \returns a row (or column) vector expression representing - * whether \b at \b least one coefficient of each respective column (or row) is \c true. - * This expression can be assigned to a vector with entries of type \c bool. - * - * \sa DenseBase::any() */ - EIGEN_DEVICE_FUNC - const AnyReturnType any() const - { return AnyReturnType(_expression()); } - - /** \returns a row (or column) vector expression representing - * the number of \c true coefficients of each respective column (or row). - * This expression can be assigned to a vector whose entries have the same type as is used to - * index entries of the original matrix; for dense matrices, this is \c std::ptrdiff_t . - * - * Example: \include PartialRedux_count.cpp - * Output: \verbinclude PartialRedux_count.out - * - * \sa DenseBase::count() */ - EIGEN_DEVICE_FUNC - const CountReturnType count() const - { return CountReturnType(_expression()); } - - /** \returns a row (or column) vector expression of the product - * of each column (or row) of the referenced expression. - * - * Example: \include PartialRedux_prod.cpp - * Output: \verbinclude PartialRedux_prod.out - * - * \sa DenseBase::prod() */ - EIGEN_DEVICE_FUNC - const ProdReturnType prod() const - { return ProdReturnType(_expression()); } - - - /** \returns a matrix expression - * where each column (or row) are reversed. - * - * Example: \include Vectorwise_reverse.cpp - * Output: \verbinclude Vectorwise_reverse.out - * - * \sa DenseBase::reverse() */ - EIGEN_DEVICE_FUNC - const ConstReverseReturnType reverse() const - { return ConstReverseReturnType( _expression() ); } - - /** \returns a writable matrix expression - * where each column (or row) are reversed. - * - * \sa reverse() const */ - EIGEN_DEVICE_FUNC - ReverseReturnType reverse() - { return ReverseReturnType( _expression() ); } - - typedef Replicate ReplicateReturnType; - EIGEN_DEVICE_FUNC - const ReplicateReturnType replicate(Index factor) const; - - /** - * \return an expression of the replication of each column (or row) of \c *this - * - * Example: \include DirectionWise_replicate.cpp - * Output: \verbinclude DirectionWise_replicate.out - * - * \sa VectorwiseOp::replicate(Index), DenseBase::replicate(), class Replicate - */ - // NOTE implemented here because of sunstudio's compilation errors - // isVertical*Factor+isHorizontal instead of (isVertical?Factor:1) to handle CUDA bug with ternary operator - template const Replicate - EIGEN_DEVICE_FUNC - replicate(Index factor = Factor) const - { - return Replicate - (_expression(),isVertical?factor:1,isHorizontal?factor:1); - } - -/////////// Artithmetic operators /////////// - - /** Copies the vector \a other to each subvector of \c *this */ - template - EIGEN_DEVICE_FUNC - ExpressionType& operator=(const DenseBase& other) - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived) - EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived) - //eigen_assert((m_matrix.isNull()) == (other.isNull())); FIXME - return m_matrix = extendedTo(other.derived()); - } - - /** Adds the vector \a other to each subvector of \c *this */ - template - EIGEN_DEVICE_FUNC - ExpressionType& operator+=(const DenseBase& other) - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived) - EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived) - return m_matrix += extendedTo(other.derived()); - } - - /** Substracts the vector \a other to each subvector of \c *this */ - template - EIGEN_DEVICE_FUNC - ExpressionType& operator-=(const DenseBase& other) - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived) - EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived) - return m_matrix -= extendedTo(other.derived()); - } - - /** Multiples each subvector of \c *this by the vector \a other */ - template - EIGEN_DEVICE_FUNC - ExpressionType& operator*=(const DenseBase& other) - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived) - EIGEN_STATIC_ASSERT_ARRAYXPR(ExpressionType) - EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived) - m_matrix *= extendedTo(other.derived()); - return m_matrix; - } - - /** Divides each subvector of \c *this by the vector \a other */ - template - EIGEN_DEVICE_FUNC - ExpressionType& operator/=(const DenseBase& other) - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived) - EIGEN_STATIC_ASSERT_ARRAYXPR(ExpressionType) - EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived) - m_matrix /= extendedTo(other.derived()); - return m_matrix; - } - - /** Returns the expression of the sum of the vector \a other to each subvector of \c *this */ - template EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC - CwiseBinaryOp, - const ExpressionTypeNestedCleaned, - const typename ExtendedType::Type> - operator+(const DenseBase& other) const - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived) - EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived) - return m_matrix + extendedTo(other.derived()); - } - - /** Returns the expression of the difference between each subvector of \c *this and the vector \a other */ - template - EIGEN_DEVICE_FUNC - CwiseBinaryOp, - const ExpressionTypeNestedCleaned, - const typename ExtendedType::Type> - operator-(const DenseBase& other) const - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived) - EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived) - return m_matrix - extendedTo(other.derived()); - } - - /** Returns the expression where each subvector is the product of the vector \a other - * by the corresponding subvector of \c *this */ - template EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC - CwiseBinaryOp, - const ExpressionTypeNestedCleaned, - const typename ExtendedType::Type> - EIGEN_DEVICE_FUNC - operator*(const DenseBase& other) const - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived) - EIGEN_STATIC_ASSERT_ARRAYXPR(ExpressionType) - EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived) - return m_matrix * extendedTo(other.derived()); - } - - /** Returns the expression where each subvector is the quotient of the corresponding - * subvector of \c *this by the vector \a other */ - template - EIGEN_DEVICE_FUNC - CwiseBinaryOp, - const ExpressionTypeNestedCleaned, - const typename ExtendedType::Type> - operator/(const DenseBase& other) const - { - EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived) - EIGEN_STATIC_ASSERT_ARRAYXPR(ExpressionType) - EIGEN_STATIC_ASSERT_SAME_XPR_KIND(ExpressionType, OtherDerived) - return m_matrix / extendedTo(other.derived()); - } - - /** \returns an expression where each column (or row) of the referenced matrix are normalized. - * The referenced matrix is \b not modified. - * \sa MatrixBase::normalized(), normalize() - */ - EIGEN_DEVICE_FUNC - CwiseBinaryOp, - const ExpressionTypeNestedCleaned, - const typename OppositeExtendedType::Type> - normalized() const { return m_matrix.cwiseQuotient(extendedToOpposite(this->norm())); } - - - /** Normalize in-place each row or columns of the referenced matrix. - * \sa MatrixBase::normalize(), normalized() - */ - EIGEN_DEVICE_FUNC void normalize() { - m_matrix = this->normalized(); - } - - EIGEN_DEVICE_FUNC inline void reverseInPlace(); - -/////////// Geometry module /////////// - - typedef Homogeneous HomogeneousReturnType; - EIGEN_DEVICE_FUNC - HomogeneousReturnType homogeneous() const; - - typedef typename ExpressionType::PlainObject CrossReturnType; - template - EIGEN_DEVICE_FUNC - const CrossReturnType cross(const MatrixBase& other) const; - - enum { - HNormalized_Size = Direction==Vertical ? internal::traits::RowsAtCompileTime + * \ingroup Core_Module + * + * \brief Pseudo expression providing broadcasting and partial reduction operations + * + * \tparam ExpressionType the type of the object on which to do partial reductions + * \tparam Direction indicates whether to operate on columns (#Vertical) or rows (#Horizontal) + * + * This class represents a pseudo expression with broadcasting and partial reduction features. + * It is the return type of DenseBase::colwise() and DenseBase::rowwise() + * and most of the time this is the only way it is explicitly used. + * + * To understand the logic of rowwise/colwise expression, let's consider a generic case `A.colwise().foo()` + * where `foo` is any method of `VectorwiseOp`. This expression is equivalent to applying `foo()` to each + * column of `A` and then re-assemble the outputs in a matrix expression: + * \code [A.col(0).foo(), A.col(1).foo(), ..., A.col(A.cols()-1).foo()] \endcode + * + * Example: \include MatrixBase_colwise.cpp + * Output: \verbinclude MatrixBase_colwise.out + * + * The begin() and end() methods are obviously exceptions to the previous rule as they + * return STL-compatible begin/end iterators to the rows or columns of the nested expression. + * Typical use cases include for-range-loop and calls to STL algorithms: + * + * Example: \include MatrixBase_colwise_iterator_cxx11.cpp + * Output: \verbinclude MatrixBase_colwise_iterator_cxx11.out + * + * For a partial reduction on an empty input, some rules apply. + * For the sake of clarity, let's consider a vertical reduction: + * - If the number of columns is zero, then a 1x0 row-major vector expression is returned. + * - Otherwise, if the number of rows is zero, then + * - a row vector of zeros is returned for sum-like reductions (sum, squaredNorm, norm, etc.) + * - a row vector of ones is returned for a product reduction (e.g., MatrixXd(n,0).colwise().prod()) + * - an assert is triggered for all other reductions (minCoeff,maxCoeff,redux(bin_op)) + * + * \sa DenseBase::colwise(), DenseBase::rowwise(), class PartialReduxExpr + */ +template +class VectorwiseOp { + public: + typedef typename ExpressionType::Scalar Scalar; + typedef typename ExpressionType::RealScalar RealScalar; + typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3 + typedef typename internal::ref_selector::non_const_type ExpressionTypeNested; + typedef internal::remove_all_t ExpressionTypeNestedCleaned; + + template